Spaces:
Runtime error
Runtime error
import gradio as gr | |
import requests | |
import json | |
from typing import Dict, List, Optional | |
import os | |
from PIL import Image | |
import io | |
import base64 | |
import asyncio | |
# Configuration | |
DASHBOARD_URL = "https://huggyguyjo01-testdashbord.static.hf.space" | |
CHAT_INTERFACE_URL = "https://huggyguyjo01-testchat.static.hf.space" | |
class ChatbotBackend: | |
def __init__(self): | |
self.conversation_history: List[Dict] = [] | |
self.user_sessions: Dict = {} | |
self.dashboard_settings = self.load_dashboard_settings() | |
def load_dashboard_settings(self) -> Dict: | |
"""Load settings from dashboard""" | |
try: | |
response = requests.get(f"{DASHBOARD_URL}/api/settings") | |
return response.json() | |
except: | |
return { | |
"chatbot_name": "AI Assistant", | |
"welcome_message": "Bonjour! Comment puis-je vous aider?", | |
"behavior": "friendly and helpful", | |
"llm_style": "professional" | |
} | |
async def process_message(self, | |
message: str, | |
image: Optional[Image.Image] = None, | |
session_id: str = "default") -> str: | |
"""Process incoming messages and images""" | |
# Initialize user session if needed | |
if session_id not in self.user_sessions: | |
self.user_sessions[session_id] = { | |
"history": [], | |
"settings": self.dashboard_settings | |
} | |
# Store message in history | |
self.user_sessions[session_id]["history"].append({ | |
"role": "user", | |
"content": message, | |
"has_image": image is not None | |
}) | |
# Process image if present | |
image_data = None | |
if image: | |
# Convert image to base64 | |
buffered = io.BytesIO() | |
image.save(buffered, format="PNG") | |
image_data = base64.b64encode(buffered.getvalue()).decode() | |
# Prepare API request | |
payload = { | |
"message": message, | |
"session_id": session_id, | |
"image": image_data, | |
"history": self.user_sessions[session_id]["history"], | |
"settings": self.user_sessions[session_id]["settings"] | |
} | |
# Send to processing endpoint | |
try: | |
response = requests.post( | |
f"{DASHBOARD_URL}/api/process", | |
json=payload | |
) | |
bot_response = response.json()["response"] | |
except: | |
bot_response = "Désolé, une erreur s'est produite." | |
# Store bot response | |
self.user_sessions[session_id]["history"].append({ | |
"role": "assistant", | |
"content": bot_response | |
}) | |
return bot_response | |
def handle_error(self, error: Exception) -> str: | |
"""Handle and log errors""" | |
error_msg = f"Error: {str(error)}" | |
print(error_msg) # Log error | |
return "Je suis désolé, une erreur s'est produite. Veuillez réessayer." | |
# Initialize Gradio interface | |
chatbot = ChatbotBackend() | |
def chat_interface(message: str, | |
image: Optional[Image.Image] = None) -> str: | |
"""Gradio interface function""" | |
try: | |
response = asyncio.run( | |
chatbot.process_message(message, image) | |
) | |
return response | |
except Exception as e: | |
return chatbot.handle_error(e) | |
# Create Gradio interface | |
iface = gr.Interface( | |
fn=chat_interface, | |
inputs=[ | |
gr.Textbox(label="Message"), | |
gr.Image(label="Upload Image", type="pil") # Removed optional parameter | |
], | |
outputs=gr.Textbox(label="Response"), | |
title="AI Chatbot Backend", | |
description="Backend service connecting dashboard and chat interface" | |
) | |
# Launch the interface with a dynamic port | |
if __name__ == "__main__": | |
iface.launch( | |
server_name="0.0.0.0", | |
share=True | |
) |