Update app2.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424import gradio as grfrom dataclasses import dataclassimport osfrom uuid import uuid4import requestsimport wikipediaimport googlesearchfrom sentence_transformers import SentenceTransformerimport PyPDF2import docximport faissimport numpy as npimport jsonimport refrom sklearn.feature_extraction.text import TfidfVectorizerfrom concurrent.futures import ThreadPoolExecutorimport nltkimport spacyfrom dotenv import load_dotenvload_dotenv()nltk.download('wordnet')nltk.download('punkt')try:spacy.cli.download("en_core_web_sm")except Exception as e:print(f"Error downloading spacy model: {e}")DEPLOYED = os.getenv("DEPLOYED", "false").lower() == "true"MODEL_NAME = "tiiuae/falcon-180B-chat"HEADERS = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}ENDPOINT_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"DEFAULT_INSTRUCTIONS = """LexAI is an advanced legal AI assistant powered by Falcon 180B, with capabilities including contract analysis, legal research, predictive litigation analysis, intelligent legal drafting, answering common legal questions, document summarization, legal entity recognition, sentiment analysis, and more. LexAI can perform document retrieval, Wikipedia searches, and internet searches to provide comprehensive assistance."""sentence_model = SentenceTransformer('all-MiniLM-L6-v2')ner_model = spacy.load("en_core_web_sm")index = faiss.IndexFlatL2(384)tfidf_vectorizer = TfidfVectorizer(stop_words='english')@dataclassclass Rating:prompt: strresponse: strratings: list[str]class Document:def __init__(self, content: str, metadata: dict):self.content = contentself.metadata = metadataself.embedding = Nonedef compute_embedding(self):self.embedding = sentence_model.encode([self.content])[0]class DocumentStore:def __init__(self):self.documents = []self.index = faiss.IndexFlatL2(384)def add_document(self, document: Document):document.compute_embedding()self.documents.append(document)self.index.add(np.array([document.embedding]))def search(self, query: str, k: int = 5):query_vector = sentence_model.encode([query])[0]distances, indices = self.index.search(np.array([query_vector]), k)return [self.documents[i] for i in indices[0]]document_store = DocumentStore()def extract_text_from_file(file):if file.name.endswith('.pdf'):reader = PyPDF2.PdfReader(file)text = ""for page in reader.pages:text += page.extract_text()elif file.name.endswith('.docx'):doc = docx.Document(file)text = "\n".join([paragraph.text for paragraph in doc.paragraphs])else:text = file.read().decode('utf-8')return textdef query_falcon(prompt: str, max_tokens: int = 100, temperature: float = 0.7) -> str:payload = {"inputs": prompt,"parameters": {"max_new_tokens": max_tokens,"do_sample": True,"temperature": temperature,"top_p": 0.9,"stop": ["User:"]}}response = requests.post(ENDPOINT_URL, headers=HEADERS, json=payload)if response.status_code == 200:return response.json()[0]['generated_text']else:print(f"Error: {response.status_code} - {response.text}")return "Error occurred while querying Falcon 180B."def summarize_text(text: str, max_length: int = 150) -> str:prompt = f"Summarize the following text in about {max_length} words:\n\n{text}\n\nSummary:"return query_falcon(prompt, max_tokens=max_length)def extract_legal_entities(text: str):doc = ner_model(text)return [ent.text for ent in doc.ents if ent.label_ in ["PERSON", "ORG", "GPE", "LAW"]]def analyze_sentiment(text: str) -> str:prompt = f"Analyze the sentiment of the following text. Respond with either 'Positive', 'Negative', or 'Neutral':\n\n{text}\n\nSentiment:"return query_falcon(prompt, max_tokens=10)def extract_keywords(text: str, top_n: int = 5):prompt = f"Extract the top {top_n} keywords from the following text:\n\n{text}\n\nKeywords:"response = query_falcon(prompt, max_tokens=50)return [keyword.strip() for keyword in response.split(',')][:top_n]def get_legal_definitions(term: str) -> str:prompt = f"Provide a legal definition for the term '{term}':"return query_falcon(prompt, max_tokens=100).strip()def perform_case_law_search(query: str):prompt = f"Perform a case law search for the following query and provide a summary of relevant cases:\n\n{query}\n\nRelevant cases:"return query_falcon(prompt, max_tokens=200)def generate_legal_document(document_type: str, details: dict) -> str:prompt = f"Generate a {document_type} with the following details:\n"for key, value in details.items():prompt += f"{key}: {value}\n"prompt += f"\nGenerated {document_type}:"return query_falcon(prompt, max_tokens=500).strip()def perform_wikipedia_search(query):try:search_results = wikipedia.search(query)if search_results:page = wikipedia.page(search_results[0])summary = wikipedia.summary(search_results[0], sentences=3)return f"Wikipedia: {summary}\n\nFull article: {page.url}"else:return "No Wikipedia results found."except:return "Error occurred while searching Wikipedia."def perform_internet_search(query):try:search_results = list(googlesearch.search(query, num_results=3))if search_results:return "Internet search results:\n" + "\n".join(search_results)else:return "No internet search results found."except:return "Error occurred while performing internet search."def chat_accordion():with gr.Accordion("Parameters", open=False):temperature = gr.Slider(minimum=0.1,maximum=1.0,value=0.7,step=0.1,interactive=True,label="Temperature",)top_p = gr.Slider(minimum=0.1,maximum=0.99,value=0.9,step=0.01,interactive=True,label="p (nucleus sampling)",)max_tokens = gr.Slider(minimum=64,maximum=1024,value=64,step=1,interactive=True,label="Max Tokens",)session_id = gr.Textbox(value=uuid4,interactive=False,visible=False,)with gr.Accordion("Instructions", open=False, visible=False):instructions = gr.Textbox(placeholder="The Instructions",value=DEFAULT_INSTRUCTIONS,lines=16,interactive=True,label="Instructions",max_lines=16,show_label=False,)with gr.Row():with gr.Column():user_name = gr.Textbox(lines=1,label="username",value="User",interactive=True,placeholder="Username: ",show_label=False,max_lines=1,)with gr.Column():bot_name = gr.Textbox(lines=1,value="LexAI",interactive=True,placeholder="Bot Name",show_label=False,max_lines=1,visible=False,)return temperature, top_p, instructions, user_name, bot_name, session_id, max_tokensdef format_chat_prompt(message: str, chat_history, instructions: str, user_name: str, bot_name: str):instructions = instructions or DEFAULT_INSTRUCTIONSinstructions = instructions.strip()prompt = instructionsfor turn in chat_history:user_message, bot_message = turnprompt = f"{prompt}\n{user_name}: {user_message}\n{bot_name}: {bot_message}"prompt = f"{prompt}\n{user_name}: {message}\n{bot_name}:"return promptdef run_chat(message: str, history, instructions: str, user_name: str, bot_name: str, temperature: float, top_p: float, session_id: str, max_tokens: int, uploaded_file: gr.File):if uploaded_file is not None:document_text = extract_text_from_file(uploaded_file)summary = summarize_text(document_text)legal_entities = extract_legal_entities(document_text)sentiment = analyze_sentiment(document_text)keywords = extract_keywords(document_text)doc = Document(content=document_text, metadata={"filename": uploaded_file.name,"summary": summary,"legal_entities": legal_entities,"sentiment": sentiment,"keywords": keywords})document_store.add_document(doc)message += f"\n[System: A document '{uploaded_file.name}' has been uploaded and processed.]"relevant_docs = document_store.search(message)retrieved_context = "\n".join([doc.content for doc in relevant_docs])with ThreadPoolExecutor(max_workers=2) as executor:wiki_future = executor.submit(perform_wikipedia_search, message)internet_future = executor.submit(perform_internet_search, message)wiki_result = wiki_future.result()internet_result = internet_future.result()case_law_results = perform_case_law_search(message)full_context = f"""Retrieved Documents:\n{retrieved_context}Wikipedia Search:\n{wiki_result}Internet Search:\n{internet_result}Relevant Case Law:\n{case_law_results}"""prompt = format_chat_prompt(message, history, instructions, user_name, bot_name)prompt += f"\nAdditional Context:\n{full_context}\n\nBased on the above information, please provide a comprehensive response:"response = query_falcon(prompt, max_tokens=max_tokens, temperature=temperature)response = post_process_output(response, message)return responsedef post_process_output(output: str, original_query: str) -> str:if "define" in original_query.lower() or "meaning of" in original_query.lower():terms = re.findall(r'\b(?!(?:the|a|an)\b)\w+', original_query)for term in terms:definition = get_legal_definitions(term)output += f"\n\nLegal definition of '{term}': {definition}"if "draft" in original_query.lower() or "create document" in original_query.lower():doc_type_match = re.search(r'draft a (\w+)', original_query.lower())if doc_type_match:doc_type = doc_type_match.group(1)details = extract_document_details(original_query)generated_document = generate_legal_document(doc_type, details)output += f"\n\nGenerated {doc_type.capitalize()}:\n\n{generated_document}"if "analyze" in original_query.lower() and "document" in original_query.lower():sentiment = analyze_sentiment(output)output += f"\n\nOverall sentiment of the analysis: {sentiment}"return outputdef extract_document_details(query: str) -> dict:details = {}if "parties" in query.lower():details["parties"] = re.search(r'parties: (.*?)(,|\.|$)', query, re.IGNORECASE).group(1)if "date" in query.lower():details["date"] = re.search(r'date: (.*?)(,|\.|$)', query, re.IGNORECASE).group(1)if "terms" in query.lower():details["terms"] = re.search(r'terms: (.*?)(,|\.|$)', query, re.IGNORECASE).group(1)return detailsdef chat_tab():with gr.Column():with gr.Row():(temperature,top_p,instructions,user_name,bot_name,session_id,max_tokens) = chat_accordion()with gr.Column():with gr.Blocks():prompt_examples = [["Analyze this contract for potential risks and summarize key points."],["Find relevant case law for an intellectual property dispute in the software industry."],["What are the key clauses in a non-disclosure agreement? Draft a template."],["Predict the outcome of this employment discrimination case based on recent precedents."],["Draft a cease and desist letter for trademark infringement. Parties: TechCorp and InnovateNow, Date: 2023-07-22"],]file_upload = gr.File(label="Upload Legal Document for Analysis")gr.ChatInterface(fn=run_chat,chatbot=gr.Chatbot(height=620,render=False,show_label=False,avatar_images=("images/user_icon.png", "images/lexai_icon.png"),),textbox=gr.Textbox(placeholder="Ask LexAI about legal matters, analyze documents, or request drafting assistance...",render=False,scale=7,),examples=prompt_examples,additional_inputs=[instructions,user_name,bot_name,temperature,top_p,session_id,max_tokens,file_upload],submit_btn="Send",stop_btn="Stop",retry_btn="🔄 Retry",undo_btn="↩️ Delete",clear_btn="🗑️ Clear",)def introduction():with gr.Column(scale=2):gr.Image("images/lexai_logo.png", elem_id="banner-image", show_label=False)with gr.Column(scale=5):gr.Markdown("""# LexAI: Advanced Legal AI Assistant**LexAI is a cutting-edge AI-driven legal assistant with a wide range of capabilities to support legal professionals and provide information to the public.**✨ This demo is powered by the state-of-the-art Falcon 180B language model and specialized legal knowledge.🧪 LexAI offers the following key features:1. Contract Analysis and Risk Assessment2. Legal Research Assistant with Case Law Search3. Predictive Litigation Analysis4. Intelligent Legal Document Drafting5. Legal Chatbot for Public Access6. Document Retrieval, Analysis, and Summarization7. Legal Entity Recognition8. Sentiment Analysis for Legal Texts9. Keyword Extraction from Legal Documents10. Legal Definition Lookup11. Wikipedia and Internet Search Integration⚠️ **Disclaimer**: LexAI is an AI assistant and does not substitute for professional legal advice. Always consult with a qualified legal professional for specific legal matters.""")def main():with gr.Blocks(css="""#chat_container {height: 820px; width: 1000px; margin-left: auto; margin-right: auto;}#chatbot {height: 600px; overflow: auto;}#create_container {height: 750px; margin-left: 0px; margin-right: 0px;}#tokenizer_renderer span {white-space: pre-wrap}""") as demo:with gr.Row():introduction()with gr.Row():chat_tab()return demodef start_demo():demo = main()if DEPLOYED:demo.queue().launch(show_api=False)else:demo.queue().launch(share=True)if __name__ == "__main__":start_demo()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255import streamlit as stimport pandas as pdimport plotly.express as pximport requestsfrom ai71 import AI71import PyPDF2import ioimport randomimport docxfrom docx import Documentfrom docx.shared import Inchesfrom datetime import datetimeimport reimport base64from typing import List, Dict, Anyimport matplotlib.pyplot as pltfrom bs4 import BeautifulSoupfrom io import StringIOimport wikipediafrom googleapiclient.discovery import buildfrom typing import List, Optionalfrom httpx_sse import SSEError# Error handling for optional dependenciestry:from streamlit_lottie import st_lottieexcept ImportError:st.error("Missing dependency: streamlit_lottie. Please install it using 'pip install streamlit-lottie'")st.stop()# ConstantsAI71_API_KEY = "api71-api-92fc2ef9-9f3c-47e5-a019-18e257b04af2"# Initialize AI71 clienttry:ai71 = AI71(AI71_API_KEY)except Exception as e:st.error(f"Failed to initialize AI71 client: {str(e)}")st.stop()# Initialize chat history and other session state variablesif "chat_history" not in st.session_state:st.session_state.chat_history = []if "uploaded_documents" not in st.session_state:st.session_state.uploaded_documents = []if "case_precedents" not in st.session_state:st.session_state.case_precedents = []def analyze_uploaded_document(file):content = ""if file.type == "application/pdf":pdf_reader = PyPDF2.PdfReader(file)for page in pdf_reader.pages:content += page.extract_text()elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":doc = docx.Document(file)for para in doc.paragraphs:content += para.text + "\n"else:content = file.getvalue().decode("utf-8")return contentdef get_document_based_response(prompt, document_content):messages = [{"role": "system", "content": "You are a helpful legal assistant. Answer questions based on the provided document content."},{"role": "user", "content": f"Document content: {document_content}\n\nQuestion: {prompt}"}]try:completion = ai71.chat.completions.create(model="tiiuae/falcon-180b-chat",messages=messages,stream=False,)return completion.choices[0].message.contentexcept Exception as e:return f"An error occurred while processing your request: {str(e)}"def get_ai_response(prompt: str) -> str:"""Gets the AI response based on the given prompt."""messages = [{"role": "system", "content": "You are a helpful legal assistant with advanced capabilities."},{"role": "user", "content": prompt}]try:# First, try streamingresponse = ""for chunk in ai71.chat.completions.create(model="tiiuae/falcon-180b-chat",messages=messages,stream=True,):if chunk.choices[0].delta.content:response += chunk.choices[0].delta.contentreturn responseexcept Exception as e:print(f"Streaming failed, falling back to non-streaming request. Error: {e}")try:# Fall back to non-streaming requestcompletion = ai71.chat.completions.create(model="tiiuae/falcon-180b-chat",messages=messages,stream=False,)return completion.choices[0].message.contentexcept Exception as e:print(f"An error occurred while getting AI response: {e}")return f"I apologize, but I encountered an error while processing your request. Error: {str(e)}"def display_chat_history():for message in st.session_state.chat_history:if isinstance(message, tuple):if len(message) == 2:user_msg, bot_msg = messagest.info(f"**You:** {user_msg}")st.success(f"**Bot:** {bot_msg}")else:st.error(f"Unexpected message format: {message}")elif isinstance(message, dict):if message.get('type') == 'wikipedia':st.success(f"**Bot:** Wikipedia Summary:\n{message.get('summary', 'No summary available.')}\n" +(f"[Read more on Wikipedia]({message.get('url')})" if message.get('url') else ""))elif message.get('type') == 'web_search':web_results_msg = "Web Search Results:\n"for result in message.get('results', []):web_results_msg += f"[{result.get('title', 'No title')}]({result.get('link', '#')})\n{result.get('snippet', 'No snippet available.')}\n\n"st.success(f"**Bot:** {web_results_msg}")else:st.error(f"Unknown message type: {message}")else:st.error(f"Unexpected message format: {message}")def analyze_document(file) -> str:"""Analyzes uploaded legal documents."""content = ""if file.type == "application/pdf":pdf_reader = PyPDF2.PdfReader(file)for page in pdf_reader.pages:content += page.extract_text()elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":doc = docx.Document(file)for para in doc.paragraphs:content += para.text + "\n"else:content = file.getvalue().decode("utf-8")return content[:5000] # Limit content to 5000 characters for analysisdef search_web(query: str, num_results: int = 3) -> List[Dict[str, str]]:try:service = build("customsearch", "v1", developerKey="AIzaSyD-1OMuZ0CxGAek0PaXrzHOmcDWFvZQtm8")# Add legal-specific terms to the querylegal_query = f"legal {query} law case precedent"# Execute the search requestres = service.cse().list(q=legal_query, cx="877170db56f5c4629", num=num_results * 2).execute()results = []if "items" in res:for item in res["items"]:# Check if the result is relevant (you may need to adjust these conditions)if any(keyword in item["title"].lower() or keyword in item["snippet"].lower()for keyword in ["law", "legal", "court", "case", "attorney", "lawyer"]):result = {"title": item["title"],"link": item["link"],"snippet": item["snippet"]}results.append(result)if len(results) == num_results:breakreturn resultsexcept Exception as e:print(f"Error performing web search: {e}")return []def perform_web_search(query: str) -> List[Dict[str, Any]]:"""Performs a web search to find recent legal cost estimates."""url = f"https://www.google.com/search?q={query}"headers = {'User-Agent': 'Mozilla/5.0'}response = requests.get(url, headers=headers)soup = BeautifulSoup(response.content, 'html.parser')results = []for g in soup.find_all('div', class_='g'):anchors = g.find_all('a')if anchors:link = anchors[0]['href']title = g.find('h3', class_='r')if title:title = title.textelse:title = "No title"snippet = g.find('div', class_='s')if snippet:snippet = snippet.textelse:snippet = "No snippet"# Extract cost estimates from the snippetcost_estimates = extract_cost_estimates(snippet)if cost_estimates:results.append({"title": title,"link": link,"cost_estimates": cost_estimates})return results[:3] # Return top 3 results with cost estimatesdef search_wikipedia(query: str, sentences: int = 2) -> Dict[str, str]:try:# Ensure query is a string before slicingtruncated_query = str(query)[:300]# Search Wikipediasearch_results = wikipedia.search(truncated_query, results=5)if not search_results:return {"summary": "No Wikipedia article found.", "url": "", "title": ""}# Try to get a summary for each result until successfulfor result in search_results:try:page = wikipedia.page(result)summary = wikipedia.summary(result, sentences=sentences)return {"summary": summary, "url": page.url, "title": page.title}except wikipedia.exceptions.DisambiguationError as e:continueexcept wikipedia.exceptions.PageError:continue# If no summary found after trying all resultsreturn {"summary": "No relevant Wikipedia article found.", "url": "", "title": ""}except Exception as e:print(f"Error searching Wikipedia: {e}")return {"summary": f"Error searching Wikipedia: {str(e)}", "url": "", "title": ""}def comprehensive_document_analysis(content: str) -> Dict[str, Any]:"""Performs a comprehensive analysis of the document, including web and Wikipedia searches."""try:analysis_prompt = f"Analyze the following legal document and provide a summary, potential issues, and key clauses:\n\n{content}"document_analysis = get_ai_response(analysis_prompt)# Extract main topics or keywords from the documenttopic_extraction_prompt = f"Extract the main topics or keywords from the following document summary:\n\n{document_analysis}"topics = get_ai_response(topic_extraction_prompt)web_results = search_web(topics)wiki_results = search_wikipedia(topics)return {"document_analysis": document_analysis,"related_articles": web_results or [], # Ensure this is always a list"wikipedia_summary": wiki_results}except Exception as e:print(f"Error in comprehensive document analysis: {e}")return {"document_analysis": "Error occurred during analysis.","related_articles": [],"wikipedia_summary": {"summary": "Error occurred", "url": "", "title": ""}}def extract_important_info(text: str) -> str:"""Extracts and highlights important information from the given text."""prompt = f"Extract and highlight the most important legal information from the following text. Use markdown to emphasize key points:\n\n{text}"return get_ai_response(prompt)def fetch_detailed_content(url: str) -> str:try:response = requests.get(url)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')# Extract main content (this may need to be adjusted based on the structure of the target websites)main_content = soup.find('main') or soup.find('article') or soup.find('div', class_='content')if main_content:# Extract text from paragraphsparagraphs = main_content.find_all('p')content = "\n\n".join([p.get_text() for p in paragraphs])# Limit content to a reasonable length (e.g., first 1000 characters)return content[:1000] + "..." if len(content) > 1000 else contentelse:return "Unable to extract detailed content from the webpage."except Exception as e:return f"Error fetching detailed content: {str(e)}"def query_public_case_law(query: str) -> List[Dict[str, Any]]:"""Query publicly available case law databases and perform a web search to find related cases."""# Perform a web search to find relevant case lawsearch_url = f"https://www.google.com/search?q={query}+case+law+site:law.justia.com"headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}try:response = requests.get(search_url, headers=headers)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')search_results = soup.find_all('div', class_='g')cases = []for result in search_results[:5]: # Limit to top 5 resultstitle_elem = result.find('h3', class_='r')link_elem = result.find('a')snippet_elem = result.find('div', class_='s')if title_elem and link_elem and snippet_elem:title = title_elem.textlink = link_elem['href']snippet = snippet_elem.text# Extract case name and citation from the titlecase_info = title.split(' - ')if len(case_info) >= 2:case_name = case_info[0]citation = case_info[1]else:case_name = titlecitation = "Citation not found"cases.append({"case_name": case_name,"citation": citation,"summary": snippet,"url": link})return casesexcept requests.RequestException as e:print(f"Error querying case law: {e}")return []def find_case_precedents(case_details: str) -> Dict[str, Any]:"""Finds relevant case precedents based on provided details."""try:# Initial AI analysis of the case detailsanalysis_prompt = f"Analyze the following case details and identify key legal concepts and relevant precedents:\n\n{case_details}"initial_analysis = get_ai_response(analysis_prompt)# Query public case law databasespublic_cases = query_public_case_law(case_details)# Perform web search (existing functionality)web_results = search_web(f"legal precedent {case_details}", num_results=3)# Perform Wikipedia search (existing functionality)wiki_result = search_wikipedia(f"legal case {case_details}")# Compile all informationcompilation_prompt = f"""Compile a comprehensive summary of case precedents based on the following information:Initial Analysis: {initial_analysis}Public Case Law Results:{public_cases}Web Search Results:{web_results}Wikipedia Information:{wiki_result['summary']}Provide a well-structured summary highlighting the most relevant precedents and legal principles."""final_summary = get_ai_response(compilation_prompt)return {"summary": final_summary,"public_cases": public_cases,"web_results": web_results,"wikipedia": wiki_result}except Exception as e:print(f"An error occurred in find_case_precedents: {e}")return {"summary": f"An error occurred while finding case precedents: {str(e)}","public_cases": [],"web_results": [],"wikipedia": {'title': 'Error','summary': 'Unable to retrieve Wikipedia information','url': ''}}def estimate_legal_costs(case_type: str, complexity: str, country: str, state: str = None) -> Dict[str, Any]:"""Estimates legal costs based on case type, complexity, and location.Performs web searches for more accurate estimates and lawyer recommendations."""# Base cost ranges per hour (in USD) for different countriesbase_costs = {"USA": {"Simple": (150, 300), "Moderate": (250, 500), "Complex": (400, 1000)},"UK": {"Simple": (100, 250), "Moderate": (200, 400), "Complex": (350, 800)},"Canada": {"Simple": (125, 275), "Moderate": (225, 450), "Complex": (375, 900)},}# Adjust costs based on case typecase_type_multipliers = {"Civil Litigation": 1.2,"Criminal Defense": 1.5,"Family Law": 1.0,"Corporate Law": 1.3,}# Estimate number of hours based on complexityestimated_hours = {"Simple": (10, 30),"Moderate": (30, 100),"Complex": (100, 300)}# Get base cost range for the specified country and complexitycountry_costs = base_costs.get(country, base_costs["USA"])min_rate, max_rate = country_costs[complexity]# Adjust rates based on case typemultiplier = case_type_multipliers.get(case_type, 1.0)min_rate *= multipliermax_rate *= multiplier# Calculate total cost rangemin_hours, max_hours = estimated_hours[complexity]min_total = min_rate * min_hoursmax_total = max_rate * max_hours# Perform web search for recent cost estimatessearch_query = f"{case_type} legal costs {country} {state if state else ''}"web_results = search_web(search_query)web_estimates = []for result in web_results:estimates = extract_cost_estimates(result['snippet'])if estimates:web_estimates.append({'source': result['title'],'link': result['link'],'estimates': estimates})# Search for lawyers or law firmslawyer_search_query = f"top rated {case_type} lawyers {country} {state if state else ''}"lawyer_results = search_web(lawyer_search_query)# Generate cost breakdowncost_breakdown = {"Hourly rate range": f"${min_rate:.2f} - ${max_rate:.2f}","Estimated hours": f"{min_hours} - {max_hours}","Total cost range": f"${min_total:.2f} - ${max_total:.2f}","Web search estimates": web_estimates}# Potential high-cost areashigh_cost_areas = ["Expert witnesses (especially in complex cases)","Extensive document review and e-discovery","Multiple depositions","Prolonged trial periods","Appeals process"]# Cost-saving tipscost_saving_tips = ["Consider alternative dispute resolution methods like mediation or arbitration","Be organized and provide all relevant documents upfront to reduce billable hours","Communicate efficiently with your lawyer, bundling questions when possible","Ask for detailed invoices and review them carefully","Discuss fee arrangements, such as flat fees or contingency fees, where applicable"]lawyer_tips = ["Research and compare multiple lawyers or law firms","Ask for references and read client reviews","Discuss fee structures and payment plans upfront","Consider lawyers with specific expertise in your case type","Ensure clear communication and understanding of your case"]return {"cost_breakdown": cost_breakdown,"high_cost_areas": high_cost_areas,"cost_saving_tips": cost_saving_tips,"lawyer_recommendations": lawyer_results,"finding_best_lawyer_tips": lawyer_tips,"web_search_results": web_results # Add this new key}def legal_cost_estimator_ui():st.subheader("Legal Cost Estimator")case_type = st.selectbox("Select case type", ["Civil Litigation", "Criminal Defense", "Family Law", "Corporate Law"])complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"])country = st.selectbox("Select country", ["USA", "UK", "Canada"])if country == "USA":state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"])else:state = Noneif st.button("Estimate Costs"):with st.spinner("Estimating costs and performing web search..."):cost_estimate = estimate_legal_costs(case_type, complexity, country, state)st.write("### Estimated Legal Costs")for key, value in cost_estimate["cost_breakdown"].items():if key != "Web search estimates":st.write(f"**{key}:** {value}")st.write("### Web Search Estimates")if cost_estimate["cost_breakdown"]["Web search estimates"]:for result in cost_estimate["cost_breakdown"]["Web search estimates"]:st.write(f"**Source:** [{result['source']}]({result['link']})")st.write("**Estimated Costs:**")for estimate in result['estimates']:st.write(f"- {estimate}")st.write("---")else:st.write("No specific cost estimates found from web search.")st.write("### Potential High-Cost Areas")for area in cost_estimate["high_cost_areas"]:st.write(f"- {area}")st.write("### Cost-Saving Tips")for tip in cost_estimate["cost_saving_tips"]:st.write(f"- {tip}")st.write("### Recommended Lawyers/Law Firms")for lawyer in cost_estimate["lawyer_recommendations"][:5]: # Display top 5 recommendationsst.write(f"**[{lawyer['title']}]({lawyer['link']})**")st.write(lawyer["snippet"])st.write("---")def extract_cost_estimates(text: str) -> List[str]:"""Extracts cost estimates from the given text."""patterns = [r'\$\d{1,3}(?:,\d{3})*(?:\.\d{2})?', # Matches currency amounts like $1,000.00r'\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|GBP|CAD|EUR)', # Matches amounts with currency codesr'(?:USD|GBP|CAD|EUR)\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?' # Matches currency codes before amounts]estimates = []for pattern in patterns:matches = re.findall(pattern, text)estimates.extend(matches)return estimatesdef generate_legal_form(form_type: str, user_details: Dict[str, str], nation: str, state: str = None) -> Dict[str, Any]:"""Generates a legal form based on user input, nation, and state (if applicable).Creates downloadable .txt and .docx files."""current_date = datetime.now().strftime("%B %d, %Y")# Helper function to get jurisdiction-specific clausesdef get_jurisdiction_clauses(form_type, nation, state):# This would ideally be a comprehensive database of clauses for different jurisdictions# For demonstration, we'll use a simplified versionclauses = {"USA": {"Power of Attorney": "This Power of Attorney is governed by the laws of the State of {state}.","Non-Disclosure Agreement": "This Agreement shall be governed by and construed in accordance with the laws of the State of {state}.","Simple Will": "This Will shall be construed in accordance with the laws of the State of {state}.","Lease Agreement": "This Lease Agreement is subject to the landlord-tenant laws of the State of {state}.","Employment Contract": "This Employment Contract is governed by the labor laws of the State of {state}."},"UK": {"Power of Attorney": "This Power of Attorney is governed by the laws of England and Wales.","Non-Disclosure Agreement": "This Agreement shall be governed by and construed in accordance with the laws of England and Wales.","Simple Will": "This Will shall be construed in accordance with the laws of England and Wales.","Lease Agreement": "This Lease Agreement is subject to the landlord and tenant laws of England and Wales.","Employment Contract": "This Employment Contract is governed by the employment laws of England and Wales."},# Add more countries as needed}return clauses.get(nation, {}).get(form_type, "").format(state=state)jurisdiction_clause = get_jurisdiction_clauses(form_type, nation, state)if form_type == "Power of Attorney":form_content = f"""POWER OF ATTORNEYThis Power of Attorney is made on {current_date}.I, {user_details['principal_name']}, hereby appoint {user_details['agent_name']} as my Attorney-in-Fact ("Agent").My Agent shall have full power and authority to act on my behalf. This power and authority shall authorize my Agent to manage and conduct all of my affairs and to exercise all of my legal rights and powers, including all rights and powers that I may acquire in the future. My Agent's powers shall include, but not be limited to:1. {', '.join(user_details['powers'])}This Power of Attorney shall become effective immediately and shall continue until it is revoked by me.{jurisdiction_clause}Signed this {current_date}.______________________{user_details['principal_name']} (Principal)______________________{user_details['agent_name']} (Agent)______________________Witness______________________Witness"""elif form_type == "Non-Disclosure Agreement":form_content = f"""NON-DISCLOSURE AGREEMENTThis Non-Disclosure Agreement (the "Agreement") is entered into on {current_date} by and between:{user_details['party_a']} ("Party A")and{user_details['party_b']} ("Party B")1. Purpose: This Agreement is entered into for the purpose of {user_details['purpose']}.2. Confidential Information: Both parties may disclose certain confidential and proprietary information to each other in connection with the Purpose.3. Non-Disclosure: Both parties agree to keep all Confidential Information strictly confidential and not to disclose such information to any third parties for a period of {user_details['duration']} years from the date of this Agreement.{jurisdiction_clause}IN WITNESS WHEREOF, the parties hereto have executed this Non-Disclosure Agreement as of the date first above written.______________________{user_details['party_a']}______________________{user_details['party_b']}"""elif form_type == "Simple Will":beneficiaries = user_details['beneficiaries'].split('\n')beneficiary_clauses = "\n".join([f"{i+1}. I give, devise, and bequeath to {b.strip()} [insert specific bequest or share of estate]." for i, b in enumerate(beneficiaries)])form_content = f"""LAST WILL AND TESTAMENTI, {user_details['testator_name']}, being of sound mind, do hereby make, publish, and declare this to be my Last Will and Testament, hereby revoking all previous wills and codicils made by me.1. EXECUTOR: I appoint {user_details['executor_name']} to be the Executor of this, my Last Will and Testament.2. BEQUESTS:{beneficiary_clauses}3. RESIDUARY ESTATE: I give, devise, and bequeath all the rest, residue, and remainder of my estate to [insert beneficiary or beneficiaries].4. POWERS OF EXECUTOR: I grant to my Executor full power and authority to sell, lease, mortgage, or otherwise dispose of the whole or any part of my estate.{jurisdiction_clause}IN WITNESS WHEREOF, I have hereunto set my hand to this my Last Will and Testament on {current_date}.______________________{user_details['testator_name']} (Testator)WITNESSES:On the date last above written, {user_details['testator_name']}, known to us to be the Testator, signed this Will in our presence and declared it to be their Last Will and Testament. At the Testator's request, in the Testator's presence, and in the presence of each other, we have signed our names as witnesses:______________________Witness 1______________________Witness 2"""elif form_type == "Lease Agreement":form_content = f"""LEASE AGREEMENTThis Lease Agreement (the "Lease") is made on {current_date} by and between:{user_details['landlord_name']} ("Landlord")and{user_details['tenant_name']} ("Tenant")1. PREMISES: The Landlord hereby leases to the Tenant the property located at {user_details['property_address']}.2. TERM: The term of this Lease shall be for {user_details['lease_term']} months, beginning on {user_details['start_date']} and ending on {user_details['end_date']}.3. RENT: The Tenant shall pay rent in the amount of {user_details['rent_amount']} per month, due on the {user_details['rent_due_day']} day of each month.4. SECURITY DEPOSIT: The Tenant shall pay a security deposit of {user_details['security_deposit']} upon signing this Lease.{jurisdiction_clause}IN WITNESS WHEREOF, the parties hereto have executed this Lease Agreement as of the date first above written.______________________{user_details['landlord_name']} (Landlord)______________________{user_details['tenant_name']} (Tenant)"""elif form_type == "Employment Contract":form_content = f"""EMPLOYMENT CONTRACTThis Employment Contract (the "Contract") is made on {current_date} by and between:{user_details['employer_name']} ("Employer")and{user_details['employee_name']} ("Employee")1. POSITION: The Employee is hired for the position of {user_details['job_title']}.2. DUTIES: The Employee's duties shall include, but are not limited to: {user_details['job_duties']}.3. COMPENSATION: The Employee shall be paid a {user_details['pay_frequency']} salary of {user_details['salary_amount']}.4. TERM: This Contract shall commence on {user_details['start_date']} and continue until terminated by either party.5. BENEFITS: The Employee shall be entitled to the following benefits: {user_details['benefits']}.{jurisdiction_clause}IN WITNESS WHEREOF, the parties hereto have executed this Employment Contract as of the date first above written.______________________{user_details['employer_name']} (Employer)______________________{user_details['employee_name']} (Employee)"""else:return {"error": "Unsupported form type"}# Generate .txt filetxt_file = io.StringIO()txt_file.write(form_content)txt_file.seek(0)# Generate .docx filedocx_file = io.BytesIO()doc = Document()doc.add_paragraph(form_content)doc.save(docx_file)docx_file.seek(0)return {"form_content": form_content,"txt_file": txt_file,"docx_file": docx_file}CASE_TYPES = ["Civil Rights", "Contract", "Real Property", "Tort", "Labor", "Intellectual Property","Bankruptcy", "Immigration", "Social Security", "Tax", "Constitutional", "Criminal","Environmental", "Antitrust", "Securities", "Administrative", "Admiralty", "Family Law","Probate", "Personal Injury"]DATA_SOURCES = {"Civil Rights": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Contract": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Real Property": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Tort": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Labor": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Intellectual Property": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Bankruptcy": "https://www.uscourts.gov/sites/default/files/data_tables/jb_f_0930.2022.pdf","Immigration": "https://www.justice.gov/eoir/workload-and-adjudication-statistics","Social Security": "https://www.ssa.gov/open/data/hearings-and-appeals-filed.html","Tax": "https://www.ustaxcourt.gov/statistics.html","Constitutional": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Criminal": "https://www.uscourts.gov/sites/default/files/data_tables/jb_d1_0930.2022.pdf","Environmental": "https://www.epa.gov/enforcement/enforcement-annual-results-numbers-glance-fiscal-year-2022","Antitrust": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Securities": "https://www.sec.gov/files/enforcement-annual-report-2022.pdf","Administrative": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Admiralty": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Family Law": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Probate": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf","Personal Injury": "https://www.uscourts.gov/sites/default/files/data_tables/jb_c2_0930.2022.pdf"}def fetch_case_data(case_type: str) -> pd.DataFrame:"""Fetches actual historical data for the given case type."""url = DATA_SOURCES[case_type]response = requests.get(url)if response.status_code == 200:if url.endswith('.pdf'):# For PDF sources, we'll use a placeholder DataFrame# In a real-world scenario, you'd need to implement PDF parsingdf = pd.DataFrame({'Year': range(2013, 2023),'Number of Cases': [random.randint(1000, 5000) for _ in range(10)]})else:# For non-PDF sources, we'll assume CSV formatdf = pd.read_csv(StringIO(response.text))else:st.error(f"Failed to fetch data for {case_type}. Using placeholder data.")df = pd.DataFrame({'Year': range(2013, 2023),'Number of Cases': [random.randint(1000, 5000) for _ in range(10)]})return dfdef visualize_case_trends(case_type: str):"""Visualizes case trends based on case type using actual historical data."""df = fetch_case_data(case_type)fig = px.line(df, x='Year', y='Number of Cases', title=f"Trend of {case_type} Cases")fig.update_layout(xaxis_title="Year",yaxis_title="Number of Cases",hovermode="x unified")fig.update_traces(mode="lines+markers")return fig, df # Return both the image and the raw data# --- Streamlit App ---# Custom CSS to improve the overall lookst.markdown("""<style>.reportview-container {background: #f0f2f6;}.main .block-container {padding-top: 2rem;padding-bottom: 2rem;padding-left: 5rem;padding-right: 5rem;}h1 {color: #1E3A8A;}h2 {color: #3B82F6;}.stButton>button {background-color: #3B82F6;color: white;border-radius: 5px;}.stTextInput>div>div>input {border-radius: 5px;}</style>""", unsafe_allow_html=True)def load_lottieurl(url: str):try:r = requests.get(url)r.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xxreturn r.json()except requests.HTTPError as http_err:print(f"HTTP error occurred while loading Lottie animation: {http_err}")except requests.RequestException as req_err:print(f"Error occurred while loading Lottie animation: {req_err}")except ValueError as json_err:print(f"Error decoding JSON for Lottie animation: {json_err}")return None# Streamlit Appst.title("Lex AI - Advanced Legal Assistant")# Sidebar with feature selectionwith st.sidebar:st.title(" AI")st.subheader("Advanced Legal Assistant")feature = st.selectbox("Select a feature",["Legal Chatbot", "Document Analysis", "Case Precedent Finder", "Legal Cost Estimator", "Legal Form Generator", "Case Trend Visualizer"])if feature == "Legal Chatbot":st.subheader("Legal Chatbot")if 'chat_history' not in st.session_state:st.session_state.chat_history = []if 'uploaded_document' not in st.session_state:st.session_state.uploaded_document = Noneif 'chat_mode' not in st.session_state:st.session_state.chat_mode = "normal"# Document uploaduploaded_file = st.file_uploader("Upload a legal document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])if uploaded_file:st.session_state.uploaded_document = analyze_uploaded_document(uploaded_file)st.success("Document uploaded successfully!")# Chat mode toggleif st.session_state.uploaded_document:if st.button("Switch Chat Mode"):st.session_state.chat_mode = "document" if st.session_state.chat_mode == "normal" else "normal"st.write(f"Current mode: {'Document-based' if st.session_state.chat_mode == 'document' else 'Normal'} chat")display_chat_history()user_input = st.text_input("Your legal question:")if user_input and st.button("Send"):with st.spinner("Processing your question..."):if st.session_state.chat_mode == "document" and st.session_state.uploaded_document:ai_response = get_document_based_response(user_input, st.session_state.uploaded_document)st.session_state.chat_history.append((user_input, ai_response))else:ai_response = get_ai_response(user_input)st.session_state.chat_history.append((user_input, ai_response))# Perform Wikipedia searchwiki_result = search_wikipedia(user_input)st.session_state.chat_history.append({'type': 'wikipedia','summary': wiki_result.get("summary", "No summary available."),'url': wiki_result.get("url", "")})# Perform web searchweb_results = search_web(user_input)st.session_state.chat_history.append({'type': 'web_search','results': web_results})st.rerun()elif feature == "Document Analysis":st.subheader("Legal Document Analyzer")uploaded_file = st.file_uploader("Upload a legal document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])if uploaded_file and st.button("Analyze Document"):with st.spinner("Analyzing document and gathering additional information..."):try:document_content = analyze_document(uploaded_file)analysis_results = comprehensive_document_analysis(document_content)st.write("Document Analysis:")st.write(analysis_results.get("document_analysis", "No analysis available."))st.write("Related Articles:")for article in analysis_results.get("related_articles", []):st.write(f"- [{article.get('title', 'No title')}]({article.get('link', '#')})")st.write(f" {article.get('snippet', 'No snippet available.')}")st.write("Wikipedia Summary:")wiki_info = analysis_results.get("wikipedia_summary", {})st.write(f"**{wiki_info.get('title', 'No title')}**")st.write(wiki_info.get('summary', 'No summary available.'))if wiki_info.get('url'):st.write(f"[Read more on Wikipedia]({wiki_info['url']})")except Exception as e:st.error(f"An error occurred during document analysis: {str(e)}")elif feature == "Case Precedent Finder":st.subheader("Case Precedent Finder")# Initialize session state for precedents if not existsif 'precedents' not in st.session_state:st.session_state.precedents = None# Initialize session state for visibility toggles if not existsif 'visibility_toggles' not in st.session_state:st.session_state.visibility_toggles = {}case_details = st.text_area("Enter case details:")if st.button("Find Precedents"):with st.spinner("Searching for relevant case precedents..."):try:st.session_state.precedents = find_case_precedents(case_details)except Exception as e:st.error(f"An error occurred while finding case precedents: {str(e)}")# Display results if precedents are availableif st.session_state.precedents:precedents = st.session_state.precedentsst.write("### Summary of Relevant Case Precedents")st.markdown(precedents["summary"])st.write("### Related Cases from Public Databases")for i, case in enumerate(precedents["public_cases"], 1):st.write(f"**{i}. {case['case_name']} - {case['citation']}**")st.write(f"Summary: {case['summary']}")st.write(f"[Read full case]({case['url']})")st.write("---")st.write("### Additional Web Results")for i, result in enumerate(precedents["web_results"], 1):st.write(f"**{i}. [{result['title']}]({result['link']})**")# Create a unique key for each toggletoggle_key = f"toggle_{i}"# Initialize the toggle state if it doesn't existif toggle_key not in st.session_state.visibility_toggles:st.session_state.visibility_toggles[toggle_key] = False# Create a button to toggle visibilityif st.button(f"{'Hide' if st.session_state.visibility_toggles[toggle_key] else 'Show'} Full Details for Result {i}", key=f"button_{i}"):st.session_state.visibility_toggles[toggle_key] = not st.session_state.visibility_toggles[toggle_key]# Show full details if toggle is Trueif st.session_state.visibility_toggles[toggle_key]:# Fetch and display more detailed contentdetailed_content = fetch_detailed_content(result['link'])st.markdown(detailed_content)else:# Show a brief summary when details are hiddenbrief_summary = result['snippet'].split('\n')[0][:200] + "..." if len(result['snippet']) > 200 else result['snippet'].split('\n')[0]st.write(f"Brief Summary: {brief_summary}")st.write("---")st.write("### Wikipedia Information")wiki_info = precedents["wikipedia"]st.write(f"**[{wiki_info['title']}]({wiki_info['url']})**")st.markdown(wiki_info['summary'])elif feature == "Legal Cost Estimator":st.subheader("Legal Cost Estimator")case_type = st.selectbox("Select case type", ["Civil Litigation", "Criminal Defense", "Family Law", "Corporate Law"], key="cost_estimator_case_type")complexity = st.selectbox("Select case complexity", ["Simple", "Moderate", "Complex"], key="cost_estimator_complexity")country = st.selectbox("Select country", ["USA", "UK", "Canada"], key="cost_estimator_country")if country == "USA":state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"], key="cost_estimator_state")else:state = None# Initialize cost_estimatecost_estimate = Noneif st.button("Estimate Costs"):with st.spinner("Estimating costs and performing web search..."):cost_estimate = estimate_legal_costs(case_type, complexity, country, state)# Check if cost_estimate is available before displaying resultsif cost_estimate:st.write("### Estimated Legal Costs")for key, value in cost_estimate["cost_breakdown"].items():st.write(f"**{key}:** {value}")st.write("### Web Search Results")if cost_estimate["web_search_results"]:for result in cost_estimate["web_search_results"]:st.write(f"**[{result['title']}]({result['link']})**")st.write(result["snippet"])st.write("---")else:st.write("No specific cost estimates found from web search.")st.write("### Potential High-Cost Areas")for area in cost_estimate["high_cost_areas"]:st.write(f"- {area}")st.write("### Cost-Saving Tips")for tip in cost_estimate["cost_saving_tips"]:st.write(f"- {tip}")st.write("### Tips for Finding the Best Legal Representation")for tip in cost_estimate["finding_best_lawyer_tips"]:st.write(f"- {tip}")st.write("### Recommended Lawyers/Law Firms")for lawyer in cost_estimate["lawyer_recommendations"][:5]: # Display top 5 recommendationsst.write(f"**[{lawyer['title']}]({lawyer['link']})**")st.write(lawyer["snippet"])st.write("---")else:st.write("Click 'Estimate Costs' to see the results.")elif feature == "Legal Form Generator":st.subheader("Legal Form Generator")form_type = st.selectbox("Select form type", ["Power of Attorney", "Non-Disclosure Agreement", "Simple Will", "Lease Agreement", "Employment Contract"], key="form_generator_type")nation = st.selectbox("Select nation", ["USA", "UK"], key="form_generator_nation")if nation == "USA":state = st.selectbox("Select state", ["California", "New York", "Texas", "Florida"], key="form_generator_state")else:state = Noneuser_details = {}if form_type == "Power of Attorney":user_details["principal_name"] = st.text_input("Principal's Full Name:")user_details["agent_name"] = st.text_input("Agent's Full Name:")user_details["powers"] = st.multiselect("Select powers to grant", ["Financial Decisions", "Healthcare Decisions", "Real Estate Transactions"])elif form_type == "Non-Disclosure Agreement":user_details["party_a"] = st.text_input("First Party's Name:")user_details["party_b"] = st.text_input("Second Party's Name:")user_details["purpose"] = st.text_input("Purpose of Disclosure:")user_details["duration"] = st.number_input("Duration of Agreement (in years):", min_value=1, max_value=10)elif form_type == "Simple Will":user_details["testator_name"] = st.text_input("Testator's Full Name:")user_details["beneficiaries"] = st.text_area("List Beneficiaries (one per line):")user_details["executor_name"] = st.text_input("Executor's Full Name:")elif form_type == "Lease Agreement":user_details["landlord_name"] = st.text_input("Landlord's Full Name:")user_details["tenant_name"] = st.text_input("Tenant's Full Name:")user_details["property_address"] = st.text_input("Property Address:")user_details["lease_term"] = st.number_input("Lease Term (in months):", min_value=1, max_value=60)user_details["start_date"] = st.date_input("Lease Start Date:")user_details["end_date"] = st.date_input("Lease End Date:")user_details["rent_amount"] = st.number_input("Monthly Rent Amount:", min_value=0)user_details["rent_due_day"] = st.number_input("Rent Due Day of Month:", min_value=1, max_value=31)user_details["security_deposit"] = st.number_input("Security Deposit Amount:", min_value=0)elif form_type == "Employment Contract":user_details["employer_name"] = st.text_input("Employer's Full Name:")user_details["employee_name"] = st.text_input("Employee's Full Name:")user_details["job_title"] = st.text_input("Job Title:")user_details["job_duties"] = st.text_area("Job Duties:")user_details["pay_frequency"] = st.selectbox("Pay Frequency:", ["Weekly", "Bi-weekly", "Monthly"])user_details["salary_amount"] = st.number_input("Salary Amount:", min_value=0)user_details["start_date"] = st.date_input("Employment Start Date:")user_details["benefits"] = st.text_area("Employee Benefits:")if st.button("Generate Form"):generated_form = generate_legal_form(form_type, user_details, nation, state)if "error" in generated_form:st.error(generated_form["error"])else:st.write("### Generated Legal Form:")st.text(generated_form["form_content"])# Provide download buttons for .txt and .docx filestxt_download = generated_form["txt_file"].getvalue()docx_download = generated_form["docx_file"].getvalue()st.download_button(label="Download as .txt",data=txt_download,file_name=f"{form_type.lower().replace(' ', '_')}_{nation}{'_' + state if state else ''}.txt",mime="text/plain")st.download_button(label="Download as .docx",data=docx_download,file_name=f"{form_type.lower().replace(' ', '_')}_{nation}{'_' + state if state else ''}.docx",mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")st.warning("Please note: This generated form is a template based on general principles of the selected jurisdiction. It should be reviewed by a legal professional licensed in the relevant jurisdiction before use.")elif feature == "Case Trend Visualizer":st.subheader("Case Trend Visualizer")case_type = st.selectbox("Select case type to visualize", CASE_TYPES)if st.button("Visualize Trend"):with st.spinner("Fetching and visualizing data..."):fig, df = visualize_case_trends(case_type)# Update session statest.session_state.df = dfst.session_state.fig = figst.plotly_chart(fig, use_container_width=True)# Display statisticsst.subheader("Case Statistics")total_cases = df['Number of Cases'].sum()avg_cases = df['Number of Cases'].mean()max_year = df.loc[df['Number of Cases'].idxmax(), 'Year']min_year = df.loc[df['Number of Cases'].idxmin(), 'Year']col1, col2, col3 = st.columns(3)col1.metric("Total Cases", f"{total_cases:,}")col2.metric("Average Cases per Year", f"{avg_cases:,.0f}")col3.metric("Years", f"{min_year} - {max_year}")# Raw Datast.subheader("Raw Data")st.dataframe(df)# Download optionscsv = df.to_csv(index=False)st.download_button(label="Download data as CSV",data=csv,file_name=f"{case_type.lower().replace(' ', '_')}_trend_data.csv",mime="text/csv",)# Additional resourcesst.subheader("Additional Resources")st.markdown(f"[Data Source]({DATA_SOURCES[case_type]})")st.markdown("[US Courts Statistics](https://www.uscourts.gov/statistics-reports)")st.markdown("[Federal Judicial Caseload Statistics](https://www.uscourts.gov/statistics-reports/analysis-reports/federal-judicial-caseload-statistics)")st.markdown(f"[Legal Information Institute](https://www.law.cornell.edu/wex/{case_type.lower().replace(' ', '_')})")# Explanatory textst.subheader("Understanding the Trend")explanation = f"""The graph above shows the trend of {case_type} cases over time. Here are some key points to consider:1. Overall Trend: Observe whether the number of cases is generally increasing, decreasing, or remaining stable over the years.2. Peak Years: The year {max_year} saw the highest number of cases ({df['Number of Cases'].max():,}). This could be due to various factors such as changes in legislation, economic conditions, or social trends.3. Low Points: The year {min_year} had the lowest number of cases ({df['Number of Cases'].min():,}). Consider what might have contributed to this decrease.4. Recent Trends: Pay attention to the most recent years to understand current patterns in {case_type} cases.5. Contextual Factors: Remember that these numbers can be influenced by various factors, including changes in law, court procedures, societal changes, and more.For a deeper understanding of these trends and their implications, consider consulting with legal professionals or reviewing academic research in this area."""st.markdown(explanation)# Interactive elementsst.subheader("Interactive Analysis")analysis_type = st.radio("Select analysis type:", ["Year-over-Year Change", "Moving Average"])if analysis_type == "Year-over-Year Change":df['YoY Change'] = df['Number of Cases'].pct_change() * 100yoy_fig = px.bar(df, x='Year', y='YoY Change', title="Year-over-Year Change in Case Numbers")st.plotly_chart(yoy_fig, use_container_width=True)elif analysis_type == "Moving Average":window = st.slider("Select moving average window:", 2, 5, 3)df['Moving Average'] = df['Number of Cases'].rolling(window=window).mean()ma_fig = px.line(df, x='Year', y=['Number of Cases', 'Moving Average'], title=f"{window}-Year Moving Average")st.plotly_chart(ma_fig, use_container_width=True)# Add a footer with a disclaimer# Footerst.markdown("---")st.markdown("""<div style="text-align: center;"><p>© 2023 Lex AI. All rights reserved.</p><p><small>Disclaimer: This tool provides general legal information and assistance. It is not a substitute for professional legal advice. Please consult with a qualified attorney for specific legal matters.</small></p></div>""",unsafe_allow_html=True)if __name__ == "__main__":st.sidebar.info("Select a feature from the dropdown above to get started.")
app2.py+1255-424