Ashar086 commited on
Commit
a0df3c4
·
verified ·
1 Parent(s): eef8a3a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -1
app.py CHANGED
@@ -5,6 +5,155 @@ from together import Together
5
  # Initialize Together AI client
6
  together_client = Together(api_key=st.secrets["TOGETHER_API_KEY"])
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  # Set up the API URL for AI/ML analysis
9
  AI_ML_API_URL = st.secrets["AI_ML_API_URL"]
10
  AI_ML_API_KEY = st.secrets["AI_ML_API_KEY"]
@@ -127,4 +276,4 @@ if st.session_state.uploaded_file is not None:
127
  st.success("Response generated for review.")
128
 
129
  else:
130
- st.write("Please upload a contract to begin the analysis.")
 
5
  # Initialize Together AI client
6
  together_client = Together(api_key=st.secrets["TOGETHER_API_KEY"])
7
 
8
+ # Set up the API URL and Key for AI/ML analysis
9
+ AI_ML_API_URL = st.secrets["AI_ML_API_URL"]
10
+ AI_ML_API_KEY = st.secrets["AI_ML_API_KEY"]
11
+
12
+ def analyze_text(text):
13
+ headers = {
14
+ "Authorization": f"Bearer {AI_ML_API_KEY}",
15
+ "Content-Type": "application/json"
16
+ }
17
+ payload = {
18
+ "text": text,
19
+ "task": "analyze_contract" # Adjust this based on your API's specific requirements
20
+ }
21
+
22
+ # Send a POST request
23
+ response = requests.post(AI_ML_API_URL, headers=headers, json=payload)
24
+
25
+ # Fallback to GET request if POST method is not allowed
26
+ if response.status_code == 405:
27
+ response = requests.get(AI_ML_API_URL, headers=headers, params=payload)
28
+
29
+ # Print the response for debugging
30
+ st.write(f"Response Status: {response.status_code}")
31
+ st.write(f"Response Text: {response.text}")
32
+
33
+ if response.status_code == 200:
34
+ # Ensure that the response is JSON before trying to parse it
35
+ if response.headers.get("Content-Type") == "application/json":
36
+ try:
37
+ return response.json()
38
+ except ValueError:
39
+ st.error("Invalid JSON received from the API.")
40
+ return None
41
+ else:
42
+ st.error("The API did not return a JSON response. Response: " + response.text)
43
+ return None
44
+ else:
45
+ # Handle failed responses
46
+ error_message = f"Failed to analyze the text. Status code: {response.status_code}. Response: {response.text}"
47
+ st.error(error_message)
48
+ return None
49
+
50
+ def call_together_for_response(analysis_results, user_decisions):
51
+ prompt = "As an AI assistant specializing in contract analysis, draft a professional and courteous response to a contract drafter based on the following analyses and decisions:\n\n"
52
+
53
+ for clause, decision in zip(analysis_results, user_decisions):
54
+ prompt += f"Clause: {clause.get('section', 'Unnamed Section')}\n"
55
+ prompt += f"Analysis: {clause.get('analysis', 'No analysis provided')}\n"
56
+ prompt += f"Decision: {decision['action']}\n"
57
+ if decision['action'] == 'Negotiate':
58
+ prompt += f"Negotiation points: {decision['negotiation_points']}\n"
59
+ prompt += "\n"
60
+
61
+ prompt += "Draft a response that addresses each clause, explaining our position on acceptance, rejection, or negotiation. The tone should be professional, courteous, and constructive."
62
+
63
+ # Send the prompt to Together AI
64
+ response = together_client.chat.completions.create(
65
+ model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
66
+ messages=[{"role": "user", "content": prompt}],
67
+ max_tokens=2048,
68
+ temperature=0.3,
69
+ top_p=0.8,
70
+ top_k=50,
71
+ repetition_penalty=1,
72
+ stop=["<|eot_id|>", "<|eom_id|>"],
73
+ stream=False
74
+ )
75
+ return response.choices[0].message.content
76
+
77
+ # Streamlit UI setup
78
+ st.title("Contract Analysis Assistant")
79
+
80
+ if 'uploaded_file' not in st.session_state:
81
+ st.session_state.uploaded_file = None
82
+ if 'analysis_results' not in st.session_state:
83
+ st.session_state.analysis_results = None
84
+
85
+ uploaded_file = st.file_uploader("Upload Contract", type=["txt", "pdf", "docx"])
86
+
87
+ if uploaded_file is not None and uploaded_file != st.session_state.uploaded_file:
88
+ st.session_state.uploaded_file = uploaded_file
89
+ st.session_state.analysis_results = None
90
+
91
+ if st.session_state.uploaded_file is not None:
92
+ if st.session_state.analysis_results is None:
93
+ with st.spinner("Analyzing contract..."):
94
+ file_content = st.session_state.uploaded_file.read()
95
+ if uploaded_file.type == "application/pdf":
96
+ # Add PDF text extraction logic here
97
+ text_content = "Extracted text from PDF" # Replace with actual extraction logic
98
+ elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
99
+ # Add DOCX text extraction logic here
100
+ text_content = "Extracted text from DOCX" # Replace with actual extraction logic
101
+ else:
102
+ text_content = file_content.decode('utf-8')
103
+
104
+ analysis_results = analyze_text(text_content)
105
+ if analysis_results:
106
+ st.session_state.analysis_results = analysis_results
107
+ st.write("Contract analyzed successfully.")
108
+ else:
109
+ st.error("Failed to analyze the contract. Please check the error message above and try again.")
110
+
111
+ if st.session_state.analysis_results is not None:
112
+ analysis_results = st.session_state.analysis_results
113
+
114
+ user_decisions = []
115
+ for clause in analysis_results:
116
+ section = clause.get('section', 'Unnamed Section')
117
+ st.subheader(f"Clause: {section}")
118
+ st.write("Analysis:")
119
+ st.write(clause.get('analysis', 'No analysis provided'))
120
+
121
+ action = st.selectbox(
122
+ f"Action for {section}",
123
+ ["Accept", "Negotiate", "Reject"],
124
+ key=f"action_{section}"
125
+ )
126
+ negotiation_points = ""
127
+ if action == "Negotiate":
128
+ negotiation_points = st.text_area("Enter your negotiation points:", key=f"negotiate_{section}")
129
+
130
+ user_decisions.append({
131
+ "section": section,
132
+ "action": action,
133
+ "negotiation_points": negotiation_points
134
+ })
135
+
136
+ st.markdown("---")
137
+
138
+ if st.button("Generate Response"):
139
+ with st.spinner("Generating response..."):
140
+ response_to_drafter = call_together_for_response(analysis_results, user_decisions)
141
+ st.subheader("Response to Contract Drafter:")
142
+ st.text_area("", response_to_drafter, height=400)
143
+ st.success("Response generated for review.")
144
+
145
+ else:
146
+ st.write("Please upload a contract to begin the analysis.")
147
+
148
+
149
+ '''
150
+ import streamlit as st
151
+ import requests
152
+ from together import Together
153
+
154
+ # Initialize Together AI client
155
+ together_client = Together(api_key=st.secrets["TOGETHER_API_KEY"])
156
+
157
  # Set up the API URL for AI/ML analysis
158
  AI_ML_API_URL = st.secrets["AI_ML_API_URL"]
159
  AI_ML_API_KEY = st.secrets["AI_ML_API_KEY"]
 
276
  st.success("Response generated for review.")
277
 
278
  else:
279
+ st.write("Please upload a contract to begin the analysis.") '''