Spaces:
Build error
Build error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import gradio as grfrom huggingface_hub import InferenceClient"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")def respond(message,history: list[tuple[str, str]],system_message,max_tokens,temperature,top_p,):messages = [{"role": "system", "content": system_message}]for val in history:if val[0]:messages.append({"role": "user", "content": val[0]})if val[1]:messages.append({"role": "assistant", "content": val[1]})messages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):token = message.choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""demo = gr.ChatInterface(respond,additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1,maximum=1.0,value=0.95,step=0.05,label="Top-p (nucleus sampling)",),],)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import osfrom dotenv import load_dotenvfrom langchain_community.utilities import SQLDatabaseload_dotenv()db_uri = os.getenv("DB_CONNECTION_STRING", "")db_final = SQLDatabase.from_uri(db_uri)import gradio as grfrom file_upload import FileHandlerfrom chat import ChatHandler# Initialize the FileHandler inlineVECTOR_DB_PATH = os.getenv("VECTOR_DB_PATH_DB", "")OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")GROK_API_KEY = os.getenv("GROK_API_KEY", "")# Initialize FileHandler and ChatHandlerfile_handler = FileHandler(VECTOR_DB_PATH, OPENAI_API_KEY, GROK_API_KEY)chat_handler = ChatHandler(VECTOR_DB_PATH, OPENAI_API_KEY, GROK_API_KEY, db_final)# Chat historychat_history = []# File Upload and Processing Functiondef handle_file_uploads(files):try:if not files:return "Please upload a file.", chat_historyfile_name = files.name # Retrieve the name of the uploaded fileresponse = file_handler.handle_file_upload(file_name, files)return response["message"]except Exception as e:return f"Error processing file: {e}", chat_history# Chat Functiondef handle_chat(user_message):global chat_historytry:if not user_message.strip():return [("system", "Please enter a question.")]# Add user message to chat historyif "chart" in user_message.strip():# or "graph" in user_message.strip() or "plot" in user_message.strip()):parts = user_message.split("for", 1) # Split only at the first occurrence of "with"# Assign the first part and second part to variablesvisual_query = user_message # Strip to remove leading/trailing spacesuser_message = parts[1].strip() if len(parts) > 1 else Noneelse:visual_query = None# Get AI responseai_response, visual_response = chat_handler.answer_question(user_message.strip(),visual_query)user_message = f"<b style='color:#6366f1;'>user:</b> {user_message.strip()}"if visual_response:from PIL import Imageimport base64from io import BytesIO# Open the image fileimg = Image.open(visual_response)# Convert the PIL Image to a base64 encoded stringbuffered = BytesIO()img.save(buffered, format="PNG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")img = f'<img src="data:image/png;base64,{img_str}" style="width:450px; height:400px;">'ai_response = img + ai_responseuser_message = visual_query.strip()ai_response = f"<b style='color:#6366f1;'>AI:</b> {ai_response}"# Add AI response to chat historychat_history.append((user_message,ai_response))return chat_historyexcept Exception as e:chat_history.append((visual_query, f"Sorry, I couldn't process your request.Please try again."))return chat_history# Chat handling functiondef chat_interaction(user_message):updated_history = handle_chat(user_message)return updated_history, "" # Return the chat history to the chatbotwith gr.Blocks(theme="soft") as app: # Use the 'soft' themegr.Markdown("<h1 style='color:blue;'>Agentic AI - Chat with Documents & Database</h1>",elem_id="title")with gr.Tab("Chat"):chat_box = gr.Chatbot(label="Chat History")with gr.Row(): # Place elements in the same rowwith gr.Column(scale=2):user_input = gr.Textbox(placeholder="Type your message here...",label="Your Message",elem_id="user-input", container=False)with gr.Column(scale=1):with gr.Row(): # Place the buttons in the same rowsend_button = gr.Button("Send", elem_id="send-button")clear_button = gr.Button("Clear", elem_id="clear-button")send_button.click(chat_interaction,inputs=[user_input],outputs=[chat_box, user_input])with gr.Tab("File Upload"):upload_button = gr.UploadButton(label="Upload your file (PDF, Excel, Docx, Txt, CSV)",file_types=[".pdf", ".xlsx", ".docx", ".txt", ".csv"],file_count="single")file_output = gr.Textbox(label="File Processing Output")upload_button.upload(fn=handle_file_uploads, inputs=upload_button, outputs=[file_output])# Clear input field functiondef clear_input():return "" # Clear the input fieldclear_button.click(clear_input,inputs=[],outputs=[user_input] # Clear only the user_input field)# Custom CSS for stylingapp.css = """#send-button {color: white;border-radius: 20px; /* Round corners */background-color: #6366f1;transition: background-color 0.3s, transform 0.3s;}#send-button:hover {background-color: #6366f0; /* Change background color on hover */transform: scale(1.05); /* Slightly enlarge on hover */}#clear-button {color: white;border-radius: 20px; /* Round corners */background-color: #6366f1;transition: background-color 0.3s, transform 0.3s;}#clear-button:hover {background-color: #6366f0; /* Change background color on hover */transform: scale(1.05); /* Slightly enlarge on hover */}#user-input {flex-grow: 1; /* Allow textbox to take remaining space */}#title {margin-bottom: 10px; /* Space below the title */text-align: center;}"""# Launch the appapp.launch(debug=True)
app.py+161-52