#!/usr/bin/env python3 """ Convierte ficheros .md de leyes a MP3. Uso: python3 scripts/leyes_a_audio.py # todos los .md de temas/bloque*/leyes/ python3 scripts/leyes_a_audio.py ruta/fichero.md ... # ficheros concretos Dependencias: pip install edge-tts Requisitos: ffmpeg instalado en el sistema Fuente: src/main/resources/temas/bloqueX/leyes/*.md Destino: src/main/resources/static/audios/leyes/*.mp3 """ import asyncio import edge_tts import re import os import sys from pathlib import Path BASE_DIR = Path(__file__).parent.parent TEMAS_DIR = BASE_DIR / "src" / "main" / "resources" / "temas" AUDIOS_DIR = BASE_DIR / "src" / "main" / "resources" / "static" / "audios" / "leyes" VOZ = "es-ES-AlvaroNeural" def limpiar_markdown(texto: str) -> str: texto = re.sub(r'```.*?```', ' [código] ', texto, flags=re.DOTALL) texto = re.sub(r'\|.*?\|', '', texto) texto = re.sub(r'[#*_~`>]', '', texto) return ' '.join(texto.split()) async def convertir(path_md: Path, mp3_dir: Path) -> None: mp3_dir.mkdir(parents=True, exist_ok=True) final_output = mp3_dir / path_md.with_suffix('.mp3').name temp_output = mp3_dir / (path_md.stem + '.temp.mp3') if final_output.exists() and final_output.stat().st_mtime >= path_md.stat().st_mtime: print(f"⏭️ Sin cambios, omitiendo: {path_md.name}") return nombre_meta = path_md.stem.replace('-', ' ').replace('_', ' ') nombre_meta_escaped = nombre_meta.replace('"', '\\"') texto = path_md.read_text(encoding="utf-8") texto_limpio = limpiar_markdown(texto) print(f"🔊 Generando: {path_md.name} ({len(texto_limpio)} caracteres)...") comunicar = edge_tts.Communicate(texto_limpio, VOZ) await comunicar.save(str(temp_output)) comando = ( f'ffmpeg -i "{temp_output}" -codec:a libmp3lame -b:a 192k -ar 44100 ' f'-metadata title="{nombre_meta_escaped}" -id3v2_version 3 -write_id3v1 1 ' f'-y "{final_output}" > /dev/null 2>&1' ) os.system(comando) if temp_output.exists(): temp_output.unlink() print(f"✅ Listo: {final_output.relative_to(BASE_DIR)}") async def main() -> None: if len(sys.argv) > 1: archivos = [Path(a) for a in sys.argv[1:]] else: archivos = sorted(TEMAS_DIR.glob("bloque*/leyes/*.md")) if not archivos: print("No se encontraron ficheros .md de leyes.") return print(f"📂 Procesando {len(archivos)} fichero(s)...\n") for path_md in archivos: await convertir(path_md, AUDIOS_DIR) print("\n✨ Proceso completado.") if __name__ == "__main__": asyncio.run(main())