File size: 57,644 Bytes
483029c 5104eb2 483029c 5104eb2 483029c 515b6b0 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 |
import streamlit as st
import pandas as pd
import plotly.express as px
import requests
from ai71 import AI71
import PyPDF2
import io
import random
import docx
from docx import Document
from docx.shared import Inches
from datetime import datetime
import re
import base64
from typing import List, Dict, Any
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
from io import StringIO
import wikipedia
from googleapiclient.discovery import build
from typing import List, Optional
from httpx_sse import SSEError
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import SentenceTransformerEmbeddings
from langchain_community.chat_models import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
from langchain.chains import ConversationalRetrievalChain
# 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()
# Constants
AI71_API_KEY = "api71-api-92fc2ef9-9f3c-47e5-a019-18e257b04af2"
# 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()
# Initialize chat history and other session state variables
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 = []
if "web_search_enabled" not in st.session_state:
st.session_state.web_search_enabled = False
if "document_chat_history" not in st.session_state:
st.session_state.document_chat_history = []
if "document_embeddings" not in st.session_state:
st.session_state.document_embeddings = None
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 with advanced capabilities."},
{"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:
# 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():
"""Displays the chat history with different formatting for different message types."""
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}")
elif message.get('type') == 'document':
st.success(f"**Bot (from document):** {message.get('content')}")
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 and returns the content."""
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]
def handle_document_upload(uploaded_file):
"""Processes uploaded documents and generates embeddings."""
try:
document_content = analyze_document(uploaded_file)
# Generate embeddings using SentenceTransformers
embeddings = SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2").embed_documents([document_content])
# Create a FAISS vector store
st.session_state.document_embeddings = FAISS.from_texts([document_content], embedding=SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2"))
st.success("Document processed and ready for chat!")
except Exception as e:
st.error(f"An error occurred while processing the document: {str(e)}")
def document_chatbot():
"""Implements the document chatbot feature."""
st.subheader("Document Chat")
uploaded_file = st.file_uploader("Upload a document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])
if uploaded_file:
handle_document_upload(uploaded_file)
if st.session_state.document_embeddings is not None:
user_input = st.text_input("Ask a question about your document:")
# Fixed: Added a unique key to the button
if st.button("Send", key="document_chat_send") and user_input:
with st.spinner("Thinking..."):
AI71_BASE_URL = "https://api.ai71.ai/v1/"
chat = ChatOpenAI(
model="tiiuae/falcon-180B-chat",
api_key=AI71_API_KEY,
base_url=AI71_BASE_URL,
streaming=True,
)
qa = ConversationalRetrievalChain.from_llm(
chat,
retriever=st.session_state.document_embeddings.as_retriever(),
return_source_documents=True
)
result = qa({"question": user_input, "chat_history": st.session_state.document_chat_history})
# Add user message to chat history
st.session_state.chat_history.append((user_input, None))
# Add document answer to chat history
st.session_state.chat_history.append({
'type': 'document',
'content': result['answer']
})
st.session_state.document_chat_history.append((user_input, result['answer']))
st.rerun()
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 (you may need to adjust these conditions)
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 cost estimates
def search_wikipedia(query: str, sentences: int = 2) -> Dict[str, str]:
try:
# Ensure 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": ""}
# Try to get a summary for each result until successful
for result in search_results:
try:
page = wikipedia.page(result)
summary = wikipedia.summary(result, sentences=sentences)
return {"summary": summary, "url": page.url, "title": page.title}
except wikipedia.exceptions.DisambiguationError as e:
continue
except wikipedia.exceptions.PageError:
continue
# If no summary found after trying all results
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 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 topics or keywords 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 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 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)
def fetch_detailed_content(url: str) -> str:
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Extract main content (this may need to be adjusted based on the structure of the target websites)
main_content = soup.find('main') or soup.find('article') or soup.find('div', class_='content')
if main_content:
# Extract text from paragraphs
paragraphs = main_content.find_all('p')
content = "\n\n".join([p.get_text() for p in paragraphs])
# Limit content to a reasonable length (e.g., first 1000 characters)
return content[:1000] + "..." if len(content) > 1000 else content
else:
return "Unable to extract detailed content from the webpage."
except Exception as e:
return f"Error fetching detailed content: {str(e)}"
def query_public_case_law(query: str) -> List[Dict[str, Any]]:
"""
Query publicly available case law databases and perform a web search to find related cases.
"""
# Perform a web search to find relevant case law
search_url = f"https://www.google.com/search?q={query}+case+law+site:law.justia.com"
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:
response = requests.get(search_url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
search_results = soup.find_all('div', class_='g')
cases = []
for result in search_results[:5]: # Limit to top 5 results
title_elem = result.find('h3', class_='r')
link_elem = result.find('a')
snippet_elem = result.find('div', class_='s')
if title_elem and link_elem and snippet_elem:
title = title_elem.text
link = link_elem['href']
snippet = snippet_elem.text
# 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({
"case_name": case_name,
"citation": citation,
"summary": snippet,
"url": link
})
return cases
except requests.RequestException as e:
print(f"Error querying case law: {e}")
return []
def find_case_precedents(case_details: str) -> Dict[str, Any]:
"""Finds relevant case precedents based on provided details."""
try:
# Initial AI analysis of the case details
analysis_prompt = f"Analyze the following case details and identify key legal concepts and relevant precedents:\n\n{case_details}"
initial_analysis = get_ai_response(analysis_prompt)
# Query public case law databases
public_cases = query_public_case_law(case_details)
# Perform web search (existing functionality)
web_results = search_web(f"legal precedent {case_details}", num_results=3)
# Perform Wikipedia search (existing functionality)
wiki_result = search_wikipedia(f"legal case {case_details}")
# Compile all information
compilation_prompt = f"""Compile a comprehensive summary of case precedents based on the following information:
Initial Analysis: {initial_analysis}
Public Case Law Results:
{public_cases}
Web Search Results:
{web_results}
Wikipedia Information:
{wiki_result['summary']}
Provide a well-structured summary highlighting the most relevant precedents and legal principles."""
final_summary = get_ai_response(compilation_prompt)
return {
"summary": final_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 estimate_legal_costs(case_type: str, complexity: str, country: str, state: str = None) -> Dict[str, Any]:
"""
Estimates legal costs based on case type, complexity, and location.
Performs web searches for more accurate estimates and lawyer recommendations.
"""
# Base cost ranges per hour (in USD) for different countries
base_costs = {
"USA": {"Simple": (150, 300), "Moderate": (250, 500), "Complex": (400, 1000)},
"UK": {"Simple": (100, 250), "Moderate": (200, 400), "Complex": (350, 800)},
"Canada": {"Simple": (125, 275), "Moderate": (225, 450), "Complex": (375, 900)},
}
# Adjust costs based on case type
case_type_multipliers = {
"Civil Litigation": 1.2,
"Criminal Defense": 1.5,
"Family Law": 1.0,
"Corporate Law": 1.3,
}
# Estimate number of hours based on complexity
estimated_hours = {
"Simple": (10, 30),
"Moderate": (30, 100),
"Complex": (100, 300)
}
# Get base cost range for the specified country and complexity
country_costs = base_costs.get(country, base_costs["USA"])
min_rate, max_rate = country_costs[complexity]
# Adjust rates based on case type
multiplier = case_type_multipliers.get(case_type, 1.0)
min_rate *= multiplier
max_rate *= multiplier
# Calculate total cost range
min_hours, max_hours = estimated_hours[complexity]
min_total = min_rate * min_hours
max_total = max_rate * max_hours
# Perform web search for recent cost estimates
search_query = f"{case_type} legal costs {country} {state if state else ''}"
web_results = search_web(search_query)
web_estimates = []
for result in web_results:
estimates = extract_cost_estimates(result['snippet'])
if estimates:
web_estimates.append({
'source': result['title'],
'link': result['link'],
'estimates': estimates
})
# Search for lawyers or law firms
lawyer_search_query = f"top rated {case_type} lawyers {country} {state if state else ''}"
lawyer_results = search_web(lawyer_search_query)
# Generate cost breakdown
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}",
"Web search estimates": web_estimates
}
# Potential high-cost areas
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
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,
"lawyer_recommendations": lawyer_results,
"finding_best_lawyer_tips": lawyer_tips,
"web_search_results": web_results # Add this new key
}
def legal_cost_estimator_ui():
st.subheader("Legal Cost Estimator")
case_type = st.selectbox("Select case type", ["Civil Litigation", "Criminal Defense", "Family Law", "Corporate Law"])
complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"])
country = st.selectbox("Select country", ["USA", "UK", "Canada"])
if country == "USA":
state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"])
else:
state = None
if st.button("Estimate Costs"):
with st.spinner("Estimating costs and performing web search..."):
cost_estimate = estimate_legal_costs(case_type, complexity, country, state)
st.write("### Estimated Legal Costs")
for key, value in cost_estimate["cost_breakdown"].items():
if key != "Web search estimates":
st.write(f"**{key}:** {value}")
st.write("### Web Search Estimates")
if cost_estimate["cost_breakdown"]["Web search estimates"]:
for result in cost_estimate["cost_breakdown"]["Web search estimates"]:
st.write(f"**Source:** [{result['source']}]({result['link']})")
st.write("**Estimated Costs:**")
for estimate in result['estimates']:
st.write(f"- {estimate}")
st.write("---")
else:
st.write("No specific cost estimates found from web search.")
st.write("### Potential High-Cost Areas")
for area in cost_estimate["high_cost_areas"]:
st.write(f"- {area}")
st.write("### Cost-Saving Tips")
for tip in cost_estimate["cost_saving_tips"]:
st.write(f"- {tip}")
st.write("### Recommended Lawyers/Law Firms")
for lawyer in cost_estimate["lawyer_recommendations"][:5]: # Display top 5 recommendations
st.write(f"**[{lawyer['title']}]({lawyer['link']})**")
st.write(lawyer["snippet"])
st.write("---")
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 generate_legal_form(form_type: str, user_details: Dict[str, str], nation: str, state: str = None) -> Dict[str, Any]:
"""
Generates a legal form based on user input, nation, and state (if applicable).
Creates downloadable .txt and .docx files.
"""
current_date = datetime.now().strftime("%B %d, %Y")
# Helper function to get jurisdiction-specific clauses
def get_jurisdiction_clauses(form_type, nation, state):
# This would ideally be a comprehensive database of clauses for different jurisdictions
# For demonstration, we'll use a simplified version
clauses = {
"USA": {
"Power of Attorney": "This Power of Attorney is governed by the laws of the State of {state}.",
"Non-Disclosure Agreement": "This Agreement shall be governed by and construed in accordance with the laws of the State of {state}.",
"Simple Will": "This Will shall be construed in accordance with the laws of the State of {state}.",
"Lease Agreement": "This Lease Agreement is subject to the landlord-tenant laws of the State of {state}.",
"Employment Contract": "This Employment Contract is governed by the labor laws of the State of {state}."
},
"UK": {
"Power of Attorney": "This Power of Attorney is governed by the laws of England and Wales.",
"Non-Disclosure Agreement": "This Agreement shall be governed by and construed in accordance with the laws of England and Wales.",
"Simple Will": "This Will shall be construed in accordance with the laws of England and Wales.",
"Lease Agreement": "This Lease Agreement is subject to the landlord and tenant laws of England and Wales.",
"Employment Contract": "This Employment Contract is governed by the employment laws of England and Wales."
},
# Add more countries as needed
}
return clauses.get(nation, {}).get(form_type, "").format(state=state)
jurisdiction_clause = get_jurisdiction_clauses(form_type, nation, state)
if form_type == "Power of Attorney":
form_content = f"""
POWER OF ATTORNEY
This Power of Attorney is made on {current_date}.
I, {user_details['principal_name']}, hereby appoint {user_details['agent_name']} as my Attorney-in-Fact ("Agent").
My Agent shall have full power and authority to act on my behalf. This power and authority shall authorize my Agent to manage and conduct all of my affairs and to exercise all of my legal rights and powers, including all rights and powers that I may acquire in the future. My Agent's powers shall include, but not be limited to:
1. {', '.join(user_details['powers'])}
This Power of Attorney shall become effective immediately and shall continue until it is revoked by me.
{jurisdiction_clause}
Signed this {current_date}.
______________________
{user_details['principal_name']} (Principal)
______________________
{user_details['agent_name']} (Agent)
______________________
Witness
______________________
Witness
"""
elif form_type == "Non-Disclosure Agreement":
form_content = f"""
NON-DISCLOSURE AGREEMENT
This Non-Disclosure Agreement (the "Agreement") is entered into on {current_date} by and between:
{user_details['party_a']} ("Party A")
and
{user_details['party_b']} ("Party B")
1. Purpose: This Agreement is entered into for the purpose of {user_details['purpose']}.
2. Confidential Information: Both parties may disclose certain confidential and proprietary information to each other in connection with the Purpose.
3. Non-Disclosure: Both parties agree to keep all Confidential Information strictly confidential and not to disclose such information to any third parties for a period of {user_details['duration']} years from the date of this Agreement.
{jurisdiction_clause}
IN WITNESS WHEREOF, the parties hereto have executed this Non-Disclosure Agreement as of the date first above written.
______________________
{user_details['party_a']}
______________________
{user_details['party_b']}
"""
elif form_type == "Simple Will":
beneficiaries = user_details['beneficiaries'].split('\n')
beneficiary_clauses = "\n".join([f"{i+1}. I give, devise, and bequeath to {b.strip()} [insert specific bequest or share of estate]." for i, b in enumerate(beneficiaries)])
form_content = f"""
LAST WILL AND TESTAMENT
I, {user_details['testator_name']}, being of sound mind, do hereby make, publish, and declare this to be my Last Will and Testament, hereby revoking all previous wills and codicils made by me.
1. EXECUTOR: I appoint {user_details['executor_name']} to be the Executor of this, my Last Will and Testament.
2. BEQUESTS:
{beneficiary_clauses}
3. RESIDUARY ESTATE: I give, devise, and bequeath all the rest, residue, and remainder of my estate to [insert beneficiary or beneficiaries].
4. POWERS OF EXECUTOR: I grant to my Executor full power and authority to sell, lease, mortgage, or otherwise dispose of the whole or any part of my estate.
{jurisdiction_clause}
IN WITNESS WHEREOF, I have hereunto set my hand to this my Last Will and Testament on {current_date}.
______________________
{user_details['testator_name']} (Testator)
WITNESSES:
On the date last above written, {user_details['testator_name']}, known to us to be the Testator, signed this Will in our presence and declared it to be their Last Will and Testament. At the Testator's request, in the Testator's presence, and in the presence of each other, we have signed our names as witnesses:
______________________
Witness 1
______________________
Witness 2
"""
elif form_type == "Lease Agreement":
form_content = f"""
LEASE AGREEMENT
This Lease Agreement (the "Lease") is made on {current_date} by and between:
{user_details['landlord_name']} ("Landlord")
and
{user_details['tenant_name']} ("Tenant")
1. PREMISES: The Landlord hereby leases to the Tenant the property located at {user_details['property_address']}.
2. TERM: The term of this Lease shall be for {user_details['lease_term']} months, beginning on {user_details['start_date']} and ending on {user_details['end_date']}.
3. RENT: The Tenant shall pay rent in the amount of {user_details['rent_amount']} per month, due on the {user_details['rent_due_day']} day of each month.
4. SECURITY DEPOSIT: The Tenant shall pay a security deposit of {user_details['security_deposit']} upon signing this Lease.
{jurisdiction_clause}
IN WITNESS WHEREOF, the parties hereto have executed this Lease Agreement as of the date first above written.
______________________
{user_details['landlord_name']} (Landlord)
______________________
{user_details['tenant_name']} (Tenant)
"""
elif form_type == "Employment Contract":
form_content = f"""
EMPLOYMENT CONTRACT
This Employment Contract (the "Contract") is made on {current_date} by and between:
{user_details['employer_name']} ("Employer")
and
{user_details['employee_name']} ("Employee")
1. POSITION: The Employee is hired for the position of {user_details['job_title']}.
2. DUTIES: The Employee's duties shall include, but are not limited to: {user_details['job_duties']}.
3. COMPENSATION: The Employee shall be paid a {user_details['pay_frequency']} salary of {user_details['salary_amount']}.
4. TERM: This Contract shall commence on {user_details['start_date']} and continue until terminated by either party.
5. BENEFITS: The Employee shall be entitled to the following benefits: {user_details['benefits']}.
{jurisdiction_clause}
IN WITNESS WHEREOF, the parties hereto have executed this Employment Contract as of the date first above written.
______________________
{user_details['employer_name']} (Employer)
______________________
{user_details['employee_name']} (Employee)
"""
else:
return {"error": "Unsupported form type"}
# Generate .txt file
txt_file = io.StringIO()
txt_file.write(form_content)
txt_file.seek(0)
# Generate .docx file
docx_file = io.BytesIO()
doc = Document()
doc.add_paragraph(form_content)
doc.save(docx_file)
docx_file.seek(0)
return {
"form_content": form_content,
"txt_file": txt_file,
"docx_file": docx_file
}
CASE_TYPES = [
"Civil Rights", "Contract", "Real Property", "Tort", "Labor", "Intellectual Property",
"Bankruptcy", "Immigration", "Social Security", "Tax", "Constitutional", "Criminal",
"Environmental", "Antitrust", "Securities", "Administrative", "Admiralty", "Family Law",
"Probate", "Personal Injury"
]
DATA_SOURCES = {
"Civil Rights": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Contract": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Real Property": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Tort": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Labor": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Intellectual Property": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Bankruptcy": "https://www.uscourts.gov/sites/default/files/data_tables/jb_f_0930.2022.pdf",
"Immigration": "https://www.justice.gov/eoir/workload-and-adjudication-statistics",
"Social Security": "https://www.ssa.gov/open/data/hearings-and-appeals-filed.html",
"Tax": "https://www.ustaxcourt.gov/statistics.html",
"Constitutional": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Criminal": "https://www.uscourts.gov/sites/default/files/data_tables/jb_d1_0930.2022.pdf",
"Environmental": "https://www.epa.gov/enforcement/enforcement-annual-results-numbers-glance-fiscal-year-2022",
"Antitrust": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Securities": "https://www.sec.gov/files/enforcement-annual-report-2022.pdf",
"Administrative": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Admiralty": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Family Law": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Probate": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
"Personal Injury": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf"
}
def fetch_case_data(case_type: str) -> pd.DataFrame:
"""Fetches actual historical data for the given case type."""
url = DATA_SOURCES[case_type]
response = requests.get(url)
if response.status_code == 200:
if url.endswith('.pdf'):
# For PDF sources, we'll use a placeholder DataFrame
# In a real-world scenario, you'd need to implement PDF parsing
df = pd.DataFrame({
'Year': range(2013, 2023),
'Number of Cases': [random.randint(1000, 5000) for _ in range(10)]
})
else:
# For non-PDF sources, we'll assume CSV format
df = pd.read_csv(StringIO(response.text))
else:
st.error(f"Failed to fetch data for {case_type}. Using placeholder data.")
df = pd.DataFrame({
'Year': range(2013, 2023),
'Number of Cases': [random.randint(1000, 5000) for _ in range(10)]
})
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)
fig = px.line(df, x='Year', y='Number of Cases', title=f"Trend of {case_type} Cases")
fig.update_layout(
xaxis_title="Year",
yaxis_title="Number of Cases",
hovermode="x unified"
)
fig.update_traces(mode="lines+markers")
return fig, df # Return both the image and the raw data
def process_document_chat(uploaded_file, query, web_search_enabled):
"""Processes the document chat, including potential web search."""
document_content = analyze_document(uploaded_file)
if web_search_enabled:
# Combine document content with web search results
web_results = search_web(query)
web_results_text = "\n\n".join([
f"[{result['title']}]({result['link']})\n{result['snippet']}"
for result in web_results
])
combined_content = f"Document Content:\n{document_content}\n\nWeb Search Results:\n{web_results_text}"
else:
combined_content = document_content
# Generate the AI response based on the combined content
ai_response = get_ai_response(f"{query}\n\n{combined_content}")
return ai_response, web_results if web_search_enabled else []
# --- Streamlit App ---
# Custom CSS to improve the overall look
st.markdown("""
<style>
.reportview-container {
background: #f0f2f6;
}
.main .block-container {
padding-top: 2rem;
padding-bottom: 2rem;
padding-left: 5rem;
padding-right: 5rem;
}
h1 {
color: #1E3A8A;
}
h2 {
color: #3B82F6;
}
.stButton>button {
background-color: #3B82F6;
color: white;
border-radius: 5px;
}
.stTextInput>div>div>input {
border-radius: 5px;
}
</style>
""", unsafe_allow_html=True)
def load_lottieurl(url: str):
try:
r = requests.get(url)
r.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xx
return r.json()
except requests.HTTPError as http_err:
print(f"HTTP error occurred while loading Lottie animation: {http_err}")
except requests.RequestException as req_err:
print(f"Error occurred while loading Lottie animation: {req_err}")
except ValueError as json_err:
print(f"Error decoding JSON for Lottie animation: {json_err}")
return None
# Streamlit App
st.title("Lex AI - Advanced Legal Assistant")
# Sidebar with feature selection
with st.sidebar:
st.title(" AI")
st.subheader("Advanced Legal Assistant")
feature = st.selectbox(
"Select a feature",
["Legal Chatbot", "Document Analysis", "Case Precedent Finder",
"Legal Cost Estimator", "Legal Form Generator", "Case Trend Visualizer",
"Document Chat"]
)
if feature == "Legal Chatbot":
st.subheader("Legal Chatbot")
# Document upload section
uploaded_file = st.file_uploader(
"Upload a document (PDF, DOCX, or TXT) to chat with",
type=["pdf", "docx", "txt"]
)
if uploaded_file:
handle_document_upload(uploaded_file)
# Chat input and display
display_chat_history()
user_input = st.text_input("Your legal question:")
if user_input and st.button("Send"):
with st.spinner("Thinking..."):
# If a document is uploaded, prioritize answering from it
if st.session_state.document_embeddings is not None:
document_chatbot() # This will add the response to chat_history
else: # If no document, answer from general knowledge and web search
ai_response = get_ai_response(user_input)
st.session_state.chat_history.append((user_input, ai_response))
# Perform Wikipedia search
wiki_result = search_wikipedia(user_input)
st.session_state.chat_history.append({
'type': 'wikipedia',
'summary': wiki_result.get("summary", "No summary available."),
'url': wiki_result.get("url", "")
})
# Perform web search
web_results = search_web(user_input)
st.session_state.chat_history.append({
'type': 'web_search',
'results': web_results
})
st.rerun()
elif feature == "Document Analysis":
st.subheader("Legal Document Analyzer")
uploaded_file = st.file_uploader("Upload a legal document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])
if uploaded_file and st.button("Analyze Document"):
with st.spinner("Analyzing document and gathering additional information..."):
try:
document_content = analyze_document(uploaded_file)
analysis_results = comprehensive_document_analysis(document_content)
st.write("Document Analysis:")
st.write(analysis_results.get("document_analysis", "No analysis available."))
st.write("Related Articles:")
for article in analysis_results.get("related_articles", []):
st.write(f"- [{article.get('title', 'No title')}]({article.get('link', '#')})")
st.write(f" {article.get('snippet', 'No snippet available.')}")
st.write("Wikipedia Summary:")
wiki_info = analysis_results.get("wikipedia_summary", {})
st.write(f"**{wiki_info.get('title', 'No title')}**")
st.write(wiki_info.get('summary', 'No summary available.'))
if wiki_info.get('url'):
st.write(f"[Read more on Wikipedia]({wiki_info['url']})")
except Exception as e:
st.error(f"An error occurred during document analysis: {str(e)}")
elif feature == "Case Precedent Finder":
st.subheader("Case Precedent Finder")
# Initialize session state for precedents if not exists
if 'precedents' not in st.session_state:
st.session_state.precedents = None
# Initialize session state for visibility toggles if not exists
if 'visibility_toggles' not in st.session_state:
st.session_state.visibility_toggles = {}
case_details = st.text_area("Enter case details:")
if st.button("Find Precedents"):
with st.spinner("Searching for relevant case precedents..."):
try:
st.session_state.precedents = find_case_precedents(case_details)
except Exception as e:
st.error(f"An error occurred while finding case precedents: {str(e)}")
# Display results if precedents are available
if st.session_state.precedents:
precedents = st.session_state.precedents
st.write("### Summary of Relevant Case Precedents")
st.markdown(precedents["summary"])
st.write("### Related Cases from Public Databases")
for i, case in enumerate(precedents["public_cases"], 1):
st.write(f"**{i}. {case['case_name']} - {case['citation']}**")
st.write(f"Summary: {case['summary']}")
st.write(f"[Read full case]({case['url']})")
st.write("---")
st.write("### Additional Web Results")
for i, result in enumerate(precedents["web_results"], 1):
st.write(f"**{i}. [{result['title']}]({result['link']})**")
# Create a unique key for each toggle
toggle_key = f"toggle_{i}"
# Initialize the toggle state if it doesn't exist
if toggle_key not in st.session_state.visibility_toggles:
st.session_state.visibility_toggles[toggle_key] = False
# Create a button to toggle visibility
if st.button(f"{'Hide' if st.session_state.visibility_toggles[toggle_key] else 'Show'} Full Details for Result {i}", key=f"button_{i}"):
st.session_state.visibility_toggles[toggle_key] = not st.session_state.visibility_toggles[toggle_key]
# Show full details if toggle is True
if st.session_state.visibility_toggles[toggle_key]:
# Fetch and display more detailed content
detailed_content = fetch_detailed_content(result['link'])
st.markdown(detailed_content)
else:
# Show a brief summary when details are hidden
brief_summary = result['snippet'].split('\n')[0][:200] + "..." if len(result['snippet']) > 200 else result['snippet'].split('\n')[0]
st.write(f"Brief Summary: {brief_summary}")
st.write("---")
st.write("### Wikipedia Information")
wiki_info = precedents["wikipedia"]
st.write(f"**[{wiki_info['title']}]({wiki_info['url']})**")
st.markdown(wiki_info['summary'])
elif feature == "Legal Cost Estimator":
st.subheader("Legal Cost Estimator")
case_type = st.selectbox("Select case type", ["Civil Litigation", "Criminal Defense", "Family Law", "Corporate Law"], key="cost_estimator_case_type")
complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"], key="cost_estimator_complexity")
country = st.selectbox("Select country", ["USA", "UK", "Canada"], key="cost_estimator_country")
if country == "USA":
state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"], key="cost_estimator_state")
else:
state = None
# Initialize cost_estimate
cost_estimate = None
if st.button("Estimate Costs"):
with st.spinner("Estimating costs and performing web search..."):
cost_estimate = estimate_legal_costs(case_type, complexity, country, state)
# Check if cost_estimate is available before displaying results
if cost_estimate:
st.write("### Estimated Legal Costs")
for key, value in cost_estimate["cost_breakdown"].items():
st.write(f"**{key}:** {value}")
st.write("### Web Search Results")
if cost_estimate["web_search_results"]:
for result in cost_estimate["web_search_results"]:
st.write(f"**[{result['title']}]({result['link']})**")
st.write(result["snippet"])
st.write("---")
else:
st.write("No specific cost estimates found from web search.")
st.write("### Potential High-Cost Areas")
for area in cost_estimate["high_cost_areas"]:
st.write(f"- {area}")
st.write("### Cost-Saving Tips")
for tip in cost_estimate["cost_saving_tips"]:
st.write(f"- {tip}")
st.write("### Tips for Finding the Best Legal Representation")
for tip in cost_estimate["finding_best_lawyer_tips"]:
st.write(f"- {tip}")
st.write("### Recommended Lawyers/Law Firms")
for lawyer in cost_estimate["lawyer_recommendations"][:5]: # Display top 5 recommendations
st.write(f"**[{lawyer['title']}]({lawyer['link']})**")
st.write(lawyer["snippet"])
st.write("---")
else:
st.write("Click 'Estimate Costs' to see the results.")
elif feature == "Legal Form Generator":
st.subheader("Legal Form Generator")
form_type = st.selectbox("Select form type", ["Power of Attorney", "Non-Disclosure Agreement", "Simple Will", "Lease Agreement", "Employment Contract"], key="form_generator_type")
nation = st.selectbox("Select nation", ["USA", "UK"], key="form_generator_nation")
if nation == "USA":
state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"], key="form_generator_state")
else:
state = None
user_details = {}
if form_type == "Power of Attorney":
user_details["principal_name"] = st.text_input("Principal's Full Name:")
user_details["agent_name"] = st.text_input("Agent's Full Name:")
user_details["powers"] = st.multiselect("Select powers to grant", ["Financial Decisions", "Healthcare Decisions", "Real Estate Transactions"])
elif form_type == "Non-Disclosure Agreement":
user_details["party_a"] = st.text_input("First Party's Name:")
user_details["party_b"] = st.text_input("Second Party's Name:")
user_details["purpose"] = st.text_input("Purpose of Disclosure:")
user_details["duration"] = st.number_input("Duration of Agreement (in years):", min_value=1, max_value=10)
elif form_type == "Simple Will":
user_details["testator_name"] = st.text_input("Testator's Full Name:")
user_details["beneficiaries"] = st.text_area("List Beneficiaries (one per line):")
user_details["executor_name"] = st.text_input("Executor's Full Name:")
elif form_type == "Lease Agreement":
user_details["landlord_name"] = st.text_input("Landlord's Full Name:")
user_details["tenant_name"] = st.text_input("Tenant's Full Name:")
user_details["property_address"] = st.text_input("Property Address:")
user_details["lease_term"] = st.number_input("Lease Term (in months):", min_value=1, max_value=60)
user_details["start_date"] = st.date_input("Lease Start Date:")
user_details["end_date"] = st.date_input("Lease End Date:")
user_details["rent_amount"] = st.number_input("Monthly Rent Amount:", min_value=0)
user_details["rent_due_day"] = st.number_input("Rent Due Day of Month:", min_value=1, max_value=31)
user_details["security_deposit"] = st.number_input("Security Deposit Amount:", min_value=0)
elif form_type == "Employment Contract":
user_details["employer_name"] = st.text_input("Employer's Full Name:")
user_details["employee_name"] = st.text_input("Employee's Full Name:")
user_details["job_title"] = st.text_input("Job Title:")
user_details["job_duties"] = st.text_area("Job Duties:")
user_details["pay_frequency"] = st.selectbox("Pay Frequency:", ["Weekly", "Bi-weekly", "Monthly"])
user_details["salary_amount"] = st.number_input("Salary Amount:", min_value=0)
user_details["start_date"] = st.date_input("Employment Start Date:")
user_details["benefits"] = st.text_area("Employee Benefits:")
if st.button("Generate Form"):
generated_form = generate_legal_form(form_type, user_details, nation, state)
if "error" in generated_form:
st.error(generated_form["error"])
else:
st.write("### Generated Legal Form:")
st.text(generated_form["form_content"])
# Provide download buttons for .txt and .docx files
txt_download = generated_form["txt_file"].getvalue()
docx_download = generated_form["docx_file"].getvalue()
st.download_button(
label="Download as .txt",
data=txt_download,
file_name=f"{form_type.lower().replace(' ', '_')}_{nation}{'_' + state if state else ''}.txt",
mime="text/plain"
)
st.download_button(
label="Download as .docx",
data=docx_download,
file_name=f"{form_type.lower().replace(' ', '_')}_{nation}{'_' + state if state else ''}.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
st.warning("Please note: This generated form is a template based on general principles of the selected jurisdiction. It should be reviewed by a legal professional licensed in the relevant jurisdiction before use.")
elif feature == "Case Trend Visualizer":
st.subheader("Case Trend Visualizer")
case_type = st.selectbox("Select case type to visualize", CASE_TYPES)
if st.button("Visualize Trend") or 'df' in st.session_state:
with st.spinner("Fetching and visualizing data..."):
if 'df' not in st.session_state:
fig, df = visualize_case_trends(case_type)
st.session_state.df = df
st.session_state.fig = fig
else:
df = st.session_state.df
fig = st.session_state.fig
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", f"{total_cases:,}")
col2.metric("Average Cases per Year", f"{avg_cases:,.0f}")
col3.metric("Years", f"{min_year} - {max_year}")
# Raw Data
st.subheader("Raw Data")
st.dataframe(df)
# Download options
csv = df.to_csv(index=False)
st.download_button(
label="Download data as CSV",
data=csv,
file_name=f"{case_type.lower().replace(' ', '_')}_trend_data.csv",
mime="text/csv",
)
# Additional resources
st.subheader("Additional Resources")
st.markdown(f"[Data Source]({DATA_SOURCES[case_type]})")
st.markdown("[US Courts Statistics](https://www.uscourts.gov/statistics-reports)")
st.markdown("[Federal Judicial Caseload Statistics](https://www.uscourts.gov/statistics-reports/analysis-reports/federal-judicial-caseload-statistics)")
st.markdown(f"[Legal Information Institute](https://www.law.cornell.edu/wex/{case_type.lower().replace(' ', '_')})")
# Explanatory text
st.subheader("Understanding the Trend")
explanation = f"""
The graph above shows the trend of {case_type} cases over time. Here are some key points to consider:
1. Overall Trend: Observe whether the number of cases is generally increasing, decreasing, or remaining stable over the years.
2. Peak Years: The year {max_year} saw the highest number of cases ({df['Number of Cases'].max():,}). This could be due to various factors such as changes in legislation, economic conditions, or social trends.
3. Low Points: The year {min_year} had the lowest number of cases ({df['Number of Cases'].min():,}). Consider what might have contributed to this decrease.
4. Recent Trends: Pay attention to the most recent years to understand current patterns in {case_type} cases.
5. Contextual Factors: Remember that these numbers can be influenced by various factors, including changes in law, court procedures, societal changes, and more.
For a deeper understanding of these trends and their implications, consider consulting with legal professionals or reviewing academic research in this area.
"""
st.markdown(explanation)
# Interactive elements
st.subheader("Interactive Analysis")
analysis_type = st.radio("Select analysis type:", ["Year-over-Year Change", "Moving Average"])
if analysis_type == "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)
elif analysis_type == "Moving Average":
window = st.slider("Select moving average window:", 2, 5, 3)
df['Moving Average'] = df['Number of Cases'].rolling(window=window).mean()
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)
elif feature == "Document Chat":
st.subheader("Document Chat")
if "document_chat_history" not in st.session_state:
st.session_state.document_chat_history = []
uploaded_file = st.file_uploader("Upload a document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])
if uploaded_file is not None:
web_search_enabled = st.checkbox("Enable Web Search")
query = st.text_input("Ask a question about the document:")
if query and st.button("Ask"):
with st.spinner("Analyzing document..."):
ai_response, web_results = process_document_chat(uploaded_file, query, web_search_enabled)
st.session_state.document_chat_history.append((query, ai_response))
if web_search_enabled:
st.session_state.document_chat_history.append({'type': 'web_search', 'results': web_results})
st.rerun()
display_chat_history(st.session_state.document_chat_history)
# Add a footer with a disclaimer
# Footer
st.markdown("---")
st.markdown(
"""
<div style="text-align: center;">
<p>© 2023 Lex AI. All rights reserved.</p>
<p><small>Disclaimer: This tool provides general legal information and assistance. It is not a substitute for professional legal advice. Please consult with a qualified attorney for specific legal matters.</small></p>
</div>
""",
unsafe_allow_html=True
)
if __name__ == "__main__":
st.sidebar.info("Select a feature from the dropdown above to get started.") |