budhadityac24 commited on
Commit
5ff8f40
1 Parent(s): 2d34e83

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +318 -0
app.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import json
4
+ from pypdf import PdfReader
5
+ from groq import Groq
6
+ from dotenv import load_dotenv
7
+ import time
8
+ import ast
9
+
10
+ # Load environment variables
11
+ load_dotenv()
12
+
13
+ # Function to extract text from the uploaded PDF
14
+ def extract_text_from_pdf(pdf_file):
15
+ text = ""
16
+ try:
17
+ reader = PdfReader(pdf_file)
18
+ for page in reader.pages:
19
+ text += page.extract_text()
20
+ except Exception as e:
21
+ st.error(f"An error occurred while reading the PDF: {e}")
22
+ return text
23
+
24
+ # Function to classify the extracted text using the LLM
25
+ def classification_LLM(text):
26
+
27
+
28
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
29
+ completion = client.chat.completions.create(
30
+ model="llama-3.1-70b-versatile",
31
+ messages=[
32
+ {
33
+ "role": "system",
34
+ "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"
35
+ },
36
+ {
37
+ "role": "user",
38
+ "content": text
39
+ }
40
+ ],
41
+ temperature=0.21,
42
+ max_tokens=2048,
43
+ top_p=1,
44
+ stream=True,
45
+ stop=None,
46
+ )
47
+
48
+ answer = ""
49
+ for chunk in completion:
50
+ answer += chunk.choices[0].delta.content or ""
51
+ return answer
52
+
53
+ def obsjsoncreate(json_template,text,ogtext):
54
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
55
+ completion = client.chat.completions.create(
56
+ model="llama-3.1-70b-versatile",
57
+ messages=[
58
+ {
59
+ "role": "system",
60
+ "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"
61
+ },
62
+ {
63
+ "role": "user",
64
+ "content": "JSON:"+str(json_template)+"\nText:"+text
65
+ }
66
+ ],
67
+ temperature=0.21,
68
+ max_tokens=2048,
69
+ top_p=1,
70
+ stream=True,
71
+ stop=None,
72
+ )
73
+ cutjson=""
74
+ for chunk in completion:
75
+ cutjson += chunk.choices[0].delta.content or ""
76
+
77
+ completion2 = client.chat.completions.create(
78
+ model="llama-3.1-70b-versatile",
79
+ messages=[
80
+ {
81
+ "role": "system",
82
+ "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."
83
+ },
84
+ {
85
+ "role": "user",
86
+ "content": "JSON: "+cutjson+"\n Text: "+ogtext
87
+ }
88
+ ],
89
+ temperature=0.21,
90
+ max_tokens=2048,
91
+ top_p=1,
92
+ stream=True,
93
+ stop=None,
94
+ )
95
+ answer = ""
96
+ for chunk in completion2:
97
+ answer += chunk.choices[0].delta.content or ""
98
+ return answer
99
+
100
+ def bizobjjsoncreate(json_template,text):
101
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
102
+ completion2 = client.chat.completions.create(
103
+ model="llama-3.1-70b-versatile",
104
+ messages=[
105
+ {
106
+ "role": "system",
107
+ "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."
108
+ },
109
+ {
110
+ "role": "user",
111
+ "content": "JSON: "+str(json_template)+"\n Text: "+text
112
+ }
113
+ ],
114
+ temperature=0.21,
115
+ max_tokens=2048,
116
+ top_p=1,
117
+ stream=True,
118
+ stop=None,
119
+ )
120
+ answer = ""
121
+ for chunk in completion2:
122
+ answer += chunk.choices[0].delta.content or ""
123
+ return answer
124
+
125
+ def question_create(json_template):
126
+
127
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
128
+ completion = client.chat.completions.create(
129
+ model="llama-3.1-70b-versatile",
130
+ messages=[
131
+ {
132
+ "role": "system",
133
+ "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."
134
+ },
135
+ {
136
+ "role": "user",
137
+ "content": str(json_template)
138
+ }
139
+ ],
140
+ temperature=0.21,
141
+ max_tokens=2048,
142
+ top_p=1,
143
+ stream=True,
144
+ stop=None,
145
+ )
146
+
147
+ answer = ""
148
+ for chunk in completion:
149
+ answer += chunk.choices[0].delta.content or ""
150
+ return answer
151
+
152
+ def answer_refill(questions,answers,obs_json_template,bizobj_json_template):
153
+
154
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
155
+ completion = client.chat.completions.create(
156
+ model="llama-3.1-70b-versatile",
157
+ messages=[
158
+ {
159
+ "role": "system",
160
+ "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"
161
+ },
162
+ {
163
+ "role": "user",
164
+ "content": "Question="+str(questions)+"\nAnswer="+str(answers)
165
+ }
166
+ ],
167
+ temperature=0.5,
168
+ max_tokens=4048,
169
+ top_p=1,
170
+ stream=True,
171
+ stop=None,
172
+ )
173
+
174
+ qapair = ""
175
+ for chunk in completion:
176
+ qapair += chunk.choices[0].delta.content or ""
177
+ # print(qapair)
178
+ # print(obs_json_template+bizobj_json_template)
179
+ # print("Question Answer:"+str(qapair)+"\nJSON:\n"+str(obs_json_template+bizobj_json_template))
180
+ completion2 = client.chat.completions.create(
181
+ model="llama-3.1-70b-versatile",
182
+ messages=[
183
+ {
184
+ "role": "system",
185
+ "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."
186
+ },
187
+ {
188
+ "role": "user",
189
+ "content": "Question Answer:"+str(qapair)+"\nJSON:\n"+str(obs_json_template+bizobj_json_template)
190
+ }
191
+ ],
192
+ temperature=1,
193
+ max_tokens=4610,
194
+ top_p=1,
195
+ stream=True,
196
+ stop=None,
197
+ )
198
+ filled_json=""
199
+ for chunk in completion2:
200
+ filled_json+=chunk.choices[0].delta.content or ""
201
+ # print(filled_json)
202
+ return filled_json
203
+
204
+
205
+ def executive_summary(json_template):
206
+
207
+
208
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
209
+ completion = client.chat.completions.create(
210
+ model="llama-3.1-70b-versatile",
211
+ messages=[
212
+ {
213
+ "role": "system",
214
+ "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."
215
+ },
216
+ {
217
+ "role": "user",
218
+ "content": str(json_template)
219
+ }
220
+ ],
221
+ temperature=0.73,
222
+ max_tokens=2610,
223
+ top_p=1,
224
+ stream=True,
225
+ stop=None,
226
+ )
227
+ final_summ=""
228
+ for chunk in completion:
229
+ final_summ+=chunk.choices[0].delta.content or ""
230
+ return final_summ
231
+
232
+ # Streamlit application
233
+ def main():
234
+ st.title("Qualitas Sales Data Collection Chatbot")
235
+ 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!")
236
+ # Initialize session state variables
237
+ if "file_processed" not in st.session_state:
238
+ st.session_state.file_processed = False
239
+ if "questionnaire_started" not in st.session_state:
240
+ st.session_state.questionnaire_started = False
241
+ if "current_question_index" not in st.session_state:
242
+ st.session_state.current_question_index = 0
243
+ if "messages" not in st.session_state:
244
+ st.session_state.messages = []
245
+ if "questions" not in st.session_state:
246
+ st.session_state.questions = []
247
+ if "questionnaire_complete" not in st.session_state:
248
+ st.session_state.questionnaire_complete = False
249
+
250
+ # File uploader for the PDF
251
+ uploaded_file = st.file_uploader("Upload a PDF document", type="pdf")
252
+ answers=[]
253
+ final_bizobj_json=[]
254
+ bizobj=[]
255
+ obs=[]
256
+ final_obs_json=[]
257
+ if uploaded_file is not None and not st.session_state.file_processed:
258
+ st.write("Processing your document...")
259
+
260
+ # Simulate file processing (replace with actual logic)
261
+ st.session_state.text = extract_text_from_pdf(uploaded_file)
262
+ st.session_state.classification_result = classification_LLM(st.session_state.text)
263
+ json_path='observationsJSON.json'
264
+ with open(json_path, 'r') as file:
265
+ obs_json_template = json.load(file)
266
+ final_obs_json=obsjsoncreate(obs_json_template,st.session_state.classification_result,st.session_state.text)
267
+ st.session_state.obs=final_obs_json
268
+ json_path='BizObjJSON.json'
269
+ with open(json_path, 'r') as file:
270
+ bizobj_json_template = json.load(file)
271
+ final_bizobj_json=bizobjjsoncreate(bizobj_json_template,st.session_state.text)
272
+ st.session_state.bizobj=final_bizobj_json
273
+ questionobs=question_create(final_obs_json)
274
+ questionbizobj=question_create(final_bizobj_json)
275
+ st.session_state.questions = ast.literal_eval(questionbizobj) + ast.literal_eval(questionobs)
276
+ # st.write(st.session_state.questions)
277
+
278
+ # Mark file as processed
279
+ st.session_state.file_processed = True
280
+ st.success("Document processed successfully.")
281
+
282
+ def show_question():
283
+ if st.session_state.current_question_index < len(st.session_state.questions):
284
+ st.write(st.session_state.questions[st.session_state.current_question_index])
285
+ user_input = st.text_input("Your answer:", key=f"input_{st.session_state.current_question_index}")
286
+ submit_button = st.button("Submit", key=f"submit_{st.session_state.current_question_index}")
287
+
288
+ if submit_button:
289
+ # Store the answer
290
+ st.session_state.messages.append({"role": "user", "content": user_input})
291
+ # Move to the next question
292
+ st.session_state.current_question_index += 1
293
+
294
+ # Check if all questions have been answered
295
+ if st.session_state.current_question_index >= len(st.session_state.questions):
296
+ st.session_state.questionnaire_complete = True
297
+
298
+ # Main loop to control the flow of the questionnaire
299
+ if not st.session_state.questionnaire_complete:
300
+ show_question()
301
+ else:
302
+ # Display the answers after completing the questionnaire
303
+ answers = [message["content"] for message in st.session_state.messages if message["role"] == "user"]
304
+ # st.write(st.session_state.questions)
305
+ # st.write(answers)
306
+ # st.subheader("Answers")
307
+ # st.write(answers)
308
+ if st.session_state.questionnaire_complete:
309
+ completed_json=answer_refill(st.session_state.questions,answers,st.session_state.obs,st.session_state.bizobj)
310
+ # st.write(completed_json)
311
+ exec_summ=executive_summary(completed_json)
312
+ st.write(exec_summ)
313
+
314
+
315
+
316
+
317
+ if __name__ == "__main__":
318
+ main()