Spaces:
Build error
Build error
Update app.py
Browse files10 unmodified lines1112131415151617171819201921222324232526272824 unmodified lines53545556575859606162576364656659676861626970717215 unmodified lines8889909192939495969798103 unmodified lines20220320419619719820520620746 unmodified lines25425525625125225325425525625725825925725825926026126226326426520 unmodified lines2862872882862892902912923 unmodified lines29629729829629930030130281 unmodified lines38438538638438538638738838738838939039139239339039139239339439539639739839940040140240340440540640739439539639739839940040140240340440540640740840941041141240941041341441541241641741441541841942041742142242342442542685 unmodified lines5125135145155165175185195205145215225165235245185195255265275285295235305255315325275285335345355305365375385395405415365425435445455465415475485495509 unmodified lines5605615625575585635645655605665675685697 unmodified lines57757857958058158258315 unmodified lines59960060160260360460528 unmodified lines6346356366296306376386396409 unmodified lines6506516526466536546486496506516526536546556566556566573 unmodified lines661662663666667668669664671672665666674675667668669670671681672673674675118 unmodified lines79479579679779879980093 unmodified lines89489589689789810 unmodified linesimport shutilimport jsonimport nltk#commenting audio related code based on Arun's input# audio packageimport speech_recognition as sr"""import speech_recognition as srfrom pydub import AudioSegmentfrom pydub.playback import playfrom pydub.playback import play"""# Commenting SMTP code since HFSpaces doesn't support it# email libraryimport smtplib, ssl"""import smtplib, sslfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersfrom 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
from tabulate import tabulate# mailjet_rest to send emailfrom mailjet_rest import Clientimport base64
# Define global variables for managing the thread and future# Define global variables for managing the thread and current_eventexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=1)future = Noneimport threadingcurrent_event = Nonestop_event = threading.Event()
# LangFuse API keys and host settings15 unmodified lines# Database setup
db = 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 lines 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) 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 Client import os import base64 # Replace these with your Mailjet API credentials api_key = '9ce0aa1f8eb21d9e2ed2433a5702185b' api_secret = '434e366db9b8c421eef99f6f92129fad'# 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 client mailjet = 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 "Base64Content": attach_img_base64 # Base64-encoded image content } ] 3 unmodified lines # Send the email result = mailjet.send.create(data=data) print(result)
# Check if the email was sent successfully if result.status_code == 200: print("Email sent successfully with attachment!")81 unmodified lines if "warehouseId" in api["params"]: api["params"]["warehouseId"] = warehouse_id
data1 = 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 = []
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", "Currency", "EAN", "UOM", "Quantity", "Gross Weight", "Volume", "Total Value"] table_data = []
for index, item in enumerate(data1['result'], start=1): row = [ index, # Serial number item['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) for index, item in enumerate(data1['result'], start=1): row = [ index, # Serial number item['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 DataFrame df = pd.DataFrame(table_data, columns=headers) # Convert to pandas DataFrame df = pd.DataFrame(table_data, columns=headers)
sdf = SmartDataframe(df, config={"llm": llm_chart}) 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) # chart = sdf.chat("Can you draw a bar chart with all avaialble item name and quantity.") chart = sdf.chat(question)
return chart return chart else: 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 = 0
def handle_query(user_question, chatbot, audio=None):
""" Function to handle the processing of user input with `AgentExecutor.invoke()`. """ global future, stop_event global current_event, stop_event
# Clear previous stop event and future # Clear previous stop event and current_event stop_event.clear() print(user_question) #if future and not future.done():
#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) print(user_question) # Start the processing in a new thread future = executor.submit(answer_question_thread, user_question, chatbot) current_event = executor.submit(answer_question_thread, user_question, chatbot) # Periodically check if future is done while not future.done(): # Periodically check if current_event is done while not current_event.done(): if stop_event.is_set(): future.cancel() 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 again
if future.cancelled(): if 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 = future.result() # Get the result of the completed future user_question1, response_text1 = current_event.result() # Get the result of the completed current_event print("output") print(user_question1) print(response_text1)9 unmodified lines """ Stops the current processing if it's running. """ global future, stop_event if future and not future.done(): global current_event, stop_event if current_event and not current_event.done(): stop_event.set() # Signal the process to stop future.cancel() # Attempt to cancel the future current_event.cancel() # Attempt to cancel the current_event chatbot.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 = audio audio_segment = AudioSegment(15 unmodified lines 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:
28 unmodified lines img_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] + img
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'9 unmodified lines subject="Warehouse Inventory Report", body=response.get("output", "").split(".")[0], # attachment_path=chart_path attachment_path=img_str) attach_img_base64=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_path attachment_path=os.getenv("IMAGE_PATH") )""" #return user_question, img
if "send email to" in user_question: try:3 unmodified lines except 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" return user_question, response_text 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_text
# without forceful stop optiondef answer_question(user_question, chatbot, audio=None): global iterations118 unmodified lines print("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 lines sample_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