completo
Browse files
app.py
CHANGED
|
@@ -11,6 +11,7 @@ class ModelHandler:
|
|
| 11 |
def __init__(self, model_names, token):
|
| 12 |
self.clients = {model_key: InferenceClient(model_name, token=token) for model_key, model_name in model_names.items()}
|
| 13 |
self.current_model = list(model_names.keys())[0]
|
|
|
|
| 14 |
|
| 15 |
def switch_model(self, model_key):
|
| 16 |
if model_key in self.clients:
|
|
@@ -19,18 +20,47 @@ class ModelHandler:
|
|
| 19 |
raise ValueError(f"Modelo {model_key} no est谩 disponible.")
|
| 20 |
|
| 21 |
def generate_response(self, input_text):
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
messages = [{"role": "user", "content": prompt}]
|
| 25 |
client = self.clients[self.current_model]
|
| 26 |
response = client.chat_completion(messages=messages, max_tokens=500)
|
| 27 |
if hasattr(response, 'choices') and response.choices:
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
else:
|
| 30 |
return str(response)
|
| 31 |
except Exception as e:
|
| 32 |
return f"Error al realizar la inferencia: {e}"
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# Lista de modelos disponibles (con nombres amigables para la interfaz)
|
| 35 |
model_names = {
|
| 36 |
"CHATBOT": "microsoft/Phi-3-mini-4k-instruct"
|
|
@@ -41,9 +71,6 @@ model_handler = ModelHandler(model_names, hf_token)
|
|
| 41 |
|
| 42 |
# Define la funci贸n para generaci贸n de im谩genes con progreso
|
| 43 |
def generate_image_with_progress(prompt):
|
| 44 |
-
"""
|
| 45 |
-
Genera una imagen utilizando el modelo de "stabilityai/stable-diffusion-2" y muestra un progreso.
|
| 46 |
-
"""
|
| 47 |
try:
|
| 48 |
client = InferenceClient("stabilityai/stable-diffusion-2", token=hf_token)
|
| 49 |
|
|
@@ -58,17 +85,16 @@ def generate_image_with_progress(prompt):
|
|
| 58 |
yield f"Error al generar la imagen: {e}", None
|
| 59 |
|
| 60 |
# Configura la interfaz en Gradio con selecci贸n de modelos y generaci贸n de im谩genes
|
| 61 |
-
with gr.Blocks(title="Multi-Model LLM Chatbot with Image Generation") as demo:
|
| 62 |
gr.Markdown(
|
| 63 |
"""
|
| 64 |
-
## Chatbot Multi-Modelo LLM con Generaci贸n de Im谩genes
|
| 65 |
-
Este chatbot permite elegir entre m煤ltiples modelos de lenguaje para responder preguntas o
|
| 66 |
-
a partir de descripciones.
|
| 67 |
"""
|
| 68 |
)
|
| 69 |
with gr.Row():
|
| 70 |
model_dropdown = gr.Dropdown(
|
| 71 |
-
choices=list(model_names.keys()) + ["Generaci贸n de Im谩genes"],
|
| 72 |
value="CHATBOT",
|
| 73 |
label="Seleccionar Acci贸n/Modelo",
|
| 74 |
interactive=True
|
|
@@ -91,12 +117,11 @@ with gr.Blocks(title="Multi-Model LLM Chatbot with Image Generation") as demo:
|
|
| 91 |
interactive=False
|
| 92 |
)
|
| 93 |
submit_button = gr.Button("Enviar")
|
| 94 |
-
|
| 95 |
# Define la funci贸n de actualizaci贸n
|
| 96 |
def process_input(selected_action, user_input):
|
| 97 |
try:
|
| 98 |
if selected_action == "Generaci贸n de Im谩genes":
|
| 99 |
-
# Manejamos el generador de progreso
|
| 100 |
progress_generator = generate_image_with_progress(user_input)
|
| 101 |
last_status = None
|
| 102 |
last_image = None
|
|
@@ -104,13 +129,16 @@ with gr.Blocks(title="Multi-Model LLM Chatbot with Image Generation") as demo:
|
|
| 104 |
last_status = status
|
| 105 |
last_image = image
|
| 106 |
return last_status, last_image
|
|
|
|
|
|
|
|
|
|
| 107 |
else:
|
| 108 |
model_handler.switch_model(selected_action)
|
| 109 |
response = model_handler.generate_response(user_input)
|
| 110 |
return response, None
|
| 111 |
except Exception as e:
|
| 112 |
return f"Error: {e}", None
|
| 113 |
-
|
| 114 |
# Conecta la funci贸n a los componentes
|
| 115 |
submit_button.click(
|
| 116 |
fn=process_input,
|
|
@@ -119,4 +147,4 @@ with gr.Blocks(title="Multi-Model LLM Chatbot with Image Generation") as demo:
|
|
| 119 |
)
|
| 120 |
|
| 121 |
# Lanza la interfaz
|
| 122 |
-
demo.launch()
|
|
|
|
| 11 |
def __init__(self, model_names, token):
|
| 12 |
self.clients = {model_key: InferenceClient(model_name, token=token) for model_key, model_name in model_names.items()}
|
| 13 |
self.current_model = list(model_names.keys())[0]
|
| 14 |
+
self.conversation_history = [] # Memoria de conversaci贸n
|
| 15 |
|
| 16 |
def switch_model(self, model_key):
|
| 17 |
if model_key in self.clients:
|
|
|
|
| 20 |
raise ValueError(f"Modelo {model_key} no est谩 disponible.")
|
| 21 |
|
| 22 |
def generate_response(self, input_text):
|
| 23 |
+
# Agrega el historial de la conversaci贸n al prompt
|
| 24 |
+
self.conversation_history.append({"role": "user", "content": input_text})
|
| 25 |
+
prompt = f"Historial de conversaci贸n: {self.conversation_history}\nPregunta: {input_text}"
|
| 26 |
+
|
| 27 |
try:
|
| 28 |
messages = [{"role": "user", "content": prompt}]
|
| 29 |
client = self.clients[self.current_model]
|
| 30 |
response = client.chat_completion(messages=messages, max_tokens=500)
|
| 31 |
if hasattr(response, 'choices') and response.choices:
|
| 32 |
+
generated_text = response.choices[0].message.content
|
| 33 |
+
self.conversation_history.append({"role": "assistant", "content": generated_text})
|
| 34 |
+
return generated_text
|
| 35 |
else:
|
| 36 |
return str(response)
|
| 37 |
except Exception as e:
|
| 38 |
return f"Error al realizar la inferencia: {e}"
|
| 39 |
|
| 40 |
+
def analyze_emotion(self, input_text):
|
| 41 |
+
# Diccionario para traducir emociones al espa帽ol
|
| 42 |
+
emotion_translation = {
|
| 43 |
+
"joy": "Alegr铆a",
|
| 44 |
+
"anger": "Enojo",
|
| 45 |
+
"fear": "Miedo",
|
| 46 |
+
"sadness": "Tristeza",
|
| 47 |
+
"love": "Amor",
|
| 48 |
+
"surprise": "Sorpresa"
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
client = InferenceClient("bhadresh-savani/distilbert-base-uncased-emotion", token=hf_token)
|
| 53 |
+
response = client.text_classification(input_text)
|
| 54 |
+
|
| 55 |
+
# Traducir las emociones y formatear la respuesta
|
| 56 |
+
emotions = [
|
| 57 |
+
f"{emotion_translation[label['label']]}: {label['score']:.2%}"
|
| 58 |
+
for label in response
|
| 59 |
+
]
|
| 60 |
+
return "\n".join(emotions)
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return f"Error al analizar la emoci贸n: {e}"
|
| 63 |
+
|
| 64 |
# Lista de modelos disponibles (con nombres amigables para la interfaz)
|
| 65 |
model_names = {
|
| 66 |
"CHATBOT": "microsoft/Phi-3-mini-4k-instruct"
|
|
|
|
| 71 |
|
| 72 |
# Define la funci贸n para generaci贸n de im谩genes con progreso
|
| 73 |
def generate_image_with_progress(prompt):
|
|
|
|
|
|
|
|
|
|
| 74 |
try:
|
| 75 |
client = InferenceClient("stabilityai/stable-diffusion-2", token=hf_token)
|
| 76 |
|
|
|
|
| 85 |
yield f"Error al generar la imagen: {e}", None
|
| 86 |
|
| 87 |
# Configura la interfaz en Gradio con selecci贸n de modelos y generaci贸n de im谩genes
|
| 88 |
+
with gr.Blocks(title="Multi-Model LLM Chatbot with Image Generation and Emotion Analysis") as demo:
|
| 89 |
gr.Markdown(
|
| 90 |
"""
|
| 91 |
+
## Chatbot Multi-Modelo LLM con Generaci贸n de Im谩genes y An谩lisis de Emociones
|
| 92 |
+
Este chatbot permite elegir entre m煤ltiples modelos de lenguaje para responder preguntas, recordar la conversaci贸n o analizar emociones en los textos.
|
|
|
|
| 93 |
"""
|
| 94 |
)
|
| 95 |
with gr.Row():
|
| 96 |
model_dropdown = gr.Dropdown(
|
| 97 |
+
choices=list(model_names.keys()) + ["Generaci贸n de Im谩genes", "An谩lisis de Emociones"],
|
| 98 |
value="CHATBOT",
|
| 99 |
label="Seleccionar Acci贸n/Modelo",
|
| 100 |
interactive=True
|
|
|
|
| 117 |
interactive=False
|
| 118 |
)
|
| 119 |
submit_button = gr.Button("Enviar")
|
| 120 |
+
|
| 121 |
# Define la funci贸n de actualizaci贸n
|
| 122 |
def process_input(selected_action, user_input):
|
| 123 |
try:
|
| 124 |
if selected_action == "Generaci贸n de Im谩genes":
|
|
|
|
| 125 |
progress_generator = generate_image_with_progress(user_input)
|
| 126 |
last_status = None
|
| 127 |
last_image = None
|
|
|
|
| 129 |
last_status = status
|
| 130 |
last_image = image
|
| 131 |
return last_status, last_image
|
| 132 |
+
elif selected_action == "An谩lisis de Emociones":
|
| 133 |
+
emotion_result = model_handler.analyze_emotion(user_input)
|
| 134 |
+
return f"Emoci贸n detectada:\n{emotion_result}", None
|
| 135 |
else:
|
| 136 |
model_handler.switch_model(selected_action)
|
| 137 |
response = model_handler.generate_response(user_input)
|
| 138 |
return response, None
|
| 139 |
except Exception as e:
|
| 140 |
return f"Error: {e}", None
|
| 141 |
+
|
| 142 |
# Conecta la funci贸n a los componentes
|
| 143 |
submit_button.click(
|
| 144 |
fn=process_input,
|
|
|
|
| 147 |
)
|
| 148 |
|
| 149 |
# Lanza la interfaz
|
| 150 |
+
demo.launch()
|