Files changed (1) hide show
  1. app.py +174 -44
app.py CHANGED
@@ -1,64 +1,194 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
3
 
4
- """
5
- 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
6
- """
7
  client = InferenceClient("mistralai/Pixtral-Large-Instruct-2411")
8
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
 
 
 
29
 
30
- for message in client.chat_completion(
 
31
  messages,
32
  max_tokens=max_tokens,
33
  stream=True,
34
  temperature=temperature,
35
  top_p=top_p,
36
  ):
37
- token = message.choices[0].delta.content
38
-
39
  response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
  demo.launch()
 
 
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import base64
4
+ import io
5
+ from PIL import Image
6
+ import requests
7
 
8
+ # Inicialización del cliente de inferencia con el modelo especificado
 
 
9
  client = InferenceClient("mistralai/Pixtral-Large-Instruct-2411")
10
 
11
+ def image_to_base64(image_path):
12
+ """Convert an image file to a base64 string."""
13
+ with open(image_path, "rb") as image_file:
14
+ encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
15
+ return encoded_string
16
 
17
+ def base64_to_image(base64_string):
18
+ """Convert a base64 string to an image."""
19
+ image_data = base64.b64decode(base64_string)
20
+ image = Image.open(io.BytesIO(image_data))
21
+ return image
 
 
 
 
22
 
23
+ def describe_image(image, system_message, max_tokens, temperature, top_p):
24
+ """Describe an image using the model."""
25
+ if image is None:
26
+ return "No image uploaded.", []
 
27
 
28
+ # Convert image to base64
29
+ buffered = io.BytesIO()
30
+ image.save(buffered, format="JPEG")
31
+ image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
32
 
33
+ messages = [
34
+ {"role": "system", "content": system_message},
35
+ {"role": "user", "content": "Describe the following image:"},
36
+ {"role": "user", "content": image_base64}
37
+ ]
38
 
39
+ response = ""
40
+ for chunk in client.chat_completion(
41
  messages,
42
  max_tokens=max_tokens,
43
  stream=True,
44
  temperature=temperature,
45
  top_p=top_p,
46
  ):
47
+ token = chunk.choices[0].delta.content
 
48
  response += token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ return response, [(f"User: Describe the following image:", response)]
51
+
52
+ def respond(
53
+ user_message: str,
54
+ chat_history: list[tuple[str, str]],
55
+ system_message: str,
56
+ max_tokens: int,
57
+ temperature: float,
58
+ top_p: float,
59
+ ) -> str:
60
+ """
61
+ Función para generar respuestas basadas en el historial de chat y parámetros de configuración.
62
+
63
+ Args:
64
+ user_message (str): Mensaje del usuario.
65
+ chat_history (list[tuple[str, str]]): Historial de chat.
66
+ system_message (str): Mensaje del sistema que define el comportamiento del chatbot.
67
+ max_tokens (int): Máximo número de tokens a generar.
68
+ temperature (float): Temperatura para el muestreo de texto.
69
+ top_p (float): Parámetro top-p para el muestreo de texto.
70
+
71
+ Yields:
72
+ str: Respuesta generada por el modelo.
73
+ """
74
+ # Construcción de la lista de mensajes
75
+ messages = [{"role": "system", "content": system_message}]
76
+ for user_msg, assistant_msg in chat_history:
77
+ if user_msg:
78
+ messages.append({"role": "user", "content": user_msg})
79
+ if assistant_msg:
80
+ messages.append({"role": "assistant", "content": assistant_msg})
81
+ messages.append({"role": "user", "content": user_message})
82
+
83
+ response = ""
84
+
85
+ try:
86
+ # Obtención de la respuesta del modelo
87
+ for chunk in client.chat_completion(
88
+ messages,
89
+ max_tokens=max_tokens,
90
+ stream=True,
91
+ temperature=temperature,
92
+ top_p=top_p,
93
+ ):
94
+ token = chunk.choices[0].delta.content
95
+ response += token
96
+ yield response
97
+ except Exception as e:
98
+ yield f"Error al obtener respuesta: {str(e)}"
99
+
100
+ def main():
101
+ """
102
+ Función principal para iniciar la interfaz de chat.
103
+ """
104
+ def update_chat(user_message, image, chat_history, system_message, max_tokens, temperature, top_p):
105
+ if image is not None:
106
+ description, new_history = describe_image(image, system_message, max_tokens, temperature, top_p)
107
+ chat_history.extend(new_history)
108
+ user_message = description
109
+ if user_message:
110
+ response_generator = respond(
111
+ user_message,
112
+ chat_history,
113
+ system_message,
114
+ max_tokens,
115
+ temperature,
116
+ top_p,
117
+ )
118
+ for response in response_generator:
119
+ chat_history.append((user_message, response))
120
+ yield "", chat_history, chat_history
121
+ else:
122
+ yield "", chat_history, chat_history
123
+
124
+ with gr.Blocks(title="Chatbot con MistralAI", theme=gr.themes.Soft()) as demo:
125
+ gr.Markdown("# Chatbot con MistralAI")
126
+ gr.Markdown("Un chatbot amigable basado en el modelo MistralAI Pixtral-Large-Instruct-2411 que puede describir imágenes y mantener un historial de chat.")
127
+
128
+ with gr.Row():
129
+ with gr.Column(scale=3):
130
+ chatbot = gr.Chatbot(label="Conversación")
131
+ user_message = gr.Textbox(label="Mensaje del Usuario", placeholder="Escribe tu mensaje aquí...")
132
+ with gr.Row():
133
+ submit_button = gr.Button("Enviar")
134
+ clear_button = gr.Button("Limpiar")
135
+
136
+ with gr.Column(scale=2):
137
+ image_input = gr.Image(label="Cargar Imagen", type="pil")
138
+ image_description = gr.Textbox(label="Descripción de la Imagen", interactive=False)
139
+
140
+ with gr.Row():
141
+ system_message = gr.Textbox(
142
+ value="You are a friendly Chatbot.",
143
+ label="Mensaje del Sistema",
144
+ placeholder="Define el comportamiento del chatbot."
145
+ )
146
+ max_tokens = gr.Slider(
147
+ minimum=1,
148
+ maximum=2048,
149
+ value=512,
150
+ step=1,
151
+ label="Max New Tokens",
152
+ info="Máximo número de tokens generados."
153
+ )
154
+ temperature = gr.Slider(
155
+ minimum=0.1,
156
+ maximum=4.0,
157
+ value=0.7,
158
+ step=0.1,
159
+ label="Temperature",
160
+ info="Controla la creatividad de la respuesta."
161
+ )
162
+ top_p = gr.Slider(
163
+ minimum=0.1,
164
+ maximum=1.0,
165
+ value=0.95,
166
+ step=0.05,
167
+ label="Top-p (Nucleus Sampling)",
168
+ info="Parámetro para el muestreo del texto."
169
+ )
170
+
171
+ chat_history = gr.State([])
172
+
173
+ submit_button.click(
174
+ fn=update_chat,
175
+ inputs=[user_message, image_input, chat_history, system_message, max_tokens, temperature, top_p],
176
+ outputs=[user_message, chatbot, chat_history]
177
+ )
178
+
179
+ clear_button.click(
180
+ fn=lambda: ([], [], []),
181
+ inputs=[],
182
+ outputs=[user_message, chatbot, chat_history]
183
+ )
184
+
185
+ image_input.upload(
186
+ fn=describe_image,
187
+ inputs=[image_input, system_message, max_tokens, temperature, top_p],
188
+ outputs=[image_description, chat_history]
189
+ )
190
 
 
191
  demo.launch()
192
+
193
+ if __name__ == "__main__":
194
+ main()