Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,21 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
import torch
|
| 4 |
import torch._dynamo
|
| 5 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
|
| 6 |
from threading import Thread
|
| 7 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Desactivar TorchDynamo para evitar errores de compilación
|
| 10 |
torch._dynamo.config.suppress_errors = True
|
|
@@ -12,9 +23,19 @@ torch._dynamo.disable()
|
|
| 12 |
|
| 13 |
# Configuración
|
| 14 |
MODEL_ID = "somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es"
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
| 16 |
DEFAULT_MAX_NEW_TOKENS = 2048
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# System prompt personalizado
|
| 20 |
DEFAULT_SYSTEM_MESSAGE = """Resuelve el siguiente problema.
|
|
@@ -22,16 +43,125 @@ Primero, piensa en voz alta qué debes hacer, paso por paso y de forma resumida,
|
|
| 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(
|
|
@@ -40,170 +170,402 @@ def load_model():
|
|
| 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
|
| 51 |
return False
|
| 52 |
else:
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
# Cargar modelo al iniciar
|
| 57 |
model_loaded = load_model()
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
"""
|
| 71 |
global model, tokenizer
|
| 72 |
|
| 73 |
if model is None or tokenizer is None:
|
| 74 |
-
|
|
|
|
| 75 |
return
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
| 85 |
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
try:
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
skip_special_tokens=True
|
| 107 |
-
)
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 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 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 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 |
-
|
| 204 |
-
demo.launch(
|
| 205 |
-
share=False,
|
| 206 |
-
show_error=True
|
| 207 |
-
)
|
| 208 |
else:
|
| 209 |
-
print("Error al cargar el modelo.
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
from gradio import ChatMessage
|
| 4 |
import torch
|
| 5 |
import torch._dynamo
|
| 6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 7 |
+
from llama_cpp import Llama
|
| 8 |
from threading import Thread
|
| 9 |
+
from huggingface_hub import hf_hub_download
|
| 10 |
+
import re
|
| 11 |
+
from typing import Iterator
|
| 12 |
+
|
| 13 |
+
# Intentar importar spaces solo si estamos en un espacio de Hugging Face
|
| 14 |
+
try:
|
| 15 |
+
import spaces
|
| 16 |
+
SPACES_AVAILABLE = True
|
| 17 |
+
except ImportError:
|
| 18 |
+
SPACES_AVAILABLE = False
|
| 19 |
|
| 20 |
# Desactivar TorchDynamo para evitar errores de compilación
|
| 21 |
torch._dynamo.config.suppress_errors = True
|
|
|
|
| 23 |
|
| 24 |
# Configuración
|
| 25 |
MODEL_ID = "somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es"
|
| 26 |
+
GGUF_MODEL_ID = "somosnlp-hackathon-2025/iberotales-gemma-3-1b-it-es-finetune-gguf"
|
| 27 |
+
GGUF_FILENAME = "gemma-3-finetune.Q8_0.gguf"
|
| 28 |
+
GGUF_REVISION = "main"
|
| 29 |
+
MAX_MAX_NEW_TOKENS = 2048
|
| 30 |
DEFAULT_MAX_NEW_TOKENS = 2048
|
| 31 |
+
|
| 32 |
+
# Verificar si estamos en un espacio de Hugging Face
|
| 33 |
+
IS_HF_SPACE = any([
|
| 34 |
+
os.getenv("SPACE_ID") is not None,
|
| 35 |
+
os.getenv("SPACE_AUTHOR_NAME") is not None,
|
| 36 |
+
os.getenv("SPACE_REPO_NAME") is not None,
|
| 37 |
+
os.getenv("SPACE_HOST") is not None,
|
| 38 |
+
])
|
| 39 |
|
| 40 |
# System prompt personalizado
|
| 41 |
DEFAULT_SYSTEM_MESSAGE = """Resuelve el siguiente problema.
|
|
|
|
| 43 |
Luego, da la respuesta final entre <SOLUTION> y </SOLUTION>.
|
| 44 |
No escribas nada fuera de ese formato."""
|
| 45 |
|
| 46 |
+
# Base de datos de personajes por país con banderas
|
| 47 |
+
PERSONAJES_POR_PAIS = {
|
| 48 |
+
"🇦🇷 Argentina": [
|
| 49 |
+
{"nombre": "La Difunta Correa", "imagen": "images/ar1.jpg", "descripcion": "Santa popular que murió de sed siguiendo a su esposo reclutado"},
|
| 50 |
+
{"nombre": "El Lobizón", "imagen": "images/ar2.jpg", "descripcion": "Hombre lobo de la tradición gaucha, séptimo hijo varón maldito"},
|
| 51 |
+
{"nombre": "La Telesita", "imagen": "images/ar3.webp", "descripcion": "Bailarina folklórica que se aparece en festivales y zambas"}
|
| 52 |
+
],
|
| 53 |
+
"🇧🇴 Bolivia": [
|
| 54 |
+
{"nombre": "El Tío del Cerro Rico", "imagen": "images/bo1.webp", "descripcion": "Señor de las minas que protege y castiga a los mineros"},
|
| 55 |
+
{"nombre": "El Ekeko", "imagen": "images/bo2.jpg", "descripcion": "Dios aymara de la abundancia y la fortuna con jorobas"},
|
| 56 |
+
{"nombre": "El Jichi", "imagen": "images/bo3.webp", "descripcion": "Serpiente protectora de ríos y lagunas en la cultura andina"}
|
| 57 |
+
],
|
| 58 |
+
"🇧🇷 Brasil": [
|
| 59 |
+
{"nombre": "Curupira", "imagen": "images/br1.jpeg", "descripcion": "Protector del bosque amazónico con pies al revés"},
|
| 60 |
+
{"nombre": "Saci-Pererê", "imagen": "images/br2.jpg", "descripcion": "Duende travieso de una pierna que fuma pipa"},
|
| 61 |
+
{"nombre": "Yebá Bëló", "imagen": "images/br3.jpg", "descripcion": "Abuela del mundo en mitología desana, creadora del universo"}
|
| 62 |
+
],
|
| 63 |
+
"🇨🇱 Chile": [
|
| 64 |
+
{"nombre": "Guallipén", "imagen": "images/ch1.webp", "descripcion": "Carnero gigante que habita en los ríos de Chiloé"},
|
| 65 |
+
{"nombre": "Colo Colo", "imagen": "images/ch2.webp", "descripcion": "Ser maléfico nacido de huevo de gallo empollado por serpiente"},
|
| 66 |
+
{"nombre": "Cuchivilu", "imagen": "images/ch3.webp", "descripcion": "Cerdo marino con cola de pez que habita en Chiloé"}
|
| 67 |
+
],
|
| 68 |
+
"🇨🇴 Colombia": [
|
| 69 |
+
{"nombre": "El Guaca", "imagen": "images/co1.jpg", "descripcion": "Espíritu guardián de tesoros enterrados por indígenas"},
|
| 70 |
+
{"nombre": "Chiminigagua", "imagen": "images/co2.webp", "descripcion": "Dios creador muisca, fuente de luz y vida universal"},
|
| 71 |
+
{"nombre": "Jukumari", "imagen": "images/co3.jpg", "descripcion": "Oso gigante mitológico de los Andes colombianos"}
|
| 72 |
+
],
|
| 73 |
+
"🇨🇷 Costa Rica": [
|
| 74 |
+
{"nombre": "El Micomalo", "imagen": "images/cr1.jpg", "descripcion": "Mono gigante y feroz que ataca a los cazadores"},
|
| 75 |
+
{"nombre": "La Carreta sin Bueyes", "imagen": "images/crr2.jpg", "descripcion": "Carreta fantasma que recorre caminos sin animales tirando"},
|
| 76 |
+
{"nombre": "El Sisimiqui", "imagen": "images/cr3.webp", "descripcion": "Duende pequeño y travieso de los bosques costarricenses"}
|
| 77 |
+
],
|
| 78 |
+
"🇨🇺 Cuba": [
|
| 79 |
+
{"nombre": "El Güije", "imagen": "images/cu1.jpg", "descripcion": "Duende negro de aguas dulces que ahoga a los bañistas"},
|
| 80 |
+
{"nombre": "Itiba Cahubaba", "imagen": "images/cu2.jpg", "descripcion": "Madre primordial taína de donde brotaron las aguas"},
|
| 81 |
+
{"nombre": "Guabancex", "imagen": "images/cu3.jpg", "descripcion": "Diosa taína de los huracanes y vientos destructores"}
|
| 82 |
+
],
|
| 83 |
+
"🇪🇨 Ecuador": [
|
| 84 |
+
{"nombre": "Salun", "imagen": "images/ec1.jpg", "descripcion": "Espíritu shamán shuar que guía en visiones espirituales"},
|
| 85 |
+
{"nombre": "Nunkui", "imagen": "images/ec2.jpg", "descripcion": "Diosa shuar de la fertilidad de la tierra y agricultura"},
|
| 86 |
+
{"nombre": "Yacuruna", "imagen": "images/ec3.jpg", "descripcion": "Hombre serpiente amazónico señor de las aguas dulces"}
|
| 87 |
+
],
|
| 88 |
+
"🇪🇸 España": [
|
| 89 |
+
{"nombre": "Ojáncanu", "imagen": "images/es1.jpg", "descripcion": "Gigante cíclope cántabro de fuerza descomunal"},
|
| 90 |
+
{"nombre": "Los Carantos", "imagen": "images/es2.jpg", "descripcion": "Espíritus gallegos que anuncian desgracias familiares"},
|
| 91 |
+
{"nombre": "Cuegle", "imagen": "images/es3.jpg", "descripcion": "Ser asturiano de tres ojos que protege casas del mal"}
|
| 92 |
+
],
|
| 93 |
+
"🇬🇹 Guatemala": [
|
| 94 |
+
{"nombre": "Camalotz", "imagen": "images/gu1.jpg", "descripcion": "Dios murciélago maya señor de las cuevas y la muerte"},
|
| 95 |
+
{"nombre": "La Siguanaba", "imagen": "images/gu2.jpg", "descripcion": "Mujer hermosa que muestra rostro de calavera a infieles"},
|
| 96 |
+
{"nombre": "Gucumatz", "imagen": "images/gu3.jpg", "descripcion": "Serpiente emplumada maya, equivalente a Quetzalcóatl"}
|
| 97 |
+
],
|
| 98 |
+
"🇭🇳 Honduras": [
|
| 99 |
+
{"nombre": "Icelaca", "imagen": "images/ho1.jpg", "descripcion": "Serpiente gigante que habita en cuevas hondureñas"},
|
| 100 |
+
{"nombre": "Cihuateteo", "imagen": "images/ho2.jpg", "descripcion": "Espíritus de mujeres muertas en parto, guerreras divinas"},
|
| 101 |
+
{"nombre": "Comelenguas", "imagen": "images/ho3.webp", "descripcion": "Demonio que devora lenguas de personas dormidas"}
|
| 102 |
+
],
|
| 103 |
+
"🇲🇽 México": [
|
| 104 |
+
{"nombre": "Quetzalcóatl", "imagen": "images/me1.jpg", "descripcion": "Serpiente emplumada, dios del viento y la sabiduría"},
|
| 105 |
+
{"nombre": "Tlacatecolotl", "imagen": "images/me2.jpg", "descripcion": "Brujo nahuatl que se transforma en búho gigante"},
|
| 106 |
+
{"nombre": "Tlalocan", "imagen": "images/me3.jpg", "descripcion": "Paraíso acuático de Tláloc donde van los ahogados"}
|
| 107 |
+
],
|
| 108 |
+
"🇳🇮 Nicaragua": [
|
| 109 |
+
{"nombre": "La Mocuana", "imagen": "images/ni1.webp", "descripcion": "Espíritu de mujer sin cabeza que vaga de noche"},
|
| 110 |
+
{"nombre": "El Guácimo Renco", "imagen": "images/ni2.jpg", "descripcion": "Árbol maldito que se transforma y persigue viajeros"},
|
| 111 |
+
{"nombre": "La Mona Bruja", "imagen": "images/ni3.jpg", "descripcion": "Bruja transformada en mona que roba niños pequeños"}
|
| 112 |
+
],
|
| 113 |
+
"🇵🇦 Panamá": [
|
| 114 |
+
{"nombre": "Humantahú", "imagen": "images/pa1.jpg", "descripcion": "Chamán kuna protector de la naturaleza y animales"},
|
| 115 |
+
{"nombre": "La Silampa", "imagen": "images/pa2.jpg", "descripcion": "Mujer fantasma que seduce y mata a hombres solitarios"},
|
| 116 |
+
{"nombre": "El Chivato", "imagen": "images/pa3.jpg", "descripcion": "Cabro diabólico que aparece en encrucijadas nocturnas"}
|
| 117 |
+
],
|
| 118 |
+
"🇵🇾 Paraguay": [
|
| 119 |
+
{"nombre": "Mbói Tata", "imagen": "images/py1.png", "descripcion": "Serpiente de fuego protectora de campos y esteros"},
|
| 120 |
+
{"nombre": "Urutau", "imagen": "images/py2.jpg", "descripcion": "Ave fantasma cuyo canto anuncia tragedias familiares"},
|
| 121 |
+
{"nombre": "Tajy", "imagen": "images/py3.jpg", "descripcion": "Espíritu del lapacho florido en la mitología guaraní"}
|
| 122 |
+
],
|
| 123 |
+
"🇵🇪 Perú": [
|
| 124 |
+
{"nombre": "Wiracocha", "imagen": "images/pe1.jpg", "descripcion": "Dios creador inca señor de todas las cosas vivientes"},
|
| 125 |
+
{"nombre": "El Muki", "imagen": "images/pe2.webp", "descripcion": "Duende minero que protege vetas de oro y plata"},
|
| 126 |
+
{"nombre": "Los Hermanos Ayar", "imagen": "images/pe3.jpg", "descripcion": "Cuatro hermanos fundadores míticos del imperio inca"}
|
| 127 |
+
],
|
| 128 |
+
"🇵🇹 Portugal": [
|
| 129 |
+
{"nombre": "El Marialva", "imagen": "images/po1.jpg", "descripcion": "Caballero galante y seductor de la tradición portuguesa"},
|
| 130 |
+
{"nombre": "El Pez Milagroso", "imagen": "images/po2.webp", "descripcion": "Pez mágico que concede deseos a pescadores devotos"},
|
| 131 |
+
{"nombre": "La Cueva da Moeda", "imagen": "images/po3.webp", "descripcion": "Cueva encantada llena de tesoros moros perdidos"}
|
| 132 |
+
],
|
| 133 |
+
"🇵🇷 Puerto Rico": [
|
| 134 |
+
{"nombre": "Yúcahu", "imagen": "images/pr1.jpg", "descripcion": "Dios taíno de la yuca y protector de cosechas"},
|
| 135 |
+
{"nombre": "Atabey", "imagen": "images/pr2.jpg", "descripcion": "Diosa madre taína de las aguas dulces y fertilidad"},
|
| 136 |
+
{"nombre": "Anacacuya", "imagen": "images/pr3.png", "descripcion": "Estrella taína guía de navegantes y pescadores"}
|
| 137 |
+
],
|
| 138 |
+
"🇩🇴 República Dominicana": [
|
| 139 |
+
{"nombre": "El Galipote", "imagen": "images/rd1.webp", "descripcion": "Brujo que se transforma en animal para hacer maldades"},
|
| 140 |
+
{"nombre": "El Lugaru", "imagen": "images/rd2.webp", "descripcion": "Hombre lobo dominicano que ataca ganado y personas"},
|
| 141 |
+
{"nombre": "Papa Legba", "imagen": "images/rd3.jpg", "descripcion": "Loa vudú guardián de encrucijadas y comunicaciones"}
|
| 142 |
+
],
|
| 143 |
+
"🇺🇾 Uruguay": [
|
| 144 |
+
{"nombre": "El Yasy Yateré", "imagen": "images/ur1.jpg", "descripcion": "Duende rubio protector de niños con bastón mágico"},
|
| 145 |
+
{"nombre": "El Ñandú Barriga Blanca", "imagen": "images/ur2.jpg", "descripcion": "Ñandú gigante y sagrado de las pampas uruguayas"},
|
| 146 |
+
{"nombre": "El Pombero", "imagen": "images/ur3.jpg", "descripcion": "Duende travieso protector de aves y la naturaleza"}
|
| 147 |
+
],
|
| 148 |
+
"🇻🇪 Venezuela": [
|
| 149 |
+
{"nombre": "Amalivaca", "imagen": "images/ve1.jpg", "descripcion": "Héroe cultural tamanaco creador del río Orinoco"},
|
| 150 |
+
{"nombre": "Osemma", "imagen": "images/ve2.jpg", "descripcion": "Espíritu warao de las palmeras de moriche"},
|
| 151 |
+
{"nombre": "La Sayona", "imagen": "images/ve3.webp", "descripcion": "Mujer vengativa que persigue y castiga a infieles"}
|
| 152 |
+
]
|
| 153 |
+
};
|
| 154 |
+
|
| 155 |
# Variables globales
|
| 156 |
model = None
|
| 157 |
tokenizer = None
|
| 158 |
+
current_personajes = [] # Para mantener el estado de los personajes actuales
|
| 159 |
|
| 160 |
def load_model():
|
| 161 |
"""Cargar modelo y tokenizador"""
|
| 162 |
global model, tokenizer
|
| 163 |
|
| 164 |
if torch.cuda.is_available():
|
|
|
|
| 165 |
try:
|
| 166 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 167 |
model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 170 |
device_map="auto",
|
| 171 |
trust_remote_code=True,
|
| 172 |
)
|
|
|
|
| 173 |
if tokenizer.pad_token is None:
|
| 174 |
tokenizer.pad_token = tokenizer.eos_token
|
|
|
|
|
|
|
| 175 |
return True
|
| 176 |
except Exception as e:
|
| 177 |
+
print(f"Error GPU: {e}")
|
| 178 |
return False
|
| 179 |
else:
|
| 180 |
+
try:
|
| 181 |
+
local_model_path = os.path.join("models", GGUF_FILENAME)
|
| 182 |
+
if os.path.exists(local_model_path):
|
| 183 |
+
model_path = local_model_path
|
| 184 |
+
else:
|
| 185 |
+
model_path = hf_hub_download(
|
| 186 |
+
repo_id=GGUF_MODEL_ID,
|
| 187 |
+
filename=GGUF_FILENAME,
|
| 188 |
+
revision=GGUF_REVISION,
|
| 189 |
+
local_dir="./models",
|
| 190 |
+
force_download=False,
|
| 191 |
+
resume_download=True
|
| 192 |
+
)
|
| 193 |
+
tokenizer = AutoTokenizer.from_pretrained("google/gemma-3-1b-it")
|
| 194 |
+
model = Llama(
|
| 195 |
+
model_path=model_path,
|
| 196 |
+
n_ctx=2048,
|
| 197 |
+
n_threads=4,
|
| 198 |
+
n_gpu_layers=0
|
| 199 |
+
)
|
| 200 |
+
return True
|
| 201 |
+
except Exception as e:
|
| 202 |
+
print(f"Error GGUF: {e}")
|
| 203 |
+
return False
|
| 204 |
|
|
|
|
| 205 |
model_loaded = load_model()
|
| 206 |
|
| 207 |
+
def format_chat_history(messages: list, exclude_last_user: bool = True) -> list:
|
| 208 |
+
"""Formatea el historial de chat para el modelo"""
|
| 209 |
+
formatted_history = []
|
| 210 |
+
messages_to_process = messages[:]
|
| 211 |
+
if exclude_last_user and messages_to_process and messages_to_process[-1].get("role") == "user":
|
| 212 |
+
messages_to_process = messages_to_process[:-1]
|
| 213 |
+
|
| 214 |
+
for message in messages_to_process:
|
| 215 |
+
current_role = message.get("role")
|
| 216 |
+
current_content = message.get("content", "").strip()
|
| 217 |
+
|
| 218 |
+
if current_role == "assistant" and message.get("metadata"):
|
| 219 |
+
continue
|
| 220 |
+
if not current_content:
|
| 221 |
+
continue
|
| 222 |
+
|
| 223 |
+
if formatted_history and formatted_history[-1]["role"] == current_role:
|
| 224 |
+
formatted_history[-1]["content"] += "\n\n" + current_content
|
| 225 |
+
else:
|
| 226 |
+
formatted_history.append({
|
| 227 |
+
"role": current_role,
|
| 228 |
+
"content": current_content
|
| 229 |
+
})
|
| 230 |
+
|
| 231 |
+
return formatted_history
|
| 232 |
+
|
| 233 |
+
def stream_iberotales_response(
|
| 234 |
+
user_message: str,
|
| 235 |
+
messages: list,
|
| 236 |
+
system_message: str = DEFAULT_SYSTEM_MESSAGE,
|
| 237 |
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
|
| 238 |
temperature: float = 0.7,
|
| 239 |
top_p: float = 0.95,
|
| 240 |
top_k: int = 50,
|
| 241 |
repetition_penalty: float = 1.2,
|
| 242 |
+
) -> Iterator[list]:
|
| 243 |
+
"""Genera respuesta con streaming"""
|
| 244 |
global model, tokenizer
|
| 245 |
|
| 246 |
if model is None or tokenizer is None:
|
| 247 |
+
messages.append(ChatMessage(role="assistant", content="Error: Modelo no disponible."))
|
| 248 |
+
yield messages
|
| 249 |
return
|
| 250 |
|
| 251 |
+
try:
|
| 252 |
+
chat_history = format_chat_history(messages, exclude_last_user=True)
|
| 253 |
+
conversation = []
|
| 254 |
+
if system_message.strip():
|
| 255 |
+
conversation.append({"role": "system", "content": system_message.strip()})
|
| 256 |
+
conversation.extend(chat_history)
|
| 257 |
+
conversation.append({"role": "user", "content": user_message})
|
| 258 |
+
|
| 259 |
+
# Validar alternancia
|
| 260 |
+
for i in range(1, len(conversation)):
|
| 261 |
+
if conversation[i]["role"] == conversation[i-1]["role"] and conversation[i-1]["role"] != "system":
|
| 262 |
+
messages.append(ChatMessage(role="assistant", content="Error: Reinicia la conversación."))
|
| 263 |
+
yield messages
|
| 264 |
+
return
|
| 265 |
+
|
| 266 |
+
prompt = tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
|
| 267 |
+
response = model(
|
| 268 |
+
prompt,
|
| 269 |
+
max_tokens=max_new_tokens,
|
| 270 |
+
temperature=temperature,
|
| 271 |
+
top_p=top_p,
|
| 272 |
+
top_k=top_k,
|
| 273 |
+
repeat_penalty=repetition_penalty,
|
| 274 |
+
stream=True
|
| 275 |
+
)
|
| 276 |
|
| 277 |
+
full_response = ""
|
| 278 |
+
thinking_message_index = None
|
| 279 |
+
solution_message_index = None
|
| 280 |
+
in_think_block = False
|
| 281 |
+
in_solution_block = False
|
| 282 |
+
thinking_complete = False
|
| 283 |
+
|
| 284 |
+
for chunk in response:
|
| 285 |
+
if chunk["choices"][0]["finish_reason"] is None:
|
| 286 |
+
new_text = chunk["choices"][0]["text"]
|
| 287 |
+
full_response += new_text
|
| 288 |
+
|
| 289 |
+
# Procesar pensamiento
|
| 290 |
+
if "<think>" in full_response and not thinking_complete:
|
| 291 |
+
if not in_think_block:
|
| 292 |
+
in_think_block = True
|
| 293 |
+
if thinking_message_index is None:
|
| 294 |
+
messages.append(ChatMessage(
|
| 295 |
+
role="assistant",
|
| 296 |
+
content="",
|
| 297 |
+
metadata={"title": "🤔 Pensando..."}
|
| 298 |
+
))
|
| 299 |
+
thinking_message_index = len(messages) - 1
|
| 300 |
+
|
| 301 |
+
think_start = full_response.find("<think>") + 7
|
| 302 |
+
if "</think>" in full_response:
|
| 303 |
+
think_end = full_response.find("</think>")
|
| 304 |
+
current_thinking = full_response[think_start:think_end].strip()
|
| 305 |
+
thinking_complete = True
|
| 306 |
+
in_think_block = False
|
| 307 |
+
else:
|
| 308 |
+
current_thinking = full_response[think_start:].strip()
|
| 309 |
+
|
| 310 |
+
if thinking_message_index is not None:
|
| 311 |
+
messages[thinking_message_index] = ChatMessage(
|
| 312 |
+
role="assistant",
|
| 313 |
+
content=current_thinking,
|
| 314 |
+
metadata={"title": "🤔 Pensando..."}
|
| 315 |
+
)
|
| 316 |
+
yield messages
|
| 317 |
+
|
| 318 |
+
# Procesar solución
|
| 319 |
+
if "<SOLUTION>" in full_response:
|
| 320 |
+
if not in_solution_block:
|
| 321 |
+
in_solution_block = True
|
| 322 |
+
if solution_message_index is None:
|
| 323 |
+
messages.append(ChatMessage(role="assistant", content=""))
|
| 324 |
+
solution_message_index = len(messages) - 1
|
| 325 |
+
|
| 326 |
+
solution_start = full_response.find("<SOLUTION>") + 10
|
| 327 |
+
if "</SOLUTION>" in full_response:
|
| 328 |
+
solution_end = full_response.find("</SOLUTION>")
|
| 329 |
+
current_solution = full_response[solution_start:solution_end].strip()
|
| 330 |
+
in_solution_block = False
|
| 331 |
+
else:
|
| 332 |
+
current_solution = full_response[solution_start:].strip()
|
| 333 |
+
|
| 334 |
+
if solution_message_index is not None and current_solution:
|
| 335 |
+
messages[solution_message_index] = ChatMessage(
|
| 336 |
+
role="assistant",
|
| 337 |
+
content=current_solution
|
| 338 |
+
)
|
| 339 |
+
yield messages
|
| 340 |
+
|
| 341 |
+
# Respuesta sin formato
|
| 342 |
+
if full_response.strip() and solution_message_index is None:
|
| 343 |
+
clean_response = full_response
|
| 344 |
+
if "<think>" in clean_response and "</think>" in clean_response:
|
| 345 |
+
clean_response = re.sub(r'<think>.*?</think>', '', clean_response, flags=re.DOTALL)
|
| 346 |
+
if "<SOLUTION>" in clean_response and "</SOLUTION>" in clean_response:
|
| 347 |
+
clean_response = re.sub(r'<SOLUTION>(.*?)</SOLUTION>', r'\1', clean_response, flags=re.DOTALL)
|
| 348 |
+
|
| 349 |
+
clean_response = clean_response.strip()
|
| 350 |
+
if clean_response:
|
| 351 |
+
messages.append(ChatMessage(role="assistant", content=clean_response))
|
| 352 |
+
yield messages
|
| 353 |
+
|
| 354 |
+
except Exception as e:
|
| 355 |
+
messages.append(ChatMessage(role="assistant", content=f"Error: {str(e)}"))
|
| 356 |
+
yield messages
|
| 357 |
|
| 358 |
+
def user_message(msg: str, history: list) -> tuple[str, list]:
|
| 359 |
+
"""Añade mensaje del usuario al historial"""
|
| 360 |
+
history.append(ChatMessage(role="user", content=msg))
|
| 361 |
+
return "", history
|
| 362 |
|
| 363 |
+
def actualizar_personajes(pais_seleccionado):
|
| 364 |
+
"""Actualiza la galería de personajes según el país seleccionado"""
|
| 365 |
+
global current_personajes
|
| 366 |
+
personajes = PERSONAJES_POR_PAIS.get(pais_seleccionado, [])
|
| 367 |
+
current_personajes = personajes # Guardamos el estado actual
|
| 368 |
+
|
| 369 |
+
if not personajes:
|
| 370 |
+
return [], "Selecciona un país para ver sus personajes"
|
| 371 |
+
|
| 372 |
+
# Crear lista de imágenes y etiquetas para la galería
|
| 373 |
+
imagenes = []
|
| 374 |
+
for p in personajes:
|
| 375 |
+
if os.path.exists(p["imagen"]):
|
| 376 |
+
imagenes.append((p["imagen"], f"{p['nombre']}: {p['descripcion']}"))
|
| 377 |
+
else:
|
| 378 |
+
# Imagen placeholder si no existe
|
| 379 |
+
imagenes.append(("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgZmlsbD0iI2NjYyIvPjx0ZXh0IHg9IjUwIiB5PSI1MCIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjY2IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+SW1hZ2VuPC90ZXh0Pjwvc3ZnPg==", f"{p['nombre']}: {p['descripcion']}"))
|
| 380 |
+
|
| 381 |
+
return imagenes, f"Personajes de {pais_seleccionado}"
|
| 382 |
|
| 383 |
+
def crear_prompt_desde_personaje(evt: gr.SelectData):
|
| 384 |
+
"""Crea un prompt basado en el personaje seleccionado"""
|
| 385 |
+
global current_personajes
|
| 386 |
+
|
| 387 |
try:
|
| 388 |
+
if evt.index is not None and evt.index < len(current_personajes):
|
| 389 |
+
personaje = current_personajes[evt.index]
|
| 390 |
+
return f"Crea una historia sobre {personaje['nombre']}, {personaje['descripcion']}" #si alguien lee esto, cambiar el dataste a cuenta en lugar de crea
|
| 391 |
+
else:
|
| 392 |
+
return "Crea una historia sobre un personaje mítico"
|
| 393 |
+
except Exception as e:
|
| 394 |
+
print(f"Error al crear prompt: {e}")
|
| 395 |
+
return "Crea una historia sobre un personaje mítico"
|
| 396 |
|
| 397 |
+
# Aplicar decorador @spaces.GPU si es necesario
|
| 398 |
+
if IS_HF_SPACE and SPACES_AVAILABLE and torch.cuda.is_available():
|
| 399 |
+
stream_iberotales_response = spaces.GPU(stream_iberotales_response)
|
| 400 |
|
| 401 |
+
# CSS personalizado para mejorar la apariencia
|
| 402 |
+
custom_css = """
|
| 403 |
+
.gradio-container {
|
| 404 |
+
max-width: 1400px !important;
|
| 405 |
+
margin: auto;
|
| 406 |
+
padding-top: 1.5rem;
|
| 407 |
+
}
|
| 408 |
|
| 409 |
+
#galeria .grid-wrap {
|
| 410 |
+
max-height: 350px;
|
| 411 |
+
overflow-y: auto;
|
| 412 |
+
}
|
|
|
|
|
|
|
| 413 |
|
| 414 |
+
#galeria .grid-container {
|
| 415 |
+
grid-template-columns: repeat(1, 1fr) !important;
|
| 416 |
+
gap: 0.5rem;
|
| 417 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
+
#galeria .thumbnail-item {
|
| 420 |
+
aspect-ratio: 1;
|
| 421 |
+
max-height: 100px;
|
| 422 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
|
| 424 |
+
#galeria .thumbnail-item img {
|
| 425 |
+
object-fit: cover;
|
| 426 |
+
width: 100%;
|
| 427 |
+
height: 100%;
|
| 428 |
+
border-radius: 8px;
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
.header-info {
|
| 432 |
+
background: linear-gradient(135deg, #2c3e50 0%, #1a1a2e 100%);
|
| 433 |
+
color: white;
|
| 434 |
+
padding: 1rem;
|
| 435 |
+
border-radius: 12px;
|
| 436 |
+
margin-bottom: 1rem;
|
| 437 |
+
text-align: center;
|
| 438 |
+
}
|
| 439 |
+
"""
|
| 440 |
+
|
| 441 |
+
# Crear la interfaz
|
| 442 |
+
with gr.Blocks(fill_height=True, title="Iberotales", css=custom_css) as demo:
|
| 443 |
+
# Header con información del proyecto
|
| 444 |
+
with gr.Row():
|
| 445 |
+
with gr.Column():
|
| 446 |
+
gr.HTML("""
|
| 447 |
+
<div class="header-info">
|
| 448 |
+
<h1>📚 Iberotales</h1>
|
| 449 |
+
<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>
|
| 450 |
+
<p><em>Alineando modelos de lenguaje con la narrativa de mitos y leyendas de Iberoamérica.</em></p>
|
| 451 |
+
<p><em>Hackathon SomosNLP 2025</em></p>
|
| 452 |
+
</div>
|
| 453 |
+
""")
|
| 454 |
+
|
| 455 |
+
with gr.Row():
|
| 456 |
+
# Panel izquierdo - Pokédex de personajes
|
| 457 |
+
with gr.Column(scale=1, min_width=320):
|
| 458 |
+
gr.Markdown("### 🗃️ Pokédex de Personajes")
|
| 459 |
+
|
| 460 |
+
pais_dropdown = gr.Dropdown(
|
| 461 |
+
choices=list(PERSONAJES_POR_PAIS.keys()),
|
| 462 |
+
value="🇵🇾 Paraguay",
|
| 463 |
+
label="País",
|
| 464 |
+
container=False
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
galeria_personajes = gr.Gallery(
|
| 468 |
+
value=[],
|
| 469 |
+
label="Personajes",
|
| 470 |
+
show_label=False,
|
| 471 |
+
elem_id="galeria",
|
| 472 |
+
columns=1,
|
| 473 |
+
rows=4,
|
| 474 |
+
height=350,
|
| 475 |
+
object_fit="cover",
|
| 476 |
+
preview=False # Esto evita que se expanda automáticamente
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
# Panel derecho - Chat
|
| 480 |
+
with gr.Column(scale=2):
|
| 481 |
+
chatbot = gr.Chatbot(
|
| 482 |
+
type="messages",
|
| 483 |
+
show_label=False,
|
| 484 |
+
height=400,
|
| 485 |
+
avatar_images=(None, "🏛️")
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
with gr.Row():
|
| 489 |
+
input_box = gr.Textbox(
|
| 490 |
+
placeholder="Escribe tu historia o selecciona un personaje...",
|
| 491 |
+
show_label=False,
|
| 492 |
+
scale=4,
|
| 493 |
+
container=False
|
| 494 |
+
)
|
| 495 |
+
send_button = gr.Button("📤", scale=1, variant="primary")
|
| 496 |
+
|
| 497 |
+
with gr.Row():
|
| 498 |
+
clear_button = gr.Button("🗑️ Limpiar", scale=1, size="sm")
|
| 499 |
+
|
| 500 |
+
with gr.Column(scale=3):
|
| 501 |
+
with gr.Row():
|
| 502 |
+
max_tokens = gr.Slider(100, MAX_MAX_NEW_TOKENS, DEFAULT_MAX_NEW_TOKENS, label="Tokens", container=False)
|
| 503 |
+
temperature = gr.Slider(0.1, 2.0, 0.7, label="Temp", container=False)
|
| 504 |
+
|
| 505 |
+
# Variables de estado
|
| 506 |
+
msg_store = gr.State("")
|
| 507 |
+
|
| 508 |
+
# Eventos
|
| 509 |
+
def submit_message(msg, history):
|
| 510 |
+
if not msg.strip():
|
| 511 |
+
return msg, history
|
| 512 |
+
return "", user_message(msg, history)[1]
|
| 513 |
+
|
| 514 |
+
def generate_response(msg, history, max_tok, temp):
|
| 515 |
+
yield from stream_iberotales_response(msg, history, DEFAULT_SYSTEM_MESSAGE, max_tok, temp)
|
| 516 |
+
|
| 517 |
+
# Actualizar personajes cuando cambia el país
|
| 518 |
+
pais_dropdown.change(
|
| 519 |
+
fn=actualizar_personajes,
|
| 520 |
+
inputs=[pais_dropdown],
|
| 521 |
+
outputs=[galeria_personajes, gr.Textbox(visible=False)]
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
# Cargar personajes iniciales
|
| 525 |
+
demo.load(
|
| 526 |
+
fn=actualizar_personajes,
|
| 527 |
+
inputs=[pais_dropdown],
|
| 528 |
+
outputs=[galeria_personajes, gr.Textbox(visible=False)]
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# Crear prompt desde galería
|
| 532 |
+
galeria_personajes.select(
|
| 533 |
+
fn=crear_prompt_desde_personaje,
|
| 534 |
+
outputs=[input_box]
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
# Envío de mensajes
|
| 538 |
+
input_box.submit(
|
| 539 |
+
lambda msg, hist: (msg, submit_message(msg, hist)[1]),
|
| 540 |
+
inputs=[input_box, chatbot],
|
| 541 |
+
outputs=[msg_store, chatbot],
|
| 542 |
+
queue=False
|
| 543 |
+
).then(
|
| 544 |
+
generate_response,
|
| 545 |
+
inputs=[msg_store, chatbot, max_tokens, temperature],
|
| 546 |
+
outputs=chatbot
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
send_button.click(
|
| 550 |
+
lambda msg, hist: (msg, submit_message(msg, hist)[1]),
|
| 551 |
+
inputs=[input_box, chatbot],
|
| 552 |
+
outputs=[msg_store, chatbot],
|
| 553 |
+
queue=False
|
| 554 |
+
).then(
|
| 555 |
+
generate_response,
|
| 556 |
+
inputs=[msg_store, chatbot, max_tokens, temperature],
|
| 557 |
+
outputs=chatbot
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
clear_button.click(
|
| 561 |
+
lambda: ([], "", ""),
|
| 562 |
+
outputs=[chatbot, input_box, msg_store],
|
| 563 |
+
queue=False
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# Lanzar aplicación
|
| 567 |
if __name__ == "__main__":
|
| 568 |
if model_loaded:
|
| 569 |
+
demo.launch(share=False, show_error=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
else:
|
| 571 |
+
print("Error al cargar el modelo.")
|