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 
 
 
 
 
 
 
 
 
 
 
 
5ff8f40
 
 
6aed8e6
 
 
 
 
5b8d529
 
6aed8e6
5ff8f40
 
 
6aed8e6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import streamlit as st
import requests
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=8000,
        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=8000,
        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=8000,
        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 ""


    client = Groq()
    completion = client.chat.completions.create(
        model="llama-3.1-70b-versatile",
        messages=[
            {
                "role": "system",
                "content": "You are an experienced writer. You will be given an array of questions. \nSome questions will ask to upload images. Ignore any of these type of questions.\nSome questions ask about different identities or descriptions of the same thing. I want you to merge the questions so as to ask input from them once.\nConvert all questions so that more of a professional but also a bit of a funny tone is maintained. AVOID REDUNDANCY. DONT RETURN MORE THAN 15 QUESTIONS.\nRETURN AN ARRAY OF THE QUESTIONS ONLY. DO NOT RETURN ANYTHING ELSE. "
            },
            {
                "role": "user",
                "content": answer
            }
        ],
        temperature=0.73,
        max_tokens=2240,
        top_p=1,
        stream=True,
        stop=None,
    )
    final=""
    for chunk in completion:
        final+=chunk.choices[0].delta.content or ""

    return final

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. After filling, merge the two filled JSONs. Then return the final completely filled JSON. 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=8000,
        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=5610,
        top_p=1,
        stream=True,
        stop=None,
    )
    final_summ=""
    for chunk in completion:
        final_summ+=chunk.choices[0].delta.content or ""
    return final_summ

def chunk_data(data, chunk_size=10):
    if isinstance(data, dict):
        # If data is a dictionary, convert it to a list of key-value pairs
        items = list(data.items())
    elif isinstance(data, list):
        items = data
    else:
        raise TypeError("Data must be either a dictionary or a list")
    
    return [dict(items[i:i + chunk_size]) for i in range(0, len(items), chunk_size)]

def airtable_write(json_template):

    client = Groq(api_key=os.getenv("GROQ_API_KEY"))

    # Groq inference
    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 unstructured JSON. I want you to convert it into a fully structured JSON which will become a structured CSV. The headings of the CSV are to be \\\"Category\\\",\\\"Sub-category\\\",\\\"Description\\\" and \\\"User Answer\\\". So shuffle around the fields accordingly. \nFields marked \"Category\" are to be directly picked as the \"Category\" for the CSV. If there is \"Observation type\", then that becomes the Category.  \nDONT LEAVE ANY FIELD. MAKE SURE ALL FIELDS ARE INCLUDED IN THE RESULT. DONT OUTPUT ANYTHING OTHER THAN THE JSON. ONLY OUTPUT THE JSON.\n"
            },
            {
                "role": "user",
                "content": json_template
            }
        ],
        temperature=0.25,
        max_tokens=8000,
        top_p=1,
        stream=True,
        # response_format={"type": "json_object"},
        stop=None,
    )
    content=""
    for chunk in completion:
        content+=chunk.choices[0].delta.content or ""
    # Get the structured JSON from Groq
    groq_json = json.loads(content)
    with open("groq_json.json", "w") as file:
        json.dump(groq_json, file, indent=4)
    API_KEY = os.getenv("AIRTABLE_KEY")
    BASE_ID = 'appcl0egQeE4pP5ID'
    TABLE_ID = 'tbl2AaOSxyBv6ObR5'
    url = f'https://api.airtable.com/v0/{BASE_ID}/{TABLE_ID}'

    headers = {
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    }

    # Chunk the data into batches of 10
    def chunk_data(data, chunk_size=10):
        for i in range(0, len(data), chunk_size):
            yield data[i:i + chunk_size]

    # Process each chunk and send it to Airtable
    for batch in chunk_data(groq_json):
        # Format the current batch for Airtable API
        airtable_data = {
            "records": [
                {
                    "fields": {
                        "Category": item["Category"],
                        "Sub-category": item["Sub-category"],
                        "Description": item["Description"],
                        "User Answer": item["User Answer"]
                    }
                } for item in batch
            ]
        }
        
        # Make the POST request to add records
        response = requests.post(url, headers=headers, data=json.dumps(airtable_data))
        
        # Check if the request was successful
        if response.status_code == 200:
            print(f"Batch of {len(batch)} records added successfully!")
        else:
            print(f"Failed to add batch. Status code: {response.status_code}, Error: {response.text}")

            
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
    init_session_state()

    # File uploader for the PDF
    uploaded_file = st.file_uploader("Upload a PDF document", type="pdf")
    if uploaded_file is not None and not st.session_state.file_processed:
        st.write("Processing your document...")
        process_document(uploaded_file)
        # Display the first question immediately after processing the document
        show_question()

    # Simulate chat interaction
    chat_interaction()

def init_session_state():
    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

def process_document(uploaded_file):
    # 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)
    while True:
        try:
            # Attempt to evaluate the expressions and assign them to session state
            st.session_state.questions = ast.literal_eval(questionbizobj) + ast.literal_eval(questionobs)
            # If successful, break out of the loop
            break
        except Exception as e:
            # Print the error for debugging purposes (optional)
            print(f"An error occurred: {e}")
            # Wait for 1 second before trying again
            time.sleep(1)
            continue
    st.write(st.session_state.questions)
    # Mark file as processed
    st.session_state.file_processed = True
    st.success("Document processed successfully.")

def chat_interaction():
    # Display chat messages from history in the correct order
    for message in st.session_state.messages[::-1]:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])

    # React to user input
    if prompt := st.chat_input("What is your question?"):
        # Display user message in chat message container
        st.chat_message("user").markdown(prompt)

        # Add user message to chat history
        st.session_state.messages.append({"role": "user", "content": prompt})

        # Process the user's input and show the next question
        show_question()

def show_question():
    if st.session_state.current_question_index < len(st.session_state.questions):
        # Display the next question
        with st.chat_message("assistant"):
            st.markdown(st.session_state.questions[st.session_state.current_question_index])

        # Add the question to the chat history
        st.session_state.messages.append({"role": "assistant", "content": st.session_state.questions[st.session_state.current_question_index]})

        # 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
            
    else:
        # Display the answers after completing the questionnaire
        answers = [message["content"] for message in st.session_state.messages if message["role"] == "user"]
        # with st.chat_message("assistant"):
            # st.subheader("Answers")
            # st.write(answers)
        
        completed_json = answer_refill(st.session_state.questions, answers, st.session_state.obs, st.session_state.bizobj)
        # st.write(completed_json)
        airtable_write(completed_json)
        exec_summ = executive_summary(completed_json)
        st.write(exec_summ)

if __name__ == "__main__":
    main()