Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import os, pathlib, tempfile, shutil, uuidfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import JSONResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport subprocess# ----------------------------------# CONFIG & PATHS (robust writable base)# ----------------------------------def _first_writable(candidates):for p in candidates:try:path = pathlib.Path(p).resolve()path.mkdir(parents=True, exist_ok=True)test_file = path / ".write_test"test_file.write_text("ok", encoding="utf-8")test_file.unlink(missing_ok=True)return pathexcept Exception:continuefallback = pathlib.Path(tempfile.gettempdir()) / "tts_app"fallback.mkdir(parents=True, exist_ok=True)return fallback.resolve()_env_base = os.environ.get("TTS_BASE_DIR", "").strip()_candidates = []if _env_base:_candidates.append(_env_base)_candidates += ["/data/tts_app", "/tmp/tts_app", "/home/user/tts_app"]BASE_DIR = _first_writable(_candidates)FILES_DIR = BASE_DIR / "files"VOICES_DIR = BASE_DIR / "voices"FILES_DIR.mkdir(parents=True, exist_ok=True)VOICES_DIR.mkdir(parents=True, exist_ok=True)# ----------------------------------# FASTAPI SETUP# ----------------------------------app = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# ----------------------------------# UTILITIES# ----------------------------------class TTSRequest(BaseModel):text: strvoice: str = "en_US-libritts-high"length_scale: float = 1.0noise_scale: float = 0.33noise_w: float = 0.8@app.get("/health")def health():return {"ok": True,"engine": "piper-tts (CLI, CPU)","default_voice": None,"voice_dir": str(VOICES_DIR),"available_voices": sorted([v.name for v in VOICES_DIR.glob("/*.onnx")]),"files_dir": str(FILES_DIR),}@app.post("/speak")def speak(body: TTSRequest):if not body.text.strip():raise HTTPException(status_code=400, detail="Empty text")text_id = str(uuid.uuid4())[:8]txt_path = FILES_DIR / f"{text_id}.txt"wav_path = FILES_DIR / f"{text_id}.wav"txt_path.write_text(body.text.strip(), encoding="utf-8")# --------------------------# Run piper# --------------------------voice = body.voicevoice_path = VOICES_DIR / voice / "model.onnx"if not voice_path.exists():return JSONResponse(content={"ok": False, "error": f"Voice not found: {voice}"})cmd = ["piper","--model", str(voice_path),"--output_file", str(wav_path),"--length_scale", str(body.length_scale),"--noise_scale", str(body.noise_scale),"--noise_w", str(body.noise_w),]try:with open(txt_path, "r", encoding="utf-8") as f:subprocess.run(cmd, stdin=f, check=True)except subprocess.CalledProcessError as e:return JSONResponse(content={"ok": False, "error": str(e)})return {"ok": True,"audio_url": f"/files/{wav_path.name}",}@app.get("/files/{filename}")def get_file(filename: str):f = FILES_DIR / filenameif not f.exists():raise HTTPException(status_code=404, detail="File not found")return JSONResponse(content={"url": f"/files/{filename}"})12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091from fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import FileResponsefrom pathlib import Pathimport uuidimport subprocessimport osimport shutilapp = FastAPI()# ========== Dynamic VOICES_DIR fix ==========# Try /tmp/tts_app/voices firstbase_dirs = [Path("/tmp/tts_app/voices"), Path("/data/voices"), Path("/home/user/voices"), Path.cwd() / "voices"]for path in base_dirs:try:path.mkdir(parents=True, exist_ok=True)test_file = path / ".write_test"test_file.write_text("ok")test_file.unlink()VOICES_DIR = pathbreakexcept Exception:continueelse:raise RuntimeError("❌ Could not find any writable directory for VOICES_DIR.")FILES_DIR = VOICES_DIR.parent / "files"FILES_DIR.mkdir(parents=True, exist_ok=True)# ========== Piper engine config ==========VOICE_TAGS = ["en_US-libritts-high", # Humanlike, CPU-friendly (VITS-based)"en_US-amy-medium", # Classic Piper Amy"en_US-lessac-high", # LJSpeech-derived VITS]@app.get("/health")def health():return {"ok": True,"engine": "piper-tts (CLI, CPU)","voice_dir": str(VOICES_DIR),"files_dir": str(FILES_DIR),"default_voice": None,"available_voices": VOICE_TAGS,}@app.post("/speak")async def speak(request: Request):try:payload = await request.json()text = payload.get("text", "").strip()voice = payload.get("voice", VOICE_TAGS[0])length_scale = float(payload.get("length_scale", 1.08))noise_scale = float(payload.get("noise_scale", 0.33))noise_w = float(payload.get("noise_w", 0.8))if not text:raise HTTPException(status_code=400, detail="No text provided")output_file = FILES_DIR / f"{uuid.uuid4().hex}.wav"command = ["piper","--model", f"voices/{voice}.onnx","--output_file", str(output_file),"--text", text,"--length_scale", str(length_scale),"--noise_scale", str(noise_scale),"--noise_w", str(noise_w),]result = subprocess.run(command, capture_output=True, text=True)if result.returncode != 0 or not output_file.exists():raise HTTPException(status_code=500, detail=f"TTS failed: {result.stderr.strip()}")return {"ok": True,"voice": voice,"audio_url": f"/file/{output_file.name}"}except Exception as e:raise HTTPException(status_code=500, detail=str(e))@app.get("/file/{filename}")async def get_file(filename: str):path = FILES_DIR / filenameif path.exists():return FileResponse(path)raise HTTPException(status_code=404, detail="File not found")
app.py+67-91