Johan713 commited on
Commit
515b6b0
·
verified ·
1 Parent(s): 1fb6f0e

Upload 3 files

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