Spaces:
Build error
Build error
Update app.py
Browse files10 unmodified lines1112131415161718192021222324252627285 unmodified lines34353637383940414243444518 unmodified lines6465666768694 unmodified lines747576777879808182838485868788899091921 unmodified line94959697989912 unmodified lines11211311411511611711842 unmodified lines16116216316416516616716816976 unmodified lines2462472482492502514 unmodified lines25625725825926026126226386 unmodified lines35035135235335435535635719 unmodified lines37737837938038138238338438538638738838939039139239339421 unmodified lines41641741841942042142242342442542642742842943043143243343443510 unmodified lines44644744844945045134 unmodified lines4864874884894904911 unmodified line49349449549649749849950050150250350450550650750850951098 unmodified lines60961061161261361461561661761861962062162262362462562684 unmodified lines7117127137147157167177187197207217227237246 unmodified lines7317327337347357365 unmodified lines74274374474574674774829 unmodified lines7787797807817827837847857867877887897907917927937947957967977987 unmodified lines8068078088098108118128138148158168178188193 unmodified lines8238248258268278288298 unmodified lines8388398408418428438448458468478488498508516 unmodified lines8588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159163 unmodified lines92092192292392492592692792892993093193293310 unmodified linesimport shutilimport jsonimport nltk#commenting audio related code based on Arun's input# audio package"""import speech_recognition as srfrom pydub import AudioSegmentfrom pydub.playback import play"""# Commenting SMTP code since HFSpaces doesn't support it# email library"""import smtplib, sslfrom 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 StrOutputParser5 unmodified linesfrom langchain.agents import create_tool_calling_agent, AgentExecutor, Toolfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.tools import StructuredToolfrom 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 pd18 unmodified linesfrom mailjet_rest import Clientimport base64# Define global variables for managing the thread and current_eventexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=1)current_event = None4 unmodified linesos.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("OPEN_AI_API")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 = ""1 unmodified linewarehouse_id = ""# Today's date to be populated in inventory APIinventory_date = datetime.today().strftime('%Y-%m-%d')apis = [# fetch warehouse ID{12 unmodified linesllm = 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_info42 unmodified linesdef 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()response.raise_for_status()76 unmodified linestexts = load_and_split_pdf(pdf_path)vector_store = create_vector_store(texts)def document_data_tool(question):print(f"Document data tool enter: {question}")4 unmodified lines# mailjet API since SMTP is not supported HF spacesdef send_email_with_attachment_mailjet(recipient_email, subject, body, attach_img_base64=None):api_key = os.getenv("MAILJET_API_KEY")api_secret = os.getenv("MAILJET_API_SECRET")86 unmodified linesdef make_api_request(url, params):"""Generic function to make API GET requests and return JSON data."""try:print(url)print(params)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 data19 unmodified linesif data:# Extracting the id for the warehouse with the name "WH"warehouse_id = next((item['id'] for item in data['result'] if item['wareHouseId'] == warehouse_name), None)#print(warehouse_id)if (warehouse_id):# 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_idprint(f"warehouseId: {warehouse_id}")print(f"warehouseId: {apis[1]}")data1 = make_api_request(apis[1]["url"], apis[1]["params"])if (data1):headers = ["S.No", "Warehouse Code", "Warehouse Name", "Customer Code", "Customer Name", "Item Code", "Item Name",21 unmodified lines# 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 chartelse:return "There are no inventory details for the warehouse you have given."else:return "Please provide a warehouse name available in the database."# 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):10 unmodified lines# Wrap the function with StructuredTool for better parameter handlingtools = [StructuredTool(func=get_ASN_data,name="APIData",34 unmodified lines]prompt_template = f"""You are an assistant that helps with database queries, API information, and document retrieval. Your job is to provide clear, complete, and detailed responses to the following queries. Please give the output response in an user friendly way and remove "**" from the response. For example, document related queries can be answered in a clear and concise way with numbering and not as a paragraph. Database related queries should be answered with proper indentation and use numbering for the rows. ASN id related queries should be answered with proper indentation and use numbering for the rows.For ASN id related questions, if the user specifies an ASN id, provide the information from the api tool. Pass only the id as input to the tool. Do not pass the entire question as input to the tool. If the details are not found, say it in a clear and concise way.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. When answering, focus on providing actionable insights and clear explanations related to the specific query. Please remove "**" from the response.For SQL database-related questions, only use the fields available in the warehouse schema, including tables such as customer_master, efs_company_master, efs_group_company_master, efs_region_master, party_address_detail, wms_warehouse_master.1 unmodified line{{agent_scratchpad}}Here is the information you need to process:Question: {{input}}"""llm = llm.bind()agent = 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):98 unmodified lineswhile 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: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]}, early_stopping_method="generate")print("response generated")print(response)if isinstance(response, dict):response_text = response.get("output", "")else:84 unmodified lineswhile 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: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]})if isinstance(response, dict):6 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 file5 unmodified linesimg_str = base64.b64encode(buffered.getvalue()).decode("utf-8")img = f'<img src="data:image/png;base64,{img_str}" style="width:450px; height:400px;">'# image = gr.Image(value=img_str)chatbot.append((user_question, img))email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'29 unmodified linesprint(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))return gr.update(value=chatbot)# response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()# return response_textdef submit_feedback(feedback, chatbot):gr.Info("Thank you for your feedback.")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")7 unmodified linesdef update_message(request: gr.Request):return f"<h2 style=' font-family: Calibri;'>Welcome, {request.username}</h4>"def send_mail_with_history(req: gr.Request,chatbot):if req.username:send_email_with_attachment_mailjet("lakshmivairamani@gmail.com","conversation history" + req.username, chatbot)def upload_file(filepath):gr.Info("File uploaded")# CSS for styling the buttons and other elementscss = """/* Example of custom button styling */.gr-button {background-color: #6366f1; /* Change to your desired button color */3 unmodified linespadding: 10px 20px;font-size: 12px;cursor: pointer;}.gr-button:hover {8 unmodified linespadding: 10px 20px;font-size: 14px;cursor: pointer;}.gr-buttonbig:hover {background-color: #8a92f7; /* Darker shade on hover */}/* Customizing the Logout link to be on the right */.logout-link {text-align: right;6 unmodified linestext-decoration: none;font-size: 16px;}.chatbot_gpt {/* width: 800px !important; Adjust width as needed */height: 600px !important; /* Adjust height as needed */}.logout-link a:hover {text-decoration: underline; /* Underline on hover */}.message-buttons-right{display: none !important;}body, .gradio-container {margin: 0;padding: 0;}"""with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:gr.HTML("<CENTER><B><h1 style='font-size:30px; font-family: Calibri;'>RedMindGPT</h1></B></CENTER>")with gr.Row():m = gr.Markdown()demo.load(update_message, None, m)# Logout link styled as text link in the right cornergr.Markdown("<div class='logout-link'><a href='/logout'><b>Logout</b></a></div>")with gr.Row():sample_button = gr.Button("What are the details of ASN24091600002",elem_classes="gr-buttonbig")sample_button1 = gr.Button("What are the active warehouses available",elem_classes="gr-buttonbig")sample_button2 = gr.Button("Explain Pre-Receiving Yard Management",elem_classes="gr-buttonbig")sample_button3 = gr.Button("Can you generate a pie chart with item names and quantities in warehouse WH1000001",elem_classes="gr-buttonbig")sample_button4 = gr.Button("Analyze item name & quantity for different customers in a stacked bar chart for the warehouse WH1000001 & send email to meetarun@gmail.com", elem_classes="gr-button")with gr.Row():chatbot = gr.Chatbot(label="Select any of the questions listed above to experience RedmindGPT in action.",elem_classes="chatbot_gpt")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-buttonbig")with gr.Column(scale=1):with gr.Row():button = gr.Button("Submit", elem_id="submit",elem_classes="gr-buttonbig")# Button to stop the current processingstop_button = gr.Button("Stop", elem_classes="gr-buttonbig")u = gr.UploadButton("Upload a file", file_count="single")u.upload(upload_file, u)#gr.ClearButton(message, elem_classes="gr-buttonbig")stop_button.click(stop_processing, [chatbot],[chatbot])button.click(handle_query, [message, chatbot], [chatbot])message.submit(handle_query, [message, chatbot], [chatbot])message.submit(lambda x: gr.update(value=""), None, [message], queue=False)3 unmodified linessubmit_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], [chatbot])sample_button.click(handle_query, [sample_button, chatbot], [chatbot])sample_button1.click(handle_query, [sample_button1, chatbot], [chatbot])sample_button2.click(handle_query, [sample_button2, chatbot], [chatbot])sample_button3.click(handle_query, [sample_button3, chatbot], [chatbot])sample_button4.click(handle_query, [sample_button4, chatbot], [chatbot])#demo.unload(lambda: send_mail_with_history(chatbot))demo.title = "RedmindGPT"#user_details for login pagedemo.launch(auth=[("lakshmi", "redmind"), ("arun", "redmind"), ("NewageGlobal", "Newage123$")], auth_message= " RedmindGPT",inline=False)10 unmodified lines11121314151617181920212223242526272829305 unmodified lines363738394041424344454647484918 unmodified lines6869707172737475767778798081824 unmodified lines878889909192939495969798991001011021031041051061071081091101111 unmodified line11311411511611711811912 unmodified lines13213313413513613742 unmodified lines18018118218318418518618718818919019176 unmodified lines2682692702712722732742752762774 unmodified lines28228328428528628786 unmodified lines37437537637737837919 unmodified lines39940040140240340440540640740840941041141221 unmodified lines43443543643743843944044144244344444544644744844945045145245345445545645745810 unmodified lines46947047147247347447534 unmodified lines5105115125135145155161 unmodified line51851952052152252352452552652752852953098 unmodified lines62963063163263363463563684 unmodified lines7217227237247257266 unmodified lines7337347357367377387397405 unmodified lines74674774874975075175229 unmodified lines7827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258267 unmodified lines83483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811293 unmodified lines1133113411351136113711388 unmodified lines1147114811491150115111521153115411551156115711586 unmodified lines11651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912703 unmodified lines12741275127612771278127912801281128212831284128512861287128810 unmodified linesimport shutilimport jsonimport nltkimport mysql.connectorimport fnmatch# audio related code is not included based on Arun's input# audio packageimport speech_recognition as srfrom pydub import AudioSegmentfrom pydub.playback import play# SMTP code is not included since HFSpaces doesn't support it# email libraryimport smtplib, sslfrom 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 StrOutputParser5 unmodified linesfrom langchain.agents import create_tool_calling_agent, AgentExecutor, Toolfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.tools import StructuredTool#from langchain.pydantic_v1 import BaseModel, Fieldfrom pydantic import BaseModel, Fieldfrom PyPDF2 import PdfReaderfrom nltk.tokenize import sent_tokenizefrom datetime import datetimefrom sqlalchemy import create_enginefrom sqlalchemy.sql import textimport openai# pandasimport pandas as pd18 unmodified linesfrom mailjet_rest import Clientimport base64#Variables Initializationagent_executor = Nonevector_store1 = Nonetexts1 = Noneexcel_dataframe = Nonefile_extension = None#This is to define the summary of the runtime tool. This summary will be updated in prompt template and description of the new toolrun_time_tool_summary=""# Define global variables for managing the thread and current_eventexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=1)current_event = None4 unmodified linesos.environ["LANGFUSE_SECRET_KEY"] = os.getenv("LANGFUSE_SECRET_KEY")os.environ["LANGFUSE_HOST"] = os.getenv("LANGFUSE_HOST")DB_USER = 'u852023448_redmindgpt'DB_PASSWORD = 'redmindGpt@123'DB_HOST = '217.21.88.10'DB_NAME = 'u852023448_redmindgpt'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 = ""1 unmodified linewarehouse_id = ""# Today's date to be populated in inventory APIinventory_date = datetime.today().strftime('%Y-%m-%d')apis = [# fetch warehouse ID{12 unmodified linesllm = 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_info42 unmodified linesdef get_ASN_data(question):base_url = os.getenv("ASN_API_URL")print(f"base_url{base_url}")complete_url = f"{base_url}branchMaster.id=343&transactionUid={question}&userId=164&transactionType=ASN"try:response = requests.get(complete_url)print(f"complete_url{complete_url}")print(f"response{response}")data = response.json()response.raise_for_status()76 unmodified linestexts = load_and_split_pdf(pdf_path)vector_store = create_vector_store(texts)def document_data_tool_runtime(question):print(f"Document data runtime tool enter: {question} with {vector_store1}")query_response = query_vector_store(vector_store1, question, config={"callbacks": [langfuse_handler]})return query_responsedef document_data_tool(question):print(f"Document data tool enter: {question}")4 unmodified lines# mailjet API since SMTP is not supported HF spacesdef send_email_with_attachment_mailjet(recipient_email, subject, body, attach_img_base64=None):api_key = os.getenv("MAILJET_API_KEY")api_secret = os.getenv("MAILJET_API_SECRET")86 unmodified linesdef 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 data19 unmodified linesif data:# Extracting the id for the warehouse with the name "WH"warehouse_id = next((item['id'] for item in data['result'] if item['wareHouseId'] == warehouse_name), None)if (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"])if (data1):headers = ["S.No", "Warehouse Code", "Warehouse Name", "Customer Code", "Customer Name", "Item Code", "Item Name",21 unmodified lines# Convert to pandas DataFramedf = pd.DataFrame(table_data, columns=headers)chart_link = chat_with_llm(df,question)return chart_linkelse:return "There are no inventory details for the warehouse you have given."else:return "Please provide a warehouse name available in the database."def chat_with_llm(df,question):sdf = SmartDataframe(df, config={"llm": llm_chart})llm_response = sdf.chat(question)return llm_responsedef bind_llm(llm, tools,prompt_template):llm = llm.bind()agent = create_tool_calling_agent(llm, tools, ChatPromptTemplate.from_template(prompt_template))agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)return agent_executor# Define input and output models using Pydanticclass QueryInput(BaseModel):10 unmodified lines# Wrap the function with StructuredTool for better parameter handlingtools = [StructuredTool(func=get_ASN_data,name="APIData",34 unmodified lines]prompt_template = f"""You are an assistant that helps with database queries, API information, and document retrieval. Your job is to provide clear, complete, and detailed responses to the following queries. Please give the output response in an user friendly way and remove "**" from the response. For example, document related queries can be answered in a clear and concise way with numbering and not as a paragraph. Database related queries should be answered with proper indentation and use numbering for the rows. ASN id related queries should be answered with proper indentation and use numbering for the rows.For ASN id related questions, if the user specifies an ASN id, provide the information from the api tool. Pass only the id as input to the tool. Do not pass the entire question as input to the tool. If the details are not found, say it in a clear and concise way.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. When answering, focus on providing actionable insights and clear explanations related to the specific query. Please remove "**" from the response.For SQL database-related questions, only use the fields available in the warehouse schema, including tables such as customer_master, efs_company_master, efs_group_company_master, efs_region_master, party_address_detail, wms_warehouse_master.1 unmodified line{{agent_scratchpad}}Here is the information you need to process:Question: {{input}}"""agent_executor = bind_llm(llm,tools,prompt_template)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):98 unmodified lineswhile iterations < max_iterations:response = agent_executor.invoke({"input": user_question}, config={"callbacks": [langfuse_handler]}, early_stopping_method="generate")if isinstance(response, dict):response_text = response.get("output", "")else:84 unmodified lineswhile iterations < max_iterations:response = agent_executor.invoke({"input": user_question}, config={"callbacks": [langfuse_handler]})if isinstance(response, dict):6 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 file5 unmodified linesimg_str = base64.b64encode(buffered.getvalue()).decode("utf-8")img = f'<img src="data:image/png;base64,{img_str}" style="width:450px; height:400px;">'chatbot.append((user_question, img))email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'29 unmodified linesprint(f"Error loading image file: {e}")chatbot.append((user_question, "Chart generation failed. Please try again."))return gr.update(value=chatbot)else:chatbot.append((user_question, response_text))return gr.update(value=chatbot)def submit_feedback(feedback, chatbot, request: gr.Request):gr.Info("Thank you for your feedback.")#save feedback with user question and response in databasesave_feedback(request.username,chatbot[-1][0], chatbot[-1][1], feedback)feedback_response = "User feedback: " + feedbackreturn chatbot + [(feedback_response, None)], gr.update(visible=False), gr.update(visible=False)# Function to connect to MySQL databasedef connect_to_db():return mysql.connector.connect(host=DB_HOST,user=DB_USER,password=DB_PASSWORD,database=DB_NAME)# Function to save feedback to the databasedef save_feedback(username, user_question, user_response, feedback):try:conn = connect_to_db()cursor = conn.cursor()query = "INSERT INTO user_feedback (username, question, response, feedback) VALUES (%s, %s, %s, %s)"cursor.execute(query, (username, user_question, user_response, feedback))conn.commit()except mysql.connector.Error as err:print(f"Error: {err}")finally:if cursor:cursor.close()if conn:conn.close()def handle_dislike(data: gr.LikeData):if not data.liked:print("downvote")7 unmodified linesdef update_message(request: gr.Request):return f"<h2 style=' font-family: Calibri;'>Welcome, {request.username}</h4>"# Function to generate a 50-word summary of the newly uploaded doc using OpenAIdef generate_summary(text):prompt = ("You are an AI that helps with document analysis. Please provide a concise title and a summary of the following document. ""The summary should be about 50 words and include key details that can help answer questions accurately:\n\n"f"{text}\n\nTitle : Summary")# Call the OpenAI API to generate a summaryresponse = openai.chat.completions.create(messages=[{"role": "user","content": prompt,}],model="gpt-4o-mini",)# Extract the title and summary from the responseresponse_content = response.choices[0].message.contentlines = response_content.split("\n")# Extract titletitle_line = lines[0]title = title_line.split("**Title:**")[-1].strip()# Extract summarysummary_line = lines[2]summary = summary_line.split("**Summary:**")[-1].strip()return title, summary#function to handle file upload decide whether excel or doc is uploaded and respective tool will be created with appropriate prompts at runtimedef upload_file(filepath):global vector_store1, file_extension# Get the file extension_, file_extension = os.path.splitext(filepath)if file_extension == ".pdf":texts1 = load_and_split_pdf(filepath)vector_store1 = create_vector_store(texts1)# Generate a 50-word summary from the extracted texttitle, summary = generate_summary(texts1)return title, summary, file_extensionelif file_extension == ".xlsx":title, prompt = process_excel(filepath)return title, promptdef generate_example_questions(sheet_name, column_headers):"""Generates natural language questions based on column headers.Args:sheet_name (str): The name of the Excel sheet.column_headers (list): List of column headers from the sheet.Returns:questions (list): List of generated questions based on the columns."""questions = []# Check for typical columns and create questionsif 'Product Name' in column_headers or 'Product' in column_headers:questions.append(f"What is the total sales for a specific product in {sheet_name}?")if 'Sales Amount' in column_headers or 'Amount' in column_headers:questions.append(f"What is the total sales amount for a specific region in {sheet_name}?")if 'Region' in column_headers:questions.append(f"Which region had the highest sales in {sheet_name}?")if 'Date' in column_headers:questions.append(f"What were the total sales during a specific month in {sheet_name}?")if 'Price' in column_headers:questions.append(f"What is the price of a specific product in {sheet_name}?")if any(fnmatch.fnmatch(header, 'Employee*') for header in column_headers):questions.append(f"What are the details of the employee names with distinct broker names?")return questionsdef generate_prompt_from_excel_file(df_dict):"""Generates a prompt from an Excel file containing multiple sheets.Args:excel_file_path (str): The path to the Excel file.Returns:prompt (str): A detailed prompt including sheet names, column headers, sample data,and example questions for each sheet."""# Initialize prompt with basic structureprompt = "You have been provided with an Excel file containing data in several sheets.\n"# Loop through each sheet to extract column headers and sample datafor sheet_name, sheet_df in df_dict.items():# Extract column headerscolumn_headers = list(sheet_df.columns)# Get a sample of the data (first few rows)sample_data = sheet_df.head(3).to_string(index=False)# Add sheet details to the promptprompt += f"For the sheet '{sheet_name}', the column headers are:"prompt += f"{', '.join(column_headers)}\n\n"#prompt += f"Example data from sheet '{sheet_name}':\n"#prompt += f"{sample_data}\n\n"# Generate example natural language questions based on columnsexample_questions = generate_example_questions(sheet_name, column_headers)#prompt += "### Example Questions:\n"#for question in example_questions:# prompt += f"- {question}\n"#prompt += "\n"# Finalize the prompt with function call descriptionprompt += f"- Query: A natural language question (e.g., {example_questions}).\n"prompt += "The function should return a result based on the Excel data, such as specific values, calculations, or summaries.\n"return "Excel data", prompt# Function to handle "Add to RedMindGPT" button clickdef add_to_redmindgpt(title, summary):"""Adds a document or Excel file to the RedmindGPT system and configures the appropriate runtime tool for handling related queries.Parameters:title (str): The title of the document or Excel file.summary (str): A brief summary of the document or Excel file.Returns:str: A message indicating whether the file has been added successfully.Behavior:- If the file extension is ".pdf", it sets up a runtime tool for handling document-related queries.- If the file extension is ".xlsx", it sets up a runtime tool for handling Excel data-related queries.- Configures the prompt template for the agent executor based on the file type.- Adds the configured runtime tool to the list of tools used by the agent executor."""global agent_executor, file_extensionif file_extension == ".pdf":run_time_tool_summary = f"For {title} document related questions, Please refer runtimeDocumentData tool. {summary}. Please provide a complete and concise response within 200 words and Ensure that the response is not truncated and covers the essential points."run_time_tool = StructuredTool(func=document_data_tool_runtime,name="runtimeDocumentData",args_schema=QueryInput,output_schema=QueryOutput,description=f"You are an AI assistant trained to help with the questions based on the uploaded document {title}. {summary}. Please provide a complete and concise response within 200 words and Ensure that the response is not truncated and covers the essential points.")# Add the new tool to the beginningtools.insert(0, run_time_tool)prompt_template = f"""You are an assistant that helps with database queries, API information, and document retrieval. Your job is to provide clear, complete, and detailed responses to the following queries. Please give the output response in an user friendly way and remove "**" from the response. For example, document related queries can be answered in a clear and concise way with numbering and not as a paragraph. Database related queries should be answered with proper indentation and use numbering for the rows. ASN id related queries should be answered with proper indentation and use numbering for the rows.{run_time_tool_summary}For ASN id related questions, if the user specifies an ASN id, provide the information from the api tool. Pass only the id as input to the tool. Do not pass the entire question as input to the tool. If the details are not found, say it in a clear and concise way.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. When answering, focus on providing actionable insights and clear explanations related to the specific query. Please remove "**" from the response.For SQL database-related questions, only use the fields available in the warehouse schema, including tables such as customer_master, efs_company_master, efs_group_company_master, efs_region_master, party_address_detail, wms_warehouse_master.For datavisualization, user will ask for inventory report of a particular warehouse. Your job is to return the image path to chat interface and display the image as output.{{agent_scratchpad}}Here is the information you need to process:Question: {{input}}"""agent_executor = bind_llm(llm,tools,prompt_template)return f"File has been added successfully."elif file_extension == ".xlsx":run_time_excel_tool_summary = f"For {title} related questions, Please refer runtimeExcelData tool. {summary}. "run_time_excel_tool = StructuredTool(func=chat_with_excel_data_dataframe,name="runtimeExcelData",args_schema=QueryInput,output_schema=QueryOutput,description="""You are an AI assistant trained to handle Excel data and return meaningful insights. Please display the output as below. If the output is not in the below format, please display the error message returned by the function as response.There are a total of {total_rows} rows. Please download the complete dataset here: <a href="https://redmindtechnologies.com/alborj/test.xlsx" download>Download</a>. Here are the first 3 rows:{sample_table}""")# Add the new tool to the beginningtools.insert(0, run_time_excel_tool)prompt_template = f"""You are an assistant that helps with database queries, API information, and document retrieval. Your job is to provide clear, complete, and detailed responses to the following queries. Please give the output response in an user friendly way and remove "**" from the response. For example, document related queries can be answered in a clear and concise way with numbering and not as a paragraph. Database related queries should be answered with proper indentation and use numbering for the rows. ASN id related queries should be answered with proper indentation and use numbering for the rows.{run_time_excel_tool_summary}For ASN id related questions, if the user specifies an ASN id, provide the information from the api tool. Pass only the id as input to the tool. Do not pass the entire question as input to the tool. If the details are not found, say it in a clear and concise way.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. When answering, focus on providing actionable insights and clear explanations related to the specific query. Please remove "**" from the response.For SQL database-related questions, only use the fields available in the warehouse schema, including tables such as customer_master, efs_company_master, efs_group_company_master, efs_region_master, party_address_detail, wms_warehouse_master.For datavisualization, user will ask for inventory report of a particular warehouse. Your job is to return the image path to chat interface and display the image as output.{{agent_scratchpad}}Here is the information you need to process:Question: {{input}}"""agent_executor = bind_llm(llm,tools,prompt_template)return f"File has been added successfully."def process_excel(file):global excel_dataframe# Check if the file is Noneif file is None:return "Excel file", "Your excel does not have values. Please upload a different file." # Return an empty dataframe if no file is uploadedelse:# Read the uploaded Excel fileexcel_dataframe = pd.read_excel(file.name, sheet_name=None) # 'file.name' to get the actual file path#to get title and summary of excel filetitle, prompt = generate_prompt_from_excel_file(excel_dataframe)excel_dataframe = pd.read_excel(file.name)return title, prompt # Return the success message.def chat_with_excel_data(question):global excel_dataframeresponse_dataframe = chat_with_llm(excel_dataframe,question)return response_dataframedef chat_with_excel_data_dataframe(question):response_dataframe = chat_with_excel_data(question)#handle large datasetresponse = handle_large_dataset(response_dataframe)return response#Save the respnse dataframe to an Excel file in hostinger so that the user can download it#save_file_path = "dataframe_output.xlsx"#response_dataframe.to_excel(save_file_path, index=False)#save_file_to_hostinger(save_file_path)# Check if the response is a DataFrame"""if isinstance(response_dataframe, pd.DataFrame):# Convert DataFrame to HTML for displaydf_html = response_dataframe.to_html(classes='dataframe', index=False)print(f"dfhtml:{df_html}")return df_html"""#return response_dataframe.head(10)#, len(response_dataframe)def save_file_to_hostinger(save_file_path):from ftplib import FTP# Step 2: FTP server credentialsftp_host = 'ftp.redmindtechnologies.com' # Replace with your FTP server addressftp_user = 'u852023448.redmindGpt' # Replace with your FTP usernameftp_pass = 'RedMind@505' # Replace with your FTP passwordremote_file_path = '/alborj/test.xlsx' # Replace with the desired path on the server# Create an FTP connectionftp = FTP(ftp_host)ftp.login(ftp_user, ftp_pass)# Open the local file and upload it to the serverwith open(save_file_path, 'rb') as file:ftp.storbinary(f'STOR {remote_file_path}', file)print(f'File {save_file_path} uploaded to {remote_file_path} on server.')# Close the FTP connectionftp.quit()def handle_large_dataset(df):total_rows = len(df)if total_rows < 4000:# 1. Limit to first 10 rowslimited_data = df.head(3)# 2. Handle missing valueslimited_data.fillna("N/A", inplace=True)# 3. Drop the original first columnlimited_data_without_first_column = limited_data.iloc[:, 1:] # Skipping the original first column# 4. Add SNo (serial number) as the first column, starting from 1limited_data_without_first_column.insert(0, 'SNo', range(1, len(limited_data_without_first_column) + 1))# 3. Save the full dataset to a downloadable filedf.to_excel('output_data.xlsx', index=False)save_file_to_hostinger('output_data.xlsx')# 4. Create a summary and table of the first 10 rows for displaycolumns = list(df.columns)sample_table = limited_data_without_first_column.to_markdown()# 5. Return the summary and downloadable linkreturn f"""There are a total of {total_rows} rows. Please download the complete dataset here: <a href="https://redmindtechnologies.com/alborj/test.xlsx" download>Download</a>. Here are the first 3 rows:{sample_table} """else:return "Your query returns a large dataset which is not supported in the current version. Please try a different query."css = """/* Example of custom button styling */.gr-button {background-color: #6366f1; /* Change to your desired button color */3 unmodified linespadding: 10px 20px;font-size: 12px;cursor: pointer;}.gr-button:hover {8 unmodified linespadding: 10px 20px;font-size: 14px;cursor: pointer;}.gr-buttonbig:hover {background-color: #8a92f7; /* Darker shade on hover */}/* Customizing the Logout link to be on the right */.logout-link {text-align: right;6 unmodified linestext-decoration: none;font-size: 16px;}.chatbot_gpt {height: 600px !important; /* Adjust height as needed */}.logout-link a:hover {text-decoration: underline; /* Underline on hover */}.message-buttons-right{display: none !important;}body, .gradio-container {margin: 0;padding: 0;}/* Styling the tab header with a blue background */.gr-tab-header {background-color: #4A90E2; /* Blue background for the tab header */padding: 10px;border-radius: 8px;color: white;font-size: 16px;}/* Styling the selected tab text color to be green */.gr-tab-header .gr-tab-active {color: green; /* Change selected tab text to green */}/* Keep non-selected tab text color white */.gr-tab-header .gr-tab {color: white;}/* Custom CSS for reducing the size of the video element */.video-player {width: 500px; /* Set a custom width for the video */height: 350px; /* Set a custom height for the video */margin: 0 auto; /* Center the video horizontally */}"""with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:gr.HTML("<CENTER><B><h1 style='font-size:30px; font-family: Calibri;'>RedMindGPT</h1></B></CENTER>")# Logout link styled as text link in the right cornergr.Markdown("<div class='logout-link'><a href='/logout'><b>Logout</b></a></div>")# Unified RedMindGPT Interfacewith gr.Row():m = gr.Markdown()demo.load(update_message, None, m)# Buttons for sample querieswith gr.Row():sample_button = gr.Button("What are the details of ASN24091600002", elem_classes="gr-buttonbig")sample_button1 = gr.Button("What are the active warehouses available", elem_classes="gr-buttonbig")sample_button2 = gr.Button("Explain Pre-Receiving Yard Management", elem_classes="gr-buttonbig")sample_button3 = gr.Button("Can you generate a pie chart with item names and quantities in warehouse WH1000001", elem_classes="gr-buttonbig")sample_button4 = gr.Button("Analyze item name & quantity for different customers in a stacked bar chart for the warehouse WH1000001 & send email to meetarun@gmail.com", elem_classes="gr-button")# Chatbot componentwith gr.Row():chatbot = gr.Chatbot(label="Select any of the questions listed above to experience RedMindGPT in action.", elem_classes="chatbot_gpt")# Textbox for user questionswith 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-buttonbig")with gr.Column(scale=1):with gr.Row():button = gr.Button("Submit", elem_id="submit", elem_classes="gr-buttonbig")stop_button = gr.Button("Stop", elem_classes="gr-buttonbig")# Rearranged to place Upload Doc and Upload Excel in the same rowwith gr.Row():with gr.Column(scale=1):# File Upload Sectiongr.Markdown("**Add a document or Excel for natural language interaction.**")with gr.Column(scale=1):u = gr.UploadButton("Upload a doc/excel", file_count="single", elem_classes="gr-buttonbig")#excel_file = gr.UploadButton("Upload an excel", file_count="single", elem_classes="gr-buttonbig", file_types=[".xlsx", ".xls"])with gr.Column(scale=1):add_button = gr.Button("Add to RedMindGPT", elem_classes="gr-buttonbig", visible=False)with gr.Row():title_textbox = gr.Textbox(label="Title", visible=False)summary_textarea = gr.Textbox(label="Summary", lines=5, visible=False)output_message = gr.Markdown() # Markdown to display output messagesuccess_message = gr.Markdown() # Placeholder for messages# Moved function calling lines to the endstop_button.click(stop_processing, [chatbot], [chatbot])button.click(handle_query, [message, chatbot], [chatbot])message.submit(handle_query, [message, chatbot], [chatbot])message.submit(lambda x: gr.update(value=""), None, [message], queue=False)3 unmodified linessubmit_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(handle_query, [sample_button, chatbot], [chatbot])sample_button1.click(handle_query, [sample_button1, chatbot], [chatbot])sample_button2.click(handle_query, [sample_button2, chatbot], [chatbot])sample_button3.click(handle_query, [sample_button3, chatbot], [chatbot])sample_button4.click(handle_query, [sample_button4, chatbot], [chatbot])u.upload(upload_file, u, [title_textbox, summary_textarea])u.upload(lambda _: (gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)), None, [title_textbox, summary_textarea, add_button])add_button.click(add_to_redmindgpt, [title_textbox, summary_textarea], output_message)add_button.click(lambda _: (gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)), None, [title_textbox, summary_textarea, add_button])demo.launch(auth=[("lakshmi", "redmind"), ("arun", "redmind"), ("NewageGlobal", "Newage123$")], auth_message="RedMindGPT", inline=False)
app.py+451-96