Spaces:
Build error
Build error
Update app.py
Browse files134 unmodified lines13513613713813914014114214314414514614714814915015115286 unmodified lines23924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127210 unmodified lines28328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632733 unmodified lines361362363364365366367368369370371372165 unmodified lines5385395405415425435443 unmodified lines5485495505515525535545551 unmodified line5575585595605615625635645655661 unmodified line5685695705715725735745755765775785792 unmodified lines58258358458558658758858959059159259359459559659759859960011 unmodified lines61261361461561661761890 unmodified lines709710711712713714715134 unmodified lines# The function that uses the above models# Define the function that will handle the database querydef database_tool(question):# print(question)sql_query = generate_sql_query(question)#print(sql_query)return run_query(sql_query)def get_ASN_data(question):# print(question)base_url = os.getenv("ASN_API_URL")complete_url = f"{base_url}branchMaster.id=343&transactionUid={question}&userId=164&transactionType=ASN"#print("complete url")#print(complete_url)try:response = requests.get(complete_url)data = response.json()86 unmodified linesprint(f"Document data tool enter: {question}")# query_string = question['tags'][0] if 'tags' in question and question['tags'] else ""query_response = query_vector_store(vector_store, question, config={"callbacks": [langfuse_handler]})#print("query****")#print(query_response)# summarized_response = summarize_document(query_response)# print("summary***")# print(summarized_response)return query_responsedef send_email_with_attachment(recipient_email, subject, body, image_data):try:print(recipient_email)print(subject)#print(image_data)sender_email = os.getenv("EMAIL_SENDER")sender_password = os.getenv("EMAIL_PASSWORD")print(sender_email)print(sender_password)# Create a multipart messagemsg = MIMEMultipart()msg['From'] = sender_emailmsg['To'] = recipient_emailmsg['Subject'] = subjectprint(body)# Attach the body with the msg instancemsg.attach(MIMEText(body, 'plain'))print(body)"""# Open the file to be sentattachment = open(attachment_path, "rb")#print("Attached the image")10 unmodified lines# Attach the instance 'part' to instance 'msg'msg.attach(part)# Create a MIMEBase instance for the attachmentpart = MIMEBase('application', 'octet-stream')# Set the payload with the image datapart.set_payload(image_data)# Encode the payload into base64encoders.encode_base64(part)# Add a header with the filename (you can set any filename you prefer)part.add_header('Content-Disposition', 'attachment; filename="image.png"')# Attach the instance 'part' to the instance 'msg'msg.attach(part)"""# Create SMTP session for sending the mailprint(body)context = ssl.create_default_context()with smtplib.SMTP("smtp.gmail.com", 587) as server:server.ehlo() # Can be omittedserver.starttls(context=context)server.ehlo() # Can be omittedserver.login(sender_email, sender_password)text = msg.as_string()server.sendmail(sender_email, recipient_email, text)with smtplib.SMTP_SSL('smtp.gmail.com', 25) as smtp_server:smtp_server.login(sender, password)#server = smtplib.SMTP('smtp.gmail.com', 587)#server.starttls()#server.login(sender_email, sender_password)print(body)text = msg.as_string()print(body)server.sendmail(sender_email, recipient_email, text)print(body)server.quit()except Exception as error:33 unmodified lineselse:return "warehouse name not found"#print(apis[0]["url"])#print(apis[0]["params"])data = make_api_request(apis[0]["url"], apis[0]["params"])#print(warehouse_name)if data:#print(data)# Extracting the id for the warehouse with the name "WH"warehouse_id = next((item['id'] for item in data['result'] if item['name'] == warehouse_name), None)#print(warehouse_id)165 unmodified linesuser_question = "Could not request results from Google Speech Recognition service."while iterations < max_iterations:#print(user_question)"""if "send email to" in user_question:email_match = re.search(r"send email to ([\w\.-]+@[\w\.-]+)", user_question)if email_match:3 unmodified lines"""response = agent_executor.invoke({"input": user_question}, config={"callbacks": [langfuse_handler]})#print("name")#print(warehouse_name)if isinstance(response, dict):response_text = response.get("output", "")else:1 unmodified lineif "invalid" not in response_text.lower():breakiterations += 1#print(os.getenv("IMAGE_PATH"))#print(response_text)#print("validating. ")#print(os.getenv("IMAGE_PATH") in response_text)if iterations == max_iterations:return "The agent could not generate a valid response within the iteration limit."1 unmodified lineif os.getenv("IMAGE_PATH") in response_text:# Open the image fileimg = Image.open(os.getenv("IMAGE_PATH"))#print(img)# Convert the PIL Image to a base64 encoded stringbuffered = BytesIO()img.save(buffered, format="PNG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")#print(img_str)img = f'<img src="data:image/png;base64,{img_str}" style="width:500px; height:400px;">'# image = gr.Image(value=img_str)chatbot.append((user_question, img))2 unmodified linesmatch = re.search(email_pattern, user_question)if match:user_email = match.group() # Return the matched email#print("user_email")#print(user_email)# email sendif len(user_email)>0:print("user_email")# Send email with the chart image attachedsend_email_with_attachment(recipient_email=user_email,subject="Warehouse Inventory Report",body=response.get("output", "").split(":")[0],image_data = img_str# attachment_path=chart_path#attachment_path=os.getenv("IMAGE_PATH"))if "send email to" in user_question:11 unmodified lines# return "/home/user/app/exports/charts/temp_chart.png"else:chatbot.append((user_question, response_text))# print(chatbot)return gr.update(value=chatbot)# response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()# return response_text90 unmodified linesreturn gr.update(visible=False), gr.update(visible=False)with gr.Blocks(css=css,theme=gr.themes.Soft()) as demo:gr.Markdown("<CENTER><h2 style='font-size: 20px; font-family: Calibri;'>NewageNXT GPT</h2></CENTER>")with gr.Row():sample_button = gr.Button("What are the details of ASN24080600008", elem_classes="custom-button" , elem_id="button1")134 unmodified lines13513613713813914014114214314414514614786 unmodified lines23423523623723823924024124224324424524624724824925025125225325410 unmodified lines26526626726826927027127227327427527633 unmodified lines310311312313314315316317165 unmodified lines4834844854864874884893 unmodified lines4934944954964974984991 unmodified line5015025035045055065071 unmodified line5095105115125135145155165175185195202 unmodified lines52352452552652752852953053153253353453553653753853911 unmodified lines55155255355455555690 unmodified lines647648649650651652653134 unmodified lines# The function that uses the above models# Define the function that will handle the database querydef database_tool(question):sql_query = generate_sql_query(question)return run_query(sql_query)def get_ASN_data(question):base_url = os.getenv("ASN_API_URL")complete_url = f"{base_url}branchMaster.id=343&transactionUid={question}&userId=164&transactionType=ASN"try:response = requests.get(complete_url)data = response.json()86 unmodified linesprint(f"Document data tool enter: {question}")# query_string = question['tags'][0] if 'tags' in question and question['tags'] else ""query_response = query_vector_store(vector_store, question, config={"callbacks": [langfuse_handler]})# summarized_response = summarize_document(query_response)return query_responsedef send_email_with_attachment(recipient_email, subject, body, image_data):try:sender_email = os.getenv("EMAIL_SENDER")sender_password = os.getenv("EMAIL_PASSWORD")# Create a multipart messagemsg = MIMEMultipart()msg['From'] = sender_emailmsg['To'] = recipient_emailmsg['Subject'] = subject# Attach the body with the msg instancemsg.attach(MIMEText(body, 'plain'))# Open the file to be sentattachment = open(attachment_path, "rb")#print("Attached the image")10 unmodified lines# Attach the instance 'part' to instance 'msg'msg.attach(part)server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(sender_email, sender_password)text = msg.as_string()server.sendmail(sender_email, recipient_email, text)server.quit()except Exception as error:33 unmodified lineselse:return "warehouse name not found"data = make_api_request(apis[0]["url"], apis[0]["params"])if data:# Extracting the id for the warehouse with the name "WH"warehouse_id = next((item['id'] for item in data['result'] if item['name'] == warehouse_name), None)#print(warehouse_id)165 unmodified linesuser_question = "Could not request results from Google Speech Recognition service."while iterations < max_iterations:"""if "send email to" in user_question:email_match = re.search(r"send email to ([\w\.-]+@[\w\.-]+)", user_question)if email_match:3 unmodified lines"""response = agent_executor.invoke({"input": user_question}, config={"callbacks": [langfuse_handler]})if isinstance(response, dict):response_text = response.get("output", "")else:1 unmodified lineif "invalid" not in response_text.lower():breakiterations += 1if iterations == max_iterations:return "The agent could not generate a valid response within the iteration limit."1 unmodified lineif os.getenv("IMAGE_PATH") in response_text:# Open the image fileimg = Image.open(os.getenv("IMAGE_PATH"))# Convert the PIL Image to a base64 encoded stringbuffered = BytesIO()img.save(buffered, format="PNG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")img = f'<img src="data:image/png;base64,{img_str}" style="width:500px; height:400px;">'# image = gr.Image(value=img_str)chatbot.append((user_question, img))2 unmodified linesmatch = re.search(email_pattern, user_question)if match:user_email = match.group() # Return the matched email# email sendif len(user_email)>0:# Send email with the chart image attachedsend_email_with_attachment(recipient_email=user_email,subject="Warehouse Inventory Report",body=response.get("output", "").split(":")[0],# attachment_path=chart_pathattachment_path=os.getenv("IMAGE_PATH"))if "send email to" in user_question:11 unmodified lines# return "/home/user/app/exports/charts/temp_chart.png"else:chatbot.append((user_question, response_text))return gr.update(value=chatbot)# response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()# return response_text90 unmodified linesreturn gr.update(visible=False), gr.update(visible=False)with gr.Blocks(css=css) as demo:gr.Markdown("<CENTER><h2 style='font-size: 20px; font-family: Calibri;'>NewageNXT GPT</h2></CENTER>")with gr.Row():sample_button = gr.Button("What are the details of ASN24080600008", elem_classes="custom-button" , elem_id="button1")
app.py+12-74