Spaces:
Build error
Build error
Update app.py
Browse files8 unmodified lines910111213141516179 unmodified lines27282930313233343536373839404142434445464721 unmodified lines697071727374757 unmodified lines8384858687888959 unmodified lines14915015115215315415511 unmodified lines1671681691701711721731741751761771781792 unmodified lines18218318418518618715 unmodified lines2032042052062072082092102112122132142152162172182192202212222232242252262272287 unmodified lines23623723823924024124224324424524621 unmodified lines26826927027127227327427527627727827928028128228328428528628728828935 unmodified lines32532632732832933033110 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336436536611 unmodified lines37837938038138238338447 unmodified lines43243343443543643720 unmodified lines4584594608 unmodified linesimport base64from io import BytesIOimport osimport requestsimport gradio as gr#import nltkfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnableSequence, RunnableLambda9 unmodified linesfrom nltk.tokenize import sent_tokenizefrom sqlalchemy import create_enginefrom sqlalchemy.sql import textimport jsonimport nltknltk.download('punkt')open_api_key_token = os.environ['OPEN_AI_API']os.environ['OPENAI_API_KEY'] = open_api_key_tokendb_uri = 'postgresql+psycopg2://postgres:postpass@193.203.162.39:5432/warehouseAi'# Database setupdb = SQLDatabase.from_uri(db_uri)# LLM setup#llm = ChatOpenAI(model="gpt-3.5-turbo-0125",max_tokens=150,temperature=0.1)llm = ChatOpenAI(model="gpt-4o-mini",max_tokens=250,temperature=0.1)def get_schema(_):schema_info = db.get_table_info() # This should be a string of your SQL schema21 unmodified linesdef run_query(query):# Clean the query by removing markdown symbols and trimming whitespaceclean_query = query.replace("```sql", "").replace("```", "").strip()#print(f"Executing SQL Query: {clean_query}")try:result = db.run(clean_query)return result7 unmodified linesdef database_tool(question):# print(question)sql_query = generate_sql_query(question)##print(sql_query)return run_query(sql_query)def get_ASN_data(question):59 unmodified linesdef 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):11 unmodified linessummarized_content = doc_contentsummarized_docs.append(summarized_content)return '\n\n'.join(summarized_docs)pdf_path = "Inbound.pdf"#pdf_path = r"D:\rajesh\python\chat_agent\Inbound.pdf"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****")2 unmodified lines#print("summary***")#print(summarized_response)return query_responsedef make_api_request(url, params):import requests15 unmodified lines"url": "http://193.203.162.39:9090/nxt-wms/userWarehouse/fetchWarehouseForUserId?","params": {"query": name, "userId": "164"}},#fetch customer id{"url": "http://193.203.162.39:9090/nxt-wms/userCustomer/fetchCustomerForUserId?","params": {"query": "TESTING 123", "userId": "164", "status": "Active"}},#Stock summary based on warehouse id{"url": "http://193.203.162.39:9090/nxt-wms/transactionHistory/stockSummary?","params": {"branchId": "343", "onDate": "2024-08-06", "warehouseId" : warehouse_id }}]def inventory_report(question):name = question.split(":")[0]#print(question)question = question.split(":")[1]#print(name)import requestsdata = make_api_request(apis[0]["url"], apis[0]["params"])if data:7 unmodified linesif "warehouseId" in api["params"]:api["params"]["warehouseId"] = warehouse_id#print(apis[2]["url"])#print(apis[2]["params"])data1 = make_api_request(apis[2]["url"], apis[2]["params"])#if data1:#print(data1)from tabulate import tabulate21 unmodified linestable_data.append(row)#if table_data:#print(tabulate(table_data, headers=headers, tablefmt="grid"))# Convert to pandas DataFrameimport pandas as pddf = pd.DataFrame(table_data, columns=headers)import pandas as pdfrom pandasai.llm.openai import OpenAIfrom pandasai import SmartDataframe#open api keyimport openaillm = OpenAI()sdf = SmartDataframe(df, config={"llm": llm})#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")35 unmodified linesname="dataVisualization",args_schema=QueryInput,output_schema=QueryOutput,description="Tool to generate visual output for a particular warehouse. Invoke this tool if the user wants to create charts. Process 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. ")]10 unmodified linesagent = create_tool_calling_agent(llm, tools, ChatPromptTemplate.from_template(prompt_template))agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)# Define the interface functionmax_iterations = 5iterations = 0def answer_question(user_question,chatbot):global iterationsiterations = 0while iterations < max_iterations:#print(user_question)response = agent_executor.invoke({"input": user_question})#print(response)if isinstance(response, dict):response_text = response.get("output", "")else:response_text = responseif "invalid" not in response_text.lower():breakiterations += 1if iterations == max_iterations:return "The agent could not generate a valid response within the iteration limit."11 unmodified lines#image = gr.Image(value=img_str)chatbot.append((user_question,img))#print(chatbot)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"47 unmodified lineswith gr.Row():with gr.Column(scale=1):message = gr.Textbox(show_label=False)with gr.Column(scale=1):with gr.Row():button = gr.Button("Submit", elem_classes="gr-button")20 unmodified linesdemo.launch()8 unmodified lines9101112131415161718192021222324252627282930313233349 unmodified lines44454647484950515253545556575859606162636465666768697071727321 unmodified lines95969798991001017 unmodified lines10911011111211311411559 unmodified lines17517617717817918018111 unmodified lines1931941951961971981992002012022032042 unmodified lines20720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025115 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882897 unmodified lines29729829930030130230330421 unmodified lines32632732832933033133233333433533633733833934034134234334434534634734834935035 unmodified lines38638738838939039139239339439539639739839940040140240340410 unmodified lines41541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448511 unmodified lines49749849950050150250350450550650750850951051151251351447 unmodified lines56256356456556656756820 unmodified lines5895905915928 unmodified linesimport base64from io import BytesIOimport osimport reimport tempfileimport waveimport requestsimport gradio as grimport timeimport 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, RunnableLambda9 unmodified linesfrom 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 schema21 unmodified linesdef run_query(query):# Clean the query by removing markdown symbols and trimming whitespaceclean_query = query.replace("```sql", "").replace("```", "").strip()print(f"Executing SQL Query: {clean_query}")try:result = db.run(clean_query)return result7 unmodified linesdef database_tool(question):# print(question)sql_query = generate_sql_query(question)print(sql_query)return run_query(sql_query)def get_ASN_data(question):59 unmodified linesdef 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):11 unmodified linessummarized_content = doc_contentsummarized_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****")2 unmodified lines#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()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")# Instance of MIMEBase and named as ppart = MIMEBase('application', 'octet-stream')# To change the payload into encoded formpart.set_payload((attachment).read())# Encode into base64encoders.encode_base64(part)part.add_header('Content-Disposition', f"attachment; filename= {attachment_path}")# Attach the instance 'part' to instance 'msg'msg.attach(part)# Create SMTP session for sending the mailserver = 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()#return 1def make_api_request(url, params):import requests15 unmodified lines"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:7 unmodified linesif "warehouseId" in api["params"]:api["params"]["warehouseId"] = warehouse_iddata1 = make_api_request(apis[1]["url"], apis[1]["params"])from tabulate import tabulate21 unmodified linestable_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")35 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"""")]10 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 = audioaudio_segment = AudioSegment(audio_data.tobytes(),frame_rate=sample_rate,sample_width=audio_data.dtype.itemsize,channels=1)with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio_file:audio_segment.export(temp_audio_file.name, format="wav")temp_audio_file_path = temp_audio_file.namerecognizer = sr.Recognizer()with sr.AudioFile(temp_audio_file_path) as source:audio_content = recognizer.record(source)try:user_question = recognizer.recognize_google(audio_content)except sr.UnknownValueError:user_question = "Sorry, I could not understand the audio."except sr.RequestError:user_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: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:response_text = responseif "invalid" not in response_text.lower():breakiterations += 1if iterations == max_iterations:return "The agent could not generate a valid response within the iteration limit."11 unmodified lines#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."))else: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"47 unmodified lineswith 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")20 unmodified linesdemo.launch()
app.py+184-52