""" Convierte archivos .md de leyes a MP3 usando edge-tts + ffmpeg. Uso: python3 leyes_a_audio.py [archivo1.md] [archivo2.md] ... (sin argumentos procesa todos los .md de bloque*/leyes/) """ import asyncio import edge_tts import re import os import sys from pathlib import Path BASE_DIR = Path(__file__).parent.parent def limpiar_markdown(texto): 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): 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 audio: {path_md.name} ({len(texto_limpio)} caracteres)...") comunicar = edge_tts.Communicate(texto_limpio, "es-ES-AlvaroNeural") 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}") async def main(): mp3_dir = BASE_DIR / "audios" / "mp3" / "leyes" if len(sys.argv) > 1: archivos = [Path(a) for a in sys.argv[1:]] else: archivos = sorted(BASE_DIR.glob("bloque*/leyes/*.md")) if not archivos: print("No se encontraron archivos .md") return for md in archivos: await convertir(md, mp3_dir) if __name__ == "__main__": asyncio.run(main())