Spaces:
Build error
Build error
Update app.py
Browse files123456789107 unmodified lines18192021222324252627282930313233347 unmodified lines4243444546474849505152535455565758596061626364656667686970717273747576777811 unmodified lines90919293949596975 unmodified lines1031041051061071083 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631643 unmodified lines16816917017117217317417517617717817918018118218310 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521628 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613625 unmodified lines3683693703713723733743753763773787 unmodified lines38638738838939039139239339439539639739839940040140212 unmodified lines41541641741841942042142242342442542642742842943043143243343443543643743843944044144244344419 unmodified lines4644654664674684694704714724734744754764774784 unmodified lines4834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265274 unmodified lines532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594# -*- coding: utf-8 -*-"""Chat_with_agent_v4.ipynbAutomatically generated by Colab.Original file is located athttps://colab.research.google.com/drive/1T5Buj_yHaAnfoO__2-gCFDSvBVheiHrF"""from PIL import Imageimport base64from io import BytesIO7 unmodified linesimport shutilimport jsonimport nltk#audio packageimport speech_recognition as srfrom pydub import AudioSegmentfrom pydub.playback import play#email libraryimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encoders#langchainfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnableSequence, RunnableLambda7 unmodified linesfrom langchain.pydantic_v1 import BaseModel, Fieldfrom PyPDF2 import PdfReaderfrom nltk.tokenize import sent_tokenizefrom sqlalchemy import create_enginefrom sqlalchemy.sql import text#pandasimport pandas as pdfrom pandasai.llm.openai import OpenAIfrom pandasai import SmartDataframenltk.download('punkt')open_api_key_token = os.environ['OPEN_AI_API']os.environ['OPENAI_API_KEY'] = open_api_key_tokenpdf_path="Inbound.pdf"db_uri = 'postgresql+psycopg2://postgres:postpass@193.203.162.39:5432/warehouseAi'# Database setupdb = SQLDatabase.from_uri(db_uri)# LLM setupllm = ChatOpenAI(model="gpt-4o-mini",max_tokens=300,temperature=0.1)llm_chart = OpenAI()def get_schema(_):schema_info = db.get_table_info() # This should be a string of your SQL schemareturn schema_infodef generate_sql_query(question):schema = get_schema(None)template_query_generation = """11 unmodified linesStrOutputParser())sql_query = sql_chain.invoke({})return sql_query.strip()def run_query(query):# Clean the query by removing markdown symbols and trimming whitespaceclean_query = query.replace("```sql", "").replace("```", "").strip()5 unmodified linesprint(f"Error executing query: {e}")return None# Define the database query tool# The function that uses the above models# Define the function that will handle the database query3 unmodified linesprint(sql_query)return run_query(sql_query)def get_ASN_data(question):#print(question)base_url = "http://193.203.162.39:9090/nxt-wms/trnHeader?"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()response.raise_for_status()if 'result' in data and 'content' in data['result'] and data['result']['content']:content = data['result']['content'][0]trnHeaderAsn = content['trnHeaderAsn']party = content['party'][0]transactionUid = trnHeaderAsn['transactionUid']customerOrderNo = trnHeaderAsn.get('customerOrderNo', 'N/A')orderDate = trnHeaderAsn.get('orderDate', 'N/A')customerInvoiceNo = trnHeaderAsn.get('customerInvoiceNo', 'N/A')invoiceDate = trnHeaderAsn.get('invoiceDate', 'N/A')expectedReceivingDate = trnHeaderAsn['expectedReceivingDate']transactionStatus = trnHeaderAsn['transactionStatus']shipper_code = party['shipper']['code'] if party['shipper'] else 'N/A'shipper_name = party['shipper']['name'] if party['shipper'] else 'N/A'data = [["Transaction UID", transactionUid],["Customer Order No", customerOrderNo],["Order Date", orderDate],["Customer Invoice No", customerInvoiceNo],["Invoice Date", invoiceDate],["Expected Receiving Date", expectedReceivingDate],["Transaction Status", transactionStatus],["Shipper Code", shipper_code],["Shipper Name", shipper_name]]return f"The ASN details of {question} is {data}."else:return "ASN Details are not found. Please contact system administrator."except requests.exceptions.HTTPError as http_err:print(f"HTTP error occurred: {http_err}")except Exception as err:print(f"An error occurred: {err}")get_ASN_data("ASN24072400001")def load_and_split_pdf(pdf_path):reader = PdfReader(pdf_path)3 unmodified linestext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)texts = text_splitter.split_text(text)return textsdef create_vector_store(texts):embeddings = OpenAIEmbeddings()vector_store = FAISS.from_texts(texts, embeddings)return vector_storedef query_vector_store(vector_store, query):docs = vector_store.similarity_search(query, k=5)print(f"Vector store return: {docs}")return docsdef summarize_document(docs):summarized_docs = []for doc in docs:10 unmodified linessummarized_docs.append(summarized_content)return '\n\n'.join(summarized_docs)texts = load_and_split_pdf(pdf_path)vector_store = create_vector_store(texts)def document_data_tool(question):print(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)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, attachment_path):sender_email = "redmind.uiautomation@gmail.com"sender_password = "jymz apyc raih eubg"# Create a multipart messagemsg = MIMEMultipart()28 unmodified linestext = msg.as_string()server.sendmail(sender_email, recipient_email, text)server.quit()#return 1def make_api_request(url, params):import requests"""Generic function to make API GET requests and return JSON data."""try:response = requests.get(url, params=params)response.raise_for_status() # Raises an HTTPError if the response was an errorreturn response.json() # Return the parsed JSON dataexcept requests.exceptions.HTTPError as http_err:print(f"HTTP error occurred: {http_err}")except Exception as err:print(f"An error occurred: {err}")name=""warehouse_id = ""apis = [#fetch warehouse ID{"url": "http://193.203.162.39:9090/nxt-wms/userWarehouse/fetchWarehouseForUserId?","params": {"query": name, "userId": "164"}},#Stock summary based on warehouse id{"url": "http://193.203.162.39:9090/nxt-wms/transactionHistory/stockSummary?","params": {"branchId": "343", "onDate": "2024-08-09", "warehouseId" : warehouse_id }}]def inventory_report(question):# Split the question to extract warehouse name, user question, and optional emailparts = question.split(":", 2)name = parts[0].strip()user_question = parts[1].strip()user_email = parts[2].strip() if len(parts) > 2 else Noneprint(f"Warehouse: {name}, Email: {user_email}, Question: {user_question}")data = make_api_request(apis[0]["url"], apis[0]["params"])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'] == name), None)#print(f"The id for the warehouse named {name} is: {warehouse_id}")#Step 3: Update the placeholder with the actual warehouse_idfor api in apis:if "warehouseId" in api["params"]:api["params"]["warehouseId"] = warehouse_iddata1 = make_api_request(apis[1]["url"], apis[1]["params"])from tabulate import tabulateheaders = ["S.No","Warehouse Code", "Warehouse Name", "Customer Code", "Customer Name", "Item Code", "Item Name", "Currency", "EAN", "UOM", "Quantity", "Gross Weight", "Volume", "Total Value"]table_data = []for index, item in enumerate(data1['result'], start=1):row = [index, # Serial numberitem['warehouse']['code'],item['warehouse']['name'],item['customer']['code'],item['customer']['name'],item['skuMaster']['code'],item['skuMaster']['name'],item['currency']['code'],item['eanUpc'],item['uom']['code'],item['totalQty'],item['grossWeight'],item['volume'],item['totalValue']]table_data.append(row)# Convert to pandas DataFramedf = pd.DataFrame(table_data, columns=headers)sdf = SmartDataframe(df, config={"llm": llm_chart})#chart = sdf.chat("Can you draw a bar chart with all avaialble item name and quantity.")chart = sdf.chat(question)#email sendif user_email:# Send email with the chart image attachedsend_email_with_attachment(recipient_email=user_email,subject="Warehouse Inventory Report",body="Please find the attached bar chart report for the warehouse inventory analysis.",#attachment_path=chart_pathattachment_path="/home/user/app/exports/charts/temp_chart.png")return chart#inventory_report("WH:can you give me a bar chart with item name and quantity for the warehouse WH")# Define input and output models using Pydanticclass QueryInput(BaseModel):question: str = Field(description="The question to be answered by appropriate tool. Please follow the instructions. For API tool, do not send the question as it is. Please send the ASN id. Invoke datavisulaization tool by processing the user question and send two inputs to the tool. One input will be the warehouse name and another input to the tool will be the entire user_question itself. Please join those two strings and send them as a single input string with ':' as delimiter")# config: dict = Field(default={}, description="Optional configuration for the database query.")# Define the output model for database queriesclass QueryOutput(BaseModel):result: str = Field(..., description="Display the answer based on the prompts given in each tool. For dataVisualization tool, it sends a image file as output. Please give the image file path only to the gr.Image. For DocumentData tool, Please provide a complete and concise response within 200 words and Ensure that the response is not truncated and covers the essential points.")# Wrap the function with StructuredTool for better parameter handlingtools = [5 unmodified linesdescription="Tool to get details of ASN api. ASN id will be in the input with the format of first three letters as ASN and it is followed by 11 digit numeral. Pass only the id as input. Do not send the complete user question to the tool. If there are any other queries related to ASN without ASN id, please use the document tool."),StructuredTool(func=document_data_tool,name="DocumentData",args_schema=QueryInput,output_schema=QueryOutput,description="You are an AI assistant trained to help with warehouse management questions based on a detailed document about our WMS. The document covers various processes such as ASN handling, purchase orders, cross docking, appointment scheduling for shipments, and yard management. Please provide a complete and concise response within 200 words and Ensure that the response is not truncated and covers the essential points. "),StructuredTool(func=database_tool,7 unmodified linesname="dataVisualization",args_schema=QueryInput,output_schema=QueryOutput,description = """Tool to generate a visual output (such as a bar chart) for a particular warehouse based on the provided question.This tool processes the user question to identify the warehouse name and the specific request. If the user specifiesan email, include the email in the input. The input format should be: 'warehouse name: user question: email (if any)'.The tool generates the requested chart and sends it to the provided email if specified.Examples:1. Question without email: "Analyze item name and quantity in a bar chart in warehouse Allcargo Logistics"Input to tool: "Allcargo Logistics: I want to analyze item name and quantity in a bar chart"2. Question with email: "Analyze item name and quantity in a bar chart in warehouse Allcargo Logistics report to send email to example@example.com"Input to tool: "Allcargo Logistics: I want to analyze item name and quantity in a bar chart: example@example.com"""")12 unmodified linesagent = create_tool_calling_agent(llm, tools, ChatPromptTemplate.from_template(prompt_template))agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)def ensure_temp_chart_dir():temp_chart_dir = "/home/user/app/exports/charts/"if not os.path.exists(temp_chart_dir):os.makedirs(temp_chart_dir)def clean_gradio_tmp_dir():tmp_dir = "/tmp/gradio/"if os.path.exists(tmp_dir):try:shutil.rmtree(tmp_dir)except Exception as e:print(f"Error cleaning up /tmp/gradio/ directory: {e}")# Define the interface functionmax_iterations = 5iterations = 0def answer_question(user_question, chatbot, audio=None):global iterationsiterations = 0# Ensure the temporary chart directory exists#ensure_temp_chart_dir()# Clean the /tmp/gradio/ directory#clean_gradio_tmp_dir()# Handle audio input if providedif audio is not None:sample_rate, audio_data = audio19 unmodified lineswhile 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:user_email = email_match.group(1).strip()user_question = user_question.replace(f"send email to {user_email}", "").strip()user_question = f"{user_question}:{user_email}"response = agent_executor.invoke({"input": user_question})if isinstance(response, dict):response_text = response.get("output", "")else:4 unmodified linesif iterations == max_iterations:return "The agent could not generate a valid response within the iteration limit."if "chart" in user_question:# Open the image fileimg = Image.open('/home/user/app/exports/charts/temp_chart.png')# 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}">'#image = gr.Image(value=img_str)chatbot.append((user_question,img))#print(chatbot)if "send email to" in user_question:try:os.remove(image_path) # Clean up the temporary image fileexcept Exception as e:print(f"Error cleaning up image file: {e}")except Exception as e:print(f"Error loading image file: {e}")chatbot.append((user_question, "Chart generation failed. Please try again."))return gr.update(value=chatbot)#return [(user_question,gr.Image("/home/user/app/exports/charts/temp_chart.png"))]# 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_textimport gradio as grcss = """.gr-chatbot {/* Custom styles for the Chatbot component */border: 1px solid #ccc;4 unmodified lines/* Adjust the width as needed */overflow-y: auto; /* Add scroll if the content exceeds the height */}.gr-button {height: 40px; /* Adjust the height as needed */"""def submit_feedback(feedback, chatbot):feedback_response = "User feedback: " + feedbackreturn chatbot + [(feedback_response,None)], gr.update(visible=False), gr.update(visible=False)def handle_dislike(data: gr.LikeData):if not data.liked:print("downvote")return gr.update(visible=True), gr.update(visible=True)else:print("upvote")return 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>")chatbot = gr.Chatbot(elem_classes="gr-chatbot", label="Ask a question about the API, Database, a Document or Warehouse inventory analysis.")#.style(color_map=["blue","grey","red"])with gr.Row():with gr.Column(scale=1):message = gr.Textbox(show_label=False)audio_input = gr.Audio(label="Record your question")with gr.Column(scale=1):with gr.Row():button = gr.Button("Submit", elem_classes="gr-button")gr.ClearButton(message, elem_classes="gr-button")with gr.Row():with gr.Column(scale=1):feedback_textbox = gr.Textbox(visible=False, show_label=False)with gr.Column(scale=1):submit_feedback_button = gr.Button("Submit Feedback", visible=False, elem_classes="gr-button")button.click(answer_question, [message, chatbot], [chatbot])message.submit(answer_question, [message, chatbot], [chatbot])message.submit(lambda x: gr.update(value=""), None, [message], queue=False)button.click(lambda x: gr.update(value=''), [], [message])chatbot.like(handle_dislike,None, outputs=[feedback_textbox, submit_feedback_button])submit_feedback_button.click(submit_feedback, [feedback_textbox, chatbot], [chatbot, feedback_textbox,submit_feedback_button])submit_feedback_button.click(lambda x: gr.update(value=''), [], [feedback_textbox])demo.launch()1237 unmodified lines11121314151617181920212223242526277 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210311 unmodified lines1151161171181191201211221231245 unmodified lines1301311321331341351363 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931943 unmodified lines19819920020120220320420520620720820921021121221321421521621721821910 unmodified lines23023123223323423523623723823924024124224324424524624724824925025125225325425528 unmodified lines2842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933945 unmodified lines4004014024034044054064074084094107 unmodified lines41841942042142242342442542642742842943043112 unmodified lines44444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747819 unmodified lines4984995005015025035045055065075085095105115125135144 unmodified lines5195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705714 unmodified lines576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690from PIL import Imageimport base64from io import BytesIO7 unmodified linesimport shutilimport jsonimport nltk# audio packageimport speech_recognition as srfrom pydub import AudioSegmentfrom pydub.playback import play# email libraryimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encoders# langchainfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnableSequence, RunnableLambda7 unmodified linesfrom langchain.pydantic_v1 import BaseModel, Fieldfrom PyPDF2 import PdfReaderfrom nltk.tokenize import sent_tokenizefrom datetime import datetimefrom sqlalchemy import create_enginefrom sqlalchemy.sql import text# pandasimport pandas as pdfrom pandasai.llm.openai import OpenAIfrom pandasai import SmartDataframefrom dotenv import load_dotenv# Load environment variablesload_dotenv()# langfuse analyticsfrom langfuse.callback import CallbackHandler# LangFuse API keys and host settingsos.environ["LANGFUSE_PUBLIC_KEY"] = os.getenv("LANGFUSE_PUBLIC_KEY")os.environ["LANGFUSE_SECRET_KEY"] = os.getenv("LANGFUSE_SECRET_KEY")os.environ["LANGFUSE_HOST"] = os.getenv("LANGFUSE_HOST")langfuse_handler = CallbackHandler()langfuse_handler.auth_check() # Optional: Checks if the authentication is successfulnltk.download('punkt')open_api_key_token = os.getenv("OPENAI_API_KEY")os.environ['OPENAI_API_KEY'] = open_api_key_tokenpdf_path = "Inbound.pdf"db_uri = os.getenv("POSTGRESQL_CONNECTION")# Database setupdb = SQLDatabase.from_uri(db_uri)user_email = "lakshmivairamani@gmail.com"warehouse_name = ""warehouse_id = ""inventory_date = datetime.today().strftime('%Y-%m-%d')apis = [# fetch warehouse ID{"url": "http://193.203.162.39:9090/nxt-wms/userWarehouse/fetchWarehouseForUserId?","params": {"query": warehouse_name, "userId": 164}},# Stock summary based on warehouse id{"url": "http://193.203.162.39:9090/nxt-wms/transactionHistory/stockSummary?","params": {"branchId": 343, "onDate": inventory_date, "warehouseId": warehouse_id}}]# LLM setupllm = ChatOpenAI(model="gpt-4o-mini", max_tokens=300, temperature=0.1)llm_chart = OpenAI()def get_schema(_):schema_info = db.get_table_info() # This should be a string of your SQL schemareturn schema_infodef generate_sql_query(question):schema = get_schema(None)template_query_generation = """11 unmodified linesStrOutputParser())sql_query = sql_chain.invoke({})sql_query = sql_chain.invoke({}, config={"callbacks": [langfuse_handler]})return sql_query.strip()def run_query(query):# Clean the query by removing markdown symbols and trimming whitespaceclean_query = query.replace("```sql", "").replace("```", "").strip()5 unmodified linesprint(f"Error executing query: {e}")return None# Define the database query tool# The function that uses the above models# Define the function that will handle the database query3 unmodified linesprint(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()response.raise_for_status()if 'result' in data and 'content' in data['result'] and data['result']['content']:content = data['result']['content'][0]trnHeaderAsn = content['trnHeaderAsn']party = content['party'][0]transactionUid = trnHeaderAsn['transactionUid']customerOrderNo = trnHeaderAsn.get('customerOrderNo', 'N/A')orderDate = trnHeaderAsn.get('orderDate', 'N/A')customerInvoiceNo = trnHeaderAsn.get('customerInvoiceNo', 'N/A')invoiceDate = trnHeaderAsn.get('invoiceDate', 'N/A')expectedReceivingDate = trnHeaderAsn['expectedReceivingDate']transactionStatus = trnHeaderAsn['transactionStatus']shipper_code = party['shipper']['code'] if party['shipper'] else 'N/A'shipper_name = party['shipper']['name'] if party['shipper'] else 'N/A'data = [["Transaction UID", transactionUid],["Customer Order No", customerOrderNo],["Order Date", orderDate],["Customer Invoice No", customerInvoiceNo],["Invoice Date", invoiceDate],["Expected Receiving Date", expectedReceivingDate],["Transaction Status", transactionStatus],["Shipper Code", shipper_code],["Shipper Name", shipper_name]]return f"The ASN details of {question} is {data}."else:return "ASN Details are not found. Please contact system administrator."except requests.exceptions.HTTPError as http_err:print(f"HTTP error occurred: {http_err}")except Exception as err:print(f"An error occurred: {err}")# get_ASN_data("ASN24072400001")def load_and_split_pdf(pdf_path):reader = PdfReader(pdf_path)3 unmodified linestext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50)texts = text_splitter.split_text(text)return textsdef create_vector_store(texts):embeddings = OpenAIEmbeddings()vector_store = FAISS.from_texts(texts, embeddings)return vector_storedef query_vector_store(vector_store, query, config=None):if config:print("Config passed:", config)docs = vector_store.similarity_search(query, k=5)print(f"Vector store return: {docs}")return docsdef summarize_document(docs):summarized_docs = []for doc in docs:10 unmodified linessummarized_docs.append(summarized_content)return '\n\n'.join(summarized_docs)texts = load_and_split_pdf(pdf_path)vector_store = create_vector_store(texts)def document_data_tool(question):print(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, attachment_path):sender_email = os.getenv("EMAIL_SENDER")sender_password = os.getenv("EMAIL_PASSWORD")# Create a multipart messagemsg = MIMEMultipart()28 unmodified linestext = msg.as_string()server.sendmail(sender_email, recipient_email, text)server.quit()# return 1def make_api_request(url, params):"""Generic function to make API GET requests and return JSON data."""try:response = requests.get(url, params=params)response.raise_for_status() # Raises an HTTPError if the response was an errorreturn response.json() # Return the parsed JSON dataexcept requests.exceptions.HTTPError as http_err:print(f"HTTP error occurred: {http_err}")except Exception as err:print(f"An error occurred: {err}")def inventory_report(question):print(question)# Split the question to extract warehouse name, user question, and optional emailif question.count(":") > 0:parts = question.split(":", 2)warehouse_name= parts[0].strip()user_question = parts[1].strip()user_email = parts[2].strip() if len(parts) > 2 else Noneprint(f"Warehouse: {warehouse_name}, Email: {user_email}, Question: {user_question}")else: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)if warehouse_id is None:return "Please provide a warehouse name available in the database."# print(f"The id for the warehouse named {name} is: {warehouse_id}")# Step 3: Update the placeholder with the actual warehouse_idfor api in apis:if "warehouseId" in api["params"]:api["params"]["warehouseId"] = warehouse_iddata1 = make_api_request(apis[1]["url"], apis[1]["params"])from tabulate import tabulateheaders = ["S.No", "Warehouse Code", "Warehouse Name", "Customer Code", "Customer Name", "Item Code", "Item Name","Currency", "EAN", "UOM", "Quantity", "Gross Weight", "Volume", "Total Value"]table_data = []for index, item in enumerate(data1['result'], start=1):row = [index, # Serial numberitem['warehouse']['code'],item['warehouse']['name'],item['customer']['code'],item['customer']['name'],item['skuMaster']['code'],item['skuMaster']['name'],item['currency']['code'],item['eanUpc'],item['uom']['code'],item['totalQty'],item['grossWeight'],item['volume'],item['totalValue']]table_data.append(row)# Convert to pandas DataFramedf = pd.DataFrame(table_data, columns=headers)sdf = SmartDataframe(df, config={"llm": llm_chart})# chart = sdf.chat("Can you draw a bar chart with all avaialble item name and quantity.")chart = sdf.chat(question)return chart# inventory_report("WH:can you give me a bar chart with item name and quantity for the warehouse WH")# Define input and output models using Pydanticclass QueryInput(BaseModel):question: str = Field(description="The question to be answered by appropriate tool. Please follow the instructions. For API tool, do not send the question as it is. Please send the ASN id.")# Invoke datavisulaization tool by processing the user question and send two inputs to the tool. One input will be the warehouse name and another input to the tool will be the entire user_question itself. Please join those two strings and send them as a single input string with ':' as delimiter")# config: dict = Field(default={}, description="Optional configuration for the database query.")# Define the output model for database queriesclass QueryOutput(BaseModel):result: str = Field(...,description="Display the answer based on the prompts given in each tool. For dataVisualization tool, it sends a image file as output. Please give the image file path only to the gr.Image. For DocumentData tool, Please provide a complete and concise response within 200 words and Ensure that the response is not truncated and covers the essential points.")# Wrap the function with StructuredTool for better parameter handlingtools = [5 unmodified linesdescription="Tool to get details of ASN api. ASN id will be in the input with the format of first three letters as ASN and it is followed by 11 digit numeral. Pass only the id as input. Do not send the complete user question to the tool. If there are any other queries related to ASN without ASN id, please use the document tool."),StructuredTool(func=document_data_tool,name="DocumentData",args_schema=QueryInput,output_schema=QueryOutput,description="You are an AI assistant trained to help with warehouse management questions based on a detailed document about our WMS. The document covers various processes such as ASN handling, purchase orders, cross docking, appointment scheduling for shipments, and yard management. Please provide a complete and concise response within 200 words and Ensure that the response is not truncated and covers the essential points. "),StructuredTool(func=database_tool,7 unmodified linesname="dataVisualization",args_schema=QueryInput,output_schema=QueryOutput,description=""" Tool to generate a visual chart output for a particular warehouse based on the provided question.This tool processes the user question to identify the warehouse name and the specific request. If the user specifiesan email, include the email in the input. The input format should be: 'warehouse name: user question: email (if any)'.The tool generates the requested chart and sends it to the provided email if specified.Examples:1. Question without email, without warehouse: "Analyze item name and quantity in a bar chart in warehouse"Input to tool: "I want to analyze item name and quantity in a bar chart"2. Question with email: "Analyze item name and quantity in a bar chart in warehouse Allcargo Logistics and send email to example@example.com"Input to tool: "Allcargo Logistics: I want to analyze item name and quantity in a bar chart: example@example.com"""")12 unmodified linesagent = create_tool_calling_agent(llm, tools, ChatPromptTemplate.from_template(prompt_template))agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)def ensure_temp_chart_dir():temp_chart_dir = os.getenv("IMAGE_MAIN_URL")if not os.path.exists(temp_chart_dir):os.makedirs(temp_chart_dir)def clean_gradio_tmp_dir():tmp_dir = os.getenv("IMAGE_GRADIO_PATH")if os.path.exists(tmp_dir):try:shutil.rmtree(tmp_dir)except Exception as e:print(f"Error cleaning up /tmp/gradio/ directory: {e}")# Define the interface functionmax_iterations = 5iterations = 0def answer_question(user_question, chatbot, audio=None):global iterationsiterations = 0# Ensure the temporary chart directory exists# ensure_temp_chart_dir()# Clean the /tmp/gradio/ directory# clean_gradio_tmp_dir()# Handle audio input if providedif audio is not None:sample_rate, audio_data = audio19 unmodified lineswhile 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:user_email = email_match.group(1).strip()user_question = user_question.replace(f"send email to {user_email}", "").strip()user_question = f"{user_question}:{user_email}""""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:4 unmodified linesif iterations == max_iterations:return "The agent could not generate a valid response within the iteration limit."if 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")# 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))# print(chatbot)# email sendif 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],# attachment_path=chart_pathattachment_path=os.getenv("IMAGE_PATH"))if "send email to" in user_question:try:os.remove(img) # Clean up the temporary image fileexcept Exception as e:print(f"Error cleaning up image file: {e}")except Exception as e:print(f"Error loading image file: {e}")chatbot.append((user_question, "Chart generation failed. Please try again."))return gr.update(value=chatbot)# return [(user_question,gr.Image("/home/user/app/exports/charts/temp_chart.png"))]# 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_textcss = """.gr-chatbot {/* Custom styles for the Chatbot component */border: 1px solid #ccc;4 unmodified lines/* Adjust the width as needed */overflow-y: auto; /* Add scroll if the content exceeds the height */}.gr-button {height: 40px; /* Adjust the height as needed */}.message-buttons-right{display: none !important;}.gr-audio {width: 30px;height: 30px;border-radius: 50%;background-size: cover;background-position: center;margin-left: 10px;cursor: pointer;}.custom-button {background-color: #4CAF50; /* Initial Green */border: none;color: black;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 11px;margin: 4px 2px;width: 50px; /* Set width to 50px */height: 100px; /* Set height to 50px */transition: background-color 0.4s, transform 0.5s ease-in-out; /* Smooth transition */cursor: pointer;}.custom-button:hover {background-color: #45a049; /* Darker Green on hover */transform: scale(1.1); /* Scale up slightly on hover */}@keyframes button-animation {0% { transform: scale(1); }50% { transform: scale(1.1); }100% { transform: scale(1); }}"""def submit_feedback(feedback, chatbot):gr.Info("Thank you for your feedback.")feedback_response = "User feedback: " + feedbackreturn chatbot + [(feedback_response, None)], gr.update(visible=False)def handle_dislike(data: gr.LikeData):if not data.liked:print("downvote")gr.Info("Please enter your feedback.")return gr.update(visible=True), gr.update(visible=True)else:print("upvote")return 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")sample_button1 = gr.Button("What are the active warehouses", elem_classes="custom-button")sample_button2 = gr.Button("Explain Pre-Receiving Yard Management", elem_classes="custom-button")sample_button3 = gr.Button("Can you generate a pie chart with item names and quantities in warehouse WH", elem_classes="custom-button")sample_button4 = gr.Button("I want to analyze item name and quantity in a bar chart in warehouse WH and send email to lakshmivairamani@gmail.comk", elem_classes="custom-button")with gr.Row():chatbot = gr.Chatbot(elem_classes="gr-chatbot",label="Ask a question about the API, Database, a Document or Warehouse inventory analysis.") # .style(color_map=["blue","grey","red"])with gr.Row():with gr.Column(scale=1):message = gr.Textbox(show_label=False, container=False, placeholder="Please enter your question")with gr.Row():feedback_textbox = gr.Textbox(visible=False, show_label=False,container=False, placeholder = "Please enter your feedback.")submit_feedback_button = gr.Button("Submit Feedback", visible=False, elem_classes="gr-button")with gr.Column(scale=2):with gr.Row():audio_input = gr.Audio(sources=["microphone"], show_label=False, container=False,waveform_options=gr.WaveformOptions(show_controls=False))button = gr.Button("Submit", elem_classes="gr-button")gr.ClearButton(message, elem_classes="gr-button")button.click(answer_question, [message, chatbot, audio_input], [chatbot])message.submit(answer_question, [message, chatbot, audio_input], [chatbot])message.submit(lambda x: gr.update(value=""), None, [message], queue=False)button.click(lambda x: gr.update(value=''), [], [message])chatbot.like(handle_dislike, None, outputs=[feedback_textbox, submit_feedback_button])submit_feedback_button.click(submit_feedback, [feedback_textbox, chatbot],[chatbot, feedback_textbox, submit_feedback_button])submit_feedback_button.click(lambda x: gr.update(value=''), [], [feedback_textbox])sample_button.click(answer_question,[sample_button, chatbot, audio_input], [chatbot])sample_button1.click(answer_question, [sample_button1, chatbot, audio_input], [chatbot])sample_button2.click(answer_question, [sample_button2, chatbot, audio_input], [chatbot])sample_button3.click(answer_question, [sample_button3, chatbot, audio_input], [chatbot])sample_button4.click(answer_question, [sample_button4, chatbot, audio_input], [chatbot])demo.launch()
app.py+338-242