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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -425
app.py DELETED
@@ -1,425 +0,0 @@
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
- def cargar_libros():
256
- libros = {}
257
- for ruta in sorted(glob.glob(os.path.join(CARPETA, "*.json"))):
258
- try:
259
- with open(ruta, encoding="utf-8") as f:
260
- d = json.load(f)
261
- lid = d.get("id") or os.path.splitext(os.path.basename(ruta))[0]
262
- libros[lid] = d
263
- except Exception as e:
264
- print("No pude leer", ruta, e)
265
- return libros
266
-
267
-
268
- LIBROS = cargar_libros()
269
- ORDEN = ["Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy"]
270
- IDS = [i for i in ORDEN if i in LIBROS] + [i for i in LIBROS if i not in ORDEN]
271
- NOMBRES = [LIBROS[i].get("es", i) for i in IDS] or ["(sube tus libros)"]
272
-
273
-
274
- def id_por_nombre(nombre):
275
- for i in IDS:
276
- if LIBROS[i].get("es", i) == nombre:
277
- return i
278
- return IDS[0] if IDS else None
279
-
280
-
281
- def versiculos(lid, cap):
282
- return LIBROS.get(lid, {}).get("capitulos", {}).get(str(cap), [])
283
-
284
-
285
- def render(nombre, cap):
286
- lid = id_por_nombre(nombre)
287
- if not lid:
288
- return "<div class='pasaje'><p>Aún no has subido libros a la carpeta <b>libros/</b>.</p></div>", "", ""
289
- try:
290
- cap = max(1, int(float(cap or 1)))
291
- except Exception:
292
- cap = 1
293
- d = LIBROS[lid]
294
- vs = versiculos(lid, cap)
295
- if not vs:
296
- return f"<div class='pasaje'><p>No hay texto para {html.escape(d.get('es',''))} {cap}.</p></div>", "", ""
297
- filas = [f"<div class='cab'><span class='h'>{html.escape(d.get('heb',''))}</span><br>"
298
- f"{html.escape(d.get('es',''))} {cap}</div>"]
299
- plano_es, plano_he = [], []
300
- for v in vs:
301
- he = html.escape(v.get("he", "")); es = html.escape(v.get("es", ""))
302
- fila = f"<div class='verso'><span class='num'>{v.get('n','')}</span>"
303
- if he:
304
- fila += f"<span class='he'>{he}</span>"; plano_he.append(v.get("he", ""))
305
- if es:
306
- fila += f"<span class='es'>{es}</span>"; plano_es.append(v.get("es", ""))
307
- fila += "</div>"
308
- filas.append(fila)
309
- return f"<div class='pasaje'>{''.join(filas)}</div>", " ".join(plano_es), " ".join(plano_he)
310
-
311
-
312
- def estudiar(mensaje, historial, contexto):
313
- if not GROQ_KEY:
314
- return "Para el estudio, añade el Secret GROQ_API_KEY en el Space."
315
- sistema = (
316
- "Eres un compañero de estudio de la Torá que responde en español, cálido y honesto. "
317
- "Ofreces el sentido literal (peshat), contexto histórico y lingüístico, capas de la "
318
- "tradición (midrash, Rashi cuando venga al caso) y reflexión espiritual. Vas al grano.\n\n" + contexto
319
- )
320
- mensajes = [{"role": "system", "content": sistema}]
321
- for m in (historial or []):
322
- if isinstance(m, dict) and m.get("role") in ("user", "assistant"):
323
- mensajes.append({"role": m["role"], "content": m["content"]})
324
- mensajes.append({"role": "user", "content": mensaje})
325
- cuerpo = {"model": MODELO_ESTUDIA, "temperature": 0.4, "max_tokens": 1200, "messages": mensajes}
326
- try:
327
- data = json.dumps(cuerpo).encode("utf-8")
328
- req = urllib.request.Request(GROQ_URL, data=data, method="POST")
329
- req.add_header("Content-Type", "application/json")
330
- req.add_header("Authorization", f"Bearer {GROQ_KEY}")
331
- with urllib.request.urlopen(req, timeout=90) as r:
332
- d = json.load(r)
333
- return (d["choices"][0]["message"]["content"] or "").strip()
334
- except Exception as e:
335
- return f"No pude consultar a la IA ahora mismo ({e})."
336
-
337
-
338
- # ============================ INTERFAZ GRADIO ============================
339
- with gr.Blocks(theme=fenix_theme(), css=FENIX_CSS, title="Centralita Torá") as demo:
340
- st_es = gr.State("")
341
- st_he = gr.State("")
342
- st_nombre = gr.State(NOMBRES[0])
343
- st_cap = gr.State(1)
344
-
345
- gr.HTML("<div id='cabecera'><div class='estrella'>✡</div>"
346
- "<h1>Centralita Torá</h1><p>hebreo y español · canto Trope con voz celectial diferenciada</p></div>")
347
-
348
- with gr.Tab("Leer"):
349
- with gr.Row():
350
- dd = gr.Dropdown(NOMBRES, value=NOMBRES[0], label="Libro")
351
- ncap = gr.Number(value=1, precision=0, label="Capítulo", minimum=1)
352
- ver_btn = gr.Button("Ver capítulo", variant="primary")
353
- salida = gr.HTML()
354
- with gr.Row():
355
- b_es = gr.Button("🔊 Canto Trope + Voz celectial", variant="secondary")
356
- b_he = gr.Button("🔊 עברית (Hebreo)", variant="secondary")
357
- audio = gr.Audio(label="Audio Litúrgico", autoplay=True)
358
-
359
- def ver(nombre, cap):
360
- md, es, he = render(nombre, cap)
361
- return md, es, he, nombre, cap
362
-
363
- ver_btn.click(ver, [dd, ncap], [salida, st_es, st_he, st_nombre, st_cap])
364
- b_es.click(leer_es, st_es, audio)
365
- b_he.click(leer_he, st_he, audio)
366
-
367
- with gr.Tab("Buscar"):
368
- q = gr.Textbox(label="Palabra o frase (hebreo o español)", placeholder="ej. luz / אור")
369
- q_btn = gr.Button("Buscar", variant="primary")
370
- q_out = gr.HTML()
371
-
372
- def buscar(texto):
373
- t = (texto or "").strip().lower()
374
- if not t:
375
- return "<p>Escribe algo para buscar.</p>"
376
- filas = []
377
- for lid in IDS:
378
- d = LIBROS[lid]
379
- for c, vs in d.get("capitulos", {}).items():
380
- for v in vs:
381
- campos = " ".join(filter(None, [v.get("es"), v.get("he")])).lower()
382
- if t in campos:
383
- ref = f"{d.get('es', lid)} {c}:{v.get('n')}"
384
- txt = html.escape(v.get("es") or v.get("he") or "")
385
- filas.append(f"<div class='resultado'><span class='ref'>{ref}</span> — {txt}</div>")
386
- if len(filas) >= 120:
387
- return "".join(filas)
388
- return "".join(filas) if filas else "<p>Sin resultados en los libros cargados.</p>"
389
-
390
- q_btn.click(buscar, q, q_out)
391
-
392
- with gr.Tab("Estudiar"):
393
- gr.Markdown("La IA usa el capítulo abierto en **Leer** como contexto.")
394
- chat = gr.Chatbot(type="messages", height=360)
395
- pin = gr.Textbox(placeholder="Pregunta sobre el pasaje…", label="")
396
- with gr.Row():
397
- enviar = gr.Button("Preguntar", variant="primary")
398
- comentar = gr.Button("Comentar este capítulo", variant="secondary")
399
-
400
- def responder(mensaje, historial, es, he, nombre, cap):
401
- mensaje = (mensaje or "").strip()
402
- if not mensaje:
403
- return historial, ""
404
- contexto = f"Pasaje en pantalla — {nombre} {cap}:\nHebreo: {he}\nEspañol: {es}"
405
- r = estudiar(mensaje, historial, contexto)
406
- historial = (historial or []) + [
407
- {"role": "user", "content": mensaje},
408
- {"role": "assistant", "content": r},
409
- ]
410
- return historial, ""
411
-
412
- enviar.click(responder, [pin, chat, st_es, st_he, st_nombre, st_cap], [chat, pin])
413
- comentar.click(
414
- lambda h, es, he, n, c: responder("Comenta y ayúdame a estudiar este capítulo.", h, es, he, n, c),
415
- [chat, st_es, st_he, st_nombre, st_cap], [chat, pin],
416
- )
417
-
418
- with gr.Tab("Cómo subir"):
419
- gr.Markdown(
420
- "Sube un JSON por libro a la carpeta `libros/`. Para el estudio, añade el Secret `GROQ_API_KEY`."
421
- )
422
-
423
- if __name__ == "__main__":
424
- demo.launch(ssr_mode=False)
425
-