Spaces:
Paused
Paused
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,952 +0,0 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
"""
|
| 3 |
-
Centralita Torá — HuggingFace Space (Gradio)
|
| 4 |
-
Leer hebreo real + español fluido con exégesis de Groq y audio optimizado
|
| 5 |
-
"""
|
| 6 |
-
import os, glob, json, tempfile, html, asyncio, subprocess, shutil, re, time
|
| 7 |
-
import urllib.request
|
| 8 |
-
import urllib.error
|
| 9 |
-
import gradio as gr
|
| 10 |
-
import edge_tts
|
| 11 |
-
try:
|
| 12 |
-
from gtts import gTTS
|
| 13 |
-
except Exception:
|
| 14 |
-
gTTS = None
|
| 15 |
-
|
| 16 |
-
from gradio_theme_fenix import fenix_theme, FENIX_CSS
|
| 17 |
-
|
| 18 |
-
# --- CONFIGURACIÓN DE VOZ Y AUDIO ---
|
| 19 |
-
VOZ_DIVINA = "es-ES-AlvaroNeural" # voz de Dios (grave, con pitch -5Hz en generar_bloque)
|
| 20 |
-
VOZ_NARRADOR = "es-MX-JorgeNeural" # voz del narrador (distinta a la de Dios)
|
| 21 |
-
|
| 22 |
-
# Perillas de entonación para Narrador en Español
|
| 23 |
-
VOZ_RATE = "-6%"
|
| 24 |
-
VOZ_PITCH = "-22Hz"
|
| 25 |
-
|
| 26 |
-
# Fondo musical
|
| 27 |
-
FONDO = "fondo.mp3"
|
| 28 |
-
FONDO_VOL = 0.18
|
| 29 |
-
|
| 30 |
-
# IA de Estudio y Refinamiento (Groq)
|
| 31 |
-
MODELO_ESTUDIA = "openai/gpt-oss-120b"
|
| 32 |
-
CARPETA = "libros"
|
| 33 |
-
GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 34 |
-
GROQ_KEY = os.environ.get("GROQ_API_KEY")
|
| 35 |
-
|
| 36 |
-
# --- SUPABASE: LECTURA DEL TANAJ ENCUADRADO ---
|
| 37 |
-
from supabase import create_client, Client
|
| 38 |
-
|
| 39 |
-
SUPABASE_URL = os.environ.get("SUPABASE_URL") or "https://bvyzbgrokexdvrhqqrla.supabase.co"
|
| 40 |
-
SUPABASE_KEY = os.environ.get("SUPABASE_KEY") # anon/public key basta para SOLO LEER
|
| 41 |
-
TABLA_TANAJ = "traducciones" # una fila por versiculo: libro, capitulo, verso, modo, es
|
| 42 |
-
MODO_A_CARGAR = "encuadrado" # el Tanaj revisado y guardado desde tanakh-translator
|
| 43 |
-
|
| 44 |
-
_supabase: "Client | None" = None
|
| 45 |
-
if SUPABASE_URL and SUPABASE_KEY:
|
| 46 |
-
try:
|
| 47 |
-
_supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 48 |
-
except Exception as e:
|
| 49 |
-
print("No pude crear el cliente de Supabase:", e)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
def _limpiar_entidades(s: str) -> str:
|
| 53 |
-
"""Deshace entidades HTML aunque vengan DOBLEMENTE escapadas
|
| 54 |
-
(p.ej. ' ' -> ' '), que es lo que rompía el hebreo en pantalla
|
| 55 |
-
mostrando literalmente ' '."""
|
| 56 |
-
prev = None
|
| 57 |
-
out = s or ""
|
| 58 |
-
for _ in range(3):
|
| 59 |
-
if out == prev:
|
| 60 |
-
break
|
| 61 |
-
prev = out
|
| 62 |
-
out = html.unescape(out)
|
| 63 |
-
return out
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
# --- TRADUCCIÓN CON SENTIDO (GROQ), VERSÍCULO POR VERSÍCULO ---
|
| 67 |
-
# Groq traduce DESDE EL HEBREO (fuente segura, siempre presente) a un español
|
| 68 |
-
# fluido y con sentido tradicional, devolviendo UNA LÍNEA POR VERSÍCULO. Así el
|
| 69 |
-
# mismo texto con sentido se muestra alineado y se usa EXACTAMENTE en el audio.
|
| 70 |
-
def _traducir_lote_groq(pares):
|
| 71 |
-
"""
|
| 72 |
-
Traduce UN LOTE pequeño de versículos (para no chocar con el límite de
|
| 73 |
-
tokens por minuto de Groq). pares: lista de (n, hebreo, es_literal).
|
| 74 |
-
Devuelve (dict {n: español_con_sentido}, estado).
|
| 75 |
-
"""
|
| 76 |
-
fallback = {n: (es or he) for (n, he, es) in pares}
|
| 77 |
-
if not pares:
|
| 78 |
-
return fallback, "sin_pares"
|
| 79 |
-
if not GROQ_KEY:
|
| 80 |
-
return fallback, "sin_key"
|
| 81 |
-
|
| 82 |
-
# Bloque de entrada numerado: el hebreo es la fuente; el literal español,
|
| 83 |
-
# si existe, va solo como ayuda.
|
| 84 |
-
lineas_in = []
|
| 85 |
-
for (n, he, es) in pares:
|
| 86 |
-
ayuda = f" (ayuda literal: {es})" if es else ""
|
| 87 |
-
lineas_in.append(f"[{n}] {he}{ayuda}")
|
| 88 |
-
entrada = "\n".join(lineas_in)
|
| 89 |
-
|
| 90 |
-
sistema = (
|
| 91 |
-
"Eres un experto en traducción bíblica del hebreo y en exégesis tradicional. "
|
| 92 |
-
"Traduces cada versículo hebreo a un español fluido, claro y natural, "
|
| 93 |
-
"con el sentido tradicional exacto, sin perder fidelidad ni profundidad. "
|
| 94 |
-
"Reglas de salida ESTRICTAS: devuelve SOLO las traducciones, una por línea, "
|
| 95 |
-
"cada línea empezando por el número entre corchetes tal cual: '[N] traducción'. "
|
| 96 |
-
"No incluyas el texto hebreo, ni títulos, ni comentarios, ni notas. "
|
| 97 |
-
"Conserva el mismo número de versículos que recibas."
|
| 98 |
-
)
|
| 99 |
-
max_tok = min(2000, max(400, len(pares) * 90))
|
| 100 |
-
cuerpo = {
|
| 101 |
-
"model": MODELO_ESTUDIA,
|
| 102 |
-
"temperature": 0.3,
|
| 103 |
-
"max_tokens": max_tok,
|
| 104 |
-
"messages": [
|
| 105 |
-
{"role": "system", "content": sistema},
|
| 106 |
-
{"role": "user", "content": f"Traduce con sentido cada versículo:\n\n{entrada}"},
|
| 107 |
-
],
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
try:
|
| 111 |
-
data = json.dumps(cuerpo).encode("utf-8")
|
| 112 |
-
req = urllib.request.Request(GROQ_URL, data=data, method="POST")
|
| 113 |
-
req.add_header("Content-Type", "application/json")
|
| 114 |
-
req.add_header("Authorization", f"Bearer {GROQ_KEY}")
|
| 115 |
-
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36")
|
| 116 |
-
with urllib.request.urlopen(req, timeout=120) as r:
|
| 117 |
-
d = json.load(r)
|
| 118 |
-
salida = (d["choices"][0]["message"]["content"] or "").strip()
|
| 119 |
-
except urllib.error.HTTPError as e:
|
| 120 |
-
cuerpo_error = ""
|
| 121 |
-
try:
|
| 122 |
-
cuerpo_error = e.read().decode("utf-8", errors="replace")[:300]
|
| 123 |
-
except Exception:
|
| 124 |
-
pass
|
| 125 |
-
motivo = f"error HTTP {e.code}: {cuerpo_error or e.reason}"
|
| 126 |
-
print(f"Error traduciendo con Groq: {motivo}")
|
| 127 |
-
return fallback, motivo
|
| 128 |
-
except Exception as e:
|
| 129 |
-
motivo = f"error: {type(e).__name__}: {e}"
|
| 130 |
-
print(f"Error traduciendo con Groq: {motivo}")
|
| 131 |
-
return fallback, motivo
|
| 132 |
-
|
| 133 |
-
if not salida:
|
| 134 |
-
return fallback, "respuesta vacía de Groq"
|
| 135 |
-
|
| 136 |
-
# Parseamos las líneas '[N] texto' a un diccionario por versículo.
|
| 137 |
-
res = {}
|
| 138 |
-
for linea in salida.splitlines():
|
| 139 |
-
m = re.match(r"\s*\[?(\d+)\]?[\.\)\|:\-]?\s*(.+)$", linea.strip())
|
| 140 |
-
if m:
|
| 141 |
-
res[int(m.group(1))] = m.group(2).strip()
|
| 142 |
-
|
| 143 |
-
if not res:
|
| 144 |
-
return fallback, "no se pudo interpretar la respuesta de Groq"
|
| 145 |
-
|
| 146 |
-
# Si Groq se saltó algún versículo, se completa con el fallback.
|
| 147 |
-
final = {n: res.get(n, fallback[n]) for (n, he, es) in pares}
|
| 148 |
-
faltantes = sum(1 for (n, he, es) in pares if n not in res)
|
| 149 |
-
estado = "ok" if faltantes == 0 else f"ok (Groq omitió {faltantes} versículo(s), se completó con literal)"
|
| 150 |
-
return final, estado
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# Tamaño de lote: capítulos largos (p.ej. Génesis 1, 31 versículos) superan el
|
| 154 |
-
# límite de tokens por minuto de Groq si se mandan de una vez. Se trocea en
|
| 155 |
-
# bloques pequeños y se hacen varias llamadas, uniendo los resultados.
|
| 156 |
-
TAMANO_LOTE_GROQ = 6
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
def _segundos_de_espera(motivo_error):
|
| 160 |
-
"""Si el error es un 429 con 'Please try again in X s', devuelve X (+1s de margen)."""
|
| 161 |
-
m = re.search(r"try again in ([\d.]+)s", motivo_error)
|
| 162 |
-
if m:
|
| 163 |
-
try:
|
| 164 |
-
return float(m.group(1)) + 1.0
|
| 165 |
-
except ValueError:
|
| 166 |
-
pass
|
| 167 |
-
return None
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def traducir_capitulo_con_groq(pares):
|
| 171 |
-
"""
|
| 172 |
-
pares: lista de (n, hebreo, es_literal) de TODO el capítulo.
|
| 173 |
-
Trocea en lotes pequeños, traduce cada uno con Groq y une los resultados.
|
| 174 |
-
Si Groq responde 429 (límite de tokens por minuto), espera el tiempo que
|
| 175 |
-
Groq indica y reintenta ese lote (hasta 3 intentos) antes de rendirse.
|
| 176 |
-
Devuelve (dict {n: español_con_sentido}, estado_general).
|
| 177 |
-
"""
|
| 178 |
-
if not pares:
|
| 179 |
-
return {}, "sin_pares"
|
| 180 |
-
|
| 181 |
-
resultado = {}
|
| 182 |
-
lotes_ok = 0
|
| 183 |
-
lotes_total = 0
|
| 184 |
-
motivos_fallo = []
|
| 185 |
-
|
| 186 |
-
for i in range(0, len(pares), TAMANO_LOTE_GROQ):
|
| 187 |
-
lote = pares[i:i + TAMANO_LOTE_GROQ]
|
| 188 |
-
lotes_total += 1
|
| 189 |
-
|
| 190 |
-
parcial, estado_lote = _traducir_lote_groq(lote)
|
| 191 |
-
intentos = 1
|
| 192 |
-
while "error HTTP 429" in estado_lote and intentos < 3:
|
| 193 |
-
espera = _segundos_de_espera(estado_lote) or 8.0
|
| 194 |
-
time.sleep(espera)
|
| 195 |
-
parcial, estado_lote = _traducir_lote_groq(lote)
|
| 196 |
-
intentos += 1
|
| 197 |
-
|
| 198 |
-
resultado.update(parcial)
|
| 199 |
-
if estado_lote == "ok" or estado_lote.startswith("ok ("):
|
| 200 |
-
lotes_ok += 1
|
| 201 |
-
else:
|
| 202 |
-
motivos_fallo.append(f"versículos {lote[0][0]}-{lote[-1][0]}: {estado_lote}")
|
| 203 |
-
|
| 204 |
-
if lotes_ok == lotes_total:
|
| 205 |
-
estado_general = "ok"
|
| 206 |
-
elif lotes_ok == 0:
|
| 207 |
-
estado_general = "; ".join(motivos_fallo[:3])
|
| 208 |
-
else:
|
| 209 |
-
estado_general = (
|
| 210 |
-
f"parcial ({lotes_ok}/{lotes_total} lotes con Groq, el resto literal) — "
|
| 211 |
-
+ "; ".join(motivos_fallo[:3])
|
| 212 |
-
)
|
| 213 |
-
|
| 214 |
-
return resultado, estado_general
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
# --- PROCESAMIENTO ACÚSTICO FFMPEG ---
|
| 218 |
-
def procesar_audio_narrador(ruta):
|
| 219 |
-
if not shutil.which("ffmpeg"):
|
| 220 |
-
return ruta
|
| 221 |
-
filtros = [
|
| 222 |
-
"atempo=0.92",
|
| 223 |
-
"bass=g=5:f=120",
|
| 224 |
-
"treble=g=2",
|
| 225 |
-
"aecho=0.8:0.88:40:0.15"
|
| 226 |
-
]
|
| 227 |
-
salida = ruta[:-4] + "_narrador.mp3"
|
| 228 |
-
cmd = ["ffmpeg", "-y", "-i", ruta, "-af", ", ".join(filtros), "-ac", "2", salida]
|
| 229 |
-
try:
|
| 230 |
-
subprocess.run(cmd, check=True, capture_output=True, timeout=60)
|
| 231 |
-
if os.path.getsize(salida) > 0:
|
| 232 |
-
return salida
|
| 233 |
-
except Exception:
|
| 234 |
-
pass
|
| 235 |
-
return ruta
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
def procesar_audio_divino(ruta):
|
| 239 |
-
if not shutil.which("ffmpeg"):
|
| 240 |
-
return ruta
|
| 241 |
-
filtros = [
|
| 242 |
-
"atempo=0.90", # Más pausado y solemne
|
| 243 |
-
"asetrate=44100*0.55", # Bajar tono (más grave y imponente)
|
| 244 |
-
"aresample=144000", # Reajustar sample rate
|
| 245 |
-
"bass=g=15:f=200", # Graves profundos sub-bass
|
| 246 |
-
"treble=g=-15", # Sonido cálido, sin aristas agudas
|
| 247 |
-
"volume=2.0", # Voz divina al doble de volumen (por encima del narrador, que queda en 1.0)
|
| 248 |
-
]
|
| 249 |
-
salida = ruta[:-4] + "_divino.mp3"
|
| 250 |
-
cmd = ["ffmpeg", "-y", "-i", ruta, "-af", ", ".join(filtros), "-ac", "2", salida]
|
| 251 |
-
try:
|
| 252 |
-
subprocess.run(cmd, check=True, capture_output=True, timeout=60)
|
| 253 |
-
if os.path.getsize(salida) > 0:
|
| 254 |
-
return salida
|
| 255 |
-
except Exception:
|
| 256 |
-
pass
|
| 257 |
-
return ruta
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
def _duracion_audio(ruta):
|
| 261 |
-
"""Duración en segundos de un archivo de audio. Se usa para calcular en
|
| 262 |
-
qué instante empieza y termina cada versículo dentro del audio final, y
|
| 263 |
-
así poder iluminar la frase que se está locutando.
|
| 264 |
-
Intenta primero ffprobe (más preciso) y, si no está disponible o falla,
|
| 265 |
-
cae a parsear la salida de ffmpeg -i (que sabemos que sí existe, porque
|
| 266 |
-
ya se usa para procesar el audio en este mismo Space)."""
|
| 267 |
-
if not (ruta and os.path.exists(ruta)):
|
| 268 |
-
return 0.0
|
| 269 |
-
|
| 270 |
-
if shutil.which("ffprobe"):
|
| 271 |
-
try:
|
| 272 |
-
cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
|
| 273 |
-
"-of", "default=noprint_wrapped=1:nokey=1", ruta]
|
| 274 |
-
out = subprocess.run(cmd, capture_output=True, text=True, timeout=30).stdout.strip()
|
| 275 |
-
d = float(out)
|
| 276 |
-
if d > 0:
|
| 277 |
-
return d
|
| 278 |
-
except Exception as e:
|
| 279 |
-
print("ffprobe falló midiendo duración, uso fallback ffmpeg -i:", e)
|
| 280 |
-
|
| 281 |
-
if shutil.which("ffmpeg"):
|
| 282 |
-
try:
|
| 283 |
-
cmd = ["ffmpeg", "-i", ruta]
|
| 284 |
-
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
| 285 |
-
m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", proc.stderr)
|
| 286 |
-
if m:
|
| 287 |
-
h, mnt, s = m.groups()
|
| 288 |
-
return int(h) * 3600 + int(mnt) * 60 + float(s)
|
| 289 |
-
except Exception as e:
|
| 290 |
-
print("ffmpeg -i también falló midiendo duración:", e)
|
| 291 |
-
|
| 292 |
-
print("No pude medir la duración de", ruta, "(ni ffprobe ni ffmpeg -i funcionaron).")
|
| 293 |
-
return 0.0
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
def concatenar_audios(lista_rutas):
|
| 297 |
-
if not lista_rutas:
|
| 298 |
-
return None
|
| 299 |
-
if len(lista_rutas) == 1:
|
| 300 |
-
return lista_rutas[0]
|
| 301 |
-
|
| 302 |
-
salida_final = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
|
| 303 |
-
list_file = tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False, encoding="utf-8")
|
| 304 |
-
|
| 305 |
-
for r in lista_rutas:
|
| 306 |
-
list_file.write(f"file '{os.path.abspath(r)}'\n")
|
| 307 |
-
list_file.close()
|
| 308 |
-
|
| 309 |
-
cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file.name, "-c", "copy", salida_final]
|
| 310 |
-
try:
|
| 311 |
-
subprocess.run(cmd, check=True, capture_output=True, timeout=120)
|
| 312 |
-
os.remove(list_file.name)
|
| 313 |
-
return salida_final
|
| 314 |
-
except Exception:
|
| 315 |
-
if os.path.exists(list_file.name):
|
| 316 |
-
os.remove(list_file.name)
|
| 317 |
-
return lista_rutas[0]
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
def mezclar_fondo(voz_path):
|
| 321 |
-
if not (os.path.exists(FONDO) and shutil.which("ffmpeg")):
|
| 322 |
-
return voz_path
|
| 323 |
-
salida = voz_path[:-4] + "_mix.mp3"
|
| 324 |
-
filtro = (f"[1:a]volume={FONDO_VOL}[m];"
|
| 325 |
-
f"[0:a][m]amix=inputs=2:duration=first:normalize=0[a]")
|
| 326 |
-
cmd = ["ffmpeg", "-y", "-i", voz_path, "-stream_loop", "-1", "-i", FONDO,
|
| 327 |
-
"-filter_complex", filtro, "-map", "[a]", salida]
|
| 328 |
-
try:
|
| 329 |
-
subprocess.run(cmd, check=True, capture_output=True, timeout=120)
|
| 330 |
-
if os.path.getsize(salida) > 0:
|
| 331 |
-
return salida
|
| 332 |
-
except Exception:
|
| 333 |
-
pass
|
| 334 |
-
return voz_path
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
# --- SEPARACIÓN DE BLOQUES (NARRADOR vs DIOS) PARA ESPAÑOL ---
|
| 338 |
-
# Fórmulas de NARRACIÓN que, si aparecen dentro de lo que dice Dios, marcan
|
| 339 |
-
# que la voz divina ya terminó y vuelve el narrador (ej. "y fue así").
|
| 340 |
-
_FIN_DIOS = re.compile(
|
| 341 |
-
r'\s*(?:;?\s*y\s+(?:fue\s+as[ií]|as[ií]\s+fue|existir\s+poner\s+erguido|'
|
| 342 |
-
r'fue\s+la\s+(?:luz|tarde|ma[nñ]ana)|vio\s+Dios|ver\s+Dios).*)$',
|
| 343 |
-
flags=re.IGNORECASE)
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
def segmentar_texto_divino(texto):
|
| 347 |
-
# Verbos de "hablar" que introducen palabras de Dios (formas del literal
|
| 348 |
-
# incluidas: decir/dijo, llamar/llamó, bendecir/bendijo, ordenar, mandar...).
|
| 349 |
-
verbo = (r'(?:dijo|dice|decir|diciendo|para\s+decir|llam[óo]|llamar|'
|
| 350 |
-
r'bendijo|bendecir|habl[óo]|hablar|orden[óo]|mand[óo]|respondi[óo])')
|
| 351 |
-
patron = re.compile(
|
| 352 |
-
r'((?:y\s+)?' + verbo + r'\s+Dios|Dios\s+' + verbo + r')' # intro (narrador)
|
| 353 |
-
r'([:,.\-–—]?\s*)' # separador
|
| 354 |
-
r'([^.\n]+)', # lo que dice Dios
|
| 355 |
-
flags=re.IGNORECASE)
|
| 356 |
-
|
| 357 |
-
bloques = []
|
| 358 |
-
ultimo = 0
|
| 359 |
-
for m in patron.finditer(texto):
|
| 360 |
-
ini, fin = m.span()
|
| 361 |
-
if ini > ultimo:
|
| 362 |
-
bloques.append(("narrador", texto[ultimo:ini]))
|
| 363 |
-
|
| 364 |
-
intro = m.group(1) + (m.group(2) or "")
|
| 365 |
-
dicho = m.group(3)
|
| 366 |
-
|
| 367 |
-
# Si dentro de lo dicho aparece una fórmula de narración, la separamos.
|
| 368 |
-
corte = _FIN_DIOS.search(dicho)
|
| 369 |
-
if corte:
|
| 370 |
-
palabras_dios = dicho[:corte.start()]
|
| 371 |
-
cola_narrador = dicho[corte.start():]
|
| 372 |
-
else:
|
| 373 |
-
palabras_dios, cola_narrador = dicho, ""
|
| 374 |
-
|
| 375 |
-
bloques.append(("narrador", intro))
|
| 376 |
-
if palabras_dios.strip():
|
| 377 |
-
bloques.append(("dios", palabras_dios))
|
| 378 |
-
if cola_narrador.strip():
|
| 379 |
-
bloques.append(("narrador", cola_narrador))
|
| 380 |
-
ultimo = fin
|
| 381 |
-
|
| 382 |
-
if ultimo < len(texto):
|
| 383 |
-
bloques.append(("narrador", texto[ultimo:]))
|
| 384 |
-
|
| 385 |
-
return bloques if bloques else [("narrador", texto)]
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
async def generar_bloque_audio(texto, es_divino):
|
| 389 |
-
"""Genera el audio de un fragmento y además devuelve, palabra por palabra,
|
| 390 |
-
en qué segundo empieza y termina cada una (según los marcadores que la
|
| 391 |
-
propia voz de Edge-TTS reporta), ya reescalados para que coincidan con
|
| 392 |
-
la duraci��n final del audio después de pasar por ffmpeg (que cambia la
|
| 393 |
-
velocidad/tono con atempo, asetrate, etc.)."""
|
| 394 |
-
ruta = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False).name
|
| 395 |
-
voz = VOZ_DIVINA if es_divino else VOZ_NARRADOR
|
| 396 |
-
pitch = "-5Hz" if es_divino else VOZ_PITCH
|
| 397 |
-
rate = "-9%" if es_divino else VOZ_RATE
|
| 398 |
-
|
| 399 |
-
palabras = []
|
| 400 |
-
try:
|
| 401 |
-
com = edge_tts.Communicate(texto[:4000], voz, rate=rate, pitch=pitch)
|
| 402 |
-
with open(ruta, "wb") as f:
|
| 403 |
-
async for trozo in com.stream():
|
| 404 |
-
if trozo["type"] == "audio":
|
| 405 |
-
f.write(trozo["data"])
|
| 406 |
-
elif trozo["type"] == "WordBoundary":
|
| 407 |
-
ini = trozo["offset"] / 10_000_000 # 100ns -> segundos
|
| 408 |
-
dur = trozo["duration"] / 10_000_000
|
| 409 |
-
palabras.append({"texto": trozo["text"], "ini": ini, "fin": ini + dur})
|
| 410 |
-
except Exception as e:
|
| 411 |
-
print("Error generando audio con edge-tts:", e)
|
| 412 |
-
return None, []
|
| 413 |
-
|
| 414 |
-
dur_cruda = _duracion_audio(ruta)
|
| 415 |
-
procesada = procesar_audio_divino(ruta) if es_divino else procesar_audio_narrador(ruta)
|
| 416 |
-
dur_final = _duracion_audio(procesada)
|
| 417 |
-
escala = (dur_final / dur_cruda) if dur_cruda > 0 else 1.0
|
| 418 |
-
|
| 419 |
-
palabras = [{"texto": p["texto"], "ini": p["ini"] * escala, "fin": p["fin"] * escala} for p in palabras]
|
| 420 |
-
return procesada, palabras
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
async def leer_es(pares_es):
|
| 424 |
-
"""pares_es: lista de (n_verso, texto_es) a locutar en orden.
|
| 425 |
-
Genera el audio versículo por versículo (cada uno puede a su vez partirse
|
| 426 |
-
en narrador/dios) y devuelve, además del audio final, un timeline JSON
|
| 427 |
-
PALABRA POR PALABRA: [{"verso": n, "idx": i, "start": s, "end": s}, ...]
|
| 428 |
-
donde 'idx' es la posición de la palabra dentro del texto de ESE versículo
|
| 429 |
-
(0-based, contando por espacios, igual que se separan en pantalla), para
|
| 430 |
-
poder iluminar exactamente la palabra que se está locutando."""
|
| 431 |
-
if not pares_es:
|
| 432 |
-
return None, "[]"
|
| 433 |
-
|
| 434 |
-
audios_segmentos = []
|
| 435 |
-
timeline = []
|
| 436 |
-
t = 0.0
|
| 437 |
-
|
| 438 |
-
for n_verso, texto in pares_es:
|
| 439 |
-
texto = (texto or "").strip()
|
| 440 |
-
if not texto:
|
| 441 |
-
continue
|
| 442 |
-
bloques = segmentar_texto_divino(texto)
|
| 443 |
-
idx_verso = 0 # índice de palabra dentro del versículo, acumulado entre sus fragmentos
|
| 444 |
-
for tipo, contenido in bloques:
|
| 445 |
-
contenido = contenido.strip()
|
| 446 |
-
if not contenido:
|
| 447 |
-
continue
|
| 448 |
-
es_divino = (tipo == "dios")
|
| 449 |
-
audio_seg, palabras = await generar_bloque_audio(contenido, es_divino)
|
| 450 |
-
if not audio_seg:
|
| 451 |
-
continue
|
| 452 |
-
audios_segmentos.append(audio_seg)
|
| 453 |
-
for p in palabras:
|
| 454 |
-
timeline.append({
|
| 455 |
-
"verso": n_verso,
|
| 456 |
-
"idx": idx_verso,
|
| 457 |
-
"start": round(t + p["ini"], 3),
|
| 458 |
-
"end": round(t + p["fin"], 3),
|
| 459 |
-
})
|
| 460 |
-
idx_verso += 1
|
| 461 |
-
t += _duracion_audio(audio_seg)
|
| 462 |
-
|
| 463 |
-
audio_final = concatenar_audios(audios_segmentos)
|
| 464 |
-
if audio_final:
|
| 465 |
-
audio_final = mezclar_fondo(audio_final)
|
| 466 |
-
|
| 467 |
-
print(f"[leer_es] {len(pares_es)} versículos, {len(timeline)} palabras con timing. Ej: {timeline[:3]}")
|
| 468 |
-
|
| 469 |
-
return audio_final, json.dumps(timeline, ensure_ascii=False)
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
# --- REPRODUCTOR DE HEBREO LITÚRGICO REAL (TROPE) ---
|
| 473 |
-
async def leer_he(nombre_espanol, capitulo):
|
| 474 |
-
libro_id = id_por_nombre(nombre_espanol)
|
| 475 |
-
if not libro_id:
|
| 476 |
-
return None
|
| 477 |
-
|
| 478 |
-
MAPEO_TORAH = {
|
| 479 |
-
"Genesis": "01",
|
| 480 |
-
"Exodus": "02",
|
| 481 |
-
"Leviticus": "03",
|
| 482 |
-
"Numbers": "04",
|
| 483 |
-
"Deuteronomy": "05"
|
| 484 |
-
}
|
| 485 |
-
|
| 486 |
-
carpeta_audios = "audios_torah"
|
| 487 |
-
if not os.path.exists(carpeta_audios):
|
| 488 |
-
os.makedirs(carpeta_audios)
|
| 489 |
-
|
| 490 |
-
ruta_local = os.path.join(carpeta_audios, f"{libro_id}_{capitulo}.mp3")
|
| 491 |
-
|
| 492 |
-
if os.path.exists(ruta_local):
|
| 493 |
-
return mezclar_fondo(ruta_local)
|
| 494 |
-
|
| 495 |
-
if libro_id in MAPEO_TORAH:
|
| 496 |
-
id_mechon = MAPEO_TORAH[libro_id]
|
| 497 |
-
cap_formateado = f"{int(capitulo):02d}"
|
| 498 |
-
url_audio = f"https://mechon-mamre.org/mp3/t{id_mechon}{cap_formateado}.mp3"
|
| 499 |
-
|
| 500 |
-
try:
|
| 501 |
-
req = urllib.request.Request(
|
| 502 |
-
url_audio,
|
| 503 |
-
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 504 |
-
)
|
| 505 |
-
with urllib.request.urlopen(req, timeout=30) as response, open(ruta_local, 'wb') as out_file:
|
| 506 |
-
out_file.write(response.read())
|
| 507 |
-
return mezclar_fondo(ruta_local)
|
| 508 |
-
except Exception as e:
|
| 509 |
-
print(f"Error descargando el audio: {e}")
|
| 510 |
-
return None
|
| 511 |
-
|
| 512 |
-
return None
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
# --- CARGA Y MANEJO DE LIBROS ---
|
| 516 |
-
NOMBRES_ES = {
|
| 517 |
-
"Genesis": "Génesis", "Exodus": "Éxodo", "Leviticus": "Levítico",
|
| 518 |
-
"Numbers": "Números", "Deuteronomy": "Deuteronomio", "Joshua": "Josué",
|
| 519 |
-
"Judges": "Jueces", "Ruth": "Rut", "1_Samuel": "1 Samuel", "2_Samuel": "2 Samuel",
|
| 520 |
-
"1_Kings": "1 Reyes", "2_Kings": "2 Reyes", "1_Chronicles": "1 Crónicas",
|
| 521 |
-
"2_Chronicles": "2 Crónicas", "Ezra": "Esdras", "Nehemiah": "Nehemías",
|
| 522 |
-
"Esther": "Ester", "Job": "Job", "Psalms": "Salmos", "Proverbs": "Proverbios",
|
| 523 |
-
"Ecclesiastes": "Eclesiastés", "Song_of_Songs": "Cantar de los Cantares",
|
| 524 |
-
"Isaiah": "Isaías", "Jeremiah": "Jeremías", "Lamentations": "Lamentaciones",
|
| 525 |
-
"Ezekiel": "Ezequiel", "Daniel": "Daniel", "Hosea": "Oseas", "Joel": "Joel",
|
| 526 |
-
"Amos": "Amós", "Obadiah": "Abdías", "Jonah": "Jonás", "Micah": "Miqueas",
|
| 527 |
-
"Nahum": "Nahúm", "Habakkuk": "Habacuc", "Zephaniah": "Sofonías",
|
| 528 |
-
"Haggai": "Hageo", "Zechariah": "Zacarías", "Malachi": "Malaquías",
|
| 529 |
-
}
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
def _convertir_traduccion_plana(book_id: str, data: dict) -> dict:
|
| 533 |
-
texto = data.get("translation", "") or ""
|
| 534 |
-
lineas = [l.strip() for l in texto.split("\n") if l.strip()]
|
| 535 |
-
versiculos = [{"n": i + 1, "he": "", "es": linea} for i, linea in enumerate(lineas)]
|
| 536 |
-
return {
|
| 537 |
-
"id": book_id,
|
| 538 |
-
"es": NOMBRES_ES.get(book_id, book_id),
|
| 539 |
-
"heb": "",
|
| 540 |
-
"capitulos": {"1": versiculos},
|
| 541 |
-
}
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
def cargar_libros():
|
| 545 |
-
"""Carga los libros del Tanaj desde Supabase (tabla TABLA_TANAJ, modo=MODO_A_CARGAR,
|
| 546 |
-
actualmente 'encuadrado' = el texto revisado y guardado desde tanakh-translator).
|
| 547 |
-
Cada fila esperada = un versículo, con columnas: libro, capitulo, verso, es."""
|
| 548 |
-
libros = {}
|
| 549 |
-
|
| 550 |
-
if not _supabase:
|
| 551 |
-
print("Faltan los Secrets SUPABASE_URL / SUPABASE_KEY en el Space "
|
| 552 |
-
"(Settings → Variables and secrets). Cargando 0 libros.")
|
| 553 |
-
return _cargar_libros_locales_fallback()
|
| 554 |
-
|
| 555 |
-
# La tabla 'traducciones' guarda UNA FILA POR VERSICULO. Traemos todas las
|
| 556 |
-
# del modo pedido, paginando (Supabase corta a 1000 por defecto), y las
|
| 557 |
-
# agrupamos por libro y capitulo. El hebreo se lee de la carpeta libros/.
|
| 558 |
-
filas = []
|
| 559 |
-
desde = 0
|
| 560 |
-
PASO = 1000
|
| 561 |
-
try:
|
| 562 |
-
while True:
|
| 563 |
-
resp = (
|
| 564 |
-
_supabase.table(TABLA_TANAJ)
|
| 565 |
-
.select("libro,capitulo,verso,es")
|
| 566 |
-
.eq("modo", MODO_A_CARGAR)
|
| 567 |
-
.range(desde, desde + PASO - 1)
|
| 568 |
-
.execute()
|
| 569 |
-
)
|
| 570 |
-
lote = resp.data or []
|
| 571 |
-
filas.extend(lote)
|
| 572 |
-
if len(lote) < PASO:
|
| 573 |
-
break
|
| 574 |
-
desde += PASO
|
| 575 |
-
except Exception as e:
|
| 576 |
-
print(f"No pude leer la tabla '{TABLA_TANAJ}' en Supabase: {e}")
|
| 577 |
-
return _cargar_libros_locales_fallback()
|
| 578 |
-
|
| 579 |
-
# Hebreo por versiculo desde libros/ (para mostrarlo arriba).
|
| 580 |
-
heb_por = {}
|
| 581 |
-
for ruta in glob.glob(os.path.join(CARPETA, "*.json")):
|
| 582 |
-
try:
|
| 583 |
-
with open(ruta, encoding="utf-8") as f:
|
| 584 |
-
d = json.load(f)
|
| 585 |
-
lid = d.get("id") or os.path.splitext(os.path.basename(ruta))[0]
|
| 586 |
-
for cap, versos in d.get("capitulos", {}).items():
|
| 587 |
-
for i, v in enumerate(versos):
|
| 588 |
-
n = v.get("n", i + 1)
|
| 589 |
-
heb_por[(lid, str(cap), n)] = v.get("he", "")
|
| 590 |
-
except Exception:
|
| 591 |
-
pass
|
| 592 |
-
|
| 593 |
-
# Agrupar versiculos por libro -> capitulo -> lista ordenada.
|
| 594 |
-
tmp = {}
|
| 595 |
-
for fila in filas:
|
| 596 |
-
lid = fila.get("libro")
|
| 597 |
-
cap = str(fila.get("capitulo"))
|
| 598 |
-
n = fila.get("verso")
|
| 599 |
-
if lid is None or n is None:
|
| 600 |
-
continue
|
| 601 |
-
tmp.setdefault(lid, {}).setdefault(cap, []).append({
|
| 602 |
-
"n": n,
|
| 603 |
-
"es": fila.get("es", ""),
|
| 604 |
-
"he": heb_por.get((lid, cap, n), ""),
|
| 605 |
-
})
|
| 606 |
-
|
| 607 |
-
for lid, caps in tmp.items():
|
| 608 |
-
capitulos = {}
|
| 609 |
-
for cap, versos in caps.items():
|
| 610 |
-
capitulos[cap] = sorted(versos, key=lambda v: v["n"])
|
| 611 |
-
libros[lid] = {
|
| 612 |
-
"id": lid,
|
| 613 |
-
"es": NOMBRES_ES.get(lid, lid),
|
| 614 |
-
"heb": "",
|
| 615 |
-
"capitulos": capitulos,
|
| 616 |
-
}
|
| 617 |
-
|
| 618 |
-
if not libros:
|
| 619 |
-
print(f"Supabase respondio pero no llego ningun versiculo con modo='{MODO_A_CARGAR}' "
|
| 620 |
-
f"en la tabla '{TABLA_TANAJ}'. Revisa nombre de tabla/columnas.")
|
| 621 |
-
|
| 622 |
-
return libros
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
def _cargar_libros_locales_fallback():
|
| 626 |
-
"""Si Supabase no está configurado o falla, intenta la carpeta local libros/ como respaldo."""
|
| 627 |
-
libros = {}
|
| 628 |
-
for ruta in sorted(glob.glob(os.path.join(CARPETA, "*.json"))):
|
| 629 |
-
try:
|
| 630 |
-
with open(ruta, encoding="utf-8") as f:
|
| 631 |
-
d = json.load(f)
|
| 632 |
-
book_id = os.path.splitext(os.path.basename(ruta))[0]
|
| 633 |
-
if "capitulos" in d:
|
| 634 |
-
lid = d.get("id") or book_id
|
| 635 |
-
libros[lid] = d
|
| 636 |
-
elif "translation" in d:
|
| 637 |
-
libros[book_id] = _convertir_traduccion_plana(book_id, d)
|
| 638 |
-
except Exception as e:
|
| 639 |
-
print("No pude leer", ruta, e)
|
| 640 |
-
return libros
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
LIBROS = cargar_libros()
|
| 644 |
-
ORDEN = ["Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy"]
|
| 645 |
-
IDS = [i for i in ORDEN if i in LIBROS] + [i for i in LIBROS if i not in ORDEN]
|
| 646 |
-
NOMBRES = [LIBROS[i].get("es", i) for i in IDS] or ["(sube tus libros)"]
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
def id_por_nombre(nombre):
|
| 650 |
-
for i in IDS:
|
| 651 |
-
if LIBROS[i].get("es", i) == nombre:
|
| 652 |
-
return i
|
| 653 |
-
return IDS[0] if IDS else None
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
def versiculos(lid, cap):
|
| 657 |
-
return LIBROS.get(lid, {}).get("capitulos", {}).get(str(cap), [])
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
def _envolver_palabras(texto):
|
| 661 |
-
"""Envuelve cada palabra en un <span data-w='i'> para poder iluminarla
|
| 662 |
-
individualmente por JS, conservando los espacios tal cual entre medio."""
|
| 663 |
-
partes = re.split(r'(\s+)', texto)
|
| 664 |
-
idx = 0
|
| 665 |
-
salida = []
|
| 666 |
-
for p in partes:
|
| 667 |
-
if p == "" :
|
| 668 |
-
continue
|
| 669 |
-
if p.strip() == "":
|
| 670 |
-
salida.append(p)
|
| 671 |
-
else:
|
| 672 |
-
salida.append(f"<span class='w' data-w='{idx}'>{html.escape(p)}</span>")
|
| 673 |
-
idx += 1
|
| 674 |
-
return "".join(salida)
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
def render(nombre, cap):
|
| 678 |
-
lid = id_por_nombre(nombre)
|
| 679 |
-
if not lid:
|
| 680 |
-
return "<div class='pasaje'><p>Aún no has subido libros a la carpeta <b>libros/</b>.</p></div>", "", ""
|
| 681 |
-
try:
|
| 682 |
-
cap = max(1, int(float(cap or 1)))
|
| 683 |
-
except Exception:
|
| 684 |
-
cap = 1
|
| 685 |
-
d = LIBROS[lid]
|
| 686 |
-
vs = versiculos(lid, cap)
|
| 687 |
-
if not vs:
|
| 688 |
-
return f"<div class='pasaje'><p>No hay texto para {html.escape(d.get('es',''))} {cap}.</p></div>", "", ""
|
| 689 |
-
|
| 690 |
-
# Recopilamos (n, hebreo_limpio, español_literal) por versículo.
|
| 691 |
-
pares = []
|
| 692 |
-
plano_he = []
|
| 693 |
-
for i, v in enumerate(vs):
|
| 694 |
-
n_verso = v.get('n', i + 1)
|
| 695 |
-
he_raw = _limpiar_entidades(v.get("he", "")).replace(" ", " ").replace("{פ}", "").replace("{ס}", "").strip()
|
| 696 |
-
es_raw = _limpiar_entidades(v.get("es", "")).replace(" ", " ").strip()
|
| 697 |
-
pares.append((n_verso, he_raw, es_raw))
|
| 698 |
-
if he_raw:
|
| 699 |
-
plano_he.append(he_raw)
|
| 700 |
-
|
| 701 |
-
# El español YA viene encuadrado desde Supabase (modo='encuadrado').
|
| 702 |
-
# No se vuelve a traducir: se muestra tal cual se guardó.
|
| 703 |
-
|
| 704 |
-
# Interfaz: hebreo intacto arriba y, debajo, la traducción con sentido
|
| 705 |
-
# (sin aviso visible; el estado queda solo en los logs del Space).
|
| 706 |
-
filas = [f"<div class='cab'><span class='h'>{html.escape(_limpiar_entidades(d.get('heb','')))}</span><br>"
|
| 707 |
-
f"{html.escape(d.get('es',''))} {cap}</div>"]
|
| 708 |
-
|
| 709 |
-
partes_es = []
|
| 710 |
-
pares_es = [] # [(n_verso, texto_es)] en orden, para locutar y sincronizar el resaltado
|
| 711 |
-
for (n_verso, he_raw, es_raw) in pares:
|
| 712 |
-
es_sentido = (es_raw or "").strip()
|
| 713 |
-
if es_sentido:
|
| 714 |
-
partes_es.append(es_sentido)
|
| 715 |
-
pares_es.append((n_verso, es_sentido))
|
| 716 |
-
|
| 717 |
-
fila = f"<div class='verso' data-n='{n_verso}'><span class='num'>{n_verso}</span>"
|
| 718 |
-
if he_raw:
|
| 719 |
-
fila += f"<span class='he'>{html.escape(he_raw)}</span>"
|
| 720 |
-
if es_sentido:
|
| 721 |
-
fila += f"<span class='es'>{_envolver_palabras(es_sentido)}</span>"
|
| 722 |
-
fila += "</div>"
|
| 723 |
-
filas.append(fila)
|
| 724 |
-
|
| 725 |
-
# Texto que se locuta = exactamente la traducción con sentido de todo el capítulo.
|
| 726 |
-
texto_es_final = " ".join(partes_es)
|
| 727 |
-
|
| 728 |
-
return f"<div class='pasaje'>{''.join(filas)}</div>", texto_es_final, " ".join(plano_he), pares_es
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
def estudiar(mensaje, historial, contexto):
|
| 732 |
-
if not GROQ_KEY:
|
| 733 |
-
return "Para el estudio, añade el Secret GROQ_API_KEY en el Space."
|
| 734 |
-
sistema = (
|
| 735 |
-
"Eres un compañero de estudio de la Torá que responde en español, cálido y honesto. "
|
| 736 |
-
"Ofreces el sentido literal (peshat), contexto histórico y lingüístico, capas de la "
|
| 737 |
-
"tradición (midrash, Rashi cuando venga al caso) y reflexión espiritual. Vas al grano.\n\n" + contexto
|
| 738 |
-
)
|
| 739 |
-
mensajes = [{"role": "system", "content": sistema}]
|
| 740 |
-
for m in (historial or []):
|
| 741 |
-
if isinstance(m, dict) and m.get("role") in ("user", "assistant"):
|
| 742 |
-
mensajes.append({"role": m["role"], "content": m["content"]})
|
| 743 |
-
mensajes.append({"role": "user", "content": mensaje})
|
| 744 |
-
cuerpo = {"model": MODELO_ESTUDIA, "temperature": 0.4, "max_tokens": 1200, "messages": mensajes}
|
| 745 |
-
try:
|
| 746 |
-
data = json.dumps(cuerpo).encode("utf-8")
|
| 747 |
-
req = urllib.request.Request(GROQ_URL, data=data, method="POST")
|
| 748 |
-
req.add_header("Content-Type", "application/json")
|
| 749 |
-
req.add_header("Authorization", f"Bearer {GROQ_KEY}")
|
| 750 |
-
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36")
|
| 751 |
-
with urllib.request.urlopen(req, timeout=90) as r:
|
| 752 |
-
d = json.load(r)
|
| 753 |
-
return (d["choices"][0]["message"]["content"] or "").strip()
|
| 754 |
-
except Exception as e:
|
| 755 |
-
return f"No pude consultar a la IA ahora mismo ({e})."
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
# ============================ INTERFAZ GRADIO ============================
|
| 759 |
-
with gr.Blocks(theme=fenix_theme(), css=FENIX_CSS, title="Centralita Torá") as demo:
|
| 760 |
-
st_es = gr.State("")
|
| 761 |
-
st_he = gr.State("")
|
| 762 |
-
st_pares_es = gr.State([])
|
| 763 |
-
st_nombre = gr.State(NOMBRES[0])
|
| 764 |
-
st_cap = gr.State(1)
|
| 765 |
-
timing_box = gr.Textbox(value="[]", visible=True, container=False, elem_id="timing_data")
|
| 766 |
-
|
| 767 |
-
gr.HTML("<div id='cabecera'><div class='estrella'>✡</div>"
|
| 768 |
-
"<h1>Centralita Torá</h1><p>hebreo real e impecable · español fluido y natural</p></div>")
|
| 769 |
-
|
| 770 |
-
# Resaltado dorado, clarito y transparente, de la frase que se está locutando ahora mismo.
|
| 771 |
-
gr.HTML("""
|
| 772 |
-
<style>
|
| 773 |
-
.verso .w {
|
| 774 |
-
transition: background-color .12s ease;
|
| 775 |
-
border-radius: 3px;
|
| 776 |
-
padding: 0 1px;
|
| 777 |
-
}
|
| 778 |
-
.verso .w.activo {
|
| 779 |
-
background-color: rgba(255, 196, 64, 0.55);
|
| 780 |
-
}
|
| 781 |
-
#fenix-debug {
|
| 782 |
-
position: fixed; bottom: 6px; right: 6px; z-index: 99999;
|
| 783 |
-
background: rgba(0,0,0,0.65); color: #ffd57a;
|
| 784 |
-
font-size: 11px; padding: 4px 8px; border-radius: 6px;
|
| 785 |
-
font-family: monospace; pointer-events: none;
|
| 786 |
-
}
|
| 787 |
-
#timing_data { display: none !important; }
|
| 788 |
-
</style>
|
| 789 |
-
<div id="fenix-debug">resaltado: esperando…</div>
|
| 790 |
-
""")
|
| 791 |
-
|
| 792 |
-
with gr.Tab("Leer"):
|
| 793 |
-
with gr.Row():
|
| 794 |
-
dd = gr.Dropdown(NOMBRES, value=NOMBRES[0], label="Libro")
|
| 795 |
-
ncap = gr.Number(value=1, precision=0, label="Capítulo", minimum=1)
|
| 796 |
-
ver_btn = gr.Button("Ver capítulo", variant="primary")
|
| 797 |
-
salida = gr.HTML()
|
| 798 |
-
with gr.Row():
|
| 799 |
-
b_es = gr.Button("🔊 Narrador + Voz Divina (Español)", variant="secondary")
|
| 800 |
-
b_he = gr.Button("🔊 עברית (Hebreo con Trope Real)", variant="secondary")
|
| 801 |
-
audio = gr.Audio(label="Audio Litúrgico", autoplay=True, elem_id="tts_audio")
|
| 802 |
-
|
| 803 |
-
def ver(nombre, cap):
|
| 804 |
-
md, es, he, pares_es = render(nombre, cap)
|
| 805 |
-
return md, es, he, pares_es, nombre, cap
|
| 806 |
-
|
| 807 |
-
ver_btn.click(ver, [dd, ncap], [salida, st_es, st_he, st_pares_es, st_nombre, st_cap])
|
| 808 |
-
b_es.click(leer_es, st_pares_es, [audio, timing_box])
|
| 809 |
-
b_he.click(leer_he, inputs=[st_nombre, st_cap], outputs=[audio])
|
| 810 |
-
|
| 811 |
-
with gr.Tab("Buscar"):
|
| 812 |
-
q = gr.Textbox(label="Palabra o frase (hebreo o español)", placeholder="ej. luz / אור")
|
| 813 |
-
q_btn = gr.Button("Buscar", variant="primary")
|
| 814 |
-
q_out = gr.HTML()
|
| 815 |
-
|
| 816 |
-
def buscar(texto):
|
| 817 |
-
t = (texto or "").strip().lower()
|
| 818 |
-
if not t:
|
| 819 |
-
return "<p>Escribe algo para buscar.</p>"
|
| 820 |
-
filas = []
|
| 821 |
-
for lid in IDS:
|
| 822 |
-
d = LIBROS[lid]
|
| 823 |
-
for c, vs in d.get("capitulos", {}).items():
|
| 824 |
-
for v in vs:
|
| 825 |
-
campos = " ".join(filter(None, [v.get("es"), v.get("he")])).lower()
|
| 826 |
-
if t in campos:
|
| 827 |
-
ref = f"{d.get('es', lid)} {c}:{v.get('n')}"
|
| 828 |
-
txt = html.escape(_limpiar_entidades(v.get("es") or v.get("he") or ""))
|
| 829 |
-
filas.append(f"<div class='resultado'><span class='ref'>{ref}</span> — {txt}</div>")
|
| 830 |
-
if len(filas) >= 120:
|
| 831 |
-
return "".join(filas)
|
| 832 |
-
return "".join(filas) if filas else "<p>Sin resultados en los libros cargados.</p>"
|
| 833 |
-
|
| 834 |
-
q_btn.click(buscar, q, q_out)
|
| 835 |
-
|
| 836 |
-
with gr.Tab("Estudiar"):
|
| 837 |
-
gr.Markdown("La IA usa el capítulo abierto en **Leer** como contexto.")
|
| 838 |
-
chat = gr.Chatbot(type="messages", height=360)
|
| 839 |
-
pin = gr.Textbox(placeholder="Pregunta sobre el pasaje…", label="")
|
| 840 |
-
with gr.Row():
|
| 841 |
-
enviar = gr.Button("Preguntar", variant="primary")
|
| 842 |
-
comentar = gr.Button("Comentar este capítulo", variant="secondary")
|
| 843 |
-
|
| 844 |
-
def responder(mensaje, historial, es, he, nombre, cap):
|
| 845 |
-
mensaje = (mensaje.strip() if mensaje else "")
|
| 846 |
-
if not mensaje:
|
| 847 |
-
return historial, ""
|
| 848 |
-
contexto = f"Pasaje en pantalla — {nombre} {cap}:\nHebreo: {he}\nEspañol: {es}"
|
| 849 |
-
r = estudiar(mensaje, historial, contexto)
|
| 850 |
-
historial = (historial or []) + [
|
| 851 |
-
{"role": "user", "content": mensaje},
|
| 852 |
-
{"role": "assistant", "content": r},
|
| 853 |
-
]
|
| 854 |
-
return historial, ""
|
| 855 |
-
|
| 856 |
-
enviar.click(responder, [pin, chat, st_es, st_he, st_nombre, st_cap], [chat, pin])
|
| 857 |
-
comentar.click(
|
| 858 |
-
lambda h, es, he, n, c: responder("Comenta y ayúdame a estudiar este capítulo.", h, es, he, n, c),
|
| 859 |
-
[chat, st_es, st_he, st_nombre, st_cap], [chat, pin],
|
| 860 |
-
)
|
| 861 |
-
|
| 862 |
-
with gr.Tab("Cómo subir"):
|
| 863 |
-
gr.Markdown(
|
| 864 |
-
"Sube un JSON por libro a la carpeta `libros/`. Para el estudio y traducción fluida, añade el Secret `GROQ_API_KEY`."
|
| 865 |
-
)
|
| 866 |
-
|
| 867 |
-
demo.load(None, None, None, js="""
|
| 868 |
-
() => {
|
| 869 |
-
if (window.__fenixHighlightInterval) return;
|
| 870 |
-
|
| 871 |
-
function parsearTiempo(s) {
|
| 872 |
-
const m = (s || '').trim().match(/^(\\d{1,2}):(\\d{2})$/);
|
| 873 |
-
if (!m) return null;
|
| 874 |
-
return parseInt(m[1], 10) * 60 + parseInt(m[2], 10);
|
| 875 |
-
}
|
| 876 |
-
|
| 877 |
-
// El reproductor de audio de Gradio no usa <audio>.currentTime para la
|
| 878 |
-
// reproducción real (usa su propio motor), así que leemos el tiempo
|
| 879 |
-
// transcurrido directamente del número que se ve en pantalla (ej "2:42").
|
| 880 |
-
function tiempoActual(contenedor) {
|
| 881 |
-
if (!contenedor) return null;
|
| 882 |
-
const candidatos = [];
|
| 883 |
-
contenedor.querySelectorAll('*').forEach(el => {
|
| 884 |
-
if (el.children.length === 0) {
|
| 885 |
-
const t = parsearTiempo(el.textContent);
|
| 886 |
-
if (t !== null) candidatos.push(t);
|
| 887 |
-
}
|
| 888 |
-
});
|
| 889 |
-
if (candidatos.length === 0) return null;
|
| 890 |
-
candidatos.sort((a, b) => a - b);
|
| 891 |
-
return candidatos[0]; // el menor de los dos relojes visibles = tiempo transcurrido
|
| 892 |
-
}
|
| 893 |
-
|
| 894 |
-
let ultimoActivo = null;
|
| 895 |
-
|
| 896 |
-
window.__fenixHighlightInterval = setInterval(() => {
|
| 897 |
-
const dbg = document.querySelector('#fenix-debug');
|
| 898 |
-
const contenedorAudio = document.querySelector('#tts_audio');
|
| 899 |
-
const timingBox = document.querySelector('#timing_data textarea') || document.querySelector('#timing_data input');
|
| 900 |
-
|
| 901 |
-
if (!contenedorAudio) { if (dbg) dbg.textContent = 'resaltado: no encuentro el reproductor'; return; }
|
| 902 |
-
if (!timingBox) { if (dbg) dbg.textContent = 'resaltado: no encuentro timing_data'; return; }
|
| 903 |
-
|
| 904 |
-
let timeline;
|
| 905 |
-
try { timeline = JSON.parse(timingBox.value || '[]'); } catch (e) {
|
| 906 |
-
if (dbg) dbg.textContent = 'resaltado: JSON inválido';
|
| 907 |
-
return;
|
| 908 |
-
}
|
| 909 |
-
if (!Array.isArray(timeline) || timeline.length === 0) {
|
| 910 |
-
if (dbg) dbg.textContent = 'resaltado: 0 palabras con timing';
|
| 911 |
-
return;
|
| 912 |
-
}
|
| 913 |
-
|
| 914 |
-
const t = tiempoActual(contenedorAudio);
|
| 915 |
-
if (t === null) { if (dbg) dbg.textContent = 'resaltado: no puedo leer el reloj del reproductor'; return; }
|
| 916 |
-
|
| 917 |
-
let i = timeline.findIndex(p => t >= p.start && t < p.end);
|
| 918 |
-
if (i === -1) {
|
| 919 |
-
// si no cae exacto en ninguna palabra (pausas, silencios), usa la última ya pasada
|
| 920 |
-
for (let k = timeline.length - 1; k >= 0; k--) {
|
| 921 |
-
if (timeline[k].start <= t) { i = k; break; }
|
| 922 |
-
}
|
| 923 |
-
}
|
| 924 |
-
|
| 925 |
-
const activos = new Set();
|
| 926 |
-
if (i !== -1) {
|
| 927 |
-
activos.add(`${timeline[i].verso}:${timeline[i].idx}`);
|
| 928 |
-
if (timeline[i + 1] && timeline[i + 1].verso === timeline[i].verso) {
|
| 929 |
-
activos.add(`${timeline[i + 1].verso}:${timeline[i + 1].idx}`);
|
| 930 |
-
}
|
| 931 |
-
}
|
| 932 |
-
|
| 933 |
-
if (JSON.stringify(Array.from(activos)) !== ultimoActivo) {
|
| 934 |
-
document.querySelectorAll('.w.activo').forEach(el => {
|
| 935 |
-
const key = `${el.closest('.verso')?.dataset.n}:${el.dataset.w}`;
|
| 936 |
-
if (!activos.has(key)) el.classList.remove('activo');
|
| 937 |
-
});
|
| 938 |
-
activos.forEach(key => {
|
| 939 |
-
const [verso, idx] = key.split(':');
|
| 940 |
-
const el = document.querySelector(`.verso[data-n='${verso}'] .w[data-w='${idx}']`);
|
| 941 |
-
if (el) el.classList.add('activo');
|
| 942 |
-
});
|
| 943 |
-
ultimoActivo = JSON.stringify(Array.from(activos));
|
| 944 |
-
}
|
| 945 |
-
|
| 946 |
-
if (dbg) dbg.textContent = `resaltado: ${timeline.length} palabras · t=${t}s · activo=${Array.from(activos).join(',') || '-'}`;
|
| 947 |
-
}, 100);
|
| 948 |
-
}
|
| 949 |
-
""")
|
| 950 |
-
|
| 951 |
-
if __name__ == "__main__":
|
| 952 |
-
demo.launch(ssr_mode=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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