Update app.py
Browse files
app.py
CHANGED
@@ -4,14 +4,12 @@ from gradio import ChatMessage
|
|
4 |
import torch
|
5 |
import torch._dynamo
|
6 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
-
from threading import Thread
|
8 |
from huggingface_hub import hf_hub_download
|
9 |
import re
|
10 |
from llama_cpp import Llama
|
11 |
from typing import Iterator
|
12 |
import spaces
|
13 |
|
14 |
-
|
15 |
# Desactivar TorchDynamo para evitar errores de compilación
|
16 |
torch._dynamo.config.suppress_errors = True
|
17 |
torch._dynamo.disable()
|
@@ -22,8 +20,7 @@ GGUF_MODEL_ID = "somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es-finetune-gg
|
|
22 |
GGUF_FILENAME = "gemma-3-finetune.Q8_0.gguf"
|
23 |
GGUF_REVISION = "main"
|
24 |
MAX_MAX_NEW_TOKENS = 2048
|
25 |
-
DEFAULT_MAX_NEW_TOKENS =
|
26 |
-
|
27 |
|
28 |
# System prompt personalizado
|
29 |
DEFAULT_SYSTEM_MESSAGE = """Resuelve el siguiente problema.
|
@@ -35,294 +32,178 @@ No escribas nada fuera de ese formato."""
|
|
35 |
PERSONAJES_POR_PAIS = {
|
36 |
"🇦🇷 Argentina": [
|
37 |
{"nombre": "La Difunta Correa", "imagen": "images/ar1.jpg", "descripcion": "Santa popular que murió de sed siguiendo a su esposo reclutado"},
|
38 |
-
{"nombre": "El Lobizón", "imagen": "images/ar2.jpg", "descripcion": "Hombre lobo de la tradición gaucha, séptimo hijo varón maldito"}
|
39 |
-
{"nombre": "La Telesita", "imagen": "images/ar3.webp", "descripcion": "Bailarina folklórica que se aparece en festivales y zambas"}
|
40 |
],
|
41 |
"🇧🇴 Bolivia": [
|
42 |
{"nombre": "El Tío del Cerro Rico", "imagen": "images/bo1.webp", "descripcion": "Señor de las minas que protege y castiga a los mineros"},
|
43 |
-
{"nombre": "El Ekeko", "imagen": "images/bo2.jpg", "descripcion": "Dios aymara de la abundancia y la fortuna con jorobas"}
|
44 |
-
{"nombre": "El Jichi", "imagen": "images/bo3.webp", "descripcion": "Serpiente protectora de ríos y lagunas en la cultura andina"}
|
45 |
-
],
|
46 |
-
"🇧🇷 Brasil": [
|
47 |
-
{"nombre": "Curupira", "imagen": "images/br1.jpeg", "descripcion": "Protector del bosque amazónico con pies al revés"},
|
48 |
-
{"nombre": "Saci-Pererê", "imagen": "images/br2.jpg", "descripcion": "Duende travieso de una pierna que fuma pipa"},
|
49 |
-
{"nombre": "Yebá Bëló", "imagen": "images/br3.jpg", "descripcion": "Abuela del mundo en mitología desana, creadora del universo"}
|
50 |
-
],
|
51 |
-
"🇨🇱 Chile": [
|
52 |
-
{"nombre": "Guallipén", "imagen": "images/ch1.webp", "descripcion": "Carnero gigante que habita en los ríos de Chiloé"},
|
53 |
-
{"nombre": "Colo Colo", "imagen": "images/ch2.webp", "descripcion": "Ser maléfico nacido de huevo de gallo empollado por serpiente"},
|
54 |
-
{"nombre": "Cuchivilu", "imagen": "images/ch3.webp", "descripcion": "Cerdo marino con cola de pez que habita en Chiloé"}
|
55 |
-
],
|
56 |
-
"🇨🇴 Colombia": [
|
57 |
-
{"nombre": "El Guaca", "imagen": "images/co1.jpg", "descripcion": "Espíritu guardián de tesoros enterrados por indígenas"},
|
58 |
-
{"nombre": "Chiminigagua", "imagen": "images/co2.webp", "descripcion": "Dios creador muisca, fuente de luz y vida universal"},
|
59 |
-
{"nombre": "Jukumari", "imagen": "images/co3.jpg", "descripcion": "Oso gigante mitológico de los Andes colombianos"}
|
60 |
-
],
|
61 |
-
"🇨🇷 Costa Rica": [
|
62 |
-
{"nombre": "El Micomalo", "imagen": "images/cr1.jpg", "descripcion": "Mono gigante y feroz que ataca a los cazadores"},
|
63 |
-
{"nombre": "La Carreta sin Bueyes", "imagen": "images/crr2.jpg", "descripcion": "Carreta fantasma que recorre caminos sin animales tirando"},
|
64 |
-
{"nombre": "El Sisimiqui", "imagen": "images/cr3.webp", "descripcion": "Duende pequeño y travieso de los bosques costarricenses"}
|
65 |
-
],
|
66 |
-
"🇨🇺 Cuba": [
|
67 |
-
{"nombre": "El Güije", "imagen": "images/cu1.jpg", "descripcion": "Duende negro de aguas dulces que ahoga a los bañistas"},
|
68 |
-
{"nombre": "Itiba Cahubaba", "imagen": "images/cu2.jpg", "descripcion": "Madre primordial taína de donde brotaron las aguas"},
|
69 |
-
{"nombre": "Guabancex", "imagen": "images/cu3.jpg", "descripcion": "Diosa taína de los huracanes y vientos destructores"}
|
70 |
-
],
|
71 |
-
"🇪🇨 Ecuador": [
|
72 |
-
{"nombre": "Salun", "imagen": "images/ec1.jpg", "descripcion": "Espíritu shamán shuar que guía en visiones espirituales"},
|
73 |
-
{"nombre": "Nunkui", "imagen": "images/ec2.jpg", "descripcion": "Diosa shuar de la fertilidad de la tierra y agricultura"},
|
74 |
-
{"nombre": "Yacuruna", "imagen": "images/ec3.jpg", "descripcion": "Hombre serpiente amazónico señor de las aguas dulces"}
|
75 |
-
],
|
76 |
-
"🇪🇸 España": [
|
77 |
-
{"nombre": "Ojáncanu", "imagen": "images/es1.jpg", "descripcion": "Gigante cíclope cántabro de fuerza descomunal"},
|
78 |
-
{"nombre": "Los Carantos", "imagen": "images/es2.jpg", "descripcion": "Espíritus gallegos que anuncian desgracias familiares"},
|
79 |
-
{"nombre": "Cuegle", "imagen": "images/es3.jpg", "descripcion": "Ser asturiano de tres ojos que protege casas del mal"}
|
80 |
-
],
|
81 |
-
"🇬🇹 Guatemala": [
|
82 |
-
{"nombre": "Camalotz", "imagen": "images/gu1.jpg", "descripcion": "Dios murciélago maya señor de las cuevas y la muerte"},
|
83 |
-
{"nombre": "La Siguanaba", "imagen": "images/gu2.jpg", "descripcion": "Mujer hermosa que muestra rostro de calavera a infieles"},
|
84 |
-
{"nombre": "Gucumatz", "imagen": "images/gu3.jpg", "descripcion": "Serpiente emplumada maya, equivalente a Quetzalcóatl"}
|
85 |
-
],
|
86 |
-
"🇭🇳 Honduras": [
|
87 |
-
{"nombre": "Icelaca", "imagen": "images/ho1.jpg", "descripcion": "Serpiente gigante que habita en cuevas hondureñas"},
|
88 |
-
{"nombre": "Cihuateteo", "imagen": "images/ho2.jpg", "descripcion": "Espíritus de mujeres muertas en parto, guerreras divinas"},
|
89 |
-
{"nombre": "Comelenguas", "imagen": "images/ho3.webp", "descripcion": "Demonio que devora lenguas de personas dormidas"}
|
90 |
-
],
|
91 |
-
"🇲🇽 México": [
|
92 |
-
{"nombre": "Quetzalcóatl", "imagen": "images/me1.jpg", "descripcion": "Serpiente emplumada, dios del viento y la sabiduría"},
|
93 |
-
{"nombre": "Tlacatecolotl", "imagen": "images/me2.jpg", "descripcion": "Brujo nahuatl que se transforma en búho gigante"},
|
94 |
-
{"nombre": "Tlalocan", "imagen": "images/me3.jpg", "descripcion": "Paraíso acuático de Tláloc donde van los ahogados"}
|
95 |
-
],
|
96 |
-
"🇳🇮 Nicaragua": [
|
97 |
-
{"nombre": "La Mocuana", "imagen": "images/ni1.webp", "descripcion": "Espíritu de mujer sin cabeza que vaga de noche"},
|
98 |
-
{"nombre": "El Guácimo Renco", "imagen": "images/ni2.jpg", "descripcion": "Árbol maldito que se transforma y persigue viajeros"},
|
99 |
-
{"nombre": "La Mona Bruja", "imagen": "images/ni3.jpg", "descripcion": "Bruja transformada en mona que roba niños pequeños"}
|
100 |
-
],
|
101 |
-
"🇵🇦 Panamá": [
|
102 |
-
{"nombre": "Humantahú", "imagen": "images/pa1.jpg", "descripcion": "Chamán kuna protector de la naturaleza y animales"},
|
103 |
-
{"nombre": "La Silampa", "imagen": "images/pa2.jpg", "descripcion": "Mujer fantasma que seduce y mata a hombres solitarios"},
|
104 |
-
{"nombre": "El Chivato", "imagen": "images/pa3.jpg", "descripcion": "Cabro diabólico que aparece en encrucijadas nocturnas"}
|
105 |
],
|
106 |
"🇵🇾 Paraguay": [
|
107 |
-
{"nombre": "
|
108 |
-
{"nombre": "
|
109 |
-
{"nombre": "Tajy", "imagen": "images/py3.jpg", "descripcion": "Espíritu del lapacho florido en la mitología guaraní"}
|
110 |
-
],
|
111 |
-
"🇵🇪 Perú": [
|
112 |
-
{"nombre": "Wiracocha", "imagen": "images/pe1.jpg", "descripcion": "Dios creador inca señor de todas las cosas vivientes"},
|
113 |
-
{"nombre": "El Muki", "imagen": "images/pe2.webp", "descripcion": "Duende minero que protege vetas de oro y plata"},
|
114 |
-
{"nombre": "Los Hermanos Ayar", "imagen": "images/pe3.jpg", "descripcion": "Cuatro hermanos fundadores míticos del imperio inca"}
|
115 |
-
],
|
116 |
-
"🇵🇹 Portugal": [
|
117 |
-
{"nombre": "El Marialva", "imagen": "images/po1.jpg", "descripcion": "Caballero galante y seductor de la tradición portuguesa"},
|
118 |
-
{"nombre": "El Pez Milagroso", "imagen": "images/po2.webp", "descripcion": "Pez mágico que concede deseos a pescadores devotos"},
|
119 |
-
{"nombre": "La Cueva da Moeda", "imagen": "images/po3.webp", "descripcion": "Cueva encantada llena de tesoros moros perdidos"}
|
120 |
-
],
|
121 |
-
"🇵🇷 Puerto Rico": [
|
122 |
-
{"nombre": "Yúcahu", "imagen": "images/pr1.jpg", "descripcion": "Dios taíno de la yuca y protector de cosechas"},
|
123 |
-
{"nombre": "Atabey", "imagen": "images/pr2.jpg", "descripcion": "Diosa madre taína de las aguas dulces y fertilidad"},
|
124 |
-
{"nombre": "Anacacuya", "imagen": "images/pr3.png", "descripcion": "Estrella taína guía de navegantes y pescadores"}
|
125 |
-
],
|
126 |
-
"🇩🇴 República Dominicana": [
|
127 |
-
{"nombre": "El Galipote", "imagen": "images/rd1.webp", "descripcion": "Brujo que se transforma en animal para hacer maldades"},
|
128 |
-
{"nombre": "El Lugaru", "imagen": "images/rd2.webp", "descripcion": "Hombre lobo dominicano que ataca ganado y personas"},
|
129 |
-
{"nombre": "Papa Legba", "imagen": "images/rd3.jpg", "descripcion": "Loa vudú guardián de encrucijadas y comunicaciones"}
|
130 |
-
],
|
131 |
-
"🇺🇾 Uruguay": [
|
132 |
-
{"nombre": "El Yasy Yateré", "imagen": "images/ur1.jpg", "descripcion": "Duende rubio protector de niños con bastón mágico"},
|
133 |
-
{"nombre": "El Ñandú Barriga Blanca", "imagen": "images/ur2.jpg", "descripcion": "Ñandú gigante y sagrado de las pampas uruguayas"},
|
134 |
-
{"nombre": "El Pombero", "imagen": "images/ur3.jpg", "descripcion": "Duende travieso protector de aves y la naturaleza"}
|
135 |
-
],
|
136 |
-
"🇻🇪 Venezuela": [
|
137 |
-
{"nombre": "Amalivaca", "imagen": "images/ve1.jpg", "descripcion": "Héroe cultural tamanaco creador del río Orinoco"},
|
138 |
-
{"nombre": "Osemma", "imagen": "images/ve2.jpg", "descripcion": "Espíritu warao de las palmeras de moriche"},
|
139 |
-
{"nombre": "La Sayona", "imagen": "images/ve3.webp", "descripcion": "Mujer vengativa que persigue y castiga a infieles"}
|
140 |
]
|
141 |
-
}
|
142 |
|
143 |
# Variables globales
|
144 |
model = None
|
145 |
tokenizer = None
|
146 |
-
current_personajes = []
|
147 |
|
148 |
-
|
149 |
-
|
150 |
-
|
|
|
|
|
|
|
|
|
151 |
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
MODEL_ID,
|
157 |
-
torch_dtype=torch.float32,
|
158 |
-
device_map="auto",
|
159 |
-
trust_remote_code=True,
|
160 |
-
)
|
161 |
-
if tokenizer.pad_token is None:
|
162 |
-
tokenizer.pad_token = tokenizer.eos_token
|
163 |
-
return True
|
164 |
-
except Exception as e:
|
165 |
-
print(f"Error GPU: {e}")
|
166 |
-
return False
|
167 |
-
else:
|
168 |
-
try:
|
169 |
-
local_model_path = os.path.join("models", GGUF_FILENAME)
|
170 |
-
if os.path.exists(local_model_path):
|
171 |
-
model_path = local_model_path
|
172 |
-
else:
|
173 |
-
model_path = hf_hub_download(
|
174 |
-
repo_id=GGUF_MODEL_ID,
|
175 |
-
filename=GGUF_FILENAME,
|
176 |
-
revision=GGUF_REVISION,
|
177 |
-
local_dir="./models",
|
178 |
-
force_download=False,
|
179 |
-
resume_download=True
|
180 |
-
)
|
181 |
-
tokenizer = AutoTokenizer.from_pretrained("google/gemma-3-1b-it")
|
182 |
-
model = Llama(
|
183 |
-
model_path=model_path,
|
184 |
-
n_ctx=2048,
|
185 |
-
n_threads=4,
|
186 |
-
n_gpu_layers=0
|
187 |
-
)
|
188 |
-
return True
|
189 |
-
except Exception as e:
|
190 |
-
print(f"Error GGUF: {e}")
|
191 |
-
return False
|
192 |
|
193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
user_message: str,
|
197 |
system_message: str = DEFAULT_SYSTEM_MESSAGE,
|
198 |
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
|
199 |
temperature: float = 0.7,
|
200 |
top_p: float = 0.95,
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
yield [ChatMessage(role="assistant", content="Error: Modelo no disponible.")]
|
209 |
-
return
|
210 |
-
|
211 |
try:
|
212 |
-
# Crear
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
|
|
|
|
|
|
241 |
messages = []
|
242 |
-
thinking_message_index = None
|
243 |
-
solution_message_index = None
|
244 |
-
in_think_block = False
|
245 |
-
in_solution_block = False
|
246 |
-
thinking_complete = False
|
247 |
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
in_think_block = False
|
271 |
-
else:
|
272 |
-
current_thinking = full_response[think_start:].strip()
|
273 |
-
|
274 |
-
if thinking_message_index is not None:
|
275 |
-
messages[thinking_message_index] = ChatMessage(
|
276 |
-
role="assistant",
|
277 |
-
content=current_thinking,
|
278 |
-
metadata={"title": "🤔 Pensando..."}
|
279 |
-
)
|
280 |
-
yield messages
|
281 |
-
|
282 |
-
# Procesar solución
|
283 |
-
if "<SOLUTION>" in full_response:
|
284 |
-
if not in_solution_block:
|
285 |
-
in_solution_block = True
|
286 |
-
if solution_message_index is None:
|
287 |
-
messages.append(ChatMessage(role="assistant", content=""))
|
288 |
-
solution_message_index = len(messages) - 1
|
289 |
-
|
290 |
-
solution_start = full_response.find("<SOLUTION>") + 10
|
291 |
-
if "</SOLUTION>" in full_response:
|
292 |
-
solution_end = full_response.find("</SOLUTION>")
|
293 |
-
current_solution = full_response[solution_start:solution_end].strip()
|
294 |
-
in_solution_block = False
|
295 |
-
else:
|
296 |
-
current_solution = full_response[solution_start:].strip()
|
297 |
-
|
298 |
-
if solution_message_index is not None and current_solution:
|
299 |
-
messages[solution_message_index] = ChatMessage(
|
300 |
-
role="assistant",
|
301 |
-
content=current_solution
|
302 |
-
)
|
303 |
-
yield messages
|
304 |
|
305 |
-
# Respuesta sin formato
|
306 |
-
if full_response.strip() and solution_message_index is None:
|
307 |
-
clean_response = full_response
|
308 |
-
if "<think>" in clean_response and "</think>" in clean_response:
|
309 |
-
clean_response = re.sub(r'<think>.*?</think>', '', clean_response, flags=re.DOTALL)
|
310 |
-
if "<SOLUTION>" in clean_response and "</SOLUTION>" in clean_response:
|
311 |
-
clean_response = re.sub(r'<SOLUTION>(.*?)</SOLUTION>', r'\1', clean_response, flags=re.DOTALL)
|
312 |
-
|
313 |
-
clean_response = clean_response.strip()
|
314 |
-
if clean_response:
|
315 |
-
messages.append(ChatMessage(role="assistant", content=clean_response))
|
316 |
-
yield messages
|
317 |
-
|
318 |
except Exception as e:
|
319 |
-
|
320 |
|
321 |
def actualizar_personajes(pais_seleccionado):
|
322 |
"""Actualiza la galería de personajes según el país seleccionado"""
|
323 |
global current_personajes
|
324 |
personajes = PERSONAJES_POR_PAIS.get(pais_seleccionado, [])
|
325 |
-
current_personajes = personajes
|
326 |
|
327 |
if not personajes:
|
328 |
return [], "Selecciona un país para ver sus personajes"
|
@@ -352,59 +233,38 @@ def crear_prompt_desde_personaje(evt: gr.SelectData):
|
|
352 |
print(f"Error al crear prompt: {e}")
|
353 |
return "Crea una historia sobre un personaje mítico"
|
354 |
|
355 |
-
|
356 |
-
|
357 |
-
.
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
#
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
}
|
372 |
-
|
373 |
-
#galeria .thumbnail-item {
|
374 |
-
aspect-ratio: 1;
|
375 |
-
max-height: 100px;
|
376 |
-
}
|
377 |
-
|
378 |
-
#galeria .thumbnail-item img {
|
379 |
-
object-fit: cover;
|
380 |
-
width: 100%;
|
381 |
-
height: 100%;
|
382 |
-
border-radius: 8px;
|
383 |
-
}
|
384 |
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
padding: 1rem;
|
389 |
-
border-radius: 12px;
|
390 |
-
margin-bottom: 1rem;
|
391 |
-
text-align: center;
|
392 |
-
}
|
393 |
-
"""
|
394 |
|
395 |
-
# Crear la interfaz
|
396 |
with gr.Blocks(title="Iberotales", css=custom_css) as demo:
|
397 |
# Header con información del proyecto
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
</div>
|
407 |
-
""")
|
408 |
|
409 |
with gr.Row():
|
410 |
# Panel izquierdo - Pokédex de personajes
|
@@ -434,7 +294,8 @@ with gr.Blocks(title="Iberotales", css=custom_css) as demo:
|
|
434 |
type="messages",
|
435 |
show_label=False,
|
436 |
height=400,
|
437 |
-
avatar_images=(None, "🏛️")
|
|
|
438 |
)
|
439 |
|
440 |
with gr.Row():
|
@@ -455,19 +316,6 @@ with gr.Blocks(title="Iberotales", css=custom_css) as demo:
|
|
455 |
temperature = gr.Slider(0.1, 2.0, 0.7, label="Temp", container=False)
|
456 |
|
457 |
# Eventos
|
458 |
-
def generate_and_display(msg, max_tok, temp):
|
459 |
-
"""Genera respuesta y la muestra en el chatbot"""
|
460 |
-
if not msg.strip():
|
461 |
-
return []
|
462 |
-
|
463 |
-
# Agregar mensaje del usuario
|
464 |
-
messages = [ChatMessage(role="user", content=msg)]
|
465 |
-
yield messages
|
466 |
-
|
467 |
-
# Generar respuesta
|
468 |
-
for response_messages in stream_iberotales_response(msg, DEFAULT_SYSTEM_MESSAGE, max_tok, temp):
|
469 |
-
yield [ChatMessage(role="user", content=msg)] + response_messages
|
470 |
-
|
471 |
# Actualizar personajes cuando cambia el país
|
472 |
pais_dropdown.change(
|
473 |
fn=actualizar_personajes,
|
@@ -490,25 +338,19 @@ with gr.Blocks(title="Iberotales", css=custom_css) as demo:
|
|
490 |
|
491 |
# Envío de mensajes
|
492 |
input_box.submit(
|
493 |
-
|
494 |
-
inputs=[input_box, max_tokens, temperature],
|
495 |
-
outputs=chatbot
|
496 |
-
).then(
|
497 |
-
lambda: "",
|
498 |
-
outputs=input_box
|
499 |
)
|
500 |
|
501 |
send_button.click(
|
502 |
-
|
503 |
-
inputs=[input_box, max_tokens, temperature],
|
504 |
-
outputs=chatbot
|
505 |
-
).then(
|
506 |
-
lambda: "",
|
507 |
-
outputs=input_box
|
508 |
)
|
509 |
|
510 |
clear_button.click(
|
511 |
-
lambda: ([], ""),
|
512 |
outputs=[chatbot, input_box],
|
513 |
queue=False
|
514 |
)
|
@@ -516,6 +358,7 @@ with gr.Blocks(title="Iberotales", css=custom_css) as demo:
|
|
516 |
# Lanzar aplicación
|
517 |
if __name__ == "__main__":
|
518 |
if model_loaded:
|
|
|
519 |
demo.launch(share=False, show_error=True)
|
520 |
else:
|
521 |
-
print("Error
|
|
|
4 |
import torch
|
5 |
import torch._dynamo
|
6 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
7 |
from huggingface_hub import hf_hub_download
|
8 |
import re
|
9 |
from llama_cpp import Llama
|
10 |
from typing import Iterator
|
11 |
import spaces
|
12 |
|
|
|
13 |
# Desactivar TorchDynamo para evitar errores de compilación
|
14 |
torch._dynamo.config.suppress_errors = True
|
15 |
torch._dynamo.disable()
|
|
|
20 |
GGUF_FILENAME = "gemma-3-finetune.Q8_0.gguf"
|
21 |
GGUF_REVISION = "main"
|
22 |
MAX_MAX_NEW_TOKENS = 2048
|
23 |
+
DEFAULT_MAX_NEW_TOKENS = 1024
|
|
|
24 |
|
25 |
# System prompt personalizado
|
26 |
DEFAULT_SYSTEM_MESSAGE = """Resuelve el siguiente problema.
|
|
|
32 |
PERSONAJES_POR_PAIS = {
|
33 |
"🇦🇷 Argentina": [
|
34 |
{"nombre": "La Difunta Correa", "imagen": "images/ar1.jpg", "descripcion": "Santa popular que murió de sed siguiendo a su esposo reclutado"},
|
35 |
+
{"nombre": "El Lobizón", "imagen": "images/ar2.jpg", "descripcion": "Hombre lobo de la tradición gaucha, séptimo hijo varón maldito"}
|
|
|
36 |
],
|
37 |
"🇧🇴 Bolivia": [
|
38 |
{"nombre": "El Tío del Cerro Rico", "imagen": "images/bo1.webp", "descripcion": "Señor de las minas que protege y castiga a los mineros"},
|
39 |
+
{"nombre": "El Ekeko", "imagen": "images/bo2.jpg", "descripcion": "Dios aymara de la abundancia y la fortuna con jorobas"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
],
|
41 |
"🇵🇾 Paraguay": [
|
42 |
+
{"nombre": "Kurupi", "imagen": "images/py1.jpg", "descripcion": "Dios guaraní de la fertilidad con poderes sobrenaturales"},
|
43 |
+
{"nombre": "Pombero", "imagen": "images/py2.jpg", "descripcion": "Duende protector de los animales y la naturaleza"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
]
|
45 |
+
}
|
46 |
|
47 |
# Variables globales
|
48 |
model = None
|
49 |
tokenizer = None
|
50 |
+
current_personajes = []
|
51 |
|
52 |
+
# CSS personalizado
|
53 |
+
custom_css = """
|
54 |
+
.gradio-container {
|
55 |
+
max-width: 1400px !important;
|
56 |
+
margin: auto;
|
57 |
+
padding-top: 1.5rem;
|
58 |
+
}
|
59 |
|
60 |
+
#galeria .grid-wrap {
|
61 |
+
max-height: 350px;
|
62 |
+
overflow-y: auto;
|
63 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
+
#galeria .grid-container {
|
66 |
+
grid-template-columns: repeat(1, 1fr) !important;
|
67 |
+
gap: 0.5rem;
|
68 |
+
}
|
69 |
+
|
70 |
+
#galeria .thumbnail-item {
|
71 |
+
aspect-ratio: 1;
|
72 |
+
max-height: 100px;
|
73 |
+
}
|
74 |
+
|
75 |
+
#galeria .thumbnail-item img {
|
76 |
+
object-fit: cover;
|
77 |
+
width: 100%;
|
78 |
+
height: 100%;
|
79 |
+
border-radius: 8px;
|
80 |
+
}
|
81 |
+
|
82 |
+
.header-info {
|
83 |
+
background: linear-gradient(135deg, #2c3e50 0%, #1a1a2e 100%);
|
84 |
+
color: white;
|
85 |
+
padding: 1rem;
|
86 |
+
border-radius: 12px;
|
87 |
+
margin-bottom: 1rem;
|
88 |
+
text-align: center;
|
89 |
+
}
|
90 |
+
"""
|
91 |
|
92 |
+
def load_model():
|
93 |
+
"""Cargar modelo GGUF"""
|
94 |
+
global model, tokenizer
|
95 |
+
|
96 |
+
try:
|
97 |
+
# Descargar modelo GGUF
|
98 |
+
print("Descargando modelo GGUF...")
|
99 |
+
model_path = hf_hub_download(
|
100 |
+
repo_id=GGUF_MODEL_ID,
|
101 |
+
filename=GGUF_FILENAME,
|
102 |
+
revision=GGUF_REVISION,
|
103 |
+
local_dir="./models",
|
104 |
+
)
|
105 |
+
|
106 |
+
print(f"Modelo descargado en: {model_path}")
|
107 |
+
|
108 |
+
# Cargar modelo GGUF
|
109 |
+
model = Llama(
|
110 |
+
model_path=model_path,
|
111 |
+
n_ctx=2048,
|
112 |
+
n_batch=512,
|
113 |
+
n_threads=4,
|
114 |
+
n_gpu_layers=0,
|
115 |
+
chat_format="gemma"
|
116 |
+
)
|
117 |
+
|
118 |
+
# Cargar tokenizer
|
119 |
+
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
|
120 |
+
|
121 |
+
print("Modelo cargado exitosamente")
|
122 |
+
return True
|
123 |
+
|
124 |
+
except Exception as e:
|
125 |
+
print(f"Error al cargar modelo: {e}")
|
126 |
+
return False
|
127 |
+
|
128 |
+
def generate_response(
|
129 |
user_message: str,
|
130 |
system_message: str = DEFAULT_SYSTEM_MESSAGE,
|
131 |
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
|
132 |
temperature: float = 0.7,
|
133 |
top_p: float = 0.95,
|
134 |
+
):
|
135 |
+
"""Genera respuesta usando el modelo GGUF"""
|
136 |
+
global model
|
137 |
+
|
138 |
+
if model is None:
|
139 |
+
return "Error: Modelo no disponible."
|
140 |
+
|
|
|
|
|
|
|
141 |
try:
|
142 |
+
# Crear mensajes
|
143 |
+
messages = [
|
144 |
+
{"role": "system", "content": system_message},
|
145 |
+
{"role": "user", "content": user_message}
|
146 |
+
]
|
147 |
+
|
148 |
+
# Generar respuesta
|
149 |
+
response = model.create_chat_completion(
|
150 |
+
messages=messages,
|
151 |
+
max_tokens=max_new_tokens,
|
152 |
+
temperature=temperature,
|
153 |
+
top_p=top_p,
|
154 |
+
stream=False
|
155 |
+
)
|
156 |
+
|
157 |
+
full_response = response['choices'][0]['message']['content']
|
158 |
+
|
159 |
+
# Procesar respuesta con formato
|
160 |
+
thinking_part = ""
|
161 |
+
solution_part = ""
|
162 |
+
|
163 |
+
# Extraer pensamiento
|
164 |
+
think_match = re.search(r'<think>(.*?)</think>', full_response, re.DOTALL)
|
165 |
+
if think_match:
|
166 |
+
thinking_part = think_match.group(1).strip()
|
167 |
+
|
168 |
+
# Extraer solución
|
169 |
+
solution_match = re.search(r'<SOLUTION>(.*?)</SOLUTION>', full_response, re.DOTALL)
|
170 |
+
if solution_match:
|
171 |
+
solution_part = solution_match.group(1).strip()
|
172 |
+
|
173 |
+
# Construir respuesta formateada
|
174 |
messages = []
|
|
|
|
|
|
|
|
|
|
|
175 |
|
176 |
+
if thinking_part:
|
177 |
+
messages.append(ChatMessage(
|
178 |
+
role="assistant",
|
179 |
+
content=thinking_part,
|
180 |
+
metadata={"title": "🤔 Pensando..."}
|
181 |
+
))
|
182 |
+
|
183 |
+
if solution_part:
|
184 |
+
messages.append(ChatMessage(
|
185 |
+
role="assistant",
|
186 |
+
content=solution_part
|
187 |
+
))
|
188 |
+
elif not thinking_part:
|
189 |
+
# Si no hay formato específico, usar respuesta completa
|
190 |
+
clean_response = re.sub(r'<think>.*?</think>', '', full_response, flags=re.DOTALL)
|
191 |
+
clean_response = re.sub(r'<SOLUTION>(.*?)</SOLUTION>', r'\1', clean_response, flags=re.DOTALL)
|
192 |
+
messages.append(ChatMessage(
|
193 |
+
role="assistant",
|
194 |
+
content=clean_response.strip()
|
195 |
+
))
|
196 |
+
|
197 |
+
return messages
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
except Exception as e:
|
200 |
+
return [ChatMessage(role="assistant", content=f"Error: {str(e)}")]
|
201 |
|
202 |
def actualizar_personajes(pais_seleccionado):
|
203 |
"""Actualiza la galería de personajes según el país seleccionado"""
|
204 |
global current_personajes
|
205 |
personajes = PERSONAJES_POR_PAIS.get(pais_seleccionado, [])
|
206 |
+
current_personajes = personajes
|
207 |
|
208 |
if not personajes:
|
209 |
return [], "Selecciona un país para ver sus personajes"
|
|
|
233 |
print(f"Error al crear prompt: {e}")
|
234 |
return "Crea una historia sobre un personaje mítico"
|
235 |
|
236 |
+
def chat_function(message, history, max_tokens, temperature):
|
237 |
+
"""Función principal del chat"""
|
238 |
+
if not message.strip():
|
239 |
+
return history, ""
|
240 |
+
|
241 |
+
# Agregar mensaje del usuario al historial
|
242 |
+
history = history + [ChatMessage(role="user", content=message)]
|
243 |
+
|
244 |
+
# Generar respuesta
|
245 |
+
response_messages = generate_response(message, DEFAULT_SYSTEM_MESSAGE, max_tokens, temperature)
|
246 |
+
|
247 |
+
# Agregar respuestas al historial
|
248 |
+
for msg in response_messages:
|
249 |
+
history = history + [msg]
|
250 |
+
|
251 |
+
return history, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
252 |
|
253 |
+
# Cargar modelo al inicio
|
254 |
+
print("Iniciando carga del modelo...")
|
255 |
+
model_loaded = load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
256 |
|
257 |
+
# Crear la interfaz con componentes renderizables
|
258 |
with gr.Blocks(title="Iberotales", css=custom_css) as demo:
|
259 |
# Header con información del proyecto
|
260 |
+
gr.HTML("""
|
261 |
+
<div class="header-info">
|
262 |
+
<h1>📚 Iberotales</h1>
|
263 |
+
<p><strong>Autor:</strong> David Quispe | <a href="https://github.com/mcdaqc/Iberotales" target="_blank" style="text-decoration: none;">GitHub</a> | <a href="https://huggingface.co/somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es" target="_blank" style="text-decoration: none;">Modelo</a> | <a href="https://huggingface.co/somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es-finetune-gguf" target="_blank" style="text-decoration: none;">GGUF</a></p>
|
264 |
+
<p><em>Alineando modelos de lenguaje con la narrativa de mitos y leyendas de Iberoamérica.</em></p>
|
265 |
+
<p><em>Hackathon SomosNLP 2025</em></p>
|
266 |
+
</div>
|
267 |
+
""")
|
|
|
|
|
268 |
|
269 |
with gr.Row():
|
270 |
# Panel izquierdo - Pokédex de personajes
|
|
|
294 |
type="messages",
|
295 |
show_label=False,
|
296 |
height=400,
|
297 |
+
avatar_images=(None, "🏛️"),
|
298 |
+
value=[]
|
299 |
)
|
300 |
|
301 |
with gr.Row():
|
|
|
316 |
temperature = gr.Slider(0.1, 2.0, 0.7, label="Temp", container=False)
|
317 |
|
318 |
# Eventos
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
319 |
# Actualizar personajes cuando cambia el país
|
320 |
pais_dropdown.change(
|
321 |
fn=actualizar_personajes,
|
|
|
338 |
|
339 |
# Envío de mensajes
|
340 |
input_box.submit(
|
341 |
+
fn=chat_function,
|
342 |
+
inputs=[input_box, chatbot, max_tokens, temperature],
|
343 |
+
outputs=[chatbot, input_box]
|
|
|
|
|
|
|
344 |
)
|
345 |
|
346 |
send_button.click(
|
347 |
+
fn=chat_function,
|
348 |
+
inputs=[input_box, chatbot, max_tokens, temperature],
|
349 |
+
outputs=[chatbot, input_box]
|
|
|
|
|
|
|
350 |
)
|
351 |
|
352 |
clear_button.click(
|
353 |
+
fn=lambda: ([], ""),
|
354 |
outputs=[chatbot, input_box],
|
355 |
queue=False
|
356 |
)
|
|
|
358 |
# Lanzar aplicación
|
359 |
if __name__ == "__main__":
|
360 |
if model_loaded:
|
361 |
+
print("Lanzando aplicación...")
|
362 |
demo.launch(share=False, show_error=True)
|
363 |
else:
|
364 |
+
print("Error: No se pudo cargar el modelo. Revisa la configuración.")
|