forked from jayash1973/aAzel-LexAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app2.py
2297 lines (1955 loc) · 111 KB
/
app2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import plotly.express as px
import requests
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from requests.exceptions import RequestException, ConnectionError, Timeout
from ai71 import AI71
import PyPDF2
import io
import random
import docx
import os
from docx import Document
from docx.shared import Inches
from datetime import datetime
import re
import logging
import base64
from typing import List, Dict, Any
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup, NavigableString, Tag
from io import StringIO
import wikipedia
from typing import List, Optional
from httpx_sse import SSEError
from difflib import SequenceMatcher
from datetime import datetime
import spacy
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import networkx as nx
nlp = spacy.load("en_core_web_sm")
# Error handling for optional dependencies
try:
from streamlit_lottie import st_lottie
except ImportError:
st.error("Missing dependency: streamlit_lottie. Please install it using 'pip install streamlit-lottie'")
st.stop()
AI71_API_KEY = "AI71 Falcon API key"
# Initialize AI71 client
try:
ai71 = AI71(AI71_API_KEY)
except Exception as e:
st.error(f"Failed to initialize AI71 client: {str(e)}")
st.stop()
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "uploaded_documents" not in st.session_state:
st.session_state.uploaded_documents = []
if "case_precedents" not in st.session_state:
st.session_state.case_precedents = []
def analyze_uploaded_document(file):
content = ""
if file.type == "application/pdf":
pdf_reader = PyPDF2.PdfReader(file)
for page in pdf_reader.pages:
content += page.extract_text()
elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
doc = docx.Document(file)
for para in doc.paragraphs:
content += para.text + "\n"
else:
content = file.getvalue().decode("utf-8")
return content
def get_document_based_response(prompt, document_content):
messages = [
{"role": "system", "content": "You are a helpful legal assistant LexAI which has all the legal information in the world and is the the best assitand for lawyers, lawfirms and a common citizen. Answer questions based on the provided document content."},
{"role": "user", "content": f"Document content: {document_content}\n\nQuestion: {prompt}"}
]
try:
completion = ai71.chat.completions.create(
model="tiiuae/falcon-180b-chat",
messages=messages,
stream=False,
)
return completion.choices[0].message.content
except Exception as e:
return f"An error occurred while processing your request: {str(e)}"
def get_ai_response(prompt: str) -> str:
"""Gets the AI response based on the given prompt."""
messages = [
{"role": "system", "content": "You are a helpful legal assistant LexAI which has all the legal information in the world and is the the best assitand for lawyers, lawfirms and a common citizen, answer the question based on the US law but if the question lies out of the context of us law then answer it too saying i am LexAI and advanced legal assistant but this is what i know about the topic you are asking"},
{"role": "user", "content": prompt}
]
try:
# First, try streaming
response = ""
for chunk in ai71.chat.completions.create(
model="tiiuae/falcon-180b-chat",
messages=messages,
stream=True,
):
if chunk.choices[0].delta.content:
response += chunk.choices[0].delta.content
return response
except Exception as e:
print(f"Streaming failed, falling back to non-streaming request. Error: {e}")
try:
# makes it fall back to non-streaming request
completion = ai71.chat.completions.create(
model="tiiuae/falcon-180b-chat",
messages=messages,
stream=False,
)
return completion.choices[0].message.content
except Exception as e:
print(f"An error occurred while getting AI response: {e}")
return f"I apologize, but I encountered an error while processing your request. Error: {str(e)}"
def display_chat_history():
for message in st.session_state.chat_history:
if isinstance(message, tuple):
if len(message) == 2:
user_msg, bot_msg = message
st.info(f"**You:** {user_msg}")
st.success(f"**Bot:** {bot_msg}")
else:
st.error(f"Unexpected message format: {message}")
elif isinstance(message, dict):
if message.get('type') == 'wikipedia':
st.success(f"**Bot:** Wikipedia Summary:\n{message.get('summary', 'No summary available.')}\n" +
(f"[Read more on Wikipedia]({message.get('url')})" if message.get('url') else ""))
elif message.get('type') == 'web_search':
web_results_msg = "Web Search Results:\n"
for result in message.get('results', []):
web_results_msg += f"[{result.get('title', 'No title')}]({result.get('link', '#')})\n{result.get('snippet', 'No snippet available.')}\n\n"
st.success(f"**Bot:** {web_results_msg}")
else:
st.error(f"Unknown message type: {message}")
else:
st.error(f"Unexpected message format: {message}")
def analyze_document(file) -> str:
"""Analyzes uploaded legal documents."""
content = ""
if file.type == "application/pdf":
pdf_reader = PyPDF2.PdfReader(file)
for page in pdf_reader.pages:
content += page.extract_text()
elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
doc = docx.Document(file)
for para in doc.paragraphs:
content += para.text + "\n"
else:
content = file.getvalue().decode("utf-8")
return content[:5000] # Limit content to 5000 characters for analysis
def search_web(query: str, num_results: int = 3) -> List[Dict[str, str]]:
try:
service = build("customsearch", "v1", developerKey="AIzaSyD-1OMuZ0CxGAek0PaXrzHOmcDWFvZQtm8")
# Add legal-specific terms to the query
legal_query = f"legal {query} law case precedent"
# Execute the search request
res = service.cse().list(q=legal_query, cx="877170db56f5c4629", num=num_results * 2).execute()
results = []
if "items" in res:
for item in res["items"]:
# Check if the result is relevant
if any(keyword in item["title"].lower() or keyword in item["snippet"].lower()
for keyword in ["law", "legal", "court", "case", "attorney", "lawyer"]):
result = {
"title": item["title"],
"link": item["link"],
"snippet": item["snippet"]
}
results.append(result)
if len(results) == num_results:
break
return results
except Exception as e:
print(f"Error performing web search: {e}")
return []
def perform_web_search(query: str) -> List[Dict[str, Any]]:
"""
Performs a web search to find recent legal cost estimates.
"""
url = f"https://www.google.com/search?q={query}"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
results = []
for g in soup.find_all('div', class_='g'):
anchors = g.find_all('a')
if anchors:
link = anchors[0]['href']
title = g.find('h3', class_='r')
if title:
title = title.text
else:
title = "No title"
snippet = g.find('div', class_='s')
if snippet:
snippet = snippet.text
else:
snippet = "No snippet"
# Extract cost estimates from the snippet
cost_estimates = extract_cost_estimates(snippet)
if cost_estimates:
results.append({
"title": title,
"link": link,
"cost_estimates": cost_estimates
})
return results[:3] # Return top 3 results with their cost estimates
def comprehensive_document_analysis(content: str) -> Dict[str, Any]:
"""Performs a comprehensive analysis of the document, including web and Wikipedia searches."""
try:
analysis_prompt = f"Analyze the following legal document and provide a summary, potential issues, and key clauses:\n\n{content}"
document_analysis = get_ai_response(analysis_prompt)
# Extract main topics or keywords from the document
topic_extraction_prompt = f"Extract the main topic or keyword from the following document summary:\n\n{document_analysis}"
topics = get_ai_response(topic_extraction_prompt)
web_results = search_web(topics)
wiki_results = search_wikipedia(topics)
return {
"document_analysis": document_analysis,
"related_articles": web_results or [], # Ensure that this this is always a list
"wikipedia_summary": wiki_results
}
except Exception as e:
print(f"Error in comprehensive document analysis: {e}")
return {
"document_analysis": "Error occurred during analysis.",
"related_articles": [],
"wikipedia_summary": {"summary": "Error occurred", "url": "", "title": ""}
}
def search_wikipedia(query: str, sentences: int = 2) -> Dict[str, str]:
try:
# Ensures that the query is a string before slicing
truncated_query = str(query)[:300]
# Search Wikipedia
search_results = wikipedia.search(truncated_query, results=5)
if not search_results:
return {"summary": "No Wikipedia article found.", "url": "", "title": ""}
# Find the most relevant page title
best_match = max(search_results, key=lambda x: SequenceMatcher(None, truncated_query.lower(), x.lower()).ratio())
try:
page = wikipedia.page(best_match, auto_suggest=False)
summary = wikipedia.summary(page.title, sentences=sentences, auto_suggest=False)
return {"summary": summary, "url": page.url, "title": page.title}
except wikipedia.exceptions.DisambiguationError as e:
try:
page = wikipedia.page(e.options[0], auto_suggest=False)
summary = wikipedia.summary(page.title, sentences=sentences, auto_suggest=False)
return {"summary": summary, "url": page.url, "title": page.title}
except:
pass
except wikipedia.exceptions.PageError:
pass
# If no summary found after trying the best match and disambiguation
return {"summary": "No relevant Wikipedia article found.", "url": "", "title": ""}
except Exception as e:
print(f"Error searching Wikipedia: {e}")
return {"summary": f"Error searching Wikipedia: {str(e)}", "url": "", "title": ""}
def extract_important_info(text: str) -> str:
"""Extracts and highlights important information from the given text."""
prompt = f"Extract and highlight the most important legal information from the following text. Use markdown to emphasize key points:\n\n{text}"
return get_ai_response(prompt)
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
]
# Rate limiting parameters
MIN_DELAY = 3 # Minimum delay between requests in seconds
MAX_DELAY = 10 # Maximum delay between requests in seconds
last_request_time = 0
def get_random_user_agent():
return random.choice(user_agents)
def rate_limit():
global last_request_time
current_time = time.time()
time_since_last_request = current_time - last_request_time
if time_since_last_request < MIN_DELAY:
sleep_time = random.uniform(MIN_DELAY, MAX_DELAY)
time.sleep(sleep_time)
last_request_time = time.time()
def fetch_detailed_content(url):
rate_limit()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument(f"user-agent={get_random_user_agent()}")
try:
# Use webdriver_manager to handle driver installation
service = Service(ChromeDriverManager().install())
with webdriver.Chrome(service=service, options=chrome_options) as driver:
driver.get(url)
# Wait for the main content to load
WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
# Scroll to load any lazy-loaded content
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2) # Wait for any dynamic content to load
# Get the page source after JavaScript execution
page_source = driver.page_source
# Use BeautifulSoup for parsing
soup = BeautifulSoup(page_source, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Extract main content (customize based on the website structure)
main_content = soup.find('main') or soup.find('article') or soup.find('div', class_=re.compile('content|main'))
if not main_content:
main_content = soup.body
# Extract text content
text_content = main_content.get_text(separator='\n', strip=True)
# Clean and process the content
cleaned_content = clean_content(text_content)
return cleaned_content
except Exception as e:
print(f"Error fetching content: {e}")
return f"Unable to fetch detailed content. Error: {str(e)}", {}
def clean_content(text):
# Remove extra whitespace and newlines
text = re.sub(r'\s+', ' ', text).strip()
# Remove any remaining HTML tags
text = re.sub(r'<[^>]+>', '', text)
# Remove special characters and digits (customize as needed)
text = re.sub(r'[^a-zA-Z\s.,;:?!-]', '', text)
# Split into sentences
sentences = re.split(r'(?<=[.!?])\s+', text)
# Remove short sentences (likely to be noise)
sentences = [s for s in sentences if len(s.split()) > 3]
# Join sentences back together
cleaned_text = ' '.join(sentences)
return cleaned_text
def extract_structured_data(soup):
structured_data = {}
# Extract title
title = soup.find('title')
if title:
structured_data['title'] = title.get_text(strip=True)
# Extract meta description
meta_desc = soup.find('meta', attrs={'name': 'description'})
if meta_desc:
structured_data['description'] = meta_desc.get('content', '')
# Extract headings
headings = []
for tag in ['h1', 'h2', 'h3']:
for heading in soup.find_all(tag):
headings.append({
'level': tag,
'text': heading.get_text(strip=True)
})
structured_data['headings'] = headings
# Extract links
links = []
for link in soup.find_all('a', href=True):
links.append({
'text': link.get_text(strip=True),
'href': link['href']
})
structured_data['links'] = links
# Extract images
images = []
for img in soup.find_all('img', src=True):
images.append({
'src': img['src'],
'alt': img.get('alt', '')
})
structured_data['images'] = images
return structured_data
def query_public_case_law(query: str) -> List[Dict[str, Any]]:
"""Query publicly available case law databases (Justia and CourtListener) to find related cases."""
cases = []
# Justia Search using Google
justia_url = f"https://www.google.com/search?q={query}+case+law+site:law.justia.com"
justia_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
try:
justia_response = requests.get(justia_url, headers=justia_headers)
justia_response.raise_for_status()
justia_soup = BeautifulSoup(justia_response.text, 'html.parser')
justia_results = justia_soup.find_all('div', class_='g')
for result in justia_results[:5]: # Limits it to top 5 results
title_elem = result.find('h3')
link_elem = result.find('a')
snippet_elem = result.find('div', class_='VwiC3b')
if title_elem and link_elem and snippet_elem:
title = title_elem.text
link = link_elem['href']
snippet = snippet_elem.text
# it extract case name and citation from the title
case_info = title.split(' - ')
if len(case_info) >= 2:
case_name = case_info[0]
citation = case_info[1]
else:
case_name = title
citation = "Citation not found"
cases.append({
"source": "Justia",
"case_name": case_name,
"citation": citation,
"summary": snippet,
"url": link
})
except requests.RequestException as e:
print(f"Error querying Justia: {e}")
# CourtListener Search
courtlistener_url = f"https://www.courtlistener.com/api/rest/v3/search/?q={query}&type=o&format=json"
courtlistener_data = {}
for attempt in range(3): # Retry up to 3 times
try:
courtlistener_response = requests.get(courtlistener_url)
courtlistener_response.raise_for_status()
courtlistener_data = courtlistener_response.json()
break
except (requests.RequestException, ValueError) as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt == 2:
print(f"Failed to retrieve or parse data from CourtListener: {e}")
time.sleep(2)
if 'results' in courtlistener_data:
for result in courtlistener_data['results'][:3]: # Limit to 3 results
case_url = f"https://www.courtlistener.com{result['absolute_url']}"
cases.append({
"source": "CourtListener",
"case_name": result['caseName'],
"date_filed": result['dateFiled'],
"docket_number": result.get('docketNumber', 'Not available'),
"court": result['court'],
"url": case_url
})
return cases
def comprehensive_document_analysis(content: str) -> Dict[str, Any]:
"""Performs a comprehensive analysis of the document, including web and Wikipedia searches."""
try:
analysis_prompt = f"Analyze the following legal document and provide a summary, potential issues, and key clauses:\n\n{content}"
document_analysis = get_ai_response(analysis_prompt)
topic_extraction_prompt = f"Extract the main topics or keywords from the following document summary relevant for web search and wikipedia search related to the document:\n\n{document_analysis}"
topics = get_ai_response(topic_extraction_prompt)
web_results = search_web(topics)
wiki_results = search_wikipedia(topics)
return {
"document_analysis": document_analysis,
"related_articles": web_results or [],
"wikipedia_summary": wiki_results
}
except Exception as e:
print(f"Error in comprehensive document analysis: {e}")
return {
"document_analysis": "Error occurred during analysis.",
"related_articles": [],
"wikipedia_summary": {"summary": "Error occurred", "url": "", "title": ""}
}
def format_public_cases(cases: List[Dict[str, Any]]) -> str:
"""Format public cases for the AI prompt."""
formatted = ""
for case in cases:
formatted += f"Source: {case['source']}\n"
formatted += f"Case Name: {case['case_name']}\n"
if 'citation' in case:
formatted += f"Citation: {case['citation']}\n"
if 'summary' in case:
formatted += f"Summary: {case['summary']}\n"
if 'date_filed' in case:
formatted += f"Date Filed: {case['date_filed']}\n"
if 'docket_number' in case:
formatted += f"Docket Number: {case['docket_number']}\n"
if 'court' in case:
formatted += f"Court: {case['court']}\n"
formatted += "\n"
return formatted
def format_web_results(results: List[Dict[str, str]]) -> str:
"""Format web search results for the AI prompt."""
formatted = ""
for result in results:
formatted += f"Title: {result['title']}\n"
formatted += f"Snippet: {result['snippet']}\n"
formatted += f"URL: {result['link']}\n\n"
return formatted
def find_case_precedents(case_details: str) -> Dict[str, Any]:
"""Finds relevant case precedents based on provided details."""
try:
# Query public case law databases
public_cases = query_public_case_law(case_details)
# Perform web search
web_results = search_web(f"legal precedent {case_details}", num_results=3)
# Perform Wikipedia search
wiki_result = search_wikipedia(f"legal case {case_details}")
# Compile all information
compilation_prompt = f"""
Analyze the following case details and identify key legal concepts and relevant precedents,
Analyze and the following case law information, focusing solely on factual elements and legal principles. Do not include any speculative or fictional content:
Case Details: {case_details}
Public Case Law Results:
{format_public_cases(public_cases)}
Web Search Results:
{format_web_results(web_results)}
Wikipedia Information:
{wiki_result['summary']}
Provide a well-structured summary highlighting the most relevant precedents and legal principles
Do not introduce any hypothetical scenarios.
And if the information from web, wikipedia and case details are not available then ask the user reframe their prompt and resubmit the prompt and also generate a case summary based on the cases that have happened before based on the data you are trained on and do not include and of the hypothical data or fiction data and also tell the user that this summary is generated based on the data falcon 180B is trained on
"""
summary = get_ai_response(compilation_prompt)
return {
"summary": summary,
"public_cases": public_cases,
"web_results": web_results,
"wikipedia": wiki_result
}
except Exception as e:
print(f"An error occurred in find_case_precedents: {e}")
return {
"summary": f"An error occurred while finding case precedents: {str(e)}",
"public_cases": [],
"web_results": [],
"wikipedia": {
'title': 'Error',
'summary': 'Unable to retrieve Wikipedia information',
'url': ''
}
}
def safe_find(element, selector, class_=None, attr=None):
"""Safely find and extract text or attribute from an element."""
found = element.find(selector, class_=class_) if class_ else element.find(selector)
if found:
return found.get(attr) if attr else found.text.strip()
return "Not available"
def search_web_duckduckgo(query: str, num_results: int = 3, max_retries: int = 3) -> List[Dict[str, str]]:
"""
Performs a web search using the Google Custom Search API.
Returns a list of dictionaries containing search result title, link, and snippet.
"""
api_key = "AIzaSyD-1OMuZ0CxGAek0PaXrzHOmcDWFvZQtm8"
cse_id = "877170db56f5c4629"
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
]
for attempt in range(max_retries):
try:
headers = {'User-Agent': random.choice(user_agents)}
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=query, cx=cse_id, num=num_results).execute()
results = []
if "items" in res:
for item in res["items"]:
result = {
"title": item["title"],
"link": item["link"],
"snippet": item.get("snippet", "")
}
results.append(result)
if len(results) == num_results:
break
return results
except HttpError as e:
print(f"HTTP error occurred: {e}. Attempt {attempt + 1} of {max_retries}")
except ConnectionError as e:
print(f"Connection error occurred: {e}. Attempt {attempt + 1} of {max_retries}")
except Timeout as e:
print(f"Timeout error occurred: {e}. Attempt {attempt + 1} of {max_retries}")
except RequestException as e:
print(f"An error occurred during the request: {e}. Attempt {attempt + 1} of {max_retries}")
except Exception as e:
print(f"An unexpected error occurred: {e}. Attempt {attempt + 1} of {max_retries}")
# Exponential backoff
time.sleep(2 ** attempt)
print("Max retries reached. No results found.")
return []
def estimate_legal_costs(case_type: str, complexity: str, state: str) -> Dict[str, Any]:
"""
Estimates legal costs based on case type, complexity, and location.
Performs web searches for more accurate estimates, lawyer recommendations, and similar cases.
"""
base_costs = {
"Simple": (150, 300),
"Moderate": (250, 500),
"Complex": (400, 1000)
}
case_type_multipliers = {
"Civil Litigation": 1.2,
"Criminal Law": 1.5,
"Family Law": 1.0,
"Business Law": 1.3,
"Intellectual Property": 1.4,
"Employment Law": 1.1,
"Immigration Law": 1.0,
"Real Estate Law": 1.2,
"Personal Injury": 1.3,
"Tax Law": 1.4,
}
estimated_hours = {
"Simple": (10, 30),
"Moderate": (30, 100),
"Complex": (100, 300)
}
min_rate, max_rate = base_costs[complexity]
multiplier = case_type_multipliers.get(case_type, 1.0)
min_rate *= multiplier
max_rate *= multiplier
min_hours, max_hours = estimated_hours[complexity]
min_total = min_rate * min_hours
max_total = max_rate * max_hours
cost_breakdown = {
"Hourly rate range": f"${min_rate:.2f} - ${max_rate:.2f}",
"Estimated hours": f"{min_hours} - {max_hours}",
"Total cost range": f"${min_total:.2f} - ${max_total:.2f}",
}
search_query = f"{case_type} legal costs {state}"
web_search_results = search_web_duckduckgo(search_query, num_results=3)
high_cost_areas = [
"Expert witnesses (especially in complex cases)",
"Extensive document review and e-discovery",
"Multiple depositions",
"Prolonged trial periods",
"Appeals process"
]
cost_saving_tips = [
"Consider alternative dispute resolution methods like mediation or arbitration",
"Be organized and provide all relevant documents upfront to reduce billable hours",
"Communicate efficiently with your lawyer, bundling questions when possible",
"Ask for detailed invoices and review them carefully",
"Discuss fee arrangements, such as flat fees or contingency fees, where applicable"
]
lawyer_tips = [
"Research and compare multiple lawyers or law firms",
"Ask for references and read client reviews",
"Discuss fee structures and payment plans upfront",
"Consider lawyers with specific expertise in your case type",
"Ensure clear communication and understanding of your case"
]
return {
"cost_breakdown": cost_breakdown,
"high_cost_areas": high_cost_areas,
"cost_saving_tips": cost_saving_tips,
"finding_best_lawyer_tips": lawyer_tips,
"web_search_results": web_search_results
}
def extract_cost_estimates(text: str) -> List[str]:
"""
Extracts cost estimates from the given text.
"""
patterns = [
r'\$\d{1,3}(?:,\d{3})*(?:\.\d{2})?', # Matches currency amounts like $1,000.00
r'\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|GBP|CAD|EUR)', # Matches amounts with currency codes
r'(?:USD|GBP|CAD|EUR)\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?' # Matches currency codes before amounts
]
estimates = []
for pattern in patterns:
matches = re.findall(pattern, text)
estimates.extend(matches)
return estimates
def legal_cost_estimator_ui():
st.title("Legal Cost Estimator")
case_types = [
"Personal Injury", "Medical Malpractice", "Criminal Law", "Family Law",
"Divorce", "Bankruptcy", "Business Law", "Employment Law",
"Estate Planning", "Immigration Law", "Intellectual Property",
"Real Estate Law", "Tax Law"
]
case_type = st.selectbox("Select case type", case_types)
complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"])
states = [
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut",
"Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire",
"New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia",
"Wisconsin", "Wyoming"
]
state = st.selectbox("Select state", states)
if st.button("Estimate Costs"):
with st.spinner("Estimating costs and retrieving data..."):
cost_estimate = estimate_legal_costs(case_type, complexity, state)
st.header("Estimated Legal Costs")
for key, value in cost_estimate["cost_breakdown"].items():
st.write(f"**{key}:** {value}")
st.header("Potential High-Cost Areas")
for area in cost_estimate["high_cost_areas"]:
st.write(f"- {area}")
st.header("Cost-Saving Tips")
for tip in cost_estimate["cost_saving_tips"]:
st.write(f"- {tip}")
st.header("Tips for Finding the Best Lawyer")
for tip in cost_estimate["finding_best_lawyer_tips"]:
st.write(f"- {tip}")
st.header("Web Search Results")
if cost_estimate["web_search_results"]:
for result in cost_estimate["web_search_results"]:
st.subheader(f"[{result['title']}]({result['link']})")
st.write(result["snippet"])
st.write("---")
else:
st.write("No web search results found for the selected criteria.")
def split_text(text, max_chunk_size=4000):
return [text[i:i+max_chunk_size] for i in range(0, len(text), max_chunk_size)]
def analyze_contract(contract_text: str) -> Dict[str, Any]:
"""Analyzes the contract text for clauses, benefits, and potential exploits."""
chunks = split_text(contract_text)
full_analysis = ""
for i, chunk in enumerate(chunks):
analysis_prompt = f"""
Analyze the following part of the contract ({i+1}/{len(chunks)}), identifying clauses that are favorable and unfavorable to each party involved.
Highlight potential areas of concern or clauses that could be exploited.
Provide specific examples within this part of the contract to support your analysis.
**Contract Text (Part {i+1}/{len(chunks)}):**
{chunk}
"""
try:
chunk_analysis = get_ai_response(analysis_prompt)
full_analysis += chunk_analysis + "\n\n"
except Exception as e:
return {"error": f"Error analyzing part {i+1} of the contract: {str(e)}"}
return {"analysis": full_analysis}
def contract_analysis_ui():
st.subheader("Contract Analyzer")
with st.expander("How to use"):
st.write('''upload the file and click on analyse contract it will generate analysis of that analysis.''')
st.warning("Do not upload too big files as it might end up consuming all the tokens and the response generation will take too much time")
uploaded_file = st.file_uploader(
"Upload a contract document (PDF, DOCX, or TXT)",
type=["pdf", "docx", "txt"],
)
if uploaded_file:
contract_text = analyze_uploaded_document(uploaded_file)
if st.button("Analyze Contract"):
with st.spinner("Analyzing contract..."):
analysis_results = analyze_contract(contract_text)
st.write("### Contract Analysis")
if "error" in analysis_results:
st.error(analysis_results["error"])
else:
st.write(analysis_results.get("analysis", "No analysis available."))
CASE_TYPES = [
"Civil Rights", "Contract", "Real Property", "Tort", "Labor", "Intellectual Property",
"Bankruptcy", "Immigration", "Tax", "Criminal", "Social Security", "Environmental"
]
DATA_SOURCES = {
"Civil Rights": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Contract": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Real Property": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Tort": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Labor": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Intellectual Property": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Bankruptcy": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Immigration": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Tax": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Criminal": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Social Security": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables",
"Environmental": "https://www.uscourts.gov/statistics-reports/caseload-statistics-data-tables"
}
def fetch_case_data(case_type: str) -> pd.DataFrame:
"""Fetches actual historical data for the given case type."""
# This data is based on U.S. District Courts—Civil Cases Commenced, by Nature of Suit
data = {
"Civil Rights": [56422, 57040, 54847, 53499, 54012, 52850, 51739, 41520, 35793, 38033, 47209, 44637],
"Contract": [31077, 29443, 28221, 28073, 28394, 29312, 28065, 26917, 28211, 30939, 36053, 35218],
"Real Property": [13716, 12760, 12482, 12340, 12410, 12537, 12211, 13173, 13088, 13068, 12527, 11991],
"Tort": [86690, 80331, 79235, 77630, 75007, 74708, 73785, 75275, 74240, 75309, 98437, 86129],
"Labor": [19229, 18586, 19690, 18550, 17190, 17356, 18511, 18284, 17583, 21208, 21118, 18743],
"Intellectual Property": [11971, 11307, 11920, 13215, 12304, 11576, 11195, 10526, 10577, 11349, 10636, 11475],
"Bankruptcy": [47806, 47951, 47134, 46194, 39091, 38784, 38125, 37751, 37153, 43498, 41876, 45119],
"Immigration": [6454, 6880, 9185, 8567, 9181, 8252, 7125, 7960, 8848, 9311, 8847, 7880],
"Tax": [1486, 1235, 1265, 1205, 1412, 1350, 1219, 1148, 1107, 1216, 1096, 1139],
"Criminal": [78864, 80897, 81374, 80069, 77357, 79787, 81553, 78127, 68856, 64565, 57287, 59453],
"Social Security": [18271, 19811, 19276, 17452, 18193, 17988, 18502, 18831, 19220, 21310, 20506, 19185],
"Environmental": [772, 1047, 1012, 1070, 1135, 1148, 993, 909, 1046, 1084, 894, 733]
}
df = pd.DataFrame({
'Year': range(2011, 2023),
'Number of Cases': data[case_type]
})
return df
def visualize_case_trends(case_type: str):
"""Visualizes case trends based on case type using actual historical data."""
df = fetch_case_data(case_type)
# Create a Plotly figure
fig = px.line(df, x='Year', y='Number of Cases', title=f"Trend of {case_type} Cases (2011-2022)")
fig.update_layout(
xaxis_title="Year",
yaxis_title="Number of Cases",
hovermode="x unified"
)
fig.update_traces(mode="lines+markers")
return fig, df
def case_trend_visualizer_ui():
st.subheader("Case Trend Visualizer")
st.warning("Please note that the data presented here is for U.S. federal courts. Data may vary slightly depending on the sources and reporting methods used.")
case_type = st.selectbox("Select case type to visualize", CASE_TYPES)
if 'current_case_type' not in st.session_state:
st.session_state.current_case_type = case_type
if 'current_data' not in st.session_state:
st.session_state.current_data = None
if st.button("Visualize Trend") or st.session_state.current_case_type != case_type:
st.session_state.current_case_type = case_type
with st.spinner("Fetching and visualizing data..."):
fig, df = visualize_case_trends(case_type)
st.session_state.current_data = df
# Display the Plotly chart
st.plotly_chart(fig, use_container_width=True)
# Display Statistics
st.subheader("Case Statistics")
total_cases = df['Number of Cases'].sum()
avg_cases = df['Number of Cases'].mean()
max_year = df.loc[df['Number of Cases'].idxmax(), 'Year']
min_year = df.loc[df['Number of Cases'].idxmin(), 'Year']
col1, col2, col3 = st.columns(3)
col1.metric("Total Cases (2011-2022)", f"{total_cases:,}")
col2.metric("Average Cases per Year", f"{avg_cases:,.0f}")
col3.metric("Peak Year", f"{max_year}")
# Trend Description
st.write("Trend Description:", get_trend_description(df))
if st.session_state.current_data is not None:
df = st.session_state.current_data
# Interactive Analysis Section
st.subheader("Interactive Analysis")
# Year-over-Year Change
df['YoY Change'] = df['Number of Cases'].pct_change() * 100
yoy_fig = px.bar(df, x='Year', y='YoY Change', title="Year-over-Year Change in Case Numbers")
st.plotly_chart(yoy_fig, use_container_width=True)
# Moving Average with slider
max_window = min(6, len(df)) # Ensure max window doesn't exceed data points
window = st.slider("Select moving average window:", 2, max_window, 2)
df['Moving Average'] = df['Number of Cases'].rolling(window=window).mean()
# Create a new figure for the moving average
ma_fig = px.line(df, x='Year', y=['Number of Cases', 'Moving Average'], title=f"{window}-Year Moving Average")
st.plotly_chart(ma_fig, use_container_width=True)
# Raw Data