Spaces:
Build error
Build error
Update app.py
Browse files10 unmodified lines1112131415161718192021222324252624 unmodified lines51525354555657585960616263646515 unmodified lines818283848586878889103 unmodified lines19319419519619719819920020146 unmodified lines24824925025125225325425525625725825926026126220 unmodified lines2832842852862872882893 unmodified lines29329429529629729829981 unmodified lines38138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942085 unmodified lines5065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435449 unmodified lines5545555565575585595605615625637 unmodified lines57157257357457557615 unmodified lines59259359459559659728 unmodified lines6266276286296306316326339 unmodified lines6436446456466476486496506516526536546556566576586593 unmodified lines663664665666667668669670671672673674675676677678679680681682683684118 unmodified lines80380480580680780893 unmodified lines90290390490510 unmodified linesimport shutilimport jsonimport nltk# audio packageimport speech_recognition as srfrom pydub import AudioSegmentfrom pydub.playback import play# 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 StrOutputParser24 unmodified lines# langfuse analyticsfrom langfuse.callback import CallbackHandler#forcefully stop the agent executionimport concurrent.futuresfrom tabulate import tabulate# Define global variables for managing the thread and futureexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=1)future = Noneimport threadingstop_event = threading.Event()# LangFuse API keys and host settings15 unmodified lines# Database setupdb = SQLDatabase.from_uri(db_uri)user_email = ""warehouse_name = ""warehouse_id = ""inventory_date = datetime.today().strftime('%Y-%m-%d')apis = [# fetch warehouse ID103 unmodified linesexcept Exception as err:print(f"An error occurred: {err}")# get_ASN_data("ASN24072400001")def load_and_split_pdf(pdf_path):reader = PdfReader(pdf_path)text = ''46 unmodified lines# summarized_response = summarize_document(query_response)return query_response#mailjet APIdef send_email_with_attachment_mailjet(recipient_email, subject, body, attachment_path):from mailjet_rest import Clientimport osimport base64# Replace these with your Mailjet API credentialsapi_key = '9ce0aa1f8eb21d9e2ed2433a5702185b'api_secret = '434e366db9b8c421eef99f6f92129fad'# Initialize the Mailjet clientmailjet = Client(auth=(api_key, api_secret), version='v3.1')20 unmodified lines{"ContentType": "image/png", # Replace with the correct MIME type of your image"Filename": "inventory_report.png", # Name of the image as it will appear in the email"Base64Content": attachment_path # Base64-encoded image content}]3 unmodified lines# Send the emailresult = mailjet.send.create(data=data)print(result)# Check if the email was sent successfullyif result.status_code == 200:print("Email sent successfully with attachment!")81 unmodified linesif "warehouseId" in api["params"]:api["params"]["warehouseId"] = warehouse_iddata1 = make_api_request(apis[1]["url"], apis[1]["params"])headers = ["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")85 unmodified linesmax_iterations = 5iterations = 0def handle_query(user_question, chatbot, audio=None):"""Function to handle the processing of user input with `AgentExecutor.invoke()`."""global future, stop_event# Clear previous stop event and futurestop_event.clear()print(user_question)#if future and not future.done():# chatbot.append(("","A query is already being processed. Please stop it before starting a new one."))# return gr.update(value=chatbot)print(user_question)# Start the processing in a new threadfuture = executor.submit(answer_question_thread, user_question, chatbot)# Periodically check if future is donewhile not future.done():if stop_event.is_set():future.cancel()chatbot.append((user_question, "Sorry, we encountered an error while processing your request. Please try after some time."))return gr.update(value=chatbot)time.sleep(1) # Wait for 1 second before checking againif future.cancelled():chatbot.append((user_question, "Sorry, we encountered an error while processing your request. Please try after some time."))return gr.update(value=chatbot)else:try:user_question1, response_text1 = future.result() # Get the result of the completed futureprint("output")print(user_question1)print(response_text1)9 unmodified lines"""Stops the current processing if it's running."""global future, stop_eventif future and not future.done():stop_event.set() # Signal the process to stopfuture.cancel() # Attempt to cancel the futurechatbot.append((user_question, "Sorry, we encountered an error while processing your request. Please try after some time."))return gr.update(value=chatbot)7 unmodified lines# 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(15 unmodified linesuser_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:28 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))response_text = response.get("output", "").split(".")[0] + imgemail_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'9 unmodified linessubject="Warehouse Inventory Report",body=response.get("output", "").split(".")[0],# attachment_path=chart_pathattachment_path=img_str)# Send email with the chart image attached"""send_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"))"""#return user_question, imgif "send email to" in user_question:try:3 unmodified linesexcept Exception as e:print(f"Error loading image file: {e}")response_text = "Chart generation failed. Please try again."#chatbot.append((user_question, "Chart generation failed. Please try again."))#return gr.update(value=chatbot)return user_question, response_text# 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)return user_question, response_text# response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()# return response_textdef answer_question(user_question, chatbot, audio=None):global iterations118 unmodified linesprint("upvote")return gr.update(visible=False), gr.update(visible=False)def update_message(request: gr.Request):return f"<h2 style=' font-family: Calibri;'>Welcome, {request.username}</h4>"93 unmodified linessample_button3.click(handle_query, [sample_button3, chatbot], [chatbot])sample_button4.click(handle_query, [sample_button4, chatbot], [chatbot])demo.launch(auth=[("lakshmi", "redmind"), ("arun", "redmind")])10 unmodified lines11121314151617181920212223242526272824 unmodified lines535455565758596061626364656667686970717215 unmodified lines8889909192939495969798103 unmodified lines20220320420520620746 unmodified lines25425525625725825926026126226326426520 unmodified lines2862872882892902912923 unmodified lines29629729829930030130281 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542685 unmodified lines5125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495509 unmodified lines5605615625635645655665675685697 unmodified lines57757857958058158258315 unmodified lines59960060160260360460528 unmodified lines6346356366376386396409 unmodified lines6506516526536546556566573 unmodified lines661662663664665666667668669670671672673674675118 unmodified lines79479579679779879980093 unmodified lines89489589689789810 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 StrOutputParser24 unmodified lines# langfuse analyticsfrom langfuse.callback import CallbackHandler# Inventory API data tablefrom tabulate import tabulate#forcefully stop the agent executionimport concurrent.futuresimport threading# mailjet_rest to send emailfrom mailjet_rest import Clientimport base64# Define global variables for managing the thread and current_eventexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=1)current_event = Nonestop_event = threading.Event()# LangFuse API keys and host settings15 unmodified lines# Database setupdb = SQLDatabase.from_uri(db_uri)user_email = ""warehouse_name = ""warehouse_id = ""# Today's date to be populated in inventory APIinventory_date = datetime.today().strftime('%Y-%m-%d')apis = [# fetch warehouse ID103 unmodified linesexcept Exception as err:print(f"An error occurred: {err}")def load_and_split_pdf(pdf_path):reader = PdfReader(pdf_path)text = ''46 unmodified lines# summarized_response = summarize_document(query_response)return query_response# mailjet API since SMTP is not supported HF spacesdef send_email_with_attachment_mailjet(recipient_email, subject, body, attach_img_base64):api_key = os.getenv("MAILJET_API_KEY")api_secret = os.getenv("MAILJET_API_SECRET")# Initialize the Mailjet clientmailjet = Client(auth=(api_key, api_secret), version='v3.1')20 unmodified lines{"ContentType": "image/png", # Replace with the correct MIME type of your image"Filename": "inventory_report.png", # Name of the image as it will appear in the email"Base64Content": attach_img_base64 # Base64-encoded image content}]3 unmodified lines# Send the emailresult = mailjet.send.create(data=data)# Check if the email was sent successfullyif result.status_code == 200:print("Email sent successfully with attachment!")81 unmodified linesif "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","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 chartelse:return "There are no inventory details for the warehouse you have given."# inventory_report("WH:can you give me a bar chart with item name and quantity for the warehouse WH")85 unmodified linesmax_iterations = 5iterations = 0def handle_query(user_question, chatbot, audio=None):"""Function to handle the processing of user input with `AgentExecutor.invoke()`."""global current_event, stop_event# Clear previous stop event and current_eventstop_event.clear()#if current_event and not current_event.done():# chatbot.append(("","A query is already being processed. Please stop it before starting a new one."))# return gr.update(value=chatbot)# Start the processing in a new threadcurrent_event = executor.submit(answer_question_thread, user_question, chatbot)# Periodically check if current_event is donewhile not current_event.done():if stop_event.is_set():current_event.cancel()chatbot.append((user_question, "Sorry, we encountered an error while processing your request. Please try after some time."))return gr.update(value=chatbot)time.sleep(1) # Wait for 1 second before checking againif current_event.cancelled():chatbot.append((user_question, "Sorry, we encountered an error while processing your request. Please try after some time."))return gr.update(value=chatbot)else:try:user_question1, response_text1 = current_event.result() # Get the result of the completed current_eventprint("output")print(user_question1)print(response_text1)9 unmodified lines"""Stops the current processing if it's running."""global current_event, stop_eventif current_event and not current_event.done():stop_event.set() # Signal the process to stopcurrent_event.cancel() # Attempt to cancel the current_eventchatbot.append((user_question, "Sorry, we encountered an error while processing your request. Please try after some time."))return gr.update(value=chatbot)7 unmodified lines# Clean the /tmp/gradio/ directory# clean_gradio_tmp_dir()# Handle audio input if provided"""if audio is not None:sample_rate, audio_data = audioaudio_segment = AudioSegment(15 unmodified linesuser_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:28 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;">'response_text = response.get("output", "").split(".")[0] + imgemail_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'9 unmodified linessubject="Warehouse Inventory Report",body=response.get("output", "").split(".")[0],# attachment_path=chart_pathattach_img_base64=img_str)if "send email to" in user_question:try:3 unmodified linesexcept Exception as e:print(f"Error loading image file: {e}")response_text = "Chart generation failed. Please try again."return user_question, response_textelse:return user_question, response_text# response_text = response_text.replace('\n', ' ').replace(' ', ' ').strip()# return response_text# without forceful stop optiondef answer_question(user_question, chatbot, audio=None):global iterations118 unmodified linesprint("upvote")return gr.update(visible=False), gr.update(visible=False)# greet with user name on successful logindef update_message(request: gr.Request):return f"<h2 style=' font-family: Calibri;'>Welcome, {request.username}</h4>"93 unmodified linessample_button3.click(handle_query, [sample_button3, chatbot], [chatbot])sample_button4.click(handle_query, [sample_button4, chatbot], [chatbot])#user_details for login pagedemo.launch(auth=[("lakshmi", "redmind"), ("arun", "redmind")])
app.py+79-86