Johan713 commited on
Commit
4e87677
·
verified ·
1 Parent(s): b806747

Delete app3copy.py

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