Anupam251272 commited on
Commit
01139f1
Β·
verified Β·
1 Parent(s): 381533e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +706 -0
app.py ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM
2
+ import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from transformers import MarianMTModel, MarianTokenizer
6
+ from sentence_transformers import SentenceTransformer
7
+ from bs4 import BeautifulSoup
8
+ from fake_useragent import UserAgent
9
+ from datetime import datetime
10
+ import warnings
11
+ import gc
12
+ import re
13
+ import time
14
+ import random
15
+ import torch
16
+ from requests.exceptions import RequestException
17
+ import concurrent.futures
18
+ import json
19
+
20
+ warnings.filterwarnings('ignore')
21
+
22
+ class LegalResearchGenerator:
23
+ def __init__(self):
24
+ self.legal_categories = [
25
+ "criminal", "civil", "constitutional", "corporate",
26
+ "tax", "family", "property", "intellectual_property"
27
+ ]
28
+
29
+ self.doc_types = {
30
+ "all": "",
31
+ "central_acts": "central-acts",
32
+ "state_acts": "state-acts",
33
+ "regulations": "regulations",
34
+ "ordinances": "ordinances",
35
+ "constitutional_orders": "constitutional-orders"
36
+ }
37
+
38
+ # Initialize translation model only when needed
39
+ self.translation_model = None
40
+ self.translation_tokenizer = None
41
+
42
+ # Initialize summarization model
43
+ self.summarization_tokenizer = AutoTokenizer.from_pretrained("akhilm97/pegasus_indian_legal")
44
+ self.summarization_model = AutoModelForSeq2SeqLM.from_pretrained("akhilm97/pegasus_indian_legal")
45
+
46
+ # Initialize drafting model
47
+ try:
48
+ self.drafting_tokenizer = AutoTokenizer.from_pretrained("gpt2")
49
+ self.drafting_model = AutoModelForCausalLM.from_pretrained("gpt2")
50
+ except Exception as e:
51
+ print(f"Error initializing drafting model: {e}")
52
+ self.drafting_tokenizer= None
53
+ self.drafting_model= None
54
+
55
+ self.session = requests.Session()
56
+ self.session.headers.update(self.get_random_headers())
57
+
58
+ self.max_retries = 3
59
+ self.retry_delay = 1
60
+
61
+ # Initialize sentence transformer model
62
+ try:
63
+ self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
64
+ except Exception as e:
65
+ print(f"Error initializing sentence transformer: {e}")
66
+ self.sentence_model = None
67
+
68
+ # List of potentially risky queries, use lowercase
69
+ self.risky_queries = [
70
+ "property disputes", "divorce proceedings", "criminal charges",
71
+ "tax evasion", "contract disputes", "intellectual property theft",
72
+ "constitutional rights violations", "corporate fraud", "inheritance disputes",
73
+ "specific sections of the cpc", "specific sections of the crpc",
74
+ "specific sections of the ipc"
75
+ ]
76
+
77
+ def initialize_translation_model(self):
78
+ """Initialize translation model only when needed"""
79
+ if self.translation_model is None:
80
+ try:
81
+ self.translation_model_name = "Helsinki-NLP/opus-mt-en-hi"
82
+ self.translation_model = MarianMTModel.from_pretrained(self.translation_model_name)
83
+ self.translation_tokenizer = MarianTokenizer.from_pretrained(self.translation_model_name)
84
+ except Exception as e:
85
+ print(f"Error initializing translation model: {e}")
86
+ return False
87
+ return True
88
+
89
+ def get_random_headers(self):
90
+ """Generate random browser headers to avoid detection"""
91
+ ua = UserAgent()
92
+ browser_list = ['chrome', 'firefox', 'safari', 'edge']
93
+ browser = random.choice(browser_list)
94
+
95
+ headers = {
96
+ 'User-Agent': ua[browser],
97
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
98
+ 'Accept-Language': 'en-US,en;q=0.5',
99
+ 'Accept-Encoding': 'gzip, deflate, br',
100
+ 'Connection': 'keep-alive',
101
+ 'DNT': '1'
102
+ }
103
+ return headers
104
+
105
+ def calculate_relevance_score(self, query, text):
106
+ """Calculate relevance score between query and text"""
107
+ if not self.sentence_model:
108
+ return 0.0
109
+
110
+ try:
111
+ query_embedding = self.sentence_model.encode([query])
112
+ text_embedding = self.sentence_model.encode([text])
113
+
114
+ similarity = float(torch.nn.functional.cosine_similarity(
115
+ torch.tensor(query_embedding),
116
+ torch.tensor(text_embedding)
117
+ ))
118
+ return max(0.0, min(1.0, similarity)) # Ensure score is between 0 and 1
119
+
120
+ except Exception as e:
121
+ print(f"Error calculating relevance score: {e}")
122
+ return 0.0
123
+
124
+ def clean_text(self, text):
125
+ """Clean and format text content"""
126
+ if not text:
127
+ return ""
128
+
129
+ # Remove extra whitespace
130
+ text = re.sub(r'\s+', ' ', text.strip())
131
+ # Remove special characters
132
+ text = re.sub(r'[^\w\s\.,;:?!-]', '', text)
133
+ return text
134
+
135
+ def summarize_text(self, text):
136
+ """Summarize text using the Pegasus model."""
137
+ try:
138
+ inputs = self.summarization_tokenizer(
139
+ self.clean_text(text),
140
+ return_tensors="pt",
141
+ truncation=True,
142
+ max_length=1024
143
+ )
144
+ summary_ids = self.summarization_model.generate(
145
+ inputs["input_ids"],
146
+ max_length=150,
147
+ min_length=50,
148
+ length_penalty=2.0,
149
+ num_beams=4,
150
+ early_stopping=True,
151
+ )
152
+ summary = self.summarization_tokenizer.decode(
153
+ summary_ids[0],
154
+ skip_special_tokens=True
155
+ )
156
+ return summary
157
+ except Exception as e:
158
+ print(f"Error during summarization: {e}")
159
+ return text # Return original text if summarization fails
160
+
161
+ def draft_text(self, input_text):
162
+ """Generate draft text based on input."""
163
+ if not self.drafting_model:
164
+ return "Drafting model not initialized."
165
+ try:
166
+ inputs = self.drafting_tokenizer(
167
+ self.clean_text(input_text),
168
+ return_tensors="pt",
169
+ truncation=True,
170
+ max_length=512
171
+ )
172
+
173
+ output = self.drafting_model.generate(
174
+ **inputs,
175
+ max_length=200,
176
+ do_sample=True,
177
+ top_k=50,
178
+ top_p=0.95,
179
+ num_return_sequences=1
180
+ )
181
+
182
+ draft = self.drafting_tokenizer.decode(
183
+ output[0],
184
+ skip_special_tokens=True
185
+ )
186
+ return draft
187
+ except Exception as e:
188
+ print(f"Error during drafting: {e}")
189
+ return f"Error during drafting : {str(e)}"
190
+
191
+ def generate_structured_response(self, query):
192
+ """Generate a structured response for sensitive queries."""
193
+
194
+ # Placeholder: List of relevant sections of the CPC for a property dispute
195
+ relevant_cpc_sections = {
196
+ "Section 26": "This section deals with the jurisdiction of courts in property suits. It's important to file your suit in the court that has jurisdiction over the property in question. This often depends on the location and value of the property.",
197
+ "Order VII, Rule 1": "This rule outlines the requirements for the plaint (the initial document filed to start the lawsuit). It specifies the information that must be included, such as the names of the parties involved, a clear statement of the cause of action (the legal basis for your claim), and the relief sought (what you want the court to order). Accuracy and completeness here are vital.",
198
+ "Order VI, Rule 17": "This rule deals with the amendment of pleadings. During the course of the lawsuit, you might need to amend your plaint or other documents. This rule outlines the process for doing so.",
199
+ "Order 26, Rule 1": "This rule deals with the appointment of a commissioner to inspect and report on the property in dispute. This can be particularly helpful in cases where the physical condition of the property is central to the dispute.",
200
+ "Order 34": "This order specifically addresses suits relating to mortgages. If your property dispute involves a mortgage, the provisions of Order 34 will be highly relevant. This includes procedures for sale or foreclosure of the mortgaged property.",
201
+ "Section 9":"This section deals with the res judicata principle, meaning that a matter already decided by a court cannot be brought before a court again. Understanding this principle is crucial to avoid unnecessary litigation."
202
+ }
203
+
204
+ response = "Hi there! Filing a civil suit for property disputes can seem complicated, but let's break down the relevant sections of the Civil Procedure Code (CPC), 1908. There isn't one single section, but rather several that come into play depending on the specifics of your dispute.\n\n"
205
+
206
+ for section, explanation in relevant_cpc_sections.items():
207
+ response += f"{section}: {explanation}\n\n"
208
+
209
+ response += """
210
+ Specific examples from your provided text:
211
+
212
+ The excerpts you provided from the CPC seem to focus on the procedures for suits relating to mortgages (Order 34). Sections dealing with preliminary decrees, applications of proceeds from sales, and the process of obtaining possession are all relevant within the context of mortgage disputes. However, these are just parts of a larger picture.
213
+
214
+ Important Note: This information is for general understanding only. The specific sections applicable to your case will depend heavily on the unique facts and circumstances of your property dispute. It's strongly recommended that you seek legal counsel from a qualified lawyer to ensure you understand your rights and obligations and to properly navigate the legal process. They can advise you on the most relevant sections of the CPC and help you prepare your case effectively.
215
+ """
216
+ return response
217
+
218
+ def is_query_risky(self, query):
219
+ """Check if a query is potentially risky."""
220
+ cleaned_query= self.clean_text(query).lower()
221
+ for risk in self.risky_queries:
222
+ if risk in cleaned_query:
223
+ return True
224
+ return False
225
+
226
+ def format_legal_case(self, case_num, case_data, target_language='english'):
227
+ """Format legal case data with improved layout"""
228
+ try:
229
+ title = self.translate_text(self.clean_text(case_data['title']), target_language)
230
+ summary_text = self.clean_text(case_data['summary']) # Get the summary text
231
+ summarized_text = self.summarize_text(summary_text)
232
+ summary = self.translate_text(summarized_text, target_language)
233
+ source = case_data.get('source', 'Unknown Source')
234
+ relevance = round(case_data.get('relevance_score', 0) * 100, 2)
235
+
236
+ # AI Drafting part
237
+ draft_input = f"Based on the title '{title}' and the summary '{summary}', draft a short legal clause or statement."
238
+ drafted_text = self.draft_text(draft_input)
239
+ translated_draft= self.translate_text(drafted_text,target_language)
240
+
241
+ output = f"""
242
+ {'═' * 80}
243
+ πŸ“‘ LEGAL DOCUMENT {case_num}
244
+ {'═' * 80}
245
+
246
+ πŸ“Œ TITLE:
247
+ {title}
248
+
249
+ πŸ“š SOURCE: {source}
250
+ 🎯 RELEVANCE: {relevance}%
251
+
252
+ πŸ“– SUMMARY:
253
+ {summary}
254
+
255
+ ✍️ AI DRAFTING SUGGESTION:
256
+ {translated_draft}
257
+
258
+ πŸ”— DOCUMENT LINK:
259
+ {case_data['url']}
260
+
261
+ {'─' * 80}
262
+ """
263
+ return output
264
+ except Exception as e:
265
+ print(f"Error formatting legal case: {e}")
266
+ return ""
267
+
268
+ def translate_text(self, text, target_language):
269
+ """Translate text to target language"""
270
+ if target_language.lower() == "english":
271
+ return text
272
+
273
+ if not self.initialize_translation_model():
274
+ return text
275
+
276
+ try:
277
+ inputs = self.translation_tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
278
+ translated = self.translation_model.generate(**inputs)
279
+ return self.translation_tokenizer.decode(translated[0], skip_special_tokens=True)
280
+ except Exception as e:
281
+ print(f"Error during translation: {e}")
282
+ return text
283
+
284
+ def fetch_from_indiacode(self, query, doc_type="all", max_results=5):
285
+ """Fetch results from India Code portal"""
286
+ for attempt in range(self.max_retries):
287
+ try:
288
+ # Using a more reliable search endpoint
289
+ base_url = "https://www.indiacode.nic.in/search"
290
+
291
+ params = {
292
+ 'q': query,
293
+ 'type': self.doc_types.get(doc_type, ""),
294
+ 'page': 1,
295
+ 'size': max_results * 2
296
+ }
297
+
298
+ response = self.session.get(
299
+ base_url,
300
+ params=params,
301
+ headers=self.get_random_headers(),
302
+ timeout=15
303
+ )
304
+
305
+ if response.status_code == 200:
306
+ soup = BeautifulSoup(response.text, 'html.parser')
307
+ results = []
308
+
309
+ items = (
310
+ soup.select('div.artifact-description') or
311
+ soup.select('.search-result-item') or
312
+ soup.select('.result-item')
313
+ )
314
+
315
+ if not items:
316
+ print(f"No results found with current selectors. Attempt {attempt + 1}/{self.max_retries}")
317
+ continue
318
+
319
+ for item in items:
320
+ try:
321
+ title_elem = (
322
+ item.select_one('h4.artifact-title a') or
323
+ item.select_one('.act-title') or
324
+ item.select_one('h3 a')
325
+ )
326
+
327
+ title = title_elem.get_text(strip=True) if title_elem else "Untitled"
328
+ url = title_elem.get('href', '') if title_elem else ""
329
+
330
+ summary_elem = (
331
+ item.select_one('div.artifact-info') or
332
+ item.select_one('.act-description') or
333
+ item.select_one('.summary')
334
+ )
335
+ summary = summary_elem.get_text(strip=True) if summary_elem else ""
336
+
337
+ if not summary:
338
+ summary = ' '.join(text for text in item.stripped_strings
339
+ if text != title and len(text) > 30)
340
+
341
+ if url and not url.startswith('http'):
342
+ url = f"https://www.indiacode.nic.in{url}"
343
+
344
+ relevance_score = self.calculate_relevance_score(
345
+ query,
346
+ f"{title} {summary}"
347
+ )
348
+
349
+ results.append({
350
+ 'title': title,
351
+ 'court': 'India Code',
352
+ 'summary': summary[:500],
353
+ 'url': url,
354
+ 'type': 'legal',
355
+ 'source': 'India Code Portal',
356
+ 'relevance_score': relevance_score
357
+ })
358
+
359
+ except Exception as e:
360
+ print(f"Error processing result: {e}")
361
+ continue
362
+
363
+ if results:
364
+ results.sort(key=lambda x: x['relevance_score'], reverse=True)
365
+ return results[:max_results]
366
+
367
+ elif response.status_code == 429:
368
+ wait_time = self.retry_delay * (attempt + 1)
369
+ time.sleep(wait_time)
370
+ continue
371
+
372
+ except Exception as e:
373
+ print(f"Error on attempt {attempt + 1}: {e}")
374
+ if attempt < self.max_retries - 1:
375
+ time.sleep(self.retry_delay)
376
+ continue
377
+
378
+ return []
379
+
380
+ def fetch_from_liiofindia(self, query, doc_type="all", max_results=5):
381
+ """Fetch results from LII of India"""
382
+ try:
383
+ # Updated to use the main search endpoint
384
+ base_url = "https://www.liiofindia.org/search/"
385
+
386
+ params = {
387
+ 'q': query,
388
+ 'page': 1,
389
+ 'per_page': max_results * 2,
390
+ 'sort': 'relevance'
391
+ }
392
+
393
+ if doc_type != "all":
394
+ params['type'] = doc_type
395
+
396
+ response = self.session.get(
397
+ base_url,
398
+ params=params,
399
+ headers={
400
+ **self.get_random_headers(),
401
+ 'Accept': 'application/json'
402
+ },
403
+ timeout=15
404
+ )
405
+
406
+ if response.status_code == 200:
407
+ try:
408
+ data = response.json()
409
+ results = []
410
+
411
+ for item in data.get('results', []):
412
+ title = item.get('title', 'Untitled')
413
+ summary = item.get('snippet', '')
414
+
415
+ relevance_score = self.calculate_relevance_score(
416
+ query,
417
+ f"{title} {summary}"
418
+ )
419
+
420
+ results.append({
421
+ 'title': title,
422
+ 'court': item.get('court', 'LII India'),
423
+ 'summary': summary[:500],
424
+ 'url': item.get('url', ''),
425
+ 'type': 'legal',
426
+ 'source': 'LII India',
427
+ 'relevance_score': relevance_score
428
+ })
429
+
430
+ results.sort(key=lambda x: x['relevance_score'], reverse=True)
431
+ return results[:max_results]
432
+
433
+ except ValueError as e:
434
+ print(f"Error parsing JSON from LII India: {e}")
435
+ return []
436
+
437
+ return []
438
+
439
+ except Exception as e:
440
+ print(f"Error fetching from LII India: {e}")
441
+ return []
442
+
443
+ def fetch_alternative_source(self, query, max_results=5):
444
+ """Fetch results from alternative sources"""
445
+ try:
446
+ # Try multiple alternative sources
447
+ sources = [
448
+ "https://indiankanoon.org/search/",
449
+ "https://main.sci.gov.in/judgments",
450
+ "https://doj.gov.in/acts-and-rules/"
451
+ ]
452
+
453
+ all_results = []
454
+ for base_url in sources: # Added colon here
455
+
456
+ params = {
457
+ 'formInput': query,
458
+ 'pageSize': max_results
459
+ }
460
+
461
+ response = self.session.get(
462
+ base_url,
463
+ params=params,
464
+ headers=self.get_random_headers(),
465
+ timeout=15
466
+ )
467
+
468
+ if response.status_code == 200:
469
+ soup = BeautifulSoup(response.text, 'html.parser')
470
+ results = []
471
+
472
+ for result in soup.select('.result_item')[:max_results]:
473
+ try:
474
+ title_elem = result.select_one('.title a')
475
+ title = title_elem.get_text(strip=True) if title_elem else "Untitled"
476
+ url = title_elem.get('href', '') if title_elem else ""
477
+
478
+ snippet_elem = result.select_one('.snippet')
479
+ summary = snippet_elem.get_text(strip=True) if snippet_elem else ""
480
+
481
+ relevance_score = self.calculate_relevance_score(
482
+ query,
483
+ f"{title} {summary}"
484
+ )
485
+
486
+ results.append({
487
+ 'title': title,
488
+ 'court': 'Alternative Source',
489
+ 'summary': summary[:500],
490
+ 'url': url if url.startswith('http') else f"https://indiankanoon.org{url}",
491
+ 'type': 'legal',
492
+ 'source': 'Indian Kanoon',
493
+ 'relevance_score': relevance_score
494
+ })
495
+
496
+ except Exception as e:
497
+ print(f"Error processing alternative result: {e}")
498
+ continue
499
+
500
+ return results
501
+
502
+ except Exception as e:
503
+ print(f"Error in alternative source: {e}")
504
+
505
+ return []
506
+
507
+ def fetch_from_multiple_sources(self, query, doc_type="all", max_results=5):
508
+ """Fetch and combine results from multiple sources"""
509
+ all_results = []
510
+
511
+ with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
512
+ future_to_source = {
513
+ executor.submit(self.fetch_from_indiacode, query, doc_type, max_results): "India Code",
514
+ executor.submit(self.fetch_from_liiofindia, query, doc_type, max_results): "LII India",
515
+ executor.submit(self.fetch_alternative_source, query, max_results): "Alternative"
516
+ }
517
+
518
+ for future in concurrent.futures.as_completed(future_to_source):
519
+ source = future_to_source[future]
520
+ try:
521
+ results = future.result()
522
+ if results:
523
+ all_results.extend(results)
524
+ except Exception as e:
525
+ print(f"Error fetching from {source}: {e}")
526
+
527
+ # Sort by relevance score and return top results
528
+ all_results.sort(key=lambda x: x['relevance_score'], reverse=True)
529
+ return all_results[:max_results]
530
+
531
+ def process_research(self, input_query, research_type="legal", doc_type="all", target_language='english'):
532
+ """Process research query and generate formatted output"""
533
+ try:
534
+ # Validate input
535
+ if not input_query.strip():
536
+ return "Error: Please enter a valid research query."
537
+
538
+ if self.is_query_risky(input_query):
539
+ return self.generate_structured_response(input_query)
540
+
541
+ # Add default sample data for testing and development
542
+ sample_data = [
543
+ {
544
+ 'title': 'Right to Privacy Judgment',
545
+ 'court': 'Supreme Court',
546
+ 'summary': 'The right to privacy is protected as an intrinsic part of the right to life and personal liberty under Article 21 and as a part of the freedoms guaranteed by Part III of the Constitution.',
547
+ 'url': 'https://main.sci.gov.in/supremecourt/2012/35071/35071_2012_Judgement_24-Aug-2017.pdf',
548
+ 'type': 'legal',
549
+ 'source': 'Supreme Court of India',
550
+ 'relevance_score': 0.95
551
+ },
552
+ {
553
+ 'title': 'Information Technology Act, 2000',
554
+ 'court': 'India Code',
555
+ 'summary': 'An Act to provide legal recognition for transactions carried out by means of electronic data interchange and other means of electronic communication.',
556
+ 'url': 'https://www.indiacode.nic.in/handle/123456789/1999/simple-search',
557
+ 'type': 'legal',
558
+ 'source': 'India Code Portal',
559
+ 'relevance_score': 0.85
560
+ }
561
+ ]
562
+
563
+ # Fetch results
564
+ cases = self.fetch_from_multiple_sources(input_query, doc_type)
565
+
566
+ # If no results found from APIs, use sample data for development
567
+ if not cases:
568
+ print("No results from APIs, using sample data")
569
+ cases = sample_data
570
+
571
+ # Generate header
572
+ header = f"""
573
+ {'β•”' + '═' * 78 + 'β•—'}
574
+ β•‘ {'LEGAL DOCUMENT ANALYSIS REPORT'.center(76)} β•‘
575
+ {'β• ' + '═' * 78 + 'β•£'}
576
+ β•‘
577
+ β•‘ 🎯 RESEARCH TOPIC: {self.translate_text(input_query, target_language)}
578
+ β•‘ πŸ“… GENERATED: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
579
+ β•‘ πŸ“š DOCUMENTS FOUND: {len(cases)}
580
+ β•‘ πŸ” SOURCES SEARCHED: India Code Portal, LII India, Indian Kanoon
581
+ β•‘
582
+ {'β•š' + '═' * 78 + '╝'}
583
+ """
584
+
585
+ # Generate body
586
+ output_text = self.translate_text(header, target_language)
587
+ for i, case in enumerate(cases, 1):
588
+ output_text += self.format_legal_case(i, case, target_language)
589
+
590
+ # Generate footer
591
+ footer = f"""
592
+ {'═' * 80}
593
+ πŸ“Š RESEARCH INSIGHTS
594
+ {'═' * 80}
595
+
596
+ β€’ Results are sorted by relevance to your query
597
+ β€’ All information should be verified from original sources
598
+ β€’ Use provided links to access complete documents
599
+
600
+ {'─' * 80}
601
+ """
602
+ output_text += self.translate_text(footer, target_language)
603
+ return output_text
604
+
605
+ except Exception as e:
606
+ return f"An error occurred during research processing: {str(e)}"
607
+
608
+ def clear_gpu_memory(self):
609
+ """Clear GPU memory after processing"""
610
+ try:
611
+ gc.collect()
612
+ if torch.cuda.is_available():
613
+ torch.cuda.empty_cache()
614
+ except Exception as e:
615
+ print(f"Error clearing GPU memory: {e}")
616
+
617
+ def create_gradio_interface():
618
+ """Create Gradio interface with improved styling and error handling"""
619
+ generator = LegalResearchGenerator()
620
+
621
+ def process_input(input_text, research_type, doc_type, target_language, output_format):
622
+ if not input_text.strip():
623
+ return "Please enter a research topic to analyze."
624
+
625
+ try:
626
+ if output_format == "Text":
627
+ result = generator.process_research(
628
+ input_text,
629
+ research_type,
630
+ doc_type,
631
+ target_language
632
+ )
633
+ generator.clear_gpu_memory()
634
+ return result
635
+ else:
636
+ return "CSV output format is not implemented yet."
637
+ except Exception as e:
638
+ generator.clear_gpu_memory()
639
+ return f"An error occurred: {str(e)}"
640
+
641
+ css = """
642
+ .gradio-container {
643
+ font-family: 'Arial', sans-serif;
644
+ }
645
+ .output-text {
646
+ font-family: 'Courier New', monospace;
647
+ white-space: pre-wrap;
648
+ }
649
+ """
650
+
651
+ iface = gr.Interface(
652
+ fn=process_input,
653
+ inputs=[
654
+ gr.Textbox(
655
+ label="Enter Research Topic",
656
+ placeholder="e.g., 'privacy rights' or 'environmental protection'",
657
+ lines=3
658
+ ),
659
+ gr.Radio(
660
+ choices=["legal"],
661
+ label="Research Type",
662
+ value="legal"
663
+ ),
664
+ gr.Dropdown(
665
+ choices=list(generator.doc_types.keys()),
666
+ label="Document Type",
667
+ value="all"
668
+ ),
669
+ gr.Dropdown(
670
+ choices=["english", "hindi", "tamil", "bengali", "telugu"],
671
+ label="Output Language",
672
+ value="english"
673
+ ),
674
+ gr.Radio(
675
+ choices=["Text", "CSV"],
676
+ label="Output Format",
677
+ value="Text"
678
+ )
679
+ ],
680
+ outputs=gr.Textbox(
681
+ label="Research Analysis Report",
682
+ lines=30,
683
+ elem_classes=["output-text"]
684
+ ),
685
+ title="πŸ”¬ Legal Research Analysis Tool",
686
+ description="""
687
+ Advanced legal research tool for Indian legal document analysis.
688
+ β€’ Multi-source search across legal databases
689
+ β€’ Smart filtering and relevance ranking
690
+ β€’ Multi-language support
691
+ β€’ Comprehensive research reports
692
+ β€’ AI powered drafting suggestions
693
+ """,
694
+ examples=[
695
+ ["right to privacy", "legal", "central_acts", "english", "Text"],
696
+ ["environmental protection", "legal", "regulations", "hindi", "Text"],
697
+ ["digital rights", "legal", "constitutional_orders", "english", "Text"]
698
+ ],
699
+ css=css
700
+ )
701
+
702
+ return iface
703
+
704
+ if __name__ == "__main__":
705
+ iface = create_gradio_interface()
706
+ iface.launch(share=True)