aAzelll / app3.py
Johan713's picture
Upload app3.py
5134bed verified
raw
history blame
53.3 kB
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
# 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 = []
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():
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 (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
# --- 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"]
)
if feature == "Legal Chatbot":
st.subheader("Legal Chatbot")
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
display_chat_history()
user_input = st.text_input("Your legal question:")
if user_input and st.button("Send"):
with st.spinner("Searching for information..."):
ai_response = get_ai_response(user_input)
# Add user message and AI response to chat history
st.session_state.chat_history.append((user_input, ai_response))
# Perform Wikipedia search
wiki_result = search_wikipedia(user_input)
# Add Wikipedia result to chat history
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)
# Add web search results to chat history
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)
# 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.")