Johan713 commited on
Commit
5df8fec
·
verified ·
1 Parent(s): dba9928

Update app2.py

Browse files
Files changed (1) hide show
  1. app2.py +181 -181
app2.py CHANGED
@@ -1812,37 +1812,40 @@ def lawyer_finder_ui():
1812
  st.warning(f"No lawyers found in {city}, {state}. Try selecting a different city or state.")
1813
 
1814
  def analyze_policy(policy_text: str) -> Dict[str, Any]:
1815
- """Analyzes the given policy text for its potential impact and benefits."""
1816
- analysis_prompt = f"""
1817
- Analyze the following policy text, taking into account US legal and societal contexts:
1818
 
1819
- Policy Text:
1820
- ```
1821
- {policy_text}
1822
- ```
1823
 
1824
- Provide a comprehensive analysis that includes:
1825
-
1826
- * **Summary:** Briefly summarize the key points of the policy.
1827
- * **Large-Scale Impact:** Discuss the potential impact of this policy on a national or state level. Consider economic, social, and legal implications.
1828
- * **Small-Scale Impact:** Analyze how this policy might affect individuals, families, or specific communities within the US.
1829
- * **Long-Term Benefits:** What are the potential advantages of this policy in the long run (5-10 years or more)?
1830
- * **Short-Term Benefits:** What benefits might be observed within the first few years of implementing this policy?
1831
- * **Potential Drawbacks:** Are there any possible negative consequences or challenges in implementing this policy?
1832
- * **Legal Considerations:** Are there any existing US laws or regulations that this policy might conflict with or be affected by?
1833
- * **Historical Context:** Are there any historical parallels or past US policies that might inform the potential outcomes of this policy?
1834
- * **Suggestions for Improvement:** Offer specific recommendations on how the policy could be modified to enhance its effectiveness or mitigate potential drawbacks.
1835
- * **Stakeholder Perspectives:** Identify different groups or entities in the US that might have an interest in this policy (e.g., businesses, consumers, government agencies), and how they might view it.
1836
-
1837
- Support your analysis with relevant examples, statistics, or legal precedents from the US, where applicable.
1838
- Maintain a neutral and objective tone, presenting both potential advantages and disadvantages of the policy.
1839
- """
 
 
 
1840
 
1841
- try:
1842
- analysis = get_ai_response(analysis_prompt)
1843
- return {"analysis": analysis}
1844
- except Exception as e:
1845
- return {"error": f"Error analyzing policy: {str(e)}"}
 
 
1846
 
1847
  def policy_analysis_ui():
1848
  st.subheader("Policy Analysis & Impact")
@@ -1852,9 +1855,6 @@ def policy_analysis_ui():
1852
  ''')
1853
 
1854
  st.warning("Please do not upload files larger than 5MB as it may cause issues and consume all available tokens.")
1855
-
1856
- if 'policy_history' not in st.session_state:
1857
- st.session_state.policy_history = []
1858
 
1859
  input_method = st.radio("Choose input method:", ("Text Input", "Document Upload"))
1860
 
@@ -1874,84 +1874,81 @@ def policy_analysis_ui():
1874
  if "error" in analysis_results:
1875
  st.error(analysis_results["error"])
1876
  else:
 
1877
  st.write("### Policy Analysis")
1878
- st.write(analysis_results.get("analysis", "No analysis available."))
1879
 
1880
- # Add download button for analysis
1881
- analysis_text = analysis_results.get("analysis", "No analysis available.")
1882
  st.download_button(
1883
- label="Download Analysis",
1884
- data=analysis_text,
1885
  file_name="policy_analysis.txt",
1886
  mime="text/plain"
1887
  )
1888
-
1889
- # Perform and display Wikipedia search
1890
- wiki_result = search_wikipedia(policy_text)
1891
- st.write("### Wikipedia Summary")
1892
- st.write(wiki_result.get("summary", "No summary available."))
1893
- if wiki_result.get("url"):
1894
- st.write(f"[Read more on Wikipedia]({wiki_result.get('url')})")
1895
-
1896
- # Perform and display web search
1897
- web_results = search_web_duckduckgo(policy_text)
1898
- st.write("### Web Search Results")
1899
- for result in web_results:
1900
- st.write(f"**{result.get('title', 'No title')}**")
1901
- st.write(result.get('snippet', 'No snippet available.'))
1902
- st.write(f"[Read more]({result.get('link', '#')})")
1903
- st.write("---")
1904
-
1905
- st.session_state.policy_history.append({
1906
- 'type': 'analysis',
1907
- 'text': policy_text,
1908
- 'analysis': analysis_results.get("analysis", "No analysis available."),
1909
- 'wikipedia': wiki_result,
1910
- 'web_results': web_results
1911
- })
1912
-
1913
- st.rerun()
1914
  else:
1915
  st.warning("Please enter policy text or upload a document to analyze.")
1916
 
1917
- display_chat_history()
1918
-
1919
- def provide_legal_advice(user_input: str) -> Dict[str, Any]:
1920
- """Provides legal advice based on the user input and performs web searches."""
1921
- advice_prompt = f"""
1922
- Provide legal advice based on US law for the following situation or question:
1923
 
1924
- User Input:
1925
  ```
1926
  {user_input}
1927
- ```
1928
-
1929
- Please include:
1930
- 1. A summary of the legal issue or question
1931
- 2. Relevant US laws or regulations that apply
1932
- 3. Possible legal implications or consequences
1933
- 4. General advice or next steps (without constituting specific legal counsel)
1934
- 5. Any important disclaimers or limitations of this advice
1935
-
1936
- Remember to maintain a professional and objective tone throughout your response.
1937
  """
1938
 
1939
  try:
1940
- legal_advice = get_ai_response(advice_prompt)
1941
- web_results = search_web_duckduckgo(user_input, num_results=3)
1942
-
1943
- return {
1944
- "advice": legal_advice,
1945
- "web_results": web_results
1946
- }
1947
  except Exception as e:
1948
- return {"error": f"Error providing legal advice: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1949
 
1950
  def legal_consultant_ui():
1951
  st.subheader("Legal Consultant")
1952
 
1953
- if 'chat_history' not in st.session_state:
1954
- st.session_state.chat_history = []
1955
 
1956
  if 'uploaded_document' not in st.session_state:
1957
  st.session_state.uploaded_document = None
@@ -1964,90 +1961,97 @@ def legal_consultant_ui():
1964
 
1965
  st.warning("Please do not upload files larger than 5MB as it may cause issues and consume all available tokens.")
1966
 
1967
- # Document upload
1968
  uploaded_file = st.file_uploader("Upload a legal document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])
1969
 
1970
  if uploaded_file:
1971
  st.session_state.uploaded_document = extract_text_from_document(uploaded_file)
1972
  st.success("Document uploaded successfully!")
1973
 
1974
- display_chat_history_legal_advise()
1975
-
 
 
 
 
 
 
 
 
 
 
1976
  user_input = st.text_input("Your legal question:")
1977
 
1978
  if user_input and st.button("Send"):
1979
  with st.spinner("Processing your question..."):
1980
  if st.session_state.uploaded_document:
1981
- # If a document is uploaded, use it as context
1982
  full_input = f"Document context: {st.session_state.uploaded_document}\n\nUser question: {user_input}"
1983
  else:
1984
  full_input = user_input
1985
 
1986
  result = provide_legal_advice(full_input)
1987
-
1988
  if "error" in result:
1989
  st.error(result["error"])
1990
  else:
1991
- st.session_state.chat_history.append(("User", user_input))
1992
- st.session_state.chat_history.append(("Lex AI", result["advice"]))
 
 
 
1993
 
1994
- st.write("### Web Search Results")
1995
- for web_result in result["web_results"]:
1996
- st.write(f"**{web_result.get('title', 'No title')}**")
1997
- st.write(web_result.get('snippet', 'No snippet available.'))
1998
- st.write(f"[Read more]({web_result.get('link', '#')})")
1999
- st.write("---")
2000
 
2001
  st.rerun()
2002
 
2003
  def display_chat_history_legal_advise():
2004
- for entry in st.session_state.chat_history:
2005
- if isinstance(entry, tuple):
2006
- sender, message = entry
2007
- if sender == "User":
2008
- st.write(f"**You:** {message}")
2009
- else:
2010
- st.write(f"**AI:** {message}")
2011
- elif isinstance(entry, dict):
2012
- if entry.get('type') == 'web_search':
2013
- st.write("### Web Search Results")
2014
- for result in entry.get('results', []):
2015
- st.write(f"**{result.get('title', 'No title')}**")
2016
- st.write(result.get('snippet', 'No snippet available.'))
2017
- st.write(f"[Read more]({result.get('link', '#')})")
2018
- st.write("---")
2019
 
2020
- # Make sure to include the extract_text_from_document function as previously defined
 
 
2021
 
 
 
 
2022
 
2023
- def draft_contract(contract_details: str) -> Dict[str, Any]:
2024
- """Drafts a contract based on the provided details."""
2025
- drafting_prompt = f"""
2026
- Draft a legally sound and comprehensive contract based on the following details, ensuring compliance with US law.
 
 
 
 
 
 
 
 
 
 
 
 
2027
 
2028
- Contract Details:
2029
- ```
2030
- {contract_details}
2031
- ```
2032
 
2033
- Output Format:
2034
- Present the drafted contract in a clear and organized manner, using sections and headings.
2035
- Include the following essential clauses (and any others relevant to the provided details):
2036
-
2037
- * Parties: Clearly identify the names and addresses of all parties entering into the contract.
2038
- * Term and Termination: Specify the duration of the contract and conditions for renewal or termination.
2039
- * Payment Terms: Outline payment details, including amounts, schedule, and methods.
2040
- * Governing Law: State that the contract shall be governed by the laws of the state specified in the details.
2041
- * Dispute Resolution: Include a clause outlining how disputes will be handled (e.g., mediation, arbitration).
2042
- * Entire Agreement: State that the written contract represents the entire agreement between the parties.
2043
- * Signatures: Leave space for the dated signatures of all parties involved.
2044
- """
2045
 
2046
- try:
2047
- contract_draft = get_ai_response(drafting_prompt)
2048
- return {"draft": contract_draft}
2049
- except Exception as e:
2050
- return {"error": f"Error drafting contract: {str(e)}"}
2051
 
2052
  def contract_drafting_ui():
2053
  st.subheader("Contract Drafting Assistant")
@@ -2085,7 +2089,7 @@ def contract_drafting_ui():
2085
  else:
2086
  st.write("### Drafted Contract")
2087
  contract_draft = draft_results.get("draft", "No draft available.")
2088
- st.text_area("Contract Draft", contract_draft, height=300)
2089
 
2090
  st.download_button(
2091
  label="Download Contract",
@@ -2093,37 +2097,43 @@ def contract_drafting_ui():
2093
  file_name="drafted_contract.txt",
2094
  mime="text/plain"
2095
  )
 
2096
  else:
2097
  st.warning("Please enter contract details or upload a document to proceed.")
2098
 
2099
  def analyze_case_for_prediction(case_details: str) -> Dict[str, Any]:
2100
- """Analyzes the case details to provide a predictive analysis."""
2101
- analysis_prompt = f"""
2102
- Analyze the following case details in the context of the US legal system and provide a predictive analysis.
2103
 
2104
- Case Details:
2105
- ```
2106
- {case_details}
2107
- ```
2108
 
2109
- Your analysis should address the following:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2110
 
2111
- * **Case Summary:** Briefly summarize the key facts, legal claims, and parties involved in the case.
2112
- * **Predicted Outcome:** What is the most likely outcome of this case based on the provided information, US legal precedents, and similar cases? Explain your reasoning.
2113
- * **Strengths of the Case:** Identify the most compelling arguments and evidence that support a favorable outcome.
2114
- * **Weaknesses of the Case:** What are potential weaknesses in the case, or areas where the opposing party might have strong arguments?
2115
- * **Areas of Caution:** What potential pitfalls or challenges should be considered? What strategies could the opposing party use?
2116
- * **Relevant US Case Law:** Cite specific US legal precedents and similar cases that support your analysis and predicted outcome.
2117
- * **Recommended Strategies:** Offer specific, actionable recommendations on how to strengthen the case and increase the likelihood of a positive result.
2118
 
2119
- Please maintain a neutral and objective tone throughout your analysis. The goal is to provide a realistic assessment of the case, not to advocate for a particular side.
2120
- """
2121
 
2122
- try:
2123
- analysis = get_ai_response(analysis_prompt)
2124
- return {"analysis": analysis}
2125
- except Exception as e:
2126
- return {"error": f"Error analyzing case: {str(e)}"}
2127
 
2128
  def predictive_analysis_ui():
2129
  st.subheader("Predictive Case Analysis")
@@ -2159,26 +2169,16 @@ def predictive_analysis_ui():
2159
  if "error" in analysis_results:
2160
  st.error(analysis_results["error"])
2161
  else:
2162
- st.write(analysis_results.get("analysis", "No analysis available."))
 
2163
 
2164
- # Add download button for analysis
2165
- analysis_text = analysis_results.get("analysis", "No analysis available.")
2166
  st.download_button(
2167
  label="Download Analysis",
2168
- data=analysis_text,
2169
  file_name="case_analysis.txt",
2170
  mime="text/plain"
2171
  )
2172
-
2173
- # Perform and display web search
2174
- web_results = search_web_duckduckgo(case_details)
2175
- st.write("### Related Web Resources")
2176
- for result in web_results:
2177
- st.write(f"**{result.get('title', 'No title')}**")
2178
- st.write(result.get('snippet', 'No snippet available.'))
2179
- st.write(f"[Read more]({result.get('link', '#')})")
2180
- st.write("---")
2181
-
2182
  else:
2183
  st.warning("Please enter case details or upload a document to analyze.")
2184
 
@@ -2419,7 +2419,7 @@ st.markdown("---")
2419
  st.markdown(
2420
  """
2421
  <div style="text-align: center;">
2422
- <p>© 2023 Lex AI. All rights reserved.</p>
2423
  <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>
2424
  </div>
2425
  """,
 
1812
  st.warning(f"No lawyers found in {city}, {state}. Try selecting a different city or state.")
1813
 
1814
  def analyze_policy(policy_text: str) -> Dict[str, Any]:
1815
+ chunks = split_text(policy_text)
1816
+ full_analysis = ""
 
1817
 
1818
+ for i, chunk in enumerate(chunks):
1819
+ analysis_prompt = f"""
1820
+ Analyze the following part of the policy text ({i+1}/{len(chunks)}), taking into account US legal and societal contexts:
 
1821
 
1822
+ Policy Text (Part {i+1}/{len(chunks)}):
1823
+ ```
1824
+ {chunk}
1825
+ ```
1826
+
1827
+ Provide a comprehensive analysis that includes:
1828
+ * **Summary:** Briefly summarize the key points of the policy.
1829
+ * **Large-Scale Impact:** Discuss the potential impact of this policy on a national or state level. Consider economic, social, and legal implications.
1830
+ * **Small-Scale Impact:** Analyze how this policy might affect individuals, families, or specific communities within the US.
1831
+ * **Long-Term Benefits:** What are the potential advantages of this policy in the long run (5-10 years or more)?
1832
+ * **Short-Term Benefits:** What benefits might be observed within the first few years of implementing this policy?
1833
+ * **Potential Drawbacks:** Are there any possible negative consequences or challenges in implementing this policy?
1834
+ * **Legal Considerations:** Are there any existing US laws or regulations that this policy might conflict with or be affected by?
1835
+ * **Historical Context:** Are there any historical parallels or past US policies that might inform the potential outcomes of this policy?
1836
+ * **Suggestions for Improvement:** Offer specific recommendations on how the policy could be modified to enhance its effectiveness or mitigate potential drawbacks.
1837
+ * **Stakeholder Perspectives:** Identify different groups or entities in the US that might have an interest in this policy (e.g., businesses, consumers, government agencies), and how they might view it.
1838
+ Support your analysis with relevant examples, statistics, or legal precedents from the US, where applicable.
1839
+ Maintain a neutral and objective tone, presenting both potential advantages and disadvantages of the policy.
1840
+ """
1841
 
1842
+ try:
1843
+ chunk_analysis = get_ai_response(analysis_prompt)
1844
+ full_analysis += chunk_analysis + "\n\n"
1845
+ except Exception as e:
1846
+ return {"error": f"Error analyzing part {i+1} of the policy text: {str(e)}"}
1847
+
1848
+ return {"analysis": full_analysis}
1849
 
1850
  def policy_analysis_ui():
1851
  st.subheader("Policy Analysis & Impact")
 
1855
  ''')
1856
 
1857
  st.warning("Please do not upload files larger than 5MB as it may cause issues and consume all available tokens.")
 
 
 
1858
 
1859
  input_method = st.radio("Choose input method:", ("Text Input", "Document Upload"))
1860
 
 
1874
  if "error" in analysis_results:
1875
  st.error(analysis_results["error"])
1876
  else:
1877
+ analysis = analysis_results.get("analysis", "No analysis available.")
1878
  st.write("### Policy Analysis")
1879
+ st.write(analysis)
1880
 
1881
+ # Download button
 
1882
  st.download_button(
1883
+ label="Download Complete Analysis",
1884
+ data=analysis,
1885
  file_name="policy_analysis.txt",
1886
  mime="text/plain"
1887
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1888
  else:
1889
  st.warning("Please enter policy text or upload a document to analyze.")
1890
 
1891
+ def generate_web_search_query(user_input: str) -> str:
1892
+ """Generates a web search query based on user input using Falcon."""
1893
+ prompt = f"""
1894
+ Generate a concise and effective web search query that can be used
1895
+ to find additional information about the following legal situation
1896
+ related to US law:
1897
 
 
1898
  ```
1899
  {user_input}
1900
+ ```
 
 
 
 
 
 
 
 
 
1901
  """
1902
 
1903
  try:
1904
+ response = ai71.chat.completions.create(
1905
+ model="tiiuae/falcon-180b-chat",
1906
+ messages=[{"role": "user", "content": prompt}],
1907
+ stream=False,
1908
+ )
1909
+ return response.choices[0].message.content.strip()
 
1910
  except Exception as e:
1911
+ print(f"Error generating web search query: {str(e)}")
1912
+ return user_input
1913
+
1914
+ def provide_legal_advice(user_input: str) -> Dict[str, Any]:
1915
+ """Provides legal advice, suggestions, and generates a web search query."""
1916
+ chunks = split_text(user_input)
1917
+ full_advice = ""
1918
+
1919
+ for i, chunk in enumerate(chunks):
1920
+ advice_prompt = f"""
1921
+ Provide legal advice based on US law for the following situation or question (part {i+1}/{len(chunks)}):
1922
+
1923
+ User Input (Part {i+1}/{len(chunks)}):
1924
+ ```
1925
+ {chunk}
1926
+ ```
1927
+
1928
+ Please include:
1929
+ 1. A summary of the legal issue or question
1930
+ 2. Relevant US laws or regulations that apply
1931
+ 3. Possible legal implications or consequences
1932
+ 4. General advice or next steps (without constituting specific legal counsel)
1933
+ 5. Any important disclaimers or limitations of this advice
1934
+ Remember to maintain a professional and objective tone throughout your response.
1935
+
1936
+ Suggestions: Provide 2-3 actionable suggestions that the user could consider based on the legal situation.
1937
+ """
1938
+
1939
+ try:
1940
+ chunk_advice = get_ai_response(advice_prompt)
1941
+ full_advice += chunk_advice + "\n\n"
1942
+ except Exception as e:
1943
+ return {"error": f"Error providing legal advice (part {i+1}): {str(e)}"}
1944
+
1945
+ return {"advice": full_advice}
1946
 
1947
  def legal_consultant_ui():
1948
  st.subheader("Legal Consultant")
1949
 
1950
+ if 'consultant_chat_history' not in st.session_state:
1951
+ st.session_state.consultant_chat_history = []
1952
 
1953
  if 'uploaded_document' not in st.session_state:
1954
  st.session_state.uploaded_document = None
 
1961
 
1962
  st.warning("Please do not upload files larger than 5MB as it may cause issues and consume all available tokens.")
1963
 
 
1964
  uploaded_file = st.file_uploader("Upload a legal document (PDF, DOCX, or TXT)", type=["pdf", "docx", "txt"])
1965
 
1966
  if uploaded_file:
1967
  st.session_state.uploaded_document = extract_text_from_document(uploaded_file)
1968
  st.success("Document uploaded successfully!")
1969
 
1970
+ for message in st.session_state.consultant_chat_history:
1971
+ if isinstance(message, tuple):
1972
+ user_msg, bot_msg = message
1973
+ st.info(f"**You:** {user_msg}")
1974
+ st.success(f"**Lex AI:** {bot_msg}")
1975
+ elif isinstance(message, dict):
1976
+ if message.get('type') == 'web_search':
1977
+ web_results_msg = "Web Search Results:\n"
1978
+ for result in message.get('results', []):
1979
+ web_results_msg += f"[{result.get('title', 'No title')}]({result.get('link', '#')})\n{result.get('snippet', 'No snippet available.')}\n\n"
1980
+ st.success(f"**Lex AI:** {web_results_msg}")
1981
+
1982
  user_input = st.text_input("Your legal question:")
1983
 
1984
  if user_input and st.button("Send"):
1985
  with st.spinner("Processing your question..."):
1986
  if st.session_state.uploaded_document:
 
1987
  full_input = f"Document context: {st.session_state.uploaded_document}\n\nUser question: {user_input}"
1988
  else:
1989
  full_input = user_input
1990
 
1991
  result = provide_legal_advice(full_input)
1992
+
1993
  if "error" in result:
1994
  st.error(result["error"])
1995
  else:
1996
+ st.session_state.consultant_chat_history.append((user_input, result["advice"]))
1997
+
1998
+ # Generate web search query and perform search
1999
+ search_query = generate_web_search_query(user_input)
2000
+ web_results = search_web_duckduckgo(search_query)
2001
 
2002
+ st.session_state.consultant_chat_history.append({
2003
+ 'type': 'web_search',
2004
+ 'results': web_results
2005
+ })
 
 
2006
 
2007
  st.rerun()
2008
 
2009
  def display_chat_history_legal_advise():
2010
+ for message in st.session_state.chat_history:
2011
+ if isinstance(message, tuple):
2012
+ user_msg, bot_msg = message
2013
+ st.info(f"**You:** {user_msg}")
2014
+ st.success(f"**Lex AI:** {bot_msg}")
2015
+ elif isinstance(message, dict):
2016
+ if message.get('type') == 'web_search':
2017
+ web_results_msg = "Web Search Results:\n"
2018
+ for result in message.get('results', []):
2019
+ web_results_msg += f"[{result.get('title', 'No title')}]({result.get('link', '#')})\n{result.get('snippet', 'No snippet available.')}\n\n"
2020
+ st.success(f"**Lex AI:** {web_results_msg}")
 
 
 
 
2021
 
2022
+ def draft_contract(contract_details: str) -> Dict[str, Any]:
2023
+ chunks = split_text(contract_details)
2024
+ full_draft = ""
2025
 
2026
+ for i, chunk in enumerate(chunks):
2027
+ drafting_prompt = f"""
2028
+ Draft a legally sound and comprehensive contract based on the following details (part {i+1}/{len(chunks)}), ensuring compliance with US law.
2029
 
2030
+ Contract Details (Part {i+1}/{len(chunks)}):
2031
+ ```
2032
+ {chunk}
2033
+ ```
2034
+
2035
+ Output Format:
2036
+ Present the drafted contract in a clear and organized manner, using sections and headings.
2037
+ Include the following essential clauses (and any others relevant to the provided details):
2038
+ * Parties: Clearly identify the names and addresses of all parties entering into the contract.
2039
+ * Term and Termination: Specify the duration of the contract and conditions for renewal or termination.
2040
+ * Payment Terms: Outline payment details, including amounts, schedule, and methods.
2041
+ * Governing Law: State that the contract shall be governed by the laws of the state specified in the details.
2042
+ * Dispute Resolution: Include a clause outlining how disputes will be handled (e.g., mediation, arbitration).
2043
+ * Entire Agreement: State that the written contract represents the entire agreement between the parties.
2044
+ * Signatures: Leave space for the dated signatures of all parties involved.
2045
+ """
2046
 
2047
+ try:
2048
+ chunk_draft = get_ai_response(drafting_prompt)
2049
+ full_draft += chunk_draft + "\n\n"
 
2050
 
2051
+ except Exception as e:
2052
+ return {"error": f"Error drafting contract (part {i+1}): {str(e)}"}
 
 
 
 
 
 
 
 
 
 
2053
 
2054
+ return {"draft": full_draft}
 
 
 
 
2055
 
2056
  def contract_drafting_ui():
2057
  st.subheader("Contract Drafting Assistant")
 
2089
  else:
2090
  st.write("### Drafted Contract")
2091
  contract_draft = draft_results.get("draft", "No draft available.")
2092
+ st.write(contract_draft)
2093
 
2094
  st.download_button(
2095
  label="Download Contract",
 
2097
  file_name="drafted_contract.txt",
2098
  mime="text/plain"
2099
  )
2100
+
2101
  else:
2102
  st.warning("Please enter contract details or upload a document to proceed.")
2103
 
2104
  def analyze_case_for_prediction(case_details: str) -> Dict[str, Any]:
2105
+ chunks = split_text(case_details)
2106
+ full_analysis = ""
 
2107
 
2108
+ for i, chunk in enumerate(chunks):
2109
+ analysis_prompt = f"""
2110
+ Analyze the following case details (part {i+1}/{len(chunks)}) in the context of the US legal system and provide a predictive analysis.
 
2111
 
2112
+ Case Details (Part {i+1}/{len(chunks)}):
2113
+ ```
2114
+ {chunk}
2115
+ ```
2116
+
2117
+ Your analysis should address the following:
2118
+ * **Case Summary:** Briefly summarize the key facts, legal claims, and parties involved in the case.
2119
+ * **Predicted Outcome:** What is the most likely outcome of this case based on the provided information, US legal precedents, and similar cases? Explain your reasoning.
2120
+ * **Strengths of the Case:** Identify the most compelling arguments and evidence that support a favorable outcome.
2121
+ * **Weaknesses of the Case:** What are potential weaknesses in the case, or areas where the opposing party might have strong arguments?
2122
+ * **Areas of Caution:** What potential pitfalls or challenges should be considered? What strategies could the opposing party use?
2123
+ * **Relevant US Case Law:** Cite specific US legal precedents and similar cases that support your analysis and predicted outcome.
2124
+ * **Recommended Strategies:** Offer specific, actionable recommendations on how to strengthen the case and increase the likelihood of a positive result.
2125
+
2126
+ Please maintain a neutral and objective tone throughout your analysis. The goal is to provide a realistic assessment of the case, not to advocate for a particular side.
2127
+ """
2128
 
2129
+ try:
2130
+ chunk_analysis = get_ai_response(analysis_prompt)
2131
+ full_analysis += chunk_analysis + "\n\n"
 
 
 
 
2132
 
2133
+ except Exception as e:
2134
+ return {"error": f"Error analyzing case (part {i+1}): {str(e)}"}
2135
 
2136
+ return {"analysis": full_analysis}
 
 
 
 
2137
 
2138
  def predictive_analysis_ui():
2139
  st.subheader("Predictive Case Analysis")
 
2169
  if "error" in analysis_results:
2170
  st.error(analysis_results["error"])
2171
  else:
2172
+ analysis = analysis_results.get("analysis", "No analysis available.")
2173
+ st.write(analysis)
2174
 
2175
+ # Download button for analysis
 
2176
  st.download_button(
2177
  label="Download Analysis",
2178
+ data=analysis,
2179
  file_name="case_analysis.txt",
2180
  mime="text/plain"
2181
  )
 
 
 
 
 
 
 
 
 
 
2182
  else:
2183
  st.warning("Please enter case details or upload a document to analyze.")
2184
 
 
2419
  st.markdown(
2420
  """
2421
  <div style="text-align: center;">
2422
+ <p>© 2024 Lex AI. All rights reserved.</p>
2423
  <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>
2424
  </div>
2425
  """,