import io import base64 from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import soundfile as sf import torch from transformers import AutoTokenizer from parler_tts import ParlerTTSForConditionalGeneration app = FastAPI(title="EchoNote TTS") # CORS: permite llamadas desde tu dominio de Vercel app.add_middleware( CORSMiddleware, allow_origins=["*"], # Cambia por tu dominio específico si quieres más seguridad allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Carga modelo (mini por defecto) device = "cuda:0" if torch.cuda.is_available() else "cpu" MODEL_ID = "parler-tts/parler-tts-mini-v1" print(f"🚀 Cargando modelo {MODEL_ID} en {device}...") model = ParlerTTSForConditionalGeneration.from_pretrained(MODEL_ID).to(device) tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) print("✅ Modelo cargado y listo") DEFAULT_DESC = ( "A male professor voice with a calm, clear and didactic tone, " "speaking naturally as if explaining to students. Very high quality audio." ) TARGET_WORDS = 600 # ~4 minutos a 150 wpm aprox class TTSRequest(BaseModel): text: str voice_description: str | None = None def truncate_words(txt: str, n: int) -> str: words = txt.split() return " ".join(words[:n]) if len(words) > n else txt @app.get("/") def root(): return { "ok": True, "message": "EchoNote TTS is up", "model": MODEL_ID, "device": device, } @app.post("/generate") def generate(req: TTSRequest): print(f"📝 Generando audio para {len(req.text.split())} palabras...") text = truncate_words(req.text, TARGET_WORDS) desc = req.voice_description or DEFAULT_DESC print(f"📊 Procesando {len(text.split())} palabras (truncado)") input_ids = tokenizer(desc, return_tensors="pt").input_ids.to(device) prompt_ids = tokenizer(text, return_tensors="pt").input_ids.to(device) print("🎙️ Generando audio con Parler-TTS...") with torch.no_grad(): audio = model.generate(input_ids=input_ids, prompt_input_ids=prompt_ids) audio_arr = audio.cpu().numpy().squeeze() sr = model.config.sampling_rate print(f"✅ Audio generado: {len(audio_arr)/sr:.1f}s @ {sr}Hz") buf = io.BytesIO() sf.write(buf, audio_arr, sr, format="WAV") wav_bytes = buf.getvalue() b64 = base64.b64encode(wav_bytes).decode("utf-8") return { "ok": True, "mime_type": "audio/wav", "audio_base64": b64, "sampling_rate": sr, "duration_seconds": len(audio_arr) / sr, "words_used": len(text.split()), }