Johan713 commited on
Commit
5134bed
·
verified ·
1 Parent(s): 156261f

Upload app3.py

Browse files
Files changed (1) hide show
  1. app3.py +1212 -0
app3.py ADDED
@@ -0,0 +1,1212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import requests
5
+ from ai71 import AI71
6
+ import PyPDF2
7
+ import io
8
+ import random
9
+ import docx
10
+ from docx import Document
11
+ from docx.shared import Inches
12
+ from datetime import datetime
13
+ import re
14
+ import base64
15
+ from typing import List, Dict, Any
16
+ import matplotlib.pyplot as plt
17
+ from bs4 import BeautifulSoup
18
+ from io import StringIO
19
+ import wikipedia
20
+ from googleapiclient.discovery import build
21
+ from typing import List, Optional
22
+ from httpx_sse import SSEError
23
+
24
+ # Error handling for optional dependencies
25
+ try:
26
+ from streamlit_lottie import st_lottie
27
+ except ImportError:
28
+ st.error("Missing dependency: streamlit_lottie. Please install it using 'pip install streamlit-lottie'")
29
+ st.stop()
30
+
31
+ # Constants
32
+ AI71_API_KEY = "api71-api-92fc2ef9-9f3c-47e5-a019-18e257b04af2"
33
+
34
+ # Initialize AI71 client
35
+ try:
36
+ ai71 = AI71(AI71_API_KEY)
37
+ except Exception as e:
38
+ st.error(f"Failed to initialize AI71 client: {str(e)}")
39
+ st.stop()
40
+
41
+ # Initialize chat history and other session state variables
42
+ if "chat_history" not in st.session_state:
43
+ st.session_state.chat_history = []
44
+ if "uploaded_documents" not in st.session_state:
45
+ st.session_state.uploaded_documents = []
46
+ if "case_precedents" not in st.session_state:
47
+ st.session_state.case_precedents = []
48
+
49
+
50
+ def get_ai_response(prompt: str) -> str:
51
+ """Gets the AI response based on the given prompt."""
52
+ messages = [
53
+ {"role": "system", "content": "You are a helpful legal assistant with advanced capabilities."},
54
+ {"role": "user", "content": prompt}
55
+ ]
56
+ try:
57
+ # First, try streaming
58
+ response = ""
59
+ for chunk in ai71.chat.completions.create(
60
+ model="tiiuae/falcon-180b-chat",
61
+ messages=messages,
62
+ stream=True,
63
+ ):
64
+ if chunk.choices[0].delta.content:
65
+ response += chunk.choices[0].delta.content
66
+ return response
67
+ except Exception as e:
68
+ print(f"Streaming failed, falling back to non-streaming request. Error: {e}")
69
+ try:
70
+ # Fall back to non-streaming request
71
+ completion = ai71.chat.completions.create(
72
+ model="tiiuae/falcon-180b-chat",
73
+ messages=messages,
74
+ stream=False,
75
+ )
76
+ return completion.choices[0].message.content
77
+ except Exception as e:
78
+ print(f"An error occurred while getting AI response: {e}")
79
+ return f"I apologize, but I encountered an error while processing your request. Error: {str(e)}"
80
+
81
+ def display_chat_history():
82
+ for message in st.session_state.chat_history:
83
+ if isinstance(message, tuple):
84
+ if len(message) == 2:
85
+ user_msg, bot_msg = message
86
+ st.info(f"**You:** {user_msg}")
87
+ st.success(f"**Bot:** {bot_msg}")
88
+ else:
89
+ st.error(f"Unexpected message format: {message}")
90
+ elif isinstance(message, dict):
91
+ if message.get('type') == 'wikipedia':
92
+ st.success(f"**Bot:** Wikipedia Summary:\n{message.get('summary', 'No summary available.')}\n" +
93
+ (f"[Read more on Wikipedia]({message.get('url')})" if message.get('url') else ""))
94
+ elif message.get('type') == 'web_search':
95
+ web_results_msg = "Web Search Results:\n"
96
+ for result in message.get('results', []):
97
+ web_results_msg += f"[{result.get('title', 'No title')}]({result.get('link', '#')})\n{result.get('snippet', 'No snippet available.')}\n\n"
98
+ st.success(f"**Bot:** {web_results_msg}")
99
+ else:
100
+ st.error(f"Unknown message type: {message}")
101
+ else:
102
+ st.error(f"Unexpected message format: {message}")
103
+
104
+ def analyze_document(file) -> str:
105
+ """Analyzes uploaded legal documents."""
106
+ content = ""
107
+ if file.type == "application/pdf":
108
+ pdf_reader = PyPDF2.PdfReader(file)
109
+ for page in pdf_reader.pages:
110
+ content += page.extract_text()
111
+ elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
112
+ doc = docx.Document(file)
113
+ for para in doc.paragraphs:
114
+ content += para.text + "\n"
115
+ else:
116
+ content = file.getvalue().decode("utf-8")
117
+
118
+ return content[:5000] # Limit content to 5000 characters for analysis
119
+
120
+ def search_web(query: str, num_results: int = 3) -> List[Dict[str, str]]:
121
+ try:
122
+ service = build("customsearch", "v1", developerKey="AIzaSyD-1OMuZ0CxGAek0PaXrzHOmcDWFvZQtm8")
123
+
124
+ # Add legal-specific terms to the query
125
+ legal_query = f"legal {query} law case precedent"
126
+
127
+ # Execute the search request
128
+ res = service.cse().list(q=legal_query, cx="877170db56f5c4629", num=num_results * 2).execute()
129
+
130
+ results = []
131
+ if "items" in res:
132
+ for item in res["items"]:
133
+ # Check if the result is relevant (you may need to adjust these conditions)
134
+ if any(keyword in item["title"].lower() or keyword in item["snippet"].lower()
135
+ for keyword in ["law", "legal", "court", "case", "attorney", "lawyer"]):
136
+ result = {
137
+ "title": item["title"],
138
+ "link": item["link"],
139
+ "snippet": item["snippet"]
140
+ }
141
+ results.append(result)
142
+ if len(results) == num_results:
143
+ break
144
+
145
+ return results
146
+ except Exception as e:
147
+ print(f"Error performing web search: {e}")
148
+ return []
149
+
150
+ def perform_web_search(query: str) -> List[Dict[str, Any]]:
151
+ """
152
+ Performs a web search to find recent legal cost estimates.
153
+ """
154
+ url = f"https://www.google.com/search?q={query}"
155
+ headers = {'User-Agent': 'Mozilla/5.0'}
156
+ response = requests.get(url, headers=headers)
157
+ soup = BeautifulSoup(response.content, 'html.parser')
158
+
159
+ results = []
160
+ for g in soup.find_all('div', class_='g'):
161
+ anchors = g.find_all('a')
162
+ if anchors:
163
+ link = anchors[0]['href']
164
+ title = g.find('h3', class_='r')
165
+ if title:
166
+ title = title.text
167
+ else:
168
+ title = "No title"
169
+ snippet = g.find('div', class_='s')
170
+ if snippet:
171
+ snippet = snippet.text
172
+ else:
173
+ snippet = "No snippet"
174
+
175
+ # Extract cost estimates from the snippet
176
+ cost_estimates = extract_cost_estimates(snippet)
177
+
178
+ if cost_estimates:
179
+ results.append({
180
+ "title": title,
181
+ "link": link,
182
+ "cost_estimates": cost_estimates
183
+ })
184
+
185
+ return results[:3] # Return top 3 results with cost estimates
186
+
187
+ def search_wikipedia(query: str, sentences: int = 2) -> Dict[str, str]:
188
+ try:
189
+ # Ensure query is a string before slicing
190
+ truncated_query = str(query)[:300]
191
+
192
+ # Search Wikipedia
193
+ search_results = wikipedia.search(truncated_query, results=5)
194
+
195
+ if not search_results:
196
+ return {"summary": "No Wikipedia article found.", "url": "", "title": ""}
197
+
198
+ # Try to get a summary for each result until successful
199
+ for result in search_results:
200
+ try:
201
+ page = wikipedia.page(result)
202
+ summary = wikipedia.summary(result, sentences=sentences)
203
+ return {"summary": summary, "url": page.url, "title": page.title}
204
+ except wikipedia.exceptions.DisambiguationError as e:
205
+ continue
206
+ except wikipedia.exceptions.PageError:
207
+ continue
208
+
209
+ # If no summary found after trying all results
210
+ return {"summary": "No relevant Wikipedia article found.", "url": "", "title": ""}
211
+ except Exception as e:
212
+ print(f"Error searching Wikipedia: {e}")
213
+ return {"summary": f"Error searching Wikipedia: {str(e)}", "url": "", "title": ""}
214
+
215
+ def comprehensive_document_analysis(content: str) -> Dict[str, Any]:
216
+ """Performs a comprehensive analysis of the document, including web and Wikipedia searches."""
217
+ try:
218
+ analysis_prompt = f"Analyze the following legal document and provide a summary, potential issues, and key clauses:\n\n{content}"
219
+ document_analysis = get_ai_response(analysis_prompt)
220
+
221
+ # Extract main topics or keywords from the document
222
+ topic_extraction_prompt = f"Extract the main topics or keywords from the following document summary:\n\n{document_analysis}"
223
+ topics = get_ai_response(topic_extraction_prompt)
224
+
225
+ web_results = search_web(topics)
226
+ wiki_results = search_wikipedia(topics)
227
+
228
+ return {
229
+ "document_analysis": document_analysis,
230
+ "related_articles": web_results or [], # Ensure this is always a list
231
+ "wikipedia_summary": wiki_results
232
+ }
233
+ except Exception as e:
234
+ print(f"Error in comprehensive document analysis: {e}")
235
+ return {
236
+ "document_analysis": "Error occurred during analysis.",
237
+ "related_articles": [],
238
+ "wikipedia_summary": {"summary": "Error occurred", "url": "", "title": ""}
239
+ }
240
+
241
+ def extract_important_info(text: str) -> str:
242
+ """Extracts and highlights important information from the given text."""
243
+ prompt = f"Extract and highlight the most important legal information from the following text. Use markdown to emphasize key points:\n\n{text}"
244
+ return get_ai_response(prompt)
245
+
246
+ def fetch_detailed_content(url: str) -> str:
247
+ try:
248
+ response = requests.get(url)
249
+ response.raise_for_status()
250
+ soup = BeautifulSoup(response.text, 'html.parser')
251
+
252
+ # Extract main content (this may need to be adjusted based on the structure of the target websites)
253
+ main_content = soup.find('main') or soup.find('article') or soup.find('div', class_='content')
254
+
255
+ if main_content:
256
+ # Extract text from paragraphs
257
+ paragraphs = main_content.find_all('p')
258
+ content = "\n\n".join([p.get_text() for p in paragraphs])
259
+
260
+ # Limit content to a reasonable length (e.g., first 1000 characters)
261
+ return content[:1000] + "..." if len(content) > 1000 else content
262
+ else:
263
+ return "Unable to extract detailed content from the webpage."
264
+ except Exception as e:
265
+ return f"Error fetching detailed content: {str(e)}"
266
+
267
+ def query_public_case_law(query: str) -> List[Dict[str, Any]]:
268
+ """
269
+ Query publicly available case law databases and perform a web search to find related cases.
270
+ """
271
+ # Perform a web search to find relevant case law
272
+ search_url = f"https://www.google.com/search?q={query}+case+law+site:law.justia.com"
273
+ 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'}
274
+
275
+ try:
276
+ response = requests.get(search_url, headers=headers)
277
+ response.raise_for_status()
278
+ soup = BeautifulSoup(response.text, 'html.parser')
279
+
280
+ search_results = soup.find_all('div', class_='g')
281
+ cases = []
282
+
283
+ for result in search_results[:5]: # Limit to top 5 results
284
+ title_elem = result.find('h3', class_='r')
285
+ link_elem = result.find('a')
286
+ snippet_elem = result.find('div', class_='s')
287
+
288
+ if title_elem and link_elem and snippet_elem:
289
+ title = title_elem.text
290
+ link = link_elem['href']
291
+ snippet = snippet_elem.text
292
+
293
+ # Extract case name and citation from the title
294
+ case_info = title.split(' - ')
295
+ if len(case_info) >= 2:
296
+ case_name = case_info[0]
297
+ citation = case_info[1]
298
+ else:
299
+ case_name = title
300
+ citation = "Citation not found"
301
+
302
+ cases.append({
303
+ "case_name": case_name,
304
+ "citation": citation,
305
+ "summary": snippet,
306
+ "url": link
307
+ })
308
+
309
+ return cases
310
+ except requests.RequestException as e:
311
+ print(f"Error querying case law: {e}")
312
+ return []
313
+
314
+ def find_case_precedents(case_details: str) -> Dict[str, Any]:
315
+ """Finds relevant case precedents based on provided details."""
316
+ try:
317
+ # Initial AI analysis of the case details
318
+ analysis_prompt = f"Analyze the following case details and identify key legal concepts and relevant precedents:\n\n{case_details}"
319
+ initial_analysis = get_ai_response(analysis_prompt)
320
+
321
+ # Query public case law databases
322
+ public_cases = query_public_case_law(case_details)
323
+
324
+ # Perform web search (existing functionality)
325
+ web_results = search_web(f"legal precedent {case_details}", num_results=3)
326
+
327
+ # Perform Wikipedia search (existing functionality)
328
+ wiki_result = search_wikipedia(f"legal case {case_details}")
329
+
330
+ # Compile all information
331
+ compilation_prompt = f"""Compile a comprehensive summary of case precedents based on the following information:
332
+
333
+ Initial Analysis: {initial_analysis}
334
+
335
+ Public Case Law Results:
336
+ {public_cases}
337
+
338
+ Web Search Results:
339
+ {web_results}
340
+
341
+ Wikipedia Information:
342
+ {wiki_result['summary']}
343
+
344
+ Provide a well-structured summary highlighting the most relevant precedents and legal principles."""
345
+
346
+ final_summary = get_ai_response(compilation_prompt)
347
+
348
+ return {
349
+ "summary": final_summary,
350
+ "public_cases": public_cases,
351
+ "web_results": web_results,
352
+ "wikipedia": wiki_result
353
+ }
354
+ except Exception as e:
355
+ print(f"An error occurred in find_case_precedents: {e}")
356
+ return {
357
+ "summary": f"An error occurred while finding case precedents: {str(e)}",
358
+ "public_cases": [],
359
+ "web_results": [],
360
+ "wikipedia": {
361
+ 'title': 'Error',
362
+ 'summary': 'Unable to retrieve Wikipedia information',
363
+ 'url': ''
364
+ }
365
+ }
366
+
367
+ def estimate_legal_costs(case_type: str, complexity: str, country: str, state: str = None) -> Dict[str, Any]:
368
+ """
369
+ Estimates legal costs based on case type, complexity, and location.
370
+ Performs web searches for more accurate estimates and lawyer recommendations.
371
+ """
372
+ # Base cost ranges per hour (in USD) for different countries
373
+ base_costs = {
374
+ "USA": {"Simple": (150, 300), "Moderate": (250, 500), "Complex": (400, 1000)},
375
+ "UK": {"Simple": (100, 250), "Moderate": (200, 400), "Complex": (350, 800)},
376
+ "Canada": {"Simple": (125, 275), "Moderate": (225, 450), "Complex": (375, 900)},
377
+ }
378
+
379
+ # Adjust costs based on case type
380
+ case_type_multipliers = {
381
+ "Civil Litigation": 1.2,
382
+ "Criminal Defense": 1.5,
383
+ "Family Law": 1.0,
384
+ "Corporate Law": 1.3,
385
+ }
386
+
387
+ # Estimate number of hours based on complexity
388
+ estimated_hours = {
389
+ "Simple": (10, 30),
390
+ "Moderate": (30, 100),
391
+ "Complex": (100, 300)
392
+ }
393
+
394
+ # Get base cost range for the specified country and complexity
395
+ country_costs = base_costs.get(country, base_costs["USA"])
396
+ min_rate, max_rate = country_costs[complexity]
397
+
398
+ # Adjust rates based on case type
399
+ multiplier = case_type_multipliers.get(case_type, 1.0)
400
+ min_rate *= multiplier
401
+ max_rate *= multiplier
402
+
403
+ # Calculate total cost range
404
+ min_hours, max_hours = estimated_hours[complexity]
405
+ min_total = min_rate * min_hours
406
+ max_total = max_rate * max_hours
407
+
408
+ # Perform web search for recent cost estimates
409
+ search_query = f"{case_type} legal costs {country} {state if state else ''}"
410
+ web_results = search_web(search_query)
411
+
412
+ web_estimates = []
413
+ for result in web_results:
414
+ estimates = extract_cost_estimates(result['snippet'])
415
+ if estimates:
416
+ web_estimates.append({
417
+ 'source': result['title'],
418
+ 'link': result['link'],
419
+ 'estimates': estimates
420
+ })
421
+
422
+ # Search for lawyers or law firms
423
+ lawyer_search_query = f"top rated {case_type} lawyers {country} {state if state else ''}"
424
+ lawyer_results = search_web(lawyer_search_query)
425
+
426
+ # Generate cost breakdown
427
+ cost_breakdown = {
428
+ "Hourly rate range": f"${min_rate:.2f} - ${max_rate:.2f}",
429
+ "Estimated hours": f"{min_hours} - {max_hours}",
430
+ "Total cost range": f"${min_total:.2f} - ${max_total:.2f}",
431
+ "Web search estimates": web_estimates
432
+ }
433
+
434
+ # Potential high-cost areas
435
+ high_cost_areas = [
436
+ "Expert witnesses (especially in complex cases)",
437
+ "Extensive document review and e-discovery",
438
+ "Multiple depositions",
439
+ "Prolonged trial periods",
440
+ "Appeals process"
441
+ ]
442
+
443
+ # Cost-saving tips
444
+ cost_saving_tips = [
445
+ "Consider alternative dispute resolution methods like mediation or arbitration",
446
+ "Be organized and provide all relevant documents upfront to reduce billable hours",
447
+ "Communicate efficiently with your lawyer, bundling questions when possible",
448
+ "Ask for detailed invoices and review them carefully",
449
+ "Discuss fee arrangements, such as flat fees or contingency fees, where applicable"
450
+ ]
451
+
452
+ lawyer_tips = [
453
+ "Research and compare multiple lawyers or law firms",
454
+ "Ask for references and read client reviews",
455
+ "Discuss fee structures and payment plans upfront",
456
+ "Consider lawyers with specific expertise in your case type",
457
+ "Ensure clear communication and understanding of your case"
458
+ ]
459
+
460
+ return {
461
+ "cost_breakdown": cost_breakdown,
462
+ "high_cost_areas": high_cost_areas,
463
+ "cost_saving_tips": cost_saving_tips,
464
+ "lawyer_recommendations": lawyer_results,
465
+ "finding_best_lawyer_tips": lawyer_tips,
466
+ "web_search_results": web_results # Add this new key
467
+ }
468
+
469
+ def legal_cost_estimator_ui():
470
+ st.subheader("Legal Cost Estimator")
471
+
472
+ case_type = st.selectbox("Select case type", ["Civil Litigation", "Criminal Defense", "Family Law", "Corporate Law"])
473
+ complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"])
474
+ country = st.selectbox("Select country", ["USA", "UK", "Canada"])
475
+
476
+ if country == "USA":
477
+ state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"])
478
+ else:
479
+ state = None
480
+
481
+ if st.button("Estimate Costs"):
482
+ with st.spinner("Estimating costs and performing web search..."):
483
+ cost_estimate = estimate_legal_costs(case_type, complexity, country, state)
484
+
485
+ st.write("### Estimated Legal Costs")
486
+ for key, value in cost_estimate["cost_breakdown"].items():
487
+ if key != "Web search estimates":
488
+ st.write(f"**{key}:** {value}")
489
+
490
+ st.write("### Web Search Estimates")
491
+ if cost_estimate["cost_breakdown"]["Web search estimates"]:
492
+ for result in cost_estimate["cost_breakdown"]["Web search estimates"]:
493
+ st.write(f"**Source:** [{result['source']}]({result['link']})")
494
+ st.write("**Estimated Costs:**")
495
+ for estimate in result['estimates']:
496
+ st.write(f"- {estimate}")
497
+ st.write("---")
498
+ else:
499
+ st.write("No specific cost estimates found from web search.")
500
+
501
+ st.write("### Potential High-Cost Areas")
502
+ for area in cost_estimate["high_cost_areas"]:
503
+ st.write(f"- {area}")
504
+
505
+ st.write("### Cost-Saving Tips")
506
+ for tip in cost_estimate["cost_saving_tips"]:
507
+ st.write(f"- {tip}")
508
+
509
+ st.write("### Recommended Lawyers/Law Firms")
510
+ for lawyer in cost_estimate["lawyer_recommendations"][:5]: # Display top 5 recommendations
511
+ st.write(f"**[{lawyer['title']}]({lawyer['link']})**")
512
+ st.write(lawyer["snippet"])
513
+ st.write("---")
514
+
515
+ def extract_cost_estimates(text: str) -> List[str]:
516
+ """
517
+ Extracts cost estimates from the given text.
518
+ """
519
+ patterns = [
520
+ r'\$\d{1,3}(?:,\d{3})*(?:\.\d{2})?', # Matches currency amounts like $1,000.00
521
+ r'\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|GBP|CAD|EUR)', # Matches amounts with currency codes
522
+ r'(?:USD|GBP|CAD|EUR)\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?' # Matches currency codes before amounts
523
+ ]
524
+
525
+ estimates = []
526
+ for pattern in patterns:
527
+ matches = re.findall(pattern, text)
528
+ estimates.extend(matches)
529
+
530
+ return estimates
531
+
532
+ def generate_legal_form(form_type: str, user_details: Dict[str, str], nation: str, state: str = None) -> Dict[str, Any]:
533
+ """
534
+ Generates a legal form based on user input, nation, and state (if applicable).
535
+ Creates downloadable .txt and .docx files.
536
+ """
537
+ current_date = datetime.now().strftime("%B %d, %Y")
538
+
539
+ # Helper function to get jurisdiction-specific clauses
540
+ def get_jurisdiction_clauses(form_type, nation, state):
541
+ # This would ideally be a comprehensive database of clauses for different jurisdictions
542
+ # For demonstration, we'll use a simplified version
543
+ clauses = {
544
+ "USA": {
545
+ "Power of Attorney": "This Power of Attorney is governed by the laws of the State of {state}.",
546
+ "Non-Disclosure Agreement": "This Agreement shall be governed by and construed in accordance with the laws of the State of {state}.",
547
+ "Simple Will": "This Will shall be construed in accordance with the laws of the State of {state}.",
548
+ "Lease Agreement": "This Lease Agreement is subject to the landlord-tenant laws of the State of {state}.",
549
+ "Employment Contract": "This Employment Contract is governed by the labor laws of the State of {state}."
550
+ },
551
+ "UK": {
552
+ "Power of Attorney": "This Power of Attorney is governed by the laws of England and Wales.",
553
+ "Non-Disclosure Agreement": "This Agreement shall be governed by and construed in accordance with the laws of England and Wales.",
554
+ "Simple Will": "This Will shall be construed in accordance with the laws of England and Wales.",
555
+ "Lease Agreement": "This Lease Agreement is subject to the landlord and tenant laws of England and Wales.",
556
+ "Employment Contract": "This Employment Contract is governed by the employment laws of England and Wales."
557
+ },
558
+ # Add more countries as needed
559
+ }
560
+ return clauses.get(nation, {}).get(form_type, "").format(state=state)
561
+
562
+ jurisdiction_clause = get_jurisdiction_clauses(form_type, nation, state)
563
+
564
+ if form_type == "Power of Attorney":
565
+ form_content = f"""
566
+ POWER OF ATTORNEY
567
+
568
+ This Power of Attorney is made on {current_date}.
569
+
570
+ I, {user_details['principal_name']}, hereby appoint {user_details['agent_name']} as my Attorney-in-Fact ("Agent").
571
+
572
+ 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:
573
+
574
+ 1. {', '.join(user_details['powers'])}
575
+
576
+ This Power of Attorney shall become effective immediately and shall continue until it is revoked by me.
577
+
578
+ {jurisdiction_clause}
579
+
580
+ Signed this {current_date}.
581
+
582
+ ______________________
583
+ {user_details['principal_name']} (Principal)
584
+
585
+ ______________________
586
+ {user_details['agent_name']} (Agent)
587
+
588
+ ______________________
589
+ Witness
590
+
591
+ ______________________
592
+ Witness
593
+ """
594
+
595
+ elif form_type == "Non-Disclosure Agreement":
596
+ form_content = f"""
597
+ NON-DISCLOSURE AGREEMENT
598
+
599
+ This Non-Disclosure Agreement (the "Agreement") is entered into on {current_date} by and between:
600
+
601
+ {user_details['party_a']} ("Party A")
602
+ and
603
+ {user_details['party_b']} ("Party B")
604
+
605
+ 1. Purpose: This Agreement is entered into for the purpose of {user_details['purpose']}.
606
+
607
+ 2. Confidential Information: Both parties may disclose certain confidential and proprietary information to each other in connection with the Purpose.
608
+
609
+ 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.
610
+
611
+ {jurisdiction_clause}
612
+
613
+ IN WITNESS WHEREOF, the parties hereto have executed this Non-Disclosure Agreement as of the date first above written.
614
+
615
+ ______________________
616
+ {user_details['party_a']}
617
+
618
+ ______________________
619
+ {user_details['party_b']}
620
+ """
621
+
622
+ elif form_type == "Simple Will":
623
+ beneficiaries = user_details['beneficiaries'].split('\n')
624
+ 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)])
625
+
626
+ form_content = f"""
627
+ LAST WILL AND TESTAMENT
628
+
629
+ 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.
630
+
631
+ 1. EXECUTOR: I appoint {user_details['executor_name']} to be the Executor of this, my Last Will and Testament.
632
+
633
+ 2. BEQUESTS:
634
+ {beneficiary_clauses}
635
+
636
+ 3. RESIDUARY ESTATE: I give, devise, and bequeath all the rest, residue, and remainder of my estate to [insert beneficiary or beneficiaries].
637
+
638
+ 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.
639
+
640
+ {jurisdiction_clause}
641
+
642
+ IN WITNESS WHEREOF, I have hereunto set my hand to this my Last Will and Testament on {current_date}.
643
+
644
+ ______________________
645
+ {user_details['testator_name']} (Testator)
646
+
647
+ WITNESSES:
648
+ 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:
649
+
650
+ ______________________
651
+ Witness 1
652
+
653
+ ______________________
654
+ Witness 2
655
+ """
656
+
657
+ elif form_type == "Lease Agreement":
658
+ form_content = f"""
659
+ LEASE AGREEMENT
660
+
661
+ This Lease Agreement (the "Lease") is made on {current_date} by and between:
662
+
663
+ {user_details['landlord_name']} ("Landlord")
664
+ and
665
+ {user_details['tenant_name']} ("Tenant")
666
+
667
+ 1. PREMISES: The Landlord hereby leases to the Tenant the property located at {user_details['property_address']}.
668
+
669
+ 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']}.
670
+
671
+ 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.
672
+
673
+ 4. SECURITY DEPOSIT: The Tenant shall pay a security deposit of {user_details['security_deposit']} upon signing this Lease.
674
+
675
+ {jurisdiction_clause}
676
+
677
+ IN WITNESS WHEREOF, the parties hereto have executed this Lease Agreement as of the date first above written.
678
+
679
+ ______________________
680
+ {user_details['landlord_name']} (Landlord)
681
+
682
+ ______________________
683
+ {user_details['tenant_name']} (Tenant)
684
+ """
685
+
686
+ elif form_type == "Employment Contract":
687
+ form_content = f"""
688
+ EMPLOYMENT CONTRACT
689
+
690
+ This Employment Contract (the "Contract") is made on {current_date} by and between:
691
+
692
+ {user_details['employer_name']} ("Employer")
693
+ and
694
+ {user_details['employee_name']} ("Employee")
695
+
696
+ 1. POSITION: The Employee is hired for the position of {user_details['job_title']}.
697
+
698
+ 2. DUTIES: The Employee's duties shall include, but are not limited to: {user_details['job_duties']}.
699
+
700
+ 3. COMPENSATION: The Employee shall be paid a {user_details['pay_frequency']} salary of {user_details['salary_amount']}.
701
+
702
+ 4. TERM: This Contract shall commence on {user_details['start_date']} and continue until terminated by either party.
703
+
704
+ 5. BENEFITS: The Employee shall be entitled to the following benefits: {user_details['benefits']}.
705
+
706
+ {jurisdiction_clause}
707
+
708
+ IN WITNESS WHEREOF, the parties hereto have executed this Employment Contract as of the date first above written.
709
+
710
+ ______________________
711
+ {user_details['employer_name']} (Employer)
712
+
713
+ ______________________
714
+ {user_details['employee_name']} (Employee)
715
+ """
716
+
717
+ else:
718
+ return {"error": "Unsupported form type"}
719
+
720
+ # Generate .txt file
721
+ txt_file = io.StringIO()
722
+ txt_file.write(form_content)
723
+ txt_file.seek(0)
724
+
725
+ # Generate .docx file
726
+ docx_file = io.BytesIO()
727
+ doc = Document()
728
+ doc.add_paragraph(form_content)
729
+ doc.save(docx_file)
730
+ docx_file.seek(0)
731
+
732
+ return {
733
+ "form_content": form_content,
734
+ "txt_file": txt_file,
735
+ "docx_file": docx_file
736
+ }
737
+
738
+ CASE_TYPES = [
739
+ "Civil Rights", "Contract", "Real Property", "Tort", "Labor", "Intellectual Property",
740
+ "Bankruptcy", "Immigration", "Social Security", "Tax", "Constitutional", "Criminal",
741
+ "Environmental", "Antitrust", "Securities", "Administrative", "Admiralty", "Family Law",
742
+ "Probate", "Personal Injury"
743
+ ]
744
+
745
+ DATA_SOURCES = {
746
+ "Civil Rights": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
747
+ "Contract": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
748
+ "Real Property": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
749
+ "Tort": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
750
+ "Labor": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
751
+ "Intellectual Property": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
752
+ "Bankruptcy": "https://www.uscourts.gov/sites/default/files/data_tables/jb_f_0930.2022.pdf",
753
+ "Immigration": "https://www.justice.gov/eoir/workload-and-adjudication-statistics",
754
+ "Social Security": "https://www.ssa.gov/open/data/hearings-and-appeals-filed.html",
755
+ "Tax": "https://www.ustaxcourt.gov/statistics.html",
756
+ "Constitutional": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
757
+ "Criminal": "https://www.uscourts.gov/sites/default/files/data_tables/jb_d1_0930.2022.pdf",
758
+ "Environmental": "https://www.epa.gov/enforcement/enforcement-annual-results-numbers-glance-fiscal-year-2022",
759
+ "Antitrust": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
760
+ "Securities": "https://www.sec.gov/files/enforcement-annual-report-2022.pdf",
761
+ "Administrative": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
762
+ "Admiralty": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
763
+ "Family Law": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
764
+ "Probate": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf",
765
+ "Personal Injury": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf"
766
+ }
767
+
768
+ def fetch_case_data(case_type: str) -> pd.DataFrame:
769
+ """Fetches actual historical data for the given case type."""
770
+ url = DATA_SOURCES[case_type]
771
+ response = requests.get(url)
772
+ if response.status_code == 200:
773
+ if url.endswith('.pdf'):
774
+ # For PDF sources, we'll use a placeholder DataFrame
775
+ # In a real-world scenario, you'd need to implement PDF parsing
776
+ df = pd.DataFrame({
777
+ 'Year': range(2013, 2023),
778
+ 'Number of Cases': [random.randint(1000, 5000) for _ in range(10)]
779
+ })
780
+ else:
781
+ # For non-PDF sources, we'll assume CSV format
782
+ df = pd.read_csv(StringIO(response.text))
783
+ else:
784
+ st.error(f"Failed to fetch data for {case_type}. Using placeholder data.")
785
+ df = pd.DataFrame({
786
+ 'Year': range(2013, 2023),
787
+ 'Number of Cases': [random.randint(1000, 5000) for _ in range(10)]
788
+ })
789
+ return df
790
+
791
+ def visualize_case_trends(case_type: str):
792
+ """Visualizes case trends based on case type using actual historical data."""
793
+ df = fetch_case_data(case_type)
794
+
795
+ fig = px.line(df, x='Year', y='Number of Cases', title=f"Trend of {case_type} Cases")
796
+ fig.update_layout(
797
+ xaxis_title="Year",
798
+ yaxis_title="Number of Cases",
799
+ hovermode="x unified"
800
+ )
801
+ fig.update_traces(mode="lines+markers")
802
+
803
+ return fig, df # Return both the image and the raw data
804
+
805
+ # --- Streamlit App ---
806
+ # Custom CSS to improve the overall look
807
+ st.markdown("""
808
+ <style>
809
+ .reportview-container {
810
+ background: #f0f2f6;
811
+ }
812
+ .main .block-container {
813
+ padding-top: 2rem;
814
+ padding-bottom: 2rem;
815
+ padding-left: 5rem;
816
+ padding-right: 5rem;
817
+ }
818
+ h1 {
819
+ color: #1E3A8A;
820
+ }
821
+ h2 {
822
+ color: #3B82F6;
823
+ }
824
+ .stButton>button {
825
+ background-color: #3B82F6;
826
+ color: white;
827
+ border-radius: 5px;
828
+ }
829
+ .stTextInput>div>div>input {
830
+ border-radius: 5px;
831
+ }
832
+ </style>
833
+ """, unsafe_allow_html=True)
834
+
835
+ def load_lottieurl(url: str):
836
+ try:
837
+ r = requests.get(url)
838
+ r.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xx
839
+ return r.json()
840
+ except requests.HTTPError as http_err:
841
+ print(f"HTTP error occurred while loading Lottie animation: {http_err}")
842
+ except requests.RequestException as req_err:
843
+ print(f"Error occurred while loading Lottie animation: {req_err}")
844
+ except ValueError as json_err:
845
+ print(f"Error decoding JSON for Lottie animation: {json_err}")
846
+ return None
847
+
848
+ # Streamlit App
849
+ st.title("Lex AI - Advanced Legal Assistant")
850
+
851
+ # Sidebar with feature selection
852
+ with st.sidebar:
853
+ st.title(" AI")
854
+ st.subheader("Advanced Legal Assistant")
855
+
856
+ feature = st.selectbox(
857
+ "Select a feature",
858
+ ["Legal Chatbot", "Document Analysis", "Case Precedent Finder", "Legal Cost Estimator", "Legal Form Generator", "Case Trend Visualizer"]
859
+ )
860
+ if feature == "Legal Chatbot":
861
+ st.subheader("Legal Chatbot")
862
+
863
+ if 'chat_history' not in st.session_state:
864
+ st.session_state.chat_history = []
865
+
866
+ display_chat_history()
867
+
868
+ user_input = st.text_input("Your legal question:")
869
+
870
+ if user_input and st.button("Send"):
871
+ with st.spinner("Searching for information..."):
872
+ ai_response = get_ai_response(user_input)
873
+
874
+ # Add user message and AI response to chat history
875
+ st.session_state.chat_history.append((user_input, ai_response))
876
+
877
+ # Perform Wikipedia search
878
+ wiki_result = search_wikipedia(user_input)
879
+
880
+ # Add Wikipedia result to chat history
881
+ st.session_state.chat_history.append({
882
+ 'type': 'wikipedia',
883
+ 'summary': wiki_result.get("summary", "No summary available."),
884
+ 'url': wiki_result.get("url", "")
885
+ })
886
+
887
+ # Perform web search
888
+ web_results = search_web(user_input)
889
+
890
+ # Add web search results to chat history
891
+ st.session_state.chat_history.append({
892
+ 'type': 'web_search',
893
+ 'results': web_results
894
+ })
895
+
896
+ st.rerun()
897
+
898
+ elif feature == "Document Analysis":
899
+ st.subheader("Legal Document Analyzer")
900
+
901
+ uploaded_file = st.file_uploader("Upload a legal document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])
902
+
903
+ if uploaded_file and st.button("Analyze Document"):
904
+ with st.spinner("Analyzing document and gathering additional information..."):
905
+ try:
906
+ document_content = analyze_document(uploaded_file)
907
+ analysis_results = comprehensive_document_analysis(document_content)
908
+
909
+ st.write("Document Analysis:")
910
+ st.write(analysis_results.get("document_analysis", "No analysis available."))
911
+
912
+ st.write("Related Articles:")
913
+ for article in analysis_results.get("related_articles", []):
914
+ st.write(f"- [{article.get('title', 'No title')}]({article.get('link', '#')})")
915
+ st.write(f" {article.get('snippet', 'No snippet available.')}")
916
+
917
+ st.write("Wikipedia Summary:")
918
+ wiki_info = analysis_results.get("wikipedia_summary", {})
919
+ st.write(f"**{wiki_info.get('title', 'No title')}**")
920
+ st.write(wiki_info.get('summary', 'No summary available.'))
921
+ if wiki_info.get('url'):
922
+ st.write(f"[Read more on Wikipedia]({wiki_info['url']})")
923
+ except Exception as e:
924
+ st.error(f"An error occurred during document analysis: {str(e)}")
925
+
926
+ elif feature == "Case Precedent Finder":
927
+ st.subheader("Case Precedent Finder")
928
+
929
+ # Initialize session state for precedents if not exists
930
+ if 'precedents' not in st.session_state:
931
+ st.session_state.precedents = None
932
+
933
+ # Initialize session state for visibility toggles if not exists
934
+ if 'visibility_toggles' not in st.session_state:
935
+ st.session_state.visibility_toggles = {}
936
+
937
+ case_details = st.text_area("Enter case details:")
938
+ if st.button("Find Precedents"):
939
+ with st.spinner("Searching for relevant case precedents..."):
940
+ try:
941
+ st.session_state.precedents = find_case_precedents(case_details)
942
+ except Exception as e:
943
+ st.error(f"An error occurred while finding case precedents: {str(e)}")
944
+
945
+ # Display results if precedents are available
946
+ if st.session_state.precedents:
947
+ precedents = st.session_state.precedents
948
+
949
+ st.write("### Summary of Relevant Case Precedents")
950
+ st.markdown(precedents["summary"])
951
+
952
+ st.write("### Related Cases from Public Databases")
953
+ for i, case in enumerate(precedents["public_cases"], 1):
954
+ st.write(f"**{i}. {case['case_name']} - {case['citation']}**")
955
+ st.write(f"Summary: {case['summary']}")
956
+ st.write(f"[Read full case]({case['url']})")
957
+ st.write("---")
958
+
959
+ st.write("### Additional Web Results")
960
+ for i, result in enumerate(precedents["web_results"], 1):
961
+ st.write(f"**{i}. [{result['title']}]({result['link']})**")
962
+
963
+ # Create a unique key for each toggle
964
+ toggle_key = f"toggle_{i}"
965
+
966
+ # Initialize the toggle state if it doesn't exist
967
+ if toggle_key not in st.session_state.visibility_toggles:
968
+ st.session_state.visibility_toggles[toggle_key] = False
969
+
970
+ # Create a button to toggle visibility
971
+ if st.button(f"{'Hide' if st.session_state.visibility_toggles[toggle_key] else 'Show'} Full Details for Result {i}", key=f"button_{i}"):
972
+ st.session_state.visibility_toggles[toggle_key] = not st.session_state.visibility_toggles[toggle_key]
973
+
974
+ # Show full details if toggle is True
975
+ if st.session_state.visibility_toggles[toggle_key]:
976
+ # Fetch and display more detailed content
977
+ detailed_content = fetch_detailed_content(result['link'])
978
+ st.markdown(detailed_content)
979
+ else:
980
+ # Show a brief summary when details are hidden
981
+ brief_summary = result['snippet'].split('\n')[0][:200] + "..." if len(result['snippet']) > 200 else result['snippet'].split('\n')[0]
982
+ st.write(f"Brief Summary: {brief_summary}")
983
+
984
+ st.write("---")
985
+
986
+ st.write("### Wikipedia Information")
987
+ wiki_info = precedents["wikipedia"]
988
+ st.write(f"**[{wiki_info['title']}]({wiki_info['url']})**")
989
+ st.markdown(wiki_info['summary'])
990
+
991
+ elif feature == "Legal Cost Estimator":
992
+ st.subheader("Legal Cost Estimator")
993
+
994
+ case_type = st.selectbox("Select case type", ["Civil Litigation", "Criminal Defense", "Family Law", "Corporate Law"], key="cost_estimator_case_type")
995
+ complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"], key="cost_estimator_complexity")
996
+ country = st.selectbox("Select country", ["USA", "UK", "Canada"], key="cost_estimator_country")
997
+
998
+ if country == "USA":
999
+ state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"], key="cost_estimator_state")
1000
+ else:
1001
+ state = None
1002
+
1003
+ # Initialize cost_estimate
1004
+ cost_estimate = None
1005
+
1006
+ if st.button("Estimate Costs"):
1007
+ with st.spinner("Estimating costs and performing web search..."):
1008
+ cost_estimate = estimate_legal_costs(case_type, complexity, country, state)
1009
+
1010
+ # Check if cost_estimate is available before displaying results
1011
+ if cost_estimate:
1012
+ st.write("### Estimated Legal Costs")
1013
+ for key, value in cost_estimate["cost_breakdown"].items():
1014
+ st.write(f"**{key}:** {value}")
1015
+
1016
+ st.write("### Web Search Results")
1017
+ if cost_estimate["web_search_results"]:
1018
+ for result in cost_estimate["web_search_results"]:
1019
+ st.write(f"**[{result['title']}]({result['link']})**")
1020
+ st.write(result["snippet"])
1021
+ st.write("---")
1022
+ else:
1023
+ st.write("No specific cost estimates found from web search.")
1024
+
1025
+ st.write("### Potential High-Cost Areas")
1026
+ for area in cost_estimate["high_cost_areas"]:
1027
+ st.write(f"- {area}")
1028
+
1029
+ st.write("### Cost-Saving Tips")
1030
+ for tip in cost_estimate["cost_saving_tips"]:
1031
+ st.write(f"- {tip}")
1032
+
1033
+ st.write("### Tips for Finding the Best Legal Representation")
1034
+ for tip in cost_estimate["finding_best_lawyer_tips"]:
1035
+ st.write(f"- {tip}")
1036
+
1037
+ st.write("### Recommended Lawyers/Law Firms")
1038
+ for lawyer in cost_estimate["lawyer_recommendations"][:5]: # Display top 5 recommendations
1039
+ st.write(f"**[{lawyer['title']}]({lawyer['link']})**")
1040
+ st.write(lawyer["snippet"])
1041
+ st.write("---")
1042
+ else:
1043
+ st.write("Click 'Estimate Costs' to see the results.")
1044
+
1045
+ elif feature == "Legal Form Generator":
1046
+ st.subheader("Legal Form Generator")
1047
+
1048
+ form_type = st.selectbox("Select form type", ["Power of Attorney", "Non-Disclosure Agreement", "Simple Will", "Lease Agreement", "Employment Contract"], key="form_generator_type")
1049
+
1050
+ nation = st.selectbox("Select nation", ["USA", "UK"], key="form_generator_nation")
1051
+ if nation == "USA":
1052
+ state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"], key="form_generator_state")
1053
+ else:
1054
+ state = None
1055
+
1056
+ user_details = {}
1057
+ if form_type == "Power of Attorney":
1058
+ user_details["principal_name"] = st.text_input("Principal's Full Name:")
1059
+ user_details["agent_name"] = st.text_input("Agent's Full Name:")
1060
+ user_details["powers"] = st.multiselect("Select powers to grant", ["Financial Decisions", "Healthcare Decisions", "Real Estate Transactions"])
1061
+ elif form_type == "Non-Disclosure Agreement":
1062
+ user_details["party_a"] = st.text_input("First Party's Name:")
1063
+ user_details["party_b"] = st.text_input("Second Party's Name:")
1064
+ user_details["purpose"] = st.text_input("Purpose of Disclosure:")
1065
+ user_details["duration"] = st.number_input("Duration of Agreement (in years):", min_value=1, max_value=10)
1066
+ elif form_type == "Simple Will":
1067
+ user_details["testator_name"] = st.text_input("Testator's Full Name:")
1068
+ user_details["beneficiaries"] = st.text_area("List Beneficiaries (one per line):")
1069
+ user_details["executor_name"] = st.text_input("Executor's Full Name:")
1070
+ elif form_type == "Lease Agreement":
1071
+ user_details["landlord_name"] = st.text_input("Landlord's Full Name:")
1072
+ user_details["tenant_name"] = st.text_input("Tenant's Full Name:")
1073
+ user_details["property_address"] = st.text_input("Property Address:")
1074
+ user_details["lease_term"] = st.number_input("Lease Term (in months):", min_value=1, max_value=60)
1075
+ user_details["start_date"] = st.date_input("Lease Start Date:")
1076
+ user_details["end_date"] = st.date_input("Lease End Date:")
1077
+ user_details["rent_amount"] = st.number_input("Monthly Rent Amount:", min_value=0)
1078
+ user_details["rent_due_day"] = st.number_input("Rent Due Day of Month:", min_value=1, max_value=31)
1079
+ user_details["security_deposit"] = st.number_input("Security Deposit Amount:", min_value=0)
1080
+ elif form_type == "Employment Contract":
1081
+ user_details["employer_name"] = st.text_input("Employer's Full Name:")
1082
+ user_details["employee_name"] = st.text_input("Employee's Full Name:")
1083
+ user_details["job_title"] = st.text_input("Job Title:")
1084
+ user_details["job_duties"] = st.text_area("Job Duties:")
1085
+ user_details["pay_frequency"] = st.selectbox("Pay Frequency:", ["Weekly", "Bi-weekly", "Monthly"])
1086
+ user_details["salary_amount"] = st.number_input("Salary Amount:", min_value=0)
1087
+ user_details["start_date"] = st.date_input("Employment Start Date:")
1088
+ user_details["benefits"] = st.text_area("Employee Benefits:")
1089
+
1090
+ if st.button("Generate Form"):
1091
+ generated_form = generate_legal_form(form_type, user_details, nation, state)
1092
+
1093
+ if "error" in generated_form:
1094
+ st.error(generated_form["error"])
1095
+ else:
1096
+ st.write("### Generated Legal Form:")
1097
+ st.text(generated_form["form_content"])
1098
+
1099
+ # Provide download buttons for .txt and .docx files
1100
+ txt_download = generated_form["txt_file"].getvalue()
1101
+ docx_download = generated_form["docx_file"].getvalue()
1102
+
1103
+ st.download_button(
1104
+ label="Download as .txt",
1105
+ data=txt_download,
1106
+ file_name=f"{form_type.lower().replace(' ', '_')}_{nation}{'_' + state if state else ''}.txt",
1107
+ mime="text/plain"
1108
+ )
1109
+
1110
+ st.download_button(
1111
+ label="Download as .docx",
1112
+ data=docx_download,
1113
+ file_name=f"{form_type.lower().replace(' ', '_')}_{nation}{'_' + state if state else ''}.docx",
1114
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
1115
+ )
1116
+
1117
+ 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.")
1118
+
1119
+ elif feature == "Case Trend Visualizer":
1120
+ st.subheader("Case Trend Visualizer")
1121
+
1122
+ case_type = st.selectbox("Select case type to visualize", CASE_TYPES)
1123
+
1124
+ if st.button("Visualize Trend") or 'df' in st.session_state:
1125
+ with st.spinner("Fetching and visualizing data..."):
1126
+ if 'df' not in st.session_state:
1127
+ fig, df = visualize_case_trends(case_type)
1128
+ st.session_state.df = df
1129
+ st.session_state.fig = fig
1130
+ else:
1131
+ df = st.session_state.df
1132
+ fig = st.session_state.fig
1133
+
1134
+ st.plotly_chart(fig, use_container_width=True)
1135
+
1136
+ # Display statistics
1137
+ st.subheader("Case Statistics")
1138
+ total_cases = df['Number of Cases'].sum()
1139
+ avg_cases = df['Number of Cases'].mean()
1140
+ max_year = df.loc[df['Number of Cases'].idxmax(), 'Year']
1141
+ min_year = df.loc[df['Number of Cases'].idxmin(), 'Year']
1142
+
1143
+ col1, col2, col3 = st.columns(3)
1144
+ col1.metric("Total Cases", f"{total_cases:,}")
1145
+ col2.metric("Average Cases per Year", f"{avg_cases:,.0f}")
1146
+ col3.metric("Years", f"{min_year} - {max_year}")
1147
+
1148
+ # Raw Data
1149
+ st.subheader("Raw Data")
1150
+ st.dataframe(df)
1151
+
1152
+ # Download options
1153
+ csv = df.to_csv(index=False)
1154
+ st.download_button(
1155
+ label="Download data as CSV",
1156
+ data=csv,
1157
+ file_name=f"{case_type.lower().replace(' ', '_')}_trend_data.csv",
1158
+ mime="text/csv",
1159
+ )
1160
+
1161
+ # Additional resources
1162
+ st.subheader("Additional Resources")
1163
+ st.markdown(f"[Data Source]({DATA_SOURCES[case_type]})")
1164
+ st.markdown("[US Courts Statistics](https://www.uscourts.gov/statistics-reports)")
1165
+ st.markdown("[Federal Judicial Caseload Statistics](https://www.uscourts.gov/statistics-reports/analysis-reports/federal-judicial-caseload-statistics)")
1166
+ st.markdown(f"[Legal Information Institute](https://www.law.cornell.edu/wex/{case_type.lower().replace(' ', '_')})")
1167
+
1168
+ # Explanatory text
1169
+ st.subheader("Understanding the Trend")
1170
+ explanation = f"""
1171
+ The graph above shows the trend of {case_type} cases over time. Here are some key points to consider:
1172
+
1173
+ 1. Overall Trend: Observe whether the number of cases is generally increasing, decreasing, or remaining stable over the years.
1174
+ 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.
1175
+ 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.
1176
+ 4. Recent Trends: Pay attention to the most recent years to understand current patterns in {case_type} cases.
1177
+ 5. Contextual Factors: Remember that these numbers can be influenced by various factors, including changes in law, court procedures, societal changes, and more.
1178
+
1179
+ For a deeper understanding of these trends and their implications, consider consulting with legal professionals or reviewing academic research in this area.
1180
+ """
1181
+ st.markdown(explanation)
1182
+
1183
+ # Interactive elements
1184
+ st.subheader("Interactive Analysis")
1185
+ analysis_type = st.radio("Select analysis type:", ["Year-over-Year Change", "Moving Average"])
1186
+
1187
+ if analysis_type == "Year-over-Year Change":
1188
+ df['YoY Change'] = df['Number of Cases'].pct_change() * 100
1189
+ yoy_fig = px.bar(df, x='Year', y='YoY Change', title="Year-over-Year Change in Case Numbers")
1190
+ st.plotly_chart(yoy_fig, use_container_width=True)
1191
+
1192
+ elif analysis_type == "Moving Average":
1193
+ window = st.slider("Select moving average window:", 2, 5, 3)
1194
+ df['Moving Average'] = df['Number of Cases'].rolling(window=window).mean()
1195
+ ma_fig = px.line(df, x='Year', y=['Number of Cases', 'Moving Average'], title=f"{window}-Year Moving Average")
1196
+ st.plotly_chart(ma_fig, use_container_width=True)
1197
+
1198
+ # Add a footer with a disclaimer
1199
+ # Footer
1200
+ st.markdown("---")
1201
+ st.markdown(
1202
+ """
1203
+ <div style="text-align: center;">
1204
+ <p>© 2023 Lex AI. All rights reserved.</p>
1205
+ <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>
1206
+ </div>
1207
+ """,
1208
+ unsafe_allow_html=True
1209
+ )
1210
+
1211
+ if __name__ == "__main__":
1212
+ st.sidebar.info("Select a feature from the dropdown above to get started.")