Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,209 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
):
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
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 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
additional_inputs=[
|
49 |
-
gr.Textbox(
|
50 |
-
|
51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
gr.Slider(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
minimum=0.1,
|
54 |
maximum=1.0,
|
|
|
55 |
value=0.95,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
step=0.05,
|
57 |
-
|
58 |
),
|
59 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
+
import torch
|
4 |
+
import torch._dynamo
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
6 |
+
from threading import Thread
|
7 |
+
import spaces
|
8 |
|
9 |
+
# Desactivar TorchDynamo para evitar errores de compilaci贸n
|
10 |
+
torch._dynamo.config.suppress_errors = True
|
11 |
+
torch._dynamo.disable()
|
|
|
12 |
|
13 |
+
# Configuraci贸n
|
14 |
+
MODEL_ID = "somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es"
|
15 |
+
MAX_MAX_NEW_TOKENS = 4096
|
16 |
+
DEFAULT_MAX_NEW_TOKENS = 2048
|
17 |
+
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "2048"))
|
18 |
|
19 |
+
# System prompt personalizado
|
20 |
+
DEFAULT_SYSTEM_MESSAGE = """Resuelve el siguiente problema.
|
21 |
+
Primero, piensa en voz alta qu茅 debes hacer, paso por paso y de forma resumida, entre <think> y </think>.
|
22 |
+
Luego, da la respuesta final entre <SOLUTION> y </SOLUTION>.
|
23 |
+
No escribas nada fuera de ese formato."""
|
24 |
+
|
25 |
+
# Variables globales
|
26 |
+
model = None
|
27 |
+
tokenizer = None
|
28 |
+
|
29 |
+
def load_model():
|
30 |
+
"""Cargar modelo y tokenizador"""
|
31 |
+
global model, tokenizer
|
32 |
+
|
33 |
+
if torch.cuda.is_available():
|
34 |
+
print(f"Cargando modelo: {MODEL_ID}")
|
35 |
+
try:
|
36 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
37 |
+
model = AutoModelForCausalLM.from_pretrained(
|
38 |
+
MODEL_ID,
|
39 |
+
torch_dtype=torch.float32,
|
40 |
+
device_map="auto",
|
41 |
+
trust_remote_code=True,
|
42 |
+
)
|
43 |
+
|
44 |
+
if tokenizer.pad_token is None:
|
45 |
+
tokenizer.pad_token = tokenizer.eos_token
|
46 |
+
|
47 |
+
print("隆Modelo cargado exitosamente!")
|
48 |
+
return True
|
49 |
+
except Exception as e:
|
50 |
+
print(f"Error al cargar el modelo: {e}")
|
51 |
+
return False
|
52 |
+
else:
|
53 |
+
print("CUDA no disponible")
|
54 |
+
return False
|
55 |
+
|
56 |
+
# Cargar modelo al iniciar
|
57 |
+
model_loaded = load_model()
|
58 |
+
|
59 |
+
@spaces.GPU
|
60 |
+
def generate(
|
61 |
+
message: str,
|
62 |
+
history: list,
|
63 |
+
system_message: str,
|
64 |
+
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
|
65 |
+
temperature: float = 0.7,
|
66 |
+
top_p: float = 0.95,
|
67 |
+
top_k: int = 50,
|
68 |
+
repetition_penalty: float = 1.2,
|
69 |
):
|
70 |
+
"""Generar historia con streaming"""
|
71 |
+
global model, tokenizer
|
72 |
+
|
73 |
+
if model is None or tokenizer is None:
|
74 |
+
yield "Error: Modelo no disponible. Por favor, reinicia la aplicaci贸n."
|
75 |
+
return
|
76 |
+
|
77 |
+
conversation = []
|
78 |
+
|
79 |
+
if system_message:
|
80 |
+
conversation.append({"role": "system", "content": system_message})
|
81 |
+
|
82 |
+
for msg in history:
|
83 |
+
if isinstance(msg, dict) and "role" in msg and "content" in msg:
|
84 |
+
conversation.append(msg)
|
85 |
+
|
86 |
+
conversation.append({"role": "user", "content": message})
|
87 |
+
|
88 |
+
try:
|
89 |
+
input_ids = tokenizer.apply_chat_template(
|
90 |
+
conversation,
|
91 |
+
return_tensors="pt",
|
92 |
+
add_generation_prompt=True,
|
93 |
+
)
|
94 |
+
|
95 |
+
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
96 |
+
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
97 |
+
gr.Warning(f"Conversaci贸n recortada a {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
98 |
|
99 |
+
input_ids = input_ids.to(model.device)
|
100 |
+
attention_mask = torch.ones_like(input_ids, device=model.device)
|
|
|
|
|
|
|
101 |
|
102 |
+
streamer = TextIteratorStreamer(
|
103 |
+
tokenizer,
|
104 |
+
timeout=30.0,
|
105 |
+
skip_prompt=True,
|
106 |
+
skip_special_tokens=True
|
107 |
+
)
|
108 |
|
109 |
+
generate_kwargs = {
|
110 |
+
"input_ids": input_ids,
|
111 |
+
"attention_mask": attention_mask,
|
112 |
+
"streamer": streamer,
|
113 |
+
"max_new_tokens": max_new_tokens,
|
114 |
+
"do_sample": True,
|
115 |
+
"top_p": top_p,
|
116 |
+
"top_k": top_k,
|
117 |
+
"temperature": temperature,
|
118 |
+
"repetition_penalty": repetition_penalty,
|
119 |
+
"pad_token_id": tokenizer.eos_token_id,
|
120 |
+
"eos_token_id": tokenizer.eos_token_id,
|
121 |
+
}
|
122 |
|
123 |
+
generation_thread = Thread(target=model.generate, kwargs=generate_kwargs)
|
124 |
+
generation_thread.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
+
outputs = []
|
127 |
+
try:
|
128 |
+
for new_text in streamer:
|
129 |
+
outputs.append(new_text)
|
130 |
+
yield "".join(outputs)
|
131 |
+
except Exception as e:
|
132 |
+
yield f"Error durante la generaci贸n: {str(e)}"
|
133 |
+
finally:
|
134 |
+
generation_thread.join(timeout=1)
|
135 |
|
136 |
+
except Exception as e:
|
137 |
+
yield f"Error: {str(e)}"
|
138 |
|
139 |
+
# Crear interfaz de chat
|
|
|
|
|
140 |
demo = gr.ChatInterface(
|
141 |
+
fn=generate,
|
142 |
+
title="Iberotales: Mitos y Leyendas Iberoamericanas",
|
143 |
+
description="Genera historias y personajes basados en el patrimonio cultural de Iberoam茅rica usando GRPO.",
|
144 |
+
chatbot=gr.Chatbot(
|
145 |
+
height=600,
|
146 |
+
show_copy_button=True,
|
147 |
+
),
|
148 |
+
textbox=gr.Textbox(
|
149 |
+
placeholder="Escribe una historia o personaje que quieras generar...",
|
150 |
+
scale=7
|
151 |
+
),
|
152 |
additional_inputs=[
|
153 |
+
gr.Textbox(
|
154 |
+
value=DEFAULT_SYSTEM_MESSAGE,
|
155 |
+
label="Mensaje del sistema (formato estructurado requerido)"
|
156 |
+
),
|
157 |
+
gr.Slider(
|
158 |
+
label="M谩ximo de tokens",
|
159 |
+
minimum=100,
|
160 |
+
maximum=MAX_MAX_NEW_TOKENS,
|
161 |
+
step=50,
|
162 |
+
value=DEFAULT_MAX_NEW_TOKENS,
|
163 |
+
),
|
164 |
gr.Slider(
|
165 |
+
label="Temperatura",
|
166 |
+
minimum=0.1,
|
167 |
+
maximum=2.0,
|
168 |
+
step=0.1,
|
169 |
+
value=0.7,
|
170 |
+
),
|
171 |
+
gr.Slider(
|
172 |
+
label="Top-p",
|
173 |
minimum=0.1,
|
174 |
maximum=1.0,
|
175 |
+
step=0.05,
|
176 |
value=0.95,
|
177 |
+
),
|
178 |
+
gr.Slider(
|
179 |
+
label="Top-k",
|
180 |
+
minimum=1,
|
181 |
+
maximum=100,
|
182 |
+
step=1,
|
183 |
+
value=50,
|
184 |
+
),
|
185 |
+
gr.Slider(
|
186 |
+
label="Penalizaci贸n por repetici贸n",
|
187 |
+
minimum=1.0,
|
188 |
+
maximum=2.0,
|
189 |
step=0.05,
|
190 |
+
value=1.2,
|
191 |
),
|
192 |
],
|
193 |
+
examples=[
|
194 |
+
["Crea una historia corta sobre el Pombero, un personaje de la mitolog铆a guaran铆."],
|
195 |
+
["Genera un personaje basado en la leyenda del Cadejo."],
|
196 |
+
["Inventa una narrativa en torno al Nahual en un entorno contempor谩neo."],
|
197 |
+
],
|
198 |
+
cache_examples=False,
|
199 |
)
|
200 |
|
|
|
201 |
if __name__ == "__main__":
|
202 |
+
if model_loaded:
|
203 |
+
print("Lanzando aplicaci贸n Gradio...")
|
204 |
+
demo.launch(
|
205 |
+
share=False,
|
206 |
+
show_error=True
|
207 |
+
)
|
208 |
+
else:
|
209 |
+
print("Error al cargar el modelo. No se puede iniciar la aplicaci贸n.")
|