Update app.py
Browse files4 unmodified lines5678910116 unmodified lines1271281291304 unmodified lines# Initialize Together AI clienttogether_client = Together(api_key=st.secrets["TOGETHER_API_KEY"])# Set up the API URL for AI/ML analysisAI_ML_API_URL = st.secrets["AI_ML_API_URL"]AI_ML_API_KEY = st.secrets["AI_ML_API_KEY"]116 unmodified linesst.success("Response generated for review.")else:st.write("Please upload a contract to begin the analysis.")4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159116 unmodified lines2762772782794 unmodified lines# Initialize Together AI clienttogether_client = Together(api_key=st.secrets["TOGETHER_API_KEY"])# Set up the API URL and Key for AI/ML analysisAI_ML_API_URL = st.secrets["AI_ML_API_URL"]AI_ML_API_KEY = st.secrets["AI_ML_API_KEY"]def analyze_text(text):headers = {"Authorization": f"Bearer {AI_ML_API_KEY}","Content-Type": "application/json"}payload = {"text": text,"task": "analyze_contract" # Adjust this based on your API's specific requirements}# Send a POST requestresponse = requests.post(AI_ML_API_URL, headers=headers, json=payload)# Fallback to GET request if POST method is not allowedif response.status_code == 405:response = requests.get(AI_ML_API_URL, headers=headers, params=payload)# Print the response for debuggingst.write(f"Response Status: {response.status_code}")st.write(f"Response Text: {response.text}")if response.status_code == 200:# Ensure that the response is JSON before trying to parse itif response.headers.get("Content-Type") == "application/json":try:return response.json()except ValueError:st.error("Invalid JSON received from the API.")return Noneelse:st.error("The API did not return a JSON response. Response: " + response.text)return Noneelse:# Handle failed responseserror_message = f"Failed to analyze the text. Status code: {response.status_code}. Response: {response.text}"st.error(error_message)return Nonedef call_together_for_response(analysis_results, user_decisions):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"for clause, decision in zip(analysis_results, user_decisions):prompt += f"Clause: {clause.get('section', 'Unnamed Section')}\n"prompt += f"Analysis: {clause.get('analysis', 'No analysis provided')}\n"prompt += f"Decision: {decision['action']}\n"if decision['action'] == 'Negotiate':prompt += f"Negotiation points: {decision['negotiation_points']}\n"prompt += "\n"prompt += "Draft a response that addresses each clause, explaining our position on acceptance, rejection, or negotiation. The tone should be professional, courteous, and constructive."# Send the prompt to Together AIresponse = together_client.chat.completions.create(model="meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",messages=[{"role": "user", "content": prompt}],max_tokens=2048,temperature=0.3,top_p=0.8,top_k=50,repetition_penalty=1,stop=["<|eot_id|>", "<|eom_id|>"],stream=False)return response.choices[0].message.content# Streamlit UI setupst.title("Contract Analysis Assistant")if 'uploaded_file' not in st.session_state:st.session_state.uploaded_file = Noneif 'analysis_results' not in st.session_state:st.session_state.analysis_results = Noneuploaded_file = st.file_uploader("Upload Contract", type=["txt", "pdf", "docx"])if uploaded_file is not None and uploaded_file != st.session_state.uploaded_file:st.session_state.uploaded_file = uploaded_filest.session_state.analysis_results = Noneif st.session_state.uploaded_file is not None:if st.session_state.analysis_results is None:with st.spinner("Analyzing contract..."):file_content = st.session_state.uploaded_file.read()if uploaded_file.type == "application/pdf":# Add PDF text extraction logic heretext_content = "Extracted text from PDF" # Replace with actual extraction logicelif uploaded_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":# Add DOCX text extraction logic heretext_content = "Extracted text from DOCX" # Replace with actual extraction logicelse:text_content = file_content.decode('utf-8')analysis_results = analyze_text(text_content)if analysis_results:st.session_state.analysis_results = analysis_resultsst.write("Contract analyzed successfully.")else:st.error("Failed to analyze the contract. Please check the error message above and try again.")if st.session_state.analysis_results is not None:analysis_results = st.session_state.analysis_resultsuser_decisions = []for clause in analysis_results:section = clause.get('section', 'Unnamed Section')st.subheader(f"Clause: {section}")st.write("Analysis:")st.write(clause.get('analysis', 'No analysis provided'))action = st.selectbox(f"Action for {section}",["Accept", "Negotiate", "Reject"],key=f"action_{section}")negotiation_points = ""if action == "Negotiate":negotiation_points = st.text_area("Enter your negotiation points:", key=f"negotiate_{section}")user_decisions.append({"section": section,"action": action,"negotiation_points": negotiation_points})st.markdown("---")if st.button("Generate Response"):with st.spinner("Generating response..."):response_to_drafter = call_together_for_response(analysis_results, user_decisions)st.subheader("Response to Contract Drafter:")st.text_area("", response_to_drafter, height=400)st.success("Response generated for review.")else:st.write("Please upload a contract to begin the analysis.")'''import streamlit as stimport requestsfrom together import Together# Initialize Together AI clienttogether_client = Together(api_key=st.secrets["TOGETHER_API_KEY"])# Set up the API URL for AI/ML analysisAI_ML_API_URL = st.secrets["AI_ML_API_URL"]AI_ML_API_KEY = st.secrets["AI_ML_API_KEY"]116 unmodified linesst.success("Response generated for review.")else:st.write("Please upload a contract to begin the analysis.") '''
app.py+150-1