Cristobal299 commited on
Commit
749bb0b
·
verified ·
1 Parent(s): 7e78175

Upload centralita_app.py

Browse files
Files changed (1) hide show
  1. centralita_app.py +470 -0
centralita_app.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Centralita Torá — HuggingFace Space (Gradio)
4
+ Leer hebreo + español · escuchar (Canto Gregoriano-Hebraico con Voz Divina Especial)
5
+ """
6
+ import os, glob, json, tempfile, html, asyncio, subprocess, shutil, re
7
+ import urllib.request
8
+ import gradio as gr
9
+ import edge_tts
10
+ try:
11
+ from gtts import gTTS
12
+ except Exception:
13
+ gTTS = None
14
+
15
+ from gradio_theme_fenix import fenix_theme, FENIX_CSS
16
+
17
+ # --- CONFIGURACIÓN DE VOZ Y CANTO ---
18
+ CANTO_GREGORIANO_HEBRAICO = True
19
+
20
+ VOZ_DIVINA = "es-ES-AlvaroNeural"
21
+ VOZ_NARRADOR = "es-ES-AlvaroNeural" # Usamos Álvaro con procesamiento acústico sagrado especial
22
+
23
+ VOZ_HE = "he-IL-AvriNeural"
24
+
25
+ # Perillas de entonación para Narrador
26
+ VOZ_RATE = "-10%"
27
+ VOZ_PITCH = "+5Hz"
28
+
29
+ # Fondo musical
30
+ FONDO = "fondo.mp3"
31
+ FONDO_VOL = 0.18
32
+
33
+ # IA de Estudio (Groq)
34
+ MODELO_ESTUDIA = "openai/gpt-oss-120b"
35
+ CARPETA = "libros"
36
+ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
37
+ GROQ_KEY = os.environ.get("GROQ_API_KEY")
38
+
39
+
40
+ # --- MOTOR FONÉTICO GREGORIANO-HEBRAICO ---
41
+ def transformar_a_canto_gregoriano_hebraico(texto_sagrado: str) -> str:
42
+ if not texto_sagrado:
43
+ return ""
44
+
45
+ texto = texto_sagrado
46
+
47
+ # Melismas gregorianos en vocales tónicas
48
+ melismas = {
49
+ 'á': 'a-a-a-a', 'é': 'e-e-e-e', 'í': 'i-i-i-i',
50
+ 'ó': 'o-o-o-o', 'ú': 'u-u-u-u',
51
+ 'Á': 'A-a-a-a', 'É': 'E-e-e-e', 'Í': 'I-i-i-i',
52
+ 'Ó': 'O-o-o-o', 'Ú': 'U-u-u-u',
53
+ }
54
+ for vocal_con_tilde, melisma in melismas.items():
55
+ texto = texto.replace(vocal_con_tilde, melisma)
56
+
57
+ # Cierres litúrgicos
58
+ def cierre_liturgico(match):
59
+ vocal = match.group(1)
60
+ puntuacion = match.group(2)
61
+ return f"{vocal}-{vocal}-{vocal}{puntuacion} ... "
62
+
63
+ texto = re.sub(r'([aeiouAEIOU])([,.:;])', cierre_liturgico, texto)
64
+
65
+ # Énfasis místico
66
+ texto = re.sub(r'\bDios\b', 'Di-o-o-os', texto, flags=re.IGNORECASE)
67
+ texto = re.sub(r'\bSeñor\b', 'Se-ñoo-or', texto, flags=re.IGNORECASE)
68
+ texto = re.sub(r'\bIsrael\b', 'Is-ra-e-el', texto, flags=re.IGNORECASE)
69
+
70
+ return texto
71
+
72
+
73
+ # --- PROCESAMIENTO ACÚSTICO FFMEPG ---
74
+ def procesar_audio_narrador(ruta):
75
+ """Efecto catedral estándar para el narrador."""
76
+ if not shutil.which("ffmpeg"):
77
+ return ruta
78
+
79
+ filtros = [
80
+ "atempo=0.22",
81
+ "bass=g=8:f=133",
82
+ "treble=g=-22",
83
+ "vibrato=f=3.5:d=0.55",
84
+ "aecho=0.75:0.70:120|240:0.4|0.25"
85
+ ]
86
+ salida = ruta[:-4] + "_narrador.mp3"
87
+ cmd = ["ffmpeg", "-y", "-i", ruta, "-af", ", ".join(filtros), "-ac", "2", salida]
88
+ try:
89
+ subprocess.run(cmd, check=True, capture_output=True, timeout=60)
90
+ if os.path.getsize(salida) > 0:
91
+ return salida
92
+ except Exception:
93
+ pass
94
+ return ruta
95
+
96
+
97
+ def procesar_audio_divino(ruta):
98
+ """
99
+ Efecto ACÚSTICO SAGRADO Y PROFUNDO para la Voz de Dios.
100
+ Tono más grave, resonancia sub-bass, eco más amplio y pureza vocal.
101
+ """
102
+ if not shutil.which("ffmpeg"):
103
+ return ruta
104
+
105
+ filtros = [
106
+ "atempo=0.80", # Más pausado y solemne
107
+ "asetrate=44100*0.45", # Bajar tono (más grave y imponente)
108
+ "aresample=144000", # Reajustar sample rate
109
+ "bass=g=15:f=200", # Graves profundos sub-bass
110
+ "treble=g=-10", # Sonido cálido, sin aristas agudas
111
+
112
+ ]
113
+ salida = ruta[:-4] + "_divino.mp3"
114
+ cmd = ["ffmpeg", "-y", "-i", ruta, "-af", ", ".join(filtros), "-ac", "2", salida]
115
+ try:
116
+ subprocess.run(cmd, check=True, capture_output=True, timeout=60)
117
+ if os.path.getsize(salida) > 0:
118
+ return salida
119
+ except Exception:
120
+ pass
121
+ return ruta
122
+
123
+
124
+ def concatenar_audios(lista_rutas):
125
+ """Concatena varios archivos MP3 en uno solo en orden estricto."""
126
+ if not lista_rutas:
127
+ return None
128
+ if len(lista_rutas) == 1:
129
+ return lista_rutas[0]
130
+
131
+ salida_final = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
132
+ list_file = tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False, encoding="utf-8")
133
+
134
+ for r in lista_rutas:
135
+ list_file.write(f"file '{os.path.abspath(r)}'\n")
136
+ list_file.close()
137
+
138
+ cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file.name, "-c", "copy", salida_final]
139
+ try:
140
+ subprocess.run(cmd, check=True, capture_output=True, timeout=120)
141
+ os.remove(list_file.name)
142
+ return salida_final
143
+ except Exception:
144
+ if os.path.exists(list_file.name):
145
+ os.remove(list_file.name)
146
+ return lista_rutas[0]
147
+
148
+
149
+ def mezclar_fondo(voz_path):
150
+ if not (os.path.exists(FONDO) and shutil.which("ffmpeg")):
151
+ return voz_path
152
+ salida = voz_path[:-4] + "_mix.mp3"
153
+ filtro = (f"[1:a]volume={FONDO_VOL}[m];"
154
+ f"[0:a][m]amix=inputs=2:duration=first:normalize=0[a]")
155
+ cmd = ["ffmpeg", "-y", "-i", voz_path, "-stream_loop", "-1", "-i", FONDO,
156
+ "-filter_complex", filtro, "-map", "[a]", salida]
157
+ try:
158
+ subprocess.run(cmd, check=True, capture_output=True, timeout=120)
159
+ if os.path.getsize(salida) > 0:
160
+ return salida
161
+ except Exception:
162
+ pass
163
+ return voz_path
164
+
165
+
166
+ # --- SEPARACIÓN DE BLOQUES (NARRADOR vs DIOS) ---
167
+ def segmentar_texto_divino(texto):
168
+ """
169
+ Detecta patrones como 'Y dijo Dios: ...' o 'Dijo Dios ...'
170
+ y divide el texto en partes ('narrador' o 'dios').
171
+ """
172
+ patron = r'((?:Y\s+dijo\s+Dios|dijo\s+Dios|Y\s+llamó\s+Dios|Y\s+bendijo\s+Dios)[^:,.–—]*[:,.–—]?\s*)([^.\n]+)'
173
+ bloques = []
174
+ ultimo_idx = 0
175
+
176
+ for match in re.finditer(patron, texto, flags=re.IGNORECASE):
177
+ start, end = match.span()
178
+ if start > ultimo_idx:
179
+ bloques.append(("narrador", texto[ultimo_idx:start]))
180
+
181
+ intro_dios = match.group(1) # Ej: "Y dijo Dios: "
182
+ palabras_dios = match.group(2) # Ej: "Sea la luz"
183
+
184
+ bloques.append(("narrador", intro_dios))
185
+ bloques.append(("dios", palabras_dios))
186
+ ultimo_idx = end
187
+
188
+ if ultimo_idx < len(texto):
189
+ bloques.append(("narrador", texto[ultimo_idx:]))
190
+
191
+ return bloques if bloques else [("narrador", texto)]
192
+
193
+
194
+ # --- GENERACIÓN DE AUDIO DINÁMICA ---
195
+ async def generar_bloque_audio(texto, es_divino):
196
+ texto_tts = transformar_a_canto_gregoriano_hebraico(texto) if CANTO_GREGORIANO_HEBRAICO else texto
197
+ ruta = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
198
+
199
+ voz = VOZ_DIVINA if es_divino else VOZ_NARRADOR
200
+ pitch = "-5Hz" if es_divino else VOZ_PITCH
201
+ rate = "-9%" if es_divino else VOZ_RATE
202
+
203
+ try:
204
+ com = edge_tts.Communicate(texto_tts[:4000], voz, rate=rate, pitch=pitch)
205
+ await com.save(ruta)
206
+ except Exception:
207
+ return None
208
+
209
+ if es_divino:
210
+ return procesar_audio_divino(ruta)
211
+ else:
212
+ return procesar_audio_narrador(ruta)
213
+
214
+
215
+ async def a_voz(texto, idioma):
216
+ if not texto or not texto.strip():
217
+ return None
218
+
219
+ if idioma == "he":
220
+ ruta = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
221
+ try:
222
+ com = edge_tts.Communicate(texto[:4000], VOZ_HE, rate=VOZ_RATE, pitch=VOZ_PITCH)
223
+ await com.save(ruta)
224
+ return mezclar_fondo(ruta)
225
+ except Exception:
226
+ return None
227
+
228
+ # Procesamiento para Español con Voz Divina Diferenciada
229
+ bloques = segmentar_texto_divino(texto)
230
+ audios_segmentos = []
231
+
232
+ for tipo, contenido in bloques:
233
+ if contenido.strip():
234
+ es_divino = (tipo == "dios")
235
+ audio_seg = await generar_bloque_audio(contenido, es_divino)
236
+ if audio_seg:
237
+ audios_segmentos.append(audio_seg)
238
+
239
+ audio_final = concatenar_audios(audios_segmentos)
240
+ if audio_final:
241
+ audio_final = mezclar_fondo(audio_final)
242
+
243
+ return audio_final
244
+
245
+
246
+ async def leer_es(t):
247
+ return await a_voz(t, "es")
248
+
249
+
250
+ async def leer_he(t):
251
+ return await a_voz(t, "he")
252
+
253
+
254
+ # --- CARGA Y MANEJO DE LIBROS ---
255
+ # Nombres de libros en español, para mostrar lindo en el desplegable
256
+ # aunque el archivo se llame en inglés (Genesis.json, Exodus.json, etc.)
257
+ NOMBRES_ES = {
258
+ "Genesis": "Génesis", "Exodus": "Éxodo", "Leviticus": "Levítico",
259
+ "Numbers": "Números", "Deuteronomy": "Deuteronomio", "Joshua": "Josué",
260
+ "Judges": "Jueces", "Ruth": "Rut", "1_Samuel": "1 Samuel", "2_Samuel": "2 Samuel",
261
+ "1_Kings": "1 Reyes", "2_Kings": "2 Reyes", "1_Chronicles": "1 Crónicas",
262
+ "2_Chronicles": "2 Crónicas", "Ezra": "Esdras", "Nehemiah": "Nehemías",
263
+ "Esther": "Ester", "Job": "Job", "Psalms": "Salmos", "Proverbs": "Proverbios",
264
+ "Ecclesiastes": "Eclesiastés", "Song_of_Songs": "Cantar de los Cantares",
265
+ "Isaiah": "Isaías", "Jeremiah": "Jeremías", "Lamentations": "Lamentaciones",
266
+ "Ezekiel": "Ezequiel", "Daniel": "Daniel", "Hosea": "Oseas", "Joel": "Joel",
267
+ "Amos": "Amós", "Obadiah": "Abdías", "Jonah": "Jonás", "Micah": "Miqueas",
268
+ "Nahum": "Nahúm", "Habakkuk": "Habacuc", "Zephaniah": "Sofonías",
269
+ "Haggai": "Hageo", "Zechariah": "Zacarías", "Malachi": "Malaquías",
270
+ }
271
+
272
+
273
+ def _convertir_traduccion_plana(book_id: str, data: dict) -> dict:
274
+ """
275
+ Convierte el formato plano que genera el traductor
276
+ ({"translation": "...", "missing_strong_numbers": [...]})
277
+ a la estructura de capítulos/versículos que usa la Centralita.
278
+ No tenemos separación real de capítulos en este formato, así que
279
+ todo el libro se muestra como Capítulo 1, con una línea = un versículo.
280
+ """
281
+ texto = data.get("translation", "") or ""
282
+ lineas = [l.strip() for l in texto.split("\n") if l.strip()]
283
+ versiculos = [{"n": i + 1, "he": "", "es": linea} for i, linea in enumerate(lineas)]
284
+ return {
285
+ "id": book_id,
286
+ "es": NOMBRES_ES.get(book_id, book_id),
287
+ "heb": "",
288
+ "capitulos": {"1": versiculos},
289
+ }
290
+
291
+
292
+ def cargar_libros():
293
+ libros = {}
294
+ for ruta in sorted(glob.glob(os.path.join(CARPETA, "*.json"))):
295
+ try:
296
+ with open(ruta, encoding="utf-8") as f:
297
+ d = json.load(f)
298
+ book_id = os.path.splitext(os.path.basename(ruta))[0]
299
+ if "capitulos" in d:
300
+ # Formato completo ya listo (id/es/heb/capitulos)
301
+ lid = d.get("id") or book_id
302
+ libros[lid] = d
303
+ elif "translation" in d:
304
+ # Formato plano del traductor (translation + missing_strong_numbers)
305
+ libros[book_id] = _convertir_traduccion_plana(book_id, d)
306
+ else:
307
+ print(f"Formato no reconocido en {ruta}, se omite.")
308
+ except Exception as e:
309
+ print("No pude leer", ruta, e)
310
+ return libros
311
+
312
+
313
+ LIBROS = cargar_libros()
314
+ ORDEN = ["Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy"]
315
+ IDS = [i for i in ORDEN if i in LIBROS] + [i for i in LIBROS if i not in ORDEN]
316
+ NOMBRES = [LIBROS[i].get("es", i) for i in IDS] or ["(sube tus libros)"]
317
+
318
+
319
+ def id_por_nombre(nombre):
320
+ for i in IDS:
321
+ if LIBROS[i].get("es", i) == nombre:
322
+ return i
323
+ return IDS[0] if IDS else None
324
+
325
+
326
+ def versiculos(lid, cap):
327
+ return LIBROS.get(lid, {}).get("capitulos", {}).get(str(cap), [])
328
+
329
+
330
+ def render(nombre, cap):
331
+ lid = id_por_nombre(nombre)
332
+ if not lid:
333
+ return "<div class='pasaje'><p>Aún no has subido libros a la carpeta <b>libros/</b>.</p></div>", "", ""
334
+ try:
335
+ cap = max(1, int(float(cap or 1)))
336
+ except Exception:
337
+ cap = 1
338
+ d = LIBROS[lid]
339
+ vs = versiculos(lid, cap)
340
+ if not vs:
341
+ return f"<div class='pasaje'><p>No hay texto para {html.escape(d.get('es',''))} {cap}.</p></div>", "", ""
342
+ filas = [f"<div class='cab'><span class='h'>{html.escape(d.get('heb',''))}</span><br>"
343
+ f"{html.escape(d.get('es',''))} {cap}</div>"]
344
+ plano_es, plano_he = [], []
345
+ for v in vs:
346
+ he = html.escape(v.get("he", "")); es = html.escape(v.get("es", ""))
347
+ fila = f"<div class='verso'><span class='num'>{v.get('n','')}</span>"
348
+ if he:
349
+ fila += f"<span class='he'>{he}</span>"; plano_he.append(v.get("he", ""))
350
+ if es:
351
+ fila += f"<span class='es'>{es}</span>"; plano_es.append(v.get("es", ""))
352
+ fila += "</div>"
353
+ filas.append(fila)
354
+ return f"<div class='pasaje'>{''.join(filas)}</div>", " ".join(plano_es), " ".join(plano_he)
355
+
356
+
357
+ def estudiar(mensaje, historial, contexto):
358
+ if not GROQ_KEY:
359
+ return "Para el estudio, añade el Secret GROQ_API_KEY en el Space."
360
+ sistema = (
361
+ "Eres un compañero de estudio de la Torá que responde en español, cálido y honesto. "
362
+ "Ofreces el sentido literal (peshat), contexto histórico y lingüístico, capas de la "
363
+ "tradición (midrash, Rashi cuando venga al caso) y reflexión espiritual. Vas al grano.\n\n" + contexto
364
+ )
365
+ mensajes = [{"role": "system", "content": sistema}]
366
+ for m in (historial or []):
367
+ if isinstance(m, dict) and m.get("role") in ("user", "assistant"):
368
+ mensajes.append({"role": m["role"], "content": m["content"]})
369
+ mensajes.append({"role": "user", "content": mensaje})
370
+ cuerpo = {"model": MODELO_ESTUDIA, "temperature": 0.4, "max_tokens": 1200, "messages": mensajes}
371
+ try:
372
+ data = json.dumps(cuerpo).encode("utf-8")
373
+ req = urllib.request.Request(GROQ_URL, data=data, method="POST")
374
+ req.add_header("Content-Type", "application/json")
375
+ req.add_header("Authorization", f"Bearer {GROQ_KEY}")
376
+ with urllib.request.urlopen(req, timeout=90) as r:
377
+ d = json.load(r)
378
+ return (d["choices"][0]["message"]["content"] or "").strip()
379
+ except Exception as e:
380
+ return f"No pude consultar a la IA ahora mismo ({e})."
381
+
382
+
383
+ # ============================ INTERFAZ GRADIO ============================
384
+ with gr.Blocks(theme=fenix_theme(), css=FENIX_CSS, title="Centralita Torá") as demo:
385
+ st_es = gr.State("")
386
+ st_he = gr.State("")
387
+ st_nombre = gr.State(NOMBRES[0])
388
+ st_cap = gr.State(1)
389
+
390
+ gr.HTML("<div id='cabecera'><div class='estrella'>✡</div>"
391
+ "<h1>Centralita Torá</h1><p>hebreo y español · canto Trope con voz celectial diferenciada</p></div>")
392
+
393
+ with gr.Tab("Leer"):
394
+ with gr.Row():
395
+ dd = gr.Dropdown(NOMBRES, value=NOMBRES[0], label="Libro")
396
+ ncap = gr.Number(value=1, precision=0, label="Capítulo", minimum=1)
397
+ ver_btn = gr.Button("Ver capítulo", variant="primary")
398
+ salida = gr.HTML()
399
+ with gr.Row():
400
+ b_es = gr.Button("🔊 Canto Trope + Voz celectial", variant="secondary")
401
+ b_he = gr.Button("🔊 עברית (Hebreo)", variant="secondary")
402
+ audio = gr.Audio(label="Audio Litúrgico", autoplay=True)
403
+
404
+ def ver(nombre, cap):
405
+ md, es, he = render(nombre, cap)
406
+ return md, es, he, nombre, cap
407
+
408
+ ver_btn.click(ver, [dd, ncap], [salida, st_es, st_he, st_nombre, st_cap])
409
+ b_es.click(leer_es, st_es, audio)
410
+ b_he.click(leer_he, st_he, audio)
411
+
412
+ with gr.Tab("Buscar"):
413
+ q = gr.Textbox(label="Palabra o frase (hebreo o español)", placeholder="ej. luz / אור")
414
+ q_btn = gr.Button("Buscar", variant="primary")
415
+ q_out = gr.HTML()
416
+
417
+ def buscar(texto):
418
+ t = (texto or "").strip().lower()
419
+ if not t:
420
+ return "<p>Escribe algo para buscar.</p>"
421
+ filas = []
422
+ for lid in IDS:
423
+ d = LIBROS[lid]
424
+ for c, vs in d.get("capitulos", {}).items():
425
+ for v in vs:
426
+ campos = " ".join(filter(None, [v.get("es"), v.get("he")])).lower()
427
+ if t in campos:
428
+ ref = f"{d.get('es', lid)} {c}:{v.get('n')}"
429
+ txt = html.escape(v.get("es") or v.get("he") or "")
430
+ filas.append(f"<div class='resultado'><span class='ref'>{ref}</span> — {txt}</div>")
431
+ if len(filas) >= 120:
432
+ return "".join(filas)
433
+ return "".join(filas) if filas else "<p>Sin resultados en los libros cargados.</p>"
434
+
435
+ q_btn.click(buscar, q, q_out)
436
+
437
+ with gr.Tab("Estudiar"):
438
+ gr.Markdown("La IA usa el capítulo abierto en **Leer** como contexto.")
439
+ chat = gr.Chatbot(type="messages", height=360)
440
+ pin = gr.Textbox(placeholder="Pregunta sobre el pasaje…", label="")
441
+ with gr.Row():
442
+ enviar = gr.Button("Preguntar", variant="primary")
443
+ comentar = gr.Button("Comentar este capítulo", variant="secondary")
444
+
445
+ def responder(mensaje, historial, es, he, nombre, cap):
446
+ mensaje = (mensaje or "").strip()
447
+ if not mensaje:
448
+ return historial, ""
449
+ contexto = f"Pasaje en pantalla — {nombre} {cap}:\nHebreo: {he}\nEspañol: {es}"
450
+ r = estudiar(mensaje, historial, contexto)
451
+ historial = (historial or []) + [
452
+ {"role": "user", "content": mensaje},
453
+ {"role": "assistant", "content": r},
454
+ ]
455
+ return historial, ""
456
+
457
+ enviar.click(responder, [pin, chat, st_es, st_he, st_nombre, st_cap], [chat, pin])
458
+ comentar.click(
459
+ lambda h, es, he, n, c: responder("Comenta y ayúdame a estudiar este capítulo.", h, es, he, n, c),
460
+ [chat, st_es, st_he, st_nombre, st_cap], [chat, pin],
461
+ )
462
+
463
+ with gr.Tab("Cómo subir"):
464
+ gr.Markdown(
465
+ "Sube un JSON por libro a la carpeta `libros/`. Para el estudio, añade el Secret `GROQ_API_KEY`."
466
+ )
467
+
468
+ if __name__ == "__main__":
469
+ demo.launch(ssr_mode=False)
470
+