import streamlit as st import os import json from pypdf import PdfReader from groq import Groq from dotenv import load_dotenv import time import ast # Load environment variables load_dotenv() # Function to extract text from the uploaded PDF def extract_text_from_pdf(pdf_file): text = "" try: reader = PdfReader(pdf_file) for page in reader.pages: text += page.extract_text() except Exception as e: st.error(f"An error occurred while reading the PDF: {e}") return text # Function to classify the extracted text using the LLM def classification_LLM(text): client = Groq(api_key=os.getenv("GROQ_API_KEY")) completion = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful classification assistant. You understand engineering concepts. You will be given some text which mostly describes a problem. You have to classify the problem according to a list of choices. More than one choice can also be applicable. Return as a array of applicable CHOICES only. Only return the choices that you are very sure about\n\n#CHOICES\n\n2D Measurement: Diameter, thickness, etc.\n\nAnomaly Detection: Scratches, dents, corrosion\n\nPrint Defect: Smudging, misalignment\n\nCounting: Individual components, features\n\n3D Measurement: Volume, surface area\n\nPresence/Absence: Missing components, color deviations\n\nOCR: Optical Character Recognition, Font types and sizes to be recognized, Reading speed and accuracy requirements\n\nCode Reading: Types of codes to read (QR, Barcode)\n\nMismatch Detection: Specific features to compare for mismatches, Component shapes, color mismatches\n\nClassification: Categories of classes to be identified, Features defining each class\n\nAssembly Verification: Checklist of components or features to verify, Sequence of assembly to be followed\n\nColor Verification: Color standards or samples to match\n" }, { "role": "user", "content": text } ], temperature=0.21, max_tokens=2048, top_p=1, stream=True, stop=None, ) answer = "" for chunk in completion: answer += chunk.choices[0].delta.content or "" return answer def obsjsoncreate(json_template,text,ogtext): client = Groq(api_key=os.getenv("GROQ_API_KEY")) completion = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful assistant. You will be given a text snippet. You will also be given a JSON where some of the fields match with the bullet points in the text. I want you return a JSON where only the fields and subproperties mentioned in the text are present. DONT OUTPUT ANYTHING OTHER THAN THE JSON\n" }, { "role": "user", "content": "JSON:"+str(json_template)+"\nText:"+text } ], temperature=0.21, max_tokens=2048, top_p=1, stream=True, stop=None, ) cutjson="" for chunk in completion: cutjson += chunk.choices[0].delta.content or "" completion2 = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful classification assistant. You understand engineering concepts. You will be given a JSON where there are properties and their descriptions. You need to fill up the JSON subproperty \"USer Answer\" from the details given in the text. If you are not sure of any field, leave the \"User Answer\" as TBD. Give the JSON output with the filled fields only. ENSURE THE JSON IS VALID AND PROPERLY FORMATTED. DO NOT OUTPUT ANYTHING OTHER THAN THE JSON." }, { "role": "user", "content": "JSON: "+cutjson+"\n Text: "+ogtext } ], temperature=0.21, max_tokens=2048, top_p=1, stream=True, stop=None, ) answer = "" for chunk in completion2: answer += chunk.choices[0].delta.content or "" return answer def bizobjjsoncreate(json_template,text): client = Groq(api_key=os.getenv("GROQ_API_KEY")) completion2 = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful classification assistant. You understand engineering concepts. You will be given a JSON where there are properties and their descriptions. You need to fill up the JSON subproperty \"USer Answer\" from the details given in the text. If you are not sure of any field, leave the \"User Answer\" as TBD. Give the JSON output with the filled fields only. ENSURE THE JSON IS VALID AND PROPERLY FORMATTED. DO NOT OUTPUT ANYTHING OTHER THAN THE JSON." }, { "role": "user", "content": "JSON: "+str(json_template)+"\n Text: "+text } ], temperature=0.21, max_tokens=2048, top_p=1, stream=True, stop=None, ) answer = "" for chunk in completion2: answer += chunk.choices[0].delta.content or "" return answer def question_create(json_template): client = Groq(api_key=os.getenv("GROQ_API_KEY")) completion = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful assistant. You will be given a JSON where some subproperties labelled \"User Answer\" are marked as \"TBD\". I want you to create questions that you as an assistant would ask the user in order to fill up the User Answer field. Return all the questions for the user in an array. DONT OUTPUT ANYTHING OTHER THAN THE QUESTION ARRAY." }, { "role": "user", "content": str(json_template) } ], temperature=0.21, max_tokens=2048, top_p=1, stream=True, stop=None, ) answer = "" for chunk in completion: answer += chunk.choices[0].delta.content or "" return answer def answer_refill(questions,answers,obs_json_template,bizobj_json_template): client = Groq(api_key=os.getenv("GROQ_API_KEY")) completion = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful assistant. You will be given two arrays, questions and answer. I want you to create a question answer pair. For example, \n#INPUT\nQuestion=['What is my name?', 'What is your age?']\nAnswer=['Mohan','69']\n\n#OUTPUT\n['Question:What is my name? Answer:Mohan','What is your age? Answer:69']\n\nDONT RETURN ANYTHING OTHER THAN THE FINAL ARRAY" }, { "role": "user", "content": "Question="+str(questions)+"\nAnswer="+str(answers) } ], temperature=0.5, max_tokens=4048, top_p=1, stream=True, stop=None, ) qapair = "" for chunk in completion: qapair += chunk.choices[0].delta.content or "" # print(qapair) # print(obs_json_template+bizobj_json_template) # print("Question Answer:"+str(qapair)+"\nJSON:\n"+str(obs_json_template+bizobj_json_template)) completion2 = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a helpful assistant. You will be given a Question-answer pair. You will be given a json. Some subproperties in the JSONs labelled \"User Answer\" are marked as TBD. Based on the question answer pair, I want you to fill the Answer of the question answer pair as it is into the \"User answer\" subproperty. Make sure you return the full JSON, without missing any field. Then return the final completely filled JSONs. DONT OUTPUT ANYTHING OTHER THAN THE JSONS." }, { "role": "user", "content": "Question Answer:"+str(qapair)+"\nJSON:\n"+str(obs_json_template+bizobj_json_template) } ], temperature=1, max_tokens=4610, top_p=1, stream=True, stop=None, ) filled_json="" for chunk in completion2: filled_json+=chunk.choices[0].delta.content or "" # print(filled_json) return filled_json def executive_summary(json_template): client = Groq(api_key=os.getenv("GROQ_API_KEY")) completion = client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ { "role": "system", "content": "You are a professional copyrighter. You will be given a JSON, I want you to create a complete executive summary with headers and subheaders. It should be a structured document. \"User Answer\" are what are the answers you have to focus on. Dont skip any of the Fields in both JSONs. Use the Description to frame the User answer. DONT OUTPUT ANYTHING OTHER THAN THE SUMMARY." }, { "role": "user", "content": str(json_template) } ], temperature=0.73, max_tokens=2610, top_p=1, stream=True, stop=None, ) final_summ="" for chunk in completion: final_summ+=chunk.choices[0].delta.content or "" return final_summ # Streamlit application def main(): st.title("Qualitas Sales Data Collection Chatbot") st.caption("Welcome to the Qualitas Bot. First upload a PDF document which should be customer correspondence, detailing some requirements. Also sometimes the Submit button for the questions is a bit sticky. So You might have to click it twice!") # Initialize session state variables if "file_processed" not in st.session_state: st.session_state.file_processed = False if "questionnaire_started" not in st.session_state: st.session_state.questionnaire_started = False if "current_question_index" not in st.session_state: st.session_state.current_question_index = 0 if "messages" not in st.session_state: st.session_state.messages = [] if "questions" not in st.session_state: st.session_state.questions = [] if "questionnaire_complete" not in st.session_state: st.session_state.questionnaire_complete = False # File uploader for the PDF uploaded_file = st.file_uploader("Upload a PDF document", type="pdf") answers=[] final_bizobj_json=[] bizobj=[] obs=[] final_obs_json=[] if uploaded_file is not None and not st.session_state.file_processed: st.write("Processing your document...") # Simulate file processing (replace with actual logic) st.session_state.text = extract_text_from_pdf(uploaded_file) st.session_state.classification_result = classification_LLM(st.session_state.text) json_path='observationsJSON.json' with open(json_path, 'r') as file: obs_json_template = json.load(file) final_obs_json=obsjsoncreate(obs_json_template,st.session_state.classification_result,st.session_state.text) st.session_state.obs=final_obs_json json_path='BizObjJSON.json' with open(json_path, 'r') as file: bizobj_json_template = json.load(file) final_bizobj_json=bizobjjsoncreate(bizobj_json_template,st.session_state.text) st.session_state.bizobj=final_bizobj_json questionobs=question_create(final_obs_json) questionbizobj=question_create(final_bizobj_json) st.session_state.questions = ast.literal_eval(questionbizobj) + ast.literal_eval(questionobs) # st.write(st.session_state.questions) # Mark file as processed st.session_state.file_processed = True st.success("Document processed successfully.") def show_question(): if st.session_state.current_question_index < len(st.session_state.questions): st.write(st.session_state.questions[st.session_state.current_question_index]) user_input = st.text_input("Your answer:", key=f"input_{st.session_state.current_question_index}") submit_button = st.button("Submit", key=f"submit_{st.session_state.current_question_index}") if submit_button: # Store the answer st.session_state.messages.append({"role": "user", "content": user_input}) # Move to the next question st.session_state.current_question_index += 1 # Check if all questions have been answered if st.session_state.current_question_index >= len(st.session_state.questions): st.session_state.questionnaire_complete = True # Main loop to control the flow of the questionnaire if not st.session_state.questionnaire_complete: show_question() else: # Display the answers after completing the questionnaire answers = [message["content"] for message in st.session_state.messages if message["role"] == "user"] # st.write(st.session_state.questions) # st.write(answers) # st.subheader("Answers") # st.write(answers) if st.session_state.questionnaire_complete: completed_json=answer_refill(st.session_state.questions,answers,st.session_state.obs,st.session_state.bizobj) # st.write(completed_json) exec_summ=executive_summary(completed_json) st.write(exec_summ) if __name__ == "__main__": main()