Redmind commited on
Commit
f7f6c3a
·
verified ·
1 Parent(s): c7cd792

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -74
app.py CHANGED
@@ -135,18 +135,13 @@ def run_query(query):
135
  # The function that uses the above models
136
  # Define the function that will handle the database query
137
  def database_tool(question):
138
- # print(question)
139
  sql_query = generate_sql_query(question)
140
- #print(sql_query)
141
  return run_query(sql_query)
142
 
143
 
144
  def get_ASN_data(question):
145
- # print(question)
146
  base_url = os.getenv("ASN_API_URL")
147
  complete_url = f"{base_url}branchMaster.id=343&transactionUid={question}&userId=164&transactionType=ASN"
148
- #print("complete url")
149
- #print(complete_url)
150
  try:
151
  response = requests.get(complete_url)
152
  data = response.json()
@@ -239,34 +234,21 @@ def document_data_tool(question):
239
  print(f"Document data tool enter: {question}")
240
  # query_string = question['tags'][0] if 'tags' in question and question['tags'] else ""
241
  query_response = query_vector_store(vector_store, question, config={"callbacks": [langfuse_handler]})
242
- #print("query****")
243
- #print(query_response)
244
  # summarized_response = summarize_document(query_response)
245
- # print("summary***")
246
- # print(summarized_response)
247
  return query_response
248
 
249
 
250
  def send_email_with_attachment(recipient_email, subject, body, image_data):
251
  try:
252
- print(recipient_email)
253
- print(subject)
254
-
255
- #print(image_data)
256
  sender_email = os.getenv("EMAIL_SENDER")
257
  sender_password = os.getenv("EMAIL_PASSWORD")
258
- print(sender_email)
259
- print(sender_password)
260
  # Create a multipart message
261
  msg = MIMEMultipart()
262
  msg['From'] = sender_email
263
  msg['To'] = recipient_email
264
  msg['Subject'] = subject
265
- print(body)
266
  # Attach the body with the msg instance
267
  msg.attach(MIMEText(body, 'plain'))
268
- print(body)
269
- """
270
  # Open the file to be sent
271
  attachment = open(attachment_path, "rb")
272
  #print("Attached the image")
@@ -283,45 +265,12 @@ def send_email_with_attachment(recipient_email, subject, body, image_data):
283
 
284
  # Attach the instance 'part' to instance 'msg'
285
  msg.attach(part)
286
- # Create a MIMEBase instance for the attachment
287
- part = MIMEBase('application', 'octet-stream')
288
-
289
- # Set the payload with the image data
290
- part.set_payload(image_data)
291
-
292
- # Encode the payload into base64
293
- encoders.encode_base64(part)
294
-
295
- # Add a header with the filename (you can set any filename you prefer)
296
- part.add_header('Content-Disposition', 'attachment; filename="image.png"')
297
-
298
- # Attach the instance 'part' to the instance 'msg'
299
- msg.attach(part)"""
300
-
301
- # Create SMTP session for sending the mail
302
- print(body)
303
- context = ssl.create_default_context()
304
- with smtplib.SMTP("smtp.gmail.com", 587) as server:
305
- server.ehlo() # Can be omitted
306
- server.starttls(context=context)
307
- server.ehlo() # Can be omitted
308
- server.login(sender_email, sender_password)
309
- text = msg.as_string()
310
- server.sendmail(sender_email, recipient_email, text)
311
-
312
-
313
 
314
- with smtplib.SMTP_SSL('smtp.gmail.com', 25) as smtp_server:
315
-
316
- smtp_server.login(sender, password)
317
- #server = smtplib.SMTP('smtp.gmail.com', 587)
318
- #server.starttls()
319
- #server.login(sender_email, sender_password)
320
- print(body)
321
  text = msg.as_string()
322
- print(body)
323
  server.sendmail(sender_email, recipient_email, text)
324
- print(body)
325
  server.quit()
326
 
327
  except Exception as error:
@@ -361,12 +310,8 @@ def inventory_report(question):
361
  else:
362
  return "warehouse name not found"
363
 
364
- #print(apis[0]["url"])
365
- #print(apis[0]["params"])
366
  data = make_api_request(apis[0]["url"], apis[0]["params"])
367
- #print(warehouse_name)
368
  if data:
369
- #print(data)
370
  # Extracting the id for the warehouse with the name "WH"
371
  warehouse_id = next((item['id'] for item in data['result'] if item['name'] == warehouse_name), None)
372
  #print(warehouse_id)
@@ -538,7 +483,7 @@ def answer_question(user_question, chatbot, audio=None):
538
  user_question = "Could not request results from Google Speech Recognition service."
539
 
540
  while iterations < max_iterations:
541
- #print(user_question)
542
  """if "send email to" in user_question:
543
  email_match = re.search(r"send email to ([\w\.-]+@[\w\.-]+)", user_question)
544
  if email_match:
@@ -548,8 +493,7 @@ def answer_question(user_question, chatbot, audio=None):
548
  """
549
 
550
  response = agent_executor.invoke({"input": user_question}, config={"callbacks": [langfuse_handler]})
551
- #print("name")
552
- #print(warehouse_name)
553
  if isinstance(response, dict):
554
  response_text = response.get("output", "")
555
  else:
@@ -557,10 +501,7 @@ def answer_question(user_question, chatbot, audio=None):
557
  if "invalid" not in response_text.lower():
558
  break
559
  iterations += 1
560
- #print(os.getenv("IMAGE_PATH"))
561
- #print(response_text)
562
- #print("validating. ")
563
- #print(os.getenv("IMAGE_PATH") in response_text)
564
  if iterations == max_iterations:
565
  return "The agent could not generate a valid response within the iteration limit."
566
 
@@ -568,12 +509,12 @@ def answer_question(user_question, chatbot, audio=None):
568
  if os.getenv("IMAGE_PATH") in response_text:
569
  # Open the image file
570
  img = Image.open(os.getenv("IMAGE_PATH"))
571
- #print(img)
572
  # Convert the PIL Image to a base64 encoded string
573
  buffered = BytesIO()
574
  img.save(buffered, format="PNG")
575
  img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
576
- #print(img_str)
577
  img = f'<img src="data:image/png;base64,{img_str}" style="width:500px; height:400px;">'
578
  # image = gr.Image(value=img_str)
579
  chatbot.append((user_question, img))
@@ -582,19 +523,17 @@ def answer_question(user_question, chatbot, audio=None):
582
  match = re.search(email_pattern, user_question)
583
  if match:
584
  user_email = match.group() # Return the matched email
585
- #print("user_email")
586
- #print(user_email)
587
  # email send
588
  if len(user_email)>0:
589
- print("user_email")
590
  # Send email with the chart image attached
591
  send_email_with_attachment(
592
  recipient_email=user_email,
593
  subject="Warehouse Inventory Report",
594
  body=response.get("output", "").split(":")[0],
595
- image_data = img_str
596
  # attachment_path=chart_path
597
- #attachment_path=os.getenv("IMAGE_PATH")
598
  )
599
 
600
  if "send email to" in user_question:
@@ -612,7 +551,6 @@ def answer_question(user_question, chatbot, audio=None):
612
  # return "/home/user/app/exports/charts/temp_chart.png"
613
  else:
614
  chatbot.append((user_question, response_text))
615
- # print(chatbot)
616
  return gr.update(value=chatbot)
617
  # response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()
618
  # return response_text
@@ -709,7 +647,7 @@ def handle_dislike(data: gr.LikeData):
709
  return gr.update(visible=False), gr.update(visible=False)
710
 
711
 
712
- with gr.Blocks(css=css,theme=gr.themes.Soft()) as demo:
713
  gr.Markdown("<CENTER><h2 style='font-size: 20px; font-family: Calibri;'>NewageNXT GPT</h2></CENTER>")
714
  with gr.Row():
715
  sample_button = gr.Button("What are the details of ASN24080600008", elem_classes="custom-button" , elem_id="button1")
 
135
  # The function that uses the above models
136
  # Define the function that will handle the database query
137
  def database_tool(question):
 
138
  sql_query = generate_sql_query(question)
 
139
  return run_query(sql_query)
140
 
141
 
142
  def get_ASN_data(question):
 
143
  base_url = os.getenv("ASN_API_URL")
144
  complete_url = f"{base_url}branchMaster.id=343&transactionUid={question}&userId=164&transactionType=ASN"
 
 
145
  try:
146
  response = requests.get(complete_url)
147
  data = response.json()
 
234
  print(f"Document data tool enter: {question}")
235
  # query_string = question['tags'][0] if 'tags' in question and question['tags'] else ""
236
  query_response = query_vector_store(vector_store, question, config={"callbacks": [langfuse_handler]})
 
 
237
  # summarized_response = summarize_document(query_response)
 
 
238
  return query_response
239
 
240
 
241
  def send_email_with_attachment(recipient_email, subject, body, image_data):
242
  try:
 
 
 
 
243
  sender_email = os.getenv("EMAIL_SENDER")
244
  sender_password = os.getenv("EMAIL_PASSWORD")
 
 
245
  # Create a multipart message
246
  msg = MIMEMultipart()
247
  msg['From'] = sender_email
248
  msg['To'] = recipient_email
249
  msg['Subject'] = subject
 
250
  # Attach the body with the msg instance
251
  msg.attach(MIMEText(body, 'plain'))
 
 
252
  # Open the file to be sent
253
  attachment = open(attachment_path, "rb")
254
  #print("Attached the image")
 
265
 
266
  # Attach the instance 'part' to instance 'msg'
267
  msg.attach(part)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
+ server = smtplib.SMTP('smtp.gmail.com', 587)
270
+ server.starttls()
271
+ server.login(sender_email, sender_password)
 
 
 
 
272
  text = msg.as_string()
 
273
  server.sendmail(sender_email, recipient_email, text)
 
274
  server.quit()
275
 
276
  except Exception as error:
 
310
  else:
311
  return "warehouse name not found"
312
 
 
 
313
  data = make_api_request(apis[0]["url"], apis[0]["params"])
 
314
  if data:
 
315
  # Extracting the id for the warehouse with the name "WH"
316
  warehouse_id = next((item['id'] for item in data['result'] if item['name'] == warehouse_name), None)
317
  #print(warehouse_id)
 
483
  user_question = "Could not request results from Google Speech Recognition service."
484
 
485
  while iterations < max_iterations:
486
+
487
  """if "send email to" in user_question:
488
  email_match = re.search(r"send email to ([\w\.-]+@[\w\.-]+)", user_question)
489
  if email_match:
 
493
  """
494
 
495
  response = agent_executor.invoke({"input": user_question}, config={"callbacks": [langfuse_handler]})
496
+
 
497
  if isinstance(response, dict):
498
  response_text = response.get("output", "")
499
  else:
 
501
  if "invalid" not in response_text.lower():
502
  break
503
  iterations += 1
504
+
 
 
 
505
  if iterations == max_iterations:
506
  return "The agent could not generate a valid response within the iteration limit."
507
 
 
509
  if os.getenv("IMAGE_PATH") in response_text:
510
  # Open the image file
511
  img = Image.open(os.getenv("IMAGE_PATH"))
512
+
513
  # Convert the PIL Image to a base64 encoded string
514
  buffered = BytesIO()
515
  img.save(buffered, format="PNG")
516
  img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
517
+
518
  img = f'<img src="data:image/png;base64,{img_str}" style="width:500px; height:400px;">'
519
  # image = gr.Image(value=img_str)
520
  chatbot.append((user_question, img))
 
523
  match = re.search(email_pattern, user_question)
524
  if match:
525
  user_email = match.group() # Return the matched email
526
+
 
527
  # email send
528
  if len(user_email)>0:
529
+
530
  # Send email with the chart image attached
531
  send_email_with_attachment(
532
  recipient_email=user_email,
533
  subject="Warehouse Inventory Report",
534
  body=response.get("output", "").split(":")[0],
 
535
  # attachment_path=chart_path
536
+ attachment_path=os.getenv("IMAGE_PATH")
537
  )
538
 
539
  if "send email to" in user_question:
 
551
  # return "/home/user/app/exports/charts/temp_chart.png"
552
  else:
553
  chatbot.append((user_question, response_text))
 
554
  return gr.update(value=chatbot)
555
  # response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()
556
  # return response_text
 
647
  return gr.update(visible=False), gr.update(visible=False)
648
 
649
 
650
+ with gr.Blocks(css=css) as demo:
651
  gr.Markdown("<CENTER><h2 style='font-size: 20px; font-family: Calibri;'>NewageNXT GPT</h2></CENTER>")
652
  with gr.Row():
653
  sample_button = gr.Button("What are the details of ASN24080600008", elem_classes="custom-button" , elem_id="button1")