Katon1 commited on
Commit
6435f99
verified
1 Parent(s): c4bf1df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -13
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,32 @@ class ModelHandler:
19
  raise ValueError(f"Modelo {model_key} no est谩 disponible.")
20
 
21
  def generate_response(self, input_text):
22
- prompt = f"Debes de responder a cualquier pregunta:\nPregunta: {input_text}"
 
 
 
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
- return response.choices[0].message.content
 
 
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 +56,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 +70,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 generar im谩genes
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 +102,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 +114,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,
 
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
+ # Analiza la emoci贸n del texto proporcionado
42
+ client = InferenceClient("microsoft/xtremedistil-l6-h384-uncased", token=hf_token)
43
+ try:
44
+ response = client.sentiment(input_text)
45
+ return response
46
+ except Exception as e:
47
+ return f"Error al analizar la emoci贸n: {e}"
48
+
49
  # Lista de modelos disponibles (con nombres amigables para la interfaz)
50
  model_names = {
51
  "CHATBOT": "microsoft/Phi-3-mini-4k-instruct"
 
56
 
57
  # Define la funci贸n para generaci贸n de im谩genes con progreso
58
  def generate_image_with_progress(prompt):
 
 
 
59
  try:
60
  client = InferenceClient("stabilityai/stable-diffusion-2", token=hf_token)
61
 
 
70
  yield f"Error al generar la imagen: {e}", None
71
 
72
  # Configura la interfaz en Gradio con selecci贸n de modelos y generaci贸n de im谩genes
73
+ with gr.Blocks(title="Multi-Model LLM Chatbot with Image Generation and Emotion Analysis") as demo:
74
  gr.Markdown(
75
  """
76
+ ## Chatbot Multi-Modelo LLM con Generaci贸n de Im谩genes y An谩lisis de Emociones
77
+ Este chatbot permite elegir entre m煤ltiples modelos de lenguaje para responder preguntas, recordar la conversaci贸n o analizar emociones en los textos.
 
78
  """
79
  )
80
  with gr.Row():
81
  model_dropdown = gr.Dropdown(
82
+ choices=list(model_names.keys()) + ["Generaci贸n de Im谩genes", "An谩lisis de Emociones"],
83
  value="CHATBOT",
84
  label="Seleccionar Acci贸n/Modelo",
85
  interactive=True
 
102
  interactive=False
103
  )
104
  submit_button = gr.Button("Enviar")
105
+
106
  # Define la funci贸n de actualizaci贸n
107
  def process_input(selected_action, user_input):
108
  try:
109
  if selected_action == "Generaci贸n de Im谩genes":
 
110
  progress_generator = generate_image_with_progress(user_input)
111
  last_status = None
112
  last_image = None
 
114
  last_status = status
115
  last_image = image
116
  return last_status, last_image
117
+ elif selected_action == "An谩lisis de Emociones":
118
+ emotion_result = model_handler.analyze_emotion(user_input)
119
+ return f"Emoci贸n detectada: {emotion_result}", None
120
  else:
121
  model_handler.switch_model(selected_action)
122
  response = model_handler.generate_response(user_input)
123
  return response, None
124
  except Exception as e:
125
  return f"Error: {e}", None
126
+
127
  # Conecta la funci贸n a los componentes
128
  submit_button.click(
129
  fn=process_input,