Cristobal299 commited on
Commit
ef0f8e1
·
verified ·
1 Parent(s): 4304b42

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -534
app.py CHANGED
@@ -33,532 +33,82 @@ GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
33
  GROQ_KEY = os.environ.get("GROQ_API_KEY")
34
 
35
 
36
- # --- REFINAMIENTO DE TRADUCCIÓN CON GROQ (SENTIDO TRADICIONAL) ---
37
- def refinar_texto_con_groq(texto_literal):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  """
39
- Toma el texto literal/interlinear y lo transforma mediante Groq
40
- a un español fluido, claro y con el sentido tradicional exacto.
41
  """
42
- if not GROQ_KEY or not texto_literal.strip():
43
- return texto_literal
44
-
 
 
 
 
 
 
 
 
 
45
  sistema = (
46
- "Eres un experto en traducción bíblica y exégesis tradicional hebrea. "
47
- "Tu tarea es tomar el texto literal o interlinear proporcionado y transformarlo "
48
- "a un español fluido, claro y con el sentido tradicional exacto, "
49
- "manteniendo la profundidad, el respeto y la fidelidad al texto original sin perder naturalidad."
 
 
 
50
  )
51
-
52
  cuerpo = {
53
  "model": MODELO_ESTUDIA,
54
  "temperature": 0.3,
55
- "max_tokens": 2000,
56
  "messages": [
57
  {"role": "system", "content": sistema},
58
- {"role": "user", "content": f"Por favor, da forma y sentido natural al siguiente texto manteniendo su tradición:\n\n{texto_literal}"}
59
- ]
60
  }
61
-
62
- try:
63
- data = json.dumps(cuerpo).encode("utf-8")
64
- req = urllib.request.Request(GROQ_URL, data=data, method="POST")
65
- req.add_header("Content-Type", "application/json")
66
- req.add_header("Authorization", f"Bearer {GROQ_KEY}")
67
- with urllib.request.urlopen(req, timeout=90) as r:
68
- d = json.load(r)
69
- return (d["choices"][0]["message"]["content"] or "").strip()
70
- except Exception as e:
71
- print(f"Error refinando con Groq: {e}")
72
- return texto_literal
73
-
74
-
75
- # --- PROCESAMIENTO ACÚSTICO FFMPEG ---
76
- def procesar_audio_narrador(ruta):
77
- if not shutil.which("ffmpeg"):
78
- return ruta
79
- filtros = [
80
- "atempo=0.92",
81
- "bass=g=5:f=120",
82
- "treble=g=2",
83
- "aecho=0.8:0.88:40:0.15"
84
- ]
85
- salida = ruta[:-4] + "_narrador.mp3"
86
- cmd = ["ffmpeg", "-y", "-i", ruta, "-af", ", ".join(filtros), "-ac", "2", salida]
87
- try:
88
- subprocess.run(cmd, check=True, capture_output=True, timeout=60)
89
- if os.path.getsize(salida) > 0:
90
- return salida
91
- except Exception:
92
- pass
93
- return ruta
94
-
95
-
96
- def procesar_audio_divino(ruta):
97
- if not shutil.which("ffmpeg"):
98
- return ruta
99
- filtros = [
100
- "atempo=0.88",
101
- "asetrate=44100*0.88",
102
- "aresample=44100",
103
- "bass=g=12:f=180",
104
- "treble=g=-3",
105
- "aecho=0.85:0.9:50:0.2"
106
- ]
107
- salida = ruta[:-4] + "_divino.mp3"
108
- cmd = ["ffmpeg", "-y", "-i", ruta, "-af", ", ".join(filtros), "-ac", "2", salida]
109
- try:
110
- subprocess.run(cmd, check=True, capture_output=True, timeout=60)
111
- if os.path.getsize(salida) > 0:
112
- return salida
113
- except Exception:
114
- pass
115
- return ruta
116
-
117
-
118
- def concatenar_audios(lista_rutas):
119
- if not lista_rutas:
120
- return None
121
- if len(lista_rutas) == 1:
122
- return lista_rutas[0]
123
-
124
- salida_final = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
125
- list_file = tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False, encoding="utf-8")
126
-
127
- for r in lista_rutas:
128
- list_file.write(f"file '{os.path.abspath(r)}'\n")
129
- list_file.close()
130
-
131
- cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file.name, "-c", "copy", salida_final]
132
- try:
133
- subprocess.run(cmd, check=True, capture_output=True, timeout=120)
134
- os.remove(list_file.name)
135
- return salida_final
136
- except Exception:
137
- if os.path.exists(list_file.name):
138
- os.remove(list_file.name)
139
- return lista_rutas[0]
140
-
141
-
142
- def mezclar_fondo(voz_path):
143
- if not (os.path.exists(FONDO) and shutil.which("ffmpeg")):
144
- return voz_path
145
- salida = voz_path[:-4] + "_mix.mp3"
146
- filtro = (f"[1:a]volume={FONDO_VOL}[m];"
147
- f"[0:a][m]amix=inputs=2:duration=first:normalize=0[a]")
148
- cmd = ["ffmpeg", "-y", "-i", voz_path, "-stream_loop", "-1", "-i", FONDO,
149
- "-filter_complex", filtro, "-map", "[a]", salida]
150
- try:
151
- subprocess.run(cmd, check=True, capture_output=True, timeout=120)
152
- if os.path.getsize(salida) > 0:
153
- return salida
154
- except Exception:
155
- pass
156
- return voz_path
157
-
158
-
159
- # --- SEPARACIÓN DE BLOQUES (NARRADOR vs DIOS) PARA ESPAÑOL ---
160
- def segmentar_texto_divino(texto):
161
- patron = r'((?:Y\s+dijo\s+Dios|dijo\s+Dios|Y\s+llamó\s+Dios|Y\s+bendijo\s+Dios)[^:,.–—]*[:,.–—]?\s*)([^.\n]+)'
162
- bloques = []
163
- ultimo_idx = 0
164
-
165
- for match in re.finditer(patron, texto, flags=re.IGNORECASE):
166
- start, end = match.span()
167
- if start > ultimo_idx:
168
- bloques.append(("narrador", texto[ultimo_idx:start]))
169
-
170
- intro_dios = match.group(1)
171
- palabras_dios = match.group(2)
172
-
173
- bloques.append(("narrador", intro_dios))
174
- bloques.append(("dios", palabras_dios))
175
- ultimo_idx = end
176
-
177
- if ultimo_idx < len(texto):
178
- bloques.append(("narrador", texto[ultimo_idx:]))
179
-
180
- return bloques if bloques else [("narrador", texto)]
181
-
182
-
183
- async def generar_bloque_audio(texto, es_divino):
184
- ruta = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
185
- voz = VOZ_DIVINA if es_divino else VOZ_NARRADOR
186
- pitch = "-5Hz" if es_divino else VOZ_PITCH
187
- rate = "-9%" if es_divino else VOZ_RATE
188
 
189
- try:
190
- com = edge_tts.Communicate(texto[:4000], voz, rate=rate, pitch=pitch)
191
- await com.save(ruta)
192
- except Exception:
193
- return None
194
-
195
- if es_divino:
196
- return procesar_audio_divino(ruta)
197
- else:
198
- return procesar_audio_narrador(ruta)
199
-
200
-
201
- async def leer_es(texto):
202
- if not texto or not texto.strip():
203
- return None
204
-
205
- bloques = segmentar_texto_divino(texto)
206
- audios_segmentos = []
207
-
208
- for tipo, contenido in bloques:
209
- if contenido.strip():
210
- es_divino = (tipo == "dios")
211
- audio_seg = await generar_bloque_audio(contenido, es_divino)
212
- if audio_seg:
213
- audios_segmentos.append(audio_seg)
214
-
215
- audio_final = concatenar_audios(audios_segmentos)
216
- if audio_final:
217
- audio_final = mezclar_fondo(audio_final)
218
-
219
- return audio_final
220
-
221
-
222
- # --- REPRODUCTOR DE HEBREO LITÚRGICO REAL (TROPE) ---
223
- async def leer_he(nombre_espanol, capitulo):
224
- libro_id = id_por_nombre(nombre_espanol)
225
- if not libro_id:
226
- return None
227
-
228
- MAPEO_TORAH = {
229
- "Genesis": "01",
230
- "Exodus": "02",
231
- "Leviticus": "03",
232
- "Numbers": "04",
233
- "Deuteronomy": "05"
234
- }
235
-
236
- carpeta_audios = "audios_torah"
237
- if not os.path.exists(carpeta_audios):
238
- os.makedirs(carpeta_audios)
239
-
240
- ruta_local = os.path.join(carpeta_audios, f"{libro_id}_{capitulo}.mp3")
241
-
242
- if os.path.exists(ruta_local):
243
- return mezclar_fondo(ruta_local)
244
-
245
- if libro_id in MAPEO_TORAH:
246
- id_mechon = MAPEO_TORAH[libro_id]
247
- cap_formateado = f"{int(capitulo):02d}"
248
- url_audio = f"https://mechon-mamre.org/mp3/t{id_mechon}{cap_formateado}.mp3"
249
-
250
- try:
251
- req = urllib.request.Request(
252
- url_audio,
253
- headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
254
- )
255
- with urllib.request.urlopen(req, timeout=30) as response, open(ruta_local, 'wb') as out_file:
256
- out_file.write(response.read())
257
- return mezclar_fondo(ruta_local)
258
- except Exception as e:
259
- print(f"Error descargando el audio: {e}")
260
- return None
261
-
262
- return None
263
-
264
-
265
- # --- CARGA Y MANEJO DE LIBROS ---
266
- NOMBRES_ES = {
267
- "Genesis": "Génesis", "Exodus": "Éxodo", "Leviticus": "Levítico",
268
- "Numbers": "Números", "Deuteronomy": "Deuteronomio", "Joshua": "Josué",
269
- "Judges": "Jueces", "Ruth": "Rut", "1_Samuel": "1 Samuel", "2_Samuel": "2 Samuel",
270
- "1_Kings": "1 Reyes", "2_Kings": "2 Reyes", "1_Chronicles": "1 Crónicas",
271
- "2_Chronicles": "2 Crónicas", "Ezra": "Esdras", "Nehemiah": "Nehemías",
272
- "Esther": "Ester", "Job": "Job", "Psalms": "Salmos", "Proverbs": "Proverbios",
273
- "Ecclesiastes": "Eclesiastés", "Song_of_Songs": "Cantar de los Cantares",
274
- "Isaiah": "Isaías", "Jeremiah": "Jeremías", "Lamentations": "Lamentaciones",
275
- "Ezekiel": "Ezequiel", "Daniel": "Daniel", "Hosea": "Oseas", "Joel": "Joel",
276
- "Amos": "Amós", "Obadiah": "Abdías", "Jonah": "Jonás", "Micah": "Miqueas",
277
- "Nahum": "Nahúm", "Habakkuk": "Habacuc", "Zephaniah": "Sofonías",
278
- "Haggai": "Hageo", "Zechariah": "Zacarías", "Malachi": "Malaquías",
279
- }
280
-
281
-
282
- def _convertir_traduccion_plana(book_id: str, data: dict) -> dict:
283
- texto = data.get("translation", "") or ""
284
- lineas = [l.strip() for l in texto.split("\n") if l.strip()]
285
- versiculos = [{"n": i + 1, "he": "", "es": linea} for i, linea in enumerate(lineas)]
286
- return {
287
- "id": book_id,
288
- "es": NOMBRES_ES.get(book_id, book_id),
289
- "heb": "",
290
- "capitulos": {"1": versiculos},
291
- }
292
-
293
-
294
- def cargar_libros():
295
- libros = {}
296
- for ruta in sorted(glob.glob(os.path.join(CARPETA, "*.json"))):
297
- try:
298
- with open(ruta, encoding="utf-8") as f:
299
- d = json.load(f)
300
- book_id = os.path.splitext(os.path.basename(ruta))[0]
301
- if "capitulos" in d:
302
- lid = d.get("id") or book_id
303
- libros[lid] = d
304
- elif "translation" in d:
305
- libros[book_id] = _convertir_traduccion_plana(book_id, d)
306
- except Exception as e:
307
- print("No pude leer", ruta, e)
308
- return libros
309
-
310
-
311
- LIBROS = cargar_libros()
312
- ORDEN = ["Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy"]
313
- IDS = [i for i in ORDEN if i in LIBROS] + [i for i in LIBROS if i not in ORDEN]
314
- NOMBRES = [LIBROS[i].get("es", i) for i in IDS] or ["(sube tus libros)"]
315
-
316
-
317
- def id_por_nombre(nombre):
318
- for i in IDS:
319
- if LIBROS[i].get("es", i) == nombre:
320
- return i
321
- return IDS[0] if IDS else None
322
-
323
-
324
- def versiculos(lid, cap):
325
- return LIBROS.get(lid, {}).get("capitulos", {}).get(str(cap), [])
326
-
327
-
328
- def render(nombre, cap):
329
- lid = id_por_nombre(nombre)
330
- if not lid:
331
- return "<div class='pasaje'><p>Aún no has subido libros a la carpeta <b>libros/</b>.</p></div>", "", ""
332
- try:
333
- cap = max(1, int(float(cap or 1)))
334
- except Exception:
335
- cap = 1
336
- d = LIBROS[lid]
337
- vs = versiculos(lid, cap)
338
- if not vs:
339
- return f"<div class='pasaje'><p>No hay texto para {html.escape(d.get('es',''))} {cap}.</p></div>", "", ""
340
-
341
- plano_es, plano_he = [], []
342
- for v in vs:
343
- he_raw = html.unescape(v.get("he", "")).replace("&nbsp;", " ").replace("{פ}", "").replace("{ס}", "").strip()
344
- es_raw = html.unescape(v.get("es", "")).replace("&nbsp;", " ").strip()
345
- if he_raw:
346
- plano_he.append(he_raw)
347
- if es_raw:
348
- plano_es.append(es_raw)
349
-
350
- # Obtenemos la versión fluida y con sentido tradicional en español mediante Groq
351
- texto_bruto_es = " ".join(plano_es)
352
- texto_refinado_es = refinar_texto_con_groq(texto_bruto_es) if plano_es else ""
353
- texto_es_final = texto_refinado_es if texto_refinado_es else texto_bruto_es
354
-
355
- # Construcción de la interfaz visual con hebreo intacto y limpio
356
- filas = [f"<div class='cab'><span class='h'>{html.escape(html.unescape(d.get('heb','')))}</span><br>"
357
- f"{html.escape(d.get('es',''))} {cap}</div>"]
358
-
359
- for i, v in enumerate(vs):
360
- n_verso = v.get('n', i + 1)
361
- he_raw = html.unescape(v.get("he", "")).replace("&nbsp;", " ").replace("{פ}", "").replace("{ס}", "").strip()
362
- he_html = html.escape(he_raw)
363
-
364
- fila = f"<div class='verso'><span class='num'>{n_verso}</span>"
365
- if he_html:
366
- fila += f"<span class='he'>{he_html}</span>"
367
- fila += "</div>"
368
- filas.append(fila)
369
-
370
- # Añadir al final el bloque completo en español con sentido fluido tradicional
371
- if texto_es_final:
372
- filas.append(f"<div class='verso' style='margin-top: 20px; border-top: 1px solid rgba(255,255,255,0.15); padding-top: 15px;'><span class='es'><b>Traducción fluida tradicional:</b><br>{html.escape(texto_es_final)}</span></div>")
373
-
374
- return f"<div class='pasaje'>{''.join(filas)}</div>", texto_es_final, " ".join(plano_he)
375
-
376
-
377
- def estudiar(mensaje, historial, contexto):
378
- if not GROQ_KEY:
379
- return "Para el estudio, añade el Secret GROQ_API_KEY en el Space."
380
- sistema = (
381
- "Eres un compañero de estudio de la Torá que responde en español, cálido y honesto. "
382
- "Ofreces el sentido literal (peshat), contexto histórico y lingüístico, capas de la "
383
- "tradición (midrash, Rashi cuando venga al caso) y reflexión espiritual. Vas al grano.\n\n" + contexto
384
- )
385
- mensajes = [{"role": "system", "content": sistema}]
386
- for m in (historial or []):
387
- if isinstance(m, dict) and m.get("role") in ("user", "assistant"):
388
- mensajes.append({"role": m["role"], "content": m["content"]})
389
- mensajes.append({"role": "user", "content": mensaje})
390
- cuerpo = {"model": MODELO_ESTUDIA, "temperature": 0.4, "max_tokens": 1200, "messages": mensajes}
391
  try:
392
  data = json.dumps(cuerpo).encode("utf-8")
393
  req = urllib.request.Request(GROQ_URL, data=data, method="POST")
394
  req.add_header("Content-Type", "application/json")
395
  req.add_header("Authorization", f"Bearer {GROQ_KEY}")
396
- with urllib.request.urlopen(req, timeout=90) as r:
397
  d = json.load(r)
398
- return (d["choices"][0]["message"]["content"] or "").strip()
399
  except Exception as e:
400
- return f"No pude consultar a la IA ahora mismo ({e})."
 
401
 
 
 
 
 
 
 
402
 
403
- # ============================ INTERFAZ GRADIO ============================
404
- with gr.Blocks(theme=fenix_theme(), css=FENIX_CSS, title="Centralita Torá") as demo:
405
- st_es = gr.State("")
406
- st_he = gr.State("")
407
- st_nombre = gr.State(NOMBRES[0])
408
- st_cap = gr.State(1)
409
-
410
- gr.HTML("<div id='cabecera'><div class='estrella'>✡</div>"
411
- "<h1>Centralita Torá</h1><p>hebreo real e impecable · español fluido y natural</p></div>")
412
-
413
- with gr.Tab("Leer"):
414
- with gr.Row():
415
- dd = gr.Dropdown(NOMBRES, value=NOMBRES[0], label="Libro")
416
- ncap = gr.Number(value=1, precision=0, label="Capítulo", minimum=1)
417
- ver_btn = gr.Button("Ver capítulo", variant="primary")
418
- salida = gr.HTML()
419
- with gr.Row():
420
- b_es = gr.Button("🔊 Narrador + Voz Divina (Español)", variant="secondary")
421
- b_he = gr.Button("🔊 עברית (Hebreo con Trope Real)", variant="secondary")
422
- audio = gr.Audio(label="Audio Litúrgico", autoplay=True)
423
-
424
- def ver(nombre, cap):
425
- md, es, he = render(nombre, cap)
426
- return md, es, he, nombre, cap
427
-
428
- ver_btn.click(ver, [dd, ncap], [salida, st_es, st_he, st_nombre, st_cap])
429
- b_es.click(leer_es, st_es, audio)
430
- b_he.click(leer_he, inputs=[st_nombre, st_cap], outputs=[audio])
431
-
432
- with gr.Tab("Buscar"):
433
- q = gr.Textbox(label="Palabra o frase (hebreo o español)", placeholder="ej. luz / אור")
434
- q_btn = gr.Button("Buscar", variant="primary")
435
- q_out = gr.HTML()
436
-
437
- def buscar(texto):
438
- t = (texto or "").strip().lower()
439
- if not t:
440
- return "<p>Escribe algo para buscar.</p>"
441
- filas = []
442
- for lid in IDS:
443
- d = LIBROS[lid]
444
- for c, vs in d.get("capitulos", {}).items():
445
- for v in vs:
446
- campos = " ".join(filter(None, [v.get("es"), v.get("he")])).lower()
447
- if t in campos:
448
- ref = f"{d.get('es', lid)} {c}:{v.get('n')}"
449
- txt = html.escape(html.unescape(v.get("es") or v.get("he") or ""))
450
- filas.append(f"<div class='resultado'><span class='ref'>{ref}</span> — {txt}</div>")
451
- if len(filas) >= 120:
452
- return "".join(filas)
453
- return "".join(filas) if filas else "<p>Sin resultados en los libros cargados.</p>"
454
-
455
- q_btn.click(buscar, q, q_out)
456
-
457
- with gr.Tab("Estudiar"):
458
- gr.Markdown("La IA usa el capítulo abierto en **Leer** como contexto.")
459
- chat = gr.Chatbot(type="messages", height=360)
460
- pin = gr.Textbox(placeholder="Pregunta sobre el pasaje…", label="")
461
- with gr.Row():
462
- enviar = gr.Button("Preguntar", variant="primary")
463
- comentar = gr.Button("Comentar este capítulo", variant="secondary")
464
-
465
- def responder(mensaje, historial, es, he, nombre, cap):
466
- mensaje = (mensaje.strip() if mensaje else "")
467
- if not mensaje:
468
- return historial, ""
469
- contexto = f"Pasaje en pantalla — {nombre} {cap}:\nHebreo: {he}\nEspañol: {es}"
470
- r = estudiar(mensaje, historial, contexto)
471
- historial = (historial or []) + [
472
- {"role": "user", "content": mensaje},
473
- {"role": "assistant", "content": r},
474
- ]
475
- return historial, ""
476
-
477
- enviar.click(responder, [pin, chat, st_es, st_he, st_nombre, st_cap], [chat, pin])
478
- comentar.click(
479
- lambda h, es, he, n, c: responder("Comenta y ayúdame a estudiar este capítulo.", h, es, he, n, c),
480
- [chat, st_es, st_he, st_nombre, st_cap], [chat, pin],
481
- )
482
-
483
- with gr.Tab("Cómo subir"):
484
- gr.Markdown(
485
- "Sube un JSON por libro a la carpeta `libros/`. Para el estudio y traducción fluida, añade el Secret `GROQ_API_KEY`."
486
- )
487
-
488
- if __name__ == "__main__":
489
- demo.launch(ssr_mode=False)
490
- # -*- coding: utf-8 -*-
491
- """
492
- Centralita Torá — HuggingFace Space (Gradio)
493
- Leer hebreo real + español fluido con exégesis de Groq y audio optimizado
494
- """
495
- import os, glob, json, tempfile, html, asyncio, subprocess, shutil, re
496
- import urllib.request
497
- import gradio as gr
498
- import edge_tts
499
- try:
500
- from gtts import gTTS
501
- except Exception:
502
- gTTS = None
503
-
504
- from gradio_theme_fenix import fenix_theme, FENIX_CSS
505
-
506
- # --- CONFIGURACIÓN DE VOZ Y AUDIO ---
507
- VOZ_DIVINA = "es-ES-AlvaroNeural"
508
- VOZ_NARRADOR = "es-ES-AlvaroNeural"
509
-
510
- # Perillas de entonación para Narrador en Español
511
- VOZ_RATE = "-10%"
512
- VOZ_PITCH = "+5Hz"
513
-
514
- # Fondo musical
515
- FONDO = "fondo.mp3"
516
- FONDO_VOL = 0.18
517
-
518
- # IA de Estudio y Refinamiento (Groq)
519
- MODELO_ESTUDIA = "openai/gpt-oss-120b"
520
- CARPETA = "libros"
521
- GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
522
- GROQ_KEY = os.environ.get("GROQ_API_KEY")
523
-
524
-
525
- # --- REFINAMIENTO DE TRADUCCIÓN CON GROQ (SENTIDO TRADICIONAL) ---
526
- def refinar_texto_con_groq(texto_literal):
527
- """
528
- Toma el texto literal/interlinear y lo transforma mediante Groq
529
- a un español fluido, claro y con el sentido tradicional exacto.
530
- """
531
- if not GROQ_KEY or not texto_literal.strip():
532
- return texto_literal
533
-
534
- sistema = (
535
- "Eres un experto en traducción bíblica y exégesis tradicional hebrea. "
536
- "Tu tarea es tomar el texto literal o interlinear proporcionado y transformarlo "
537
- "a un español fluido, claro y con el sentido tradicional exacto, "
538
- "manteniendo la profundidad, el respeto y la fidelidad al texto original sin perder naturalidad."
539
- )
540
-
541
- cuerpo = {
542
- "model": MODELO_ESTUDIA,
543
- "temperature": 0.3,
544
- "max_tokens": 2000,
545
- "messages": [
546
- {"role": "system", "content": sistema},
547
- {"role": "user", "content": f"Por favor, da forma y sentido natural al siguiente texto manteniendo su tradición:\n\n{texto_literal}"}
548
- ]
549
- }
550
-
551
- try:
552
- data = json.dumps(cuerpo).encode("utf-8")
553
- req = urllib.request.Request(GROQ_URL, data=data, method="POST")
554
- req.add_header("Content-Type", "application/json")
555
- req.add_header("Authorization", f"Bearer {GROQ_KEY}")
556
- with urllib.request.urlopen(req, timeout=90) as r:
557
- d = json.load(r)
558
- return (d["choices"][0]["message"]["content"] or "").strip()
559
- except Exception as e:
560
- print(f"Error refinando con Groq: {e}")
561
- return texto_literal
562
 
563
 
564
  # --- PROCESAMIENTO ACÚSTICO FFMPEG ---
@@ -827,39 +377,42 @@ def render(nombre, cap):
827
  if not vs:
828
  return f"<div class='pasaje'><p>No hay texto para {html.escape(d.get('es',''))} {cap}.</p></div>", "", ""
829
 
830
- plano_es, plano_he = [], []
831
- for v in vs:
832
- he_raw = html.unescape(v.get("he", "")).replace("&nbsp;", " ").replace("{פ}", "").replace("{ס}", "").strip()
833
- es_raw = html.unescape(v.get("es", "")).replace("&nbsp;", " ").strip()
 
 
 
 
834
  if he_raw:
835
  plano_he.append(he_raw)
836
- if es_raw:
837
- plano_es.append(es_raw)
838
-
839
- # Obtenemos la versión fluida y con sentido tradicional en español mediante Groq
840
- texto_bruto_es = " ".join(plano_es)
841
- texto_refinado_es = refinar_texto_con_groq(texto_bruto_es) if plano_es else ""
842
- texto_es_final = texto_refinado_es if texto_refinado_es else texto_bruto_es
843
 
844
- # Construcción de la interfaz visual con hebreo intacto y limpio
845
- filas = [f"<div class='cab'><span class='h'>{html.escape(html.unescape(d.get('heb','')))}</span><br>"
 
 
 
 
846
  f"{html.escape(d.get('es',''))} {cap}</div>"]
847
-
848
- for i, v in enumerate(vs):
849
- n_verso = v.get('n', i + 1)
850
- he_raw = html.unescape(v.get("he", "")).replace("&nbsp;", " ").replace("{פ}", "").replace("{ס}", "").strip()
851
- he_html = html.escape(he_raw)
852
-
 
853
  fila = f"<div class='verso'><span class='num'>{n_verso}</span>"
854
- if he_html:
855
- fila += f"<span class='he'>{he_html}</span>"
 
 
856
  fila += "</div>"
857
  filas.append(fila)
858
-
859
- # Añadir al final el bloque completo en español con sentido fluido tradicional
860
- if texto_es_final:
861
- filas.append(f"<div class='verso' style='margin-top: 20px; border-top: 1px solid rgba(255,255,255,0.15); padding-top: 15px;'><span class='es'><b>Traducción fluida tradicional:</b><br>{html.escape(texto_es_final)}</span></div>")
862
-
863
  return f"<div class='pasaje'>{''.join(filas)}</div>", texto_es_final, " ".join(plano_he)
864
 
865
 
@@ -935,7 +488,7 @@ with gr.Blocks(theme=fenix_theme(), css=FENIX_CSS, title="Centralita Torá") as
935
  campos = " ".join(filter(None, [v.get("es"), v.get("he")])).lower()
936
  if t in campos:
937
  ref = f"{d.get('es', lid)} {c}:{v.get('n')}"
938
- txt = html.escape(html.unescape(v.get("es") or v.get("he") or ""))
939
  filas.append(f"<div class='resultado'><span class='ref'>{ref}</span> — {txt}</div>")
940
  if len(filas) >= 120:
941
  return "".join(filas)
@@ -976,4 +529,3 @@ with gr.Blocks(theme=fenix_theme(), css=FENIX_CSS, title="Centralita Torá") as
976
 
977
  if __name__ == "__main__":
978
  demo.launch(ssr_mode=False)
979
-
 
33
  GROQ_KEY = os.environ.get("GROQ_API_KEY")
34
 
35
 
36
+ def _limpiar_entidades(s: str) -> str:
37
+ """Deshace entidades HTML aunque vengan DOBLEMENTE escapadas
38
+ (p.ej. '&amp;thinsp;' -> ' '), que es lo que rompía el hebreo en pantalla
39
+ mostrando literalmente '&thinsp;'."""
40
+ prev = None
41
+ out = s or ""
42
+ for _ in range(3):
43
+ if out == prev:
44
+ break
45
+ prev = out
46
+ out = html.unescape(out)
47
+ return out
48
+
49
+
50
+ # --- TRADUCCIÓN CON SENTIDO (GROQ), VERSÍCULO POR VERSÍCULO ---
51
+ # Groq traduce DESDE EL HEBREO (fuente segura, siempre presente) a un español
52
+ # fluido y con sentido tradicional, devolviendo UNA LÍNEA POR VERSÍCULO. Así el
53
+ # mismo texto con sentido se muestra alineado y se usa EXACTAMENTE en el audio.
54
+ def traducir_capitulo_con_groq(pares):
55
  """
56
+ pares: lista de (n, hebreo, es_literal). Devuelve dict {n: español_con_sentido}.
57
+ Si Groq no está disponible o falla, cae al literal español (o al hebreo).
58
  """
59
+ fallback = {n: (es or he) for (n, he, es) in pares}
60
+ if not GROQ_KEY or not pares:
61
+ return fallback
62
+
63
+ # Bloque de entrada numerado: el hebreo es la fuente; el literal español,
64
+ # si existe, va solo como ayuda.
65
+ lineas_in = []
66
+ for (n, he, es) in pares:
67
+ ayuda = f" (ayuda literal: {es})" if es else ""
68
+ lineas_in.append(f"[{n}] {he}{ayuda}")
69
+ entrada = "\n".join(lineas_in)
70
+
71
  sistema = (
72
+ "Eres un experto en traducción bíblica del hebreo y en exégesis tradicional. "
73
+ "Traduces cada versículo hebreo a un español fluido, claro y natural, "
74
+ "con el sentido tradicional exacto, sin perder fidelidad ni profundidad. "
75
+ "Reglas de salida ESTRICTAS: devuelve SOLO las traducciones, una por línea, "
76
+ "cada línea empezando por el número entre corchetes tal cual: '[N] traducción'. "
77
+ "No incluyas el texto hebreo, ni títulos, ni comentarios, ni notas. "
78
+ "Conserva el mismo número de versículos que recibas."
79
  )
80
+ max_tok = min(8000, max(1500, len(pares) * 90))
81
  cuerpo = {
82
  "model": MODELO_ESTUDIA,
83
  "temperature": 0.3,
84
+ "max_tokens": max_tok,
85
  "messages": [
86
  {"role": "system", "content": sistema},
87
+ {"role": "user", "content": f"Traduce con sentido cada versículo:\n\n{entrada}"},
88
+ ],
89
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  try:
92
  data = json.dumps(cuerpo).encode("utf-8")
93
  req = urllib.request.Request(GROQ_URL, data=data, method="POST")
94
  req.add_header("Content-Type", "application/json")
95
  req.add_header("Authorization", f"Bearer {GROQ_KEY}")
96
+ with urllib.request.urlopen(req, timeout=120) as r:
97
  d = json.load(r)
98
+ salida = (d["choices"][0]["message"]["content"] or "").strip()
99
  except Exception as e:
100
+ print(f"Error traduciendo con Groq: {e}")
101
+ return fallback
102
 
103
+ # Parseamos las líneas '[N] texto' a un diccionario por versículo.
104
+ res = {}
105
+ for linea in salida.splitlines():
106
+ m = re.match(r"\s*\[?(\d+)\]?[\.\)\|:\-]?\s*(.+)$", linea.strip())
107
+ if m:
108
+ res[int(m.group(1))] = m.group(2).strip()
109
 
110
+ # Si Groq se saltó algún versículo, se completa con el fallback.
111
+ return {n: res.get(n, fallback[n]) for (n, he, es) in pares}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
 
114
  # --- PROCESAMIENTO ACÚSTICO FFMPEG ---
 
377
  if not vs:
378
  return f"<div class='pasaje'><p>No hay texto para {html.escape(d.get('es',''))} {cap}.</p></div>", "", ""
379
 
380
+ # Recopilamos (n, hebreo_limpio, español_literal) por versículo.
381
+ pares = []
382
+ plano_he = []
383
+ for i, v in enumerate(vs):
384
+ n_verso = v.get('n', i + 1)
385
+ he_raw = _limpiar_entidades(v.get("he", "")).replace("&nbsp;", " ").replace("{פ}", "").replace("{ס}", "").strip()
386
+ es_raw = _limpiar_entidades(v.get("es", "")).replace("&nbsp;", " ").strip()
387
+ pares.append((n_verso, he_raw, es_raw))
388
  if he_raw:
389
  plano_he.append(he_raw)
 
 
 
 
 
 
 
390
 
391
+ # Groq da SENTIDO a las palabras ANTES de mostrarlas: traduce el capítulo
392
+ # desde el hebreo, versículo por versículo.
393
+ es_por_verso = traducir_capitulo_con_groq(pares)
394
+
395
+ # Interfaz: hebreo intacto arriba y, debajo, la traducción con sentido.
396
+ filas = [f"<div class='cab'><span class='h'>{html.escape(_limpiar_entidades(d.get('heb','')))}</span><br>"
397
  f"{html.escape(d.get('es',''))} {cap}</div>"]
398
+
399
+ partes_es = []
400
+ for (n_verso, he_raw, es_raw) in pares:
401
+ es_sentido = (es_por_verso.get(n_verso) or es_raw or "").strip()
402
+ if es_sentido:
403
+ partes_es.append(es_sentido)
404
+
405
  fila = f"<div class='verso'><span class='num'>{n_verso}</span>"
406
+ if he_raw:
407
+ fila += f"<span class='he'>{html.escape(he_raw)}</span>"
408
+ if es_sentido:
409
+ fila += f"<span class='es'>{html.escape(es_sentido)}</span>"
410
  fila += "</div>"
411
  filas.append(fila)
412
+
413
+ # Texto que se locuta = exactamente la traducción con sentido de todo el capítulo.
414
+ texto_es_final = " ".join(partes_es)
415
+
 
416
  return f"<div class='pasaje'>{''.join(filas)}</div>", texto_es_final, " ".join(plano_he)
417
 
418
 
 
488
  campos = " ".join(filter(None, [v.get("es"), v.get("he")])).lower()
489
  if t in campos:
490
  ref = f"{d.get('es', lid)} {c}:{v.get('n')}"
491
+ txt = html.escape(_limpiar_entidades(v.get("es") or v.get("he") or ""))
492
  filas.append(f"<div class='resultado'><span class='ref'>{ref}</span> — {txt}</div>")
493
  if len(filas) >= 120:
494
  return "".join(filas)
 
529
 
530
  if __name__ == "__main__":
531
  demo.launch(ssr_mode=False)