Update app.py
Browse files12341 unmodified line67891011123 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import os, io, timefrom fastapi import FastAPI, UploadFile, File, HTTPExceptionfrom pydantic import BaseModelfrom faster_whisper import WhisperModel1 unmodified lineMODEL_NAME = os.getenv("FASTER_WHISPER_MODEL", "tiny.en")NUM_THREADS = int(os.getenv("NUM_THREADS", "2"))# Load model at startup (CPU, int8)model = WhisperModel(MODEL_NAME, device="cpu", compute_type="int8", num_workers=NUM_THREADS)app = FastAPI(title="STT (faster-whisper CPU)")3 unmodified lineslanguage: str | None = Noneduration: float | None = None@app.get("/health")def health():return {"ok": True, "model": MODEL_NAME}@app.post("/transcribe", response_model=TranscribeOut)async def transcribe(file: UploadFile = File(...)):# Basic validationsif not file.filename:raise HTTPException(status_code=400, detail="No filename")if not file.content_type or not file.content_type.startswith("audio/"):# Allow unknown types; client may not set correctlypass# Read all bytes in memory (small test files)try:payload = await file.read()finally:await file.close()if not payload:raise HTTPException(status_code=400, detail="Empty file")# Run inferencestart = time.time()audio_buf = io.BytesIO(payload)try:segments, info = model.transcribe(audio_buf, vad_filter=True)except Exception as e:# Most common: ffmpeg missing (fixed by Dockerfile), or invalid audioraise HTTPException(status_code=500, detail=f"Transcription failed: {e}")text_chunks = []for seg in segments:text_chunks.append(seg.text.strip())text = " ".join([t for t in text_chunks if t])return TranscribeOut(text=text.strip(),language=getattr(info, "language", None),duration=getattr(info, "duration", None),)12341 unmodified line67891011123 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import os, uuid, tempfile, shutilfrom fastapi import FastAPI, UploadFile, File, HTTPExceptionfrom pydantic import BaseModelfrom faster_whisper import WhisperModel1 unmodified lineMODEL_NAME = os.getenv("FASTER_WHISPER_MODEL", "tiny.en")NUM_THREADS = int(os.getenv("NUM_THREADS", "2"))# Load model once (CPU, int8)model = WhisperModel(MODEL_NAME, device="cpu", compute_type="int8", num_workers=NUM_THREADS)app = FastAPI(title="STT (faster-whisper CPU)")3 unmodified lineslanguage: str | None = Noneduration: float | None = None@app.post("/transcribe", response_model=TranscribeOut)async def transcribe(file: UploadFile = File(...),beam_size: int = 1,vad_filter: bool = True,):# Read the uploadpayload = await file.read()await file.close()if not payload:raise HTTPException(status_code=400, detail="Empty file")# Persist to a temp file so ffmpeg can probe it robustlysuffix = os.path.splitext(file.filename or "")[1] or ".wav"tmp_path = os.path.join(tempfile.gettempdir(), f"stt_{uuid.uuid4().hex}{suffix}")try:with open(tmp_path, "wb") as f:f.write(payload)# Transcribe via file path (lets faster-whisper/ffmpeg do decoding)segments, info = model.transcribe(tmp_path,beam_size=beam_size,vad_filter=vad_filter,)parts = [seg.text.strip() for seg in segments if seg.text and seg.text.strip()]text = " ".join(parts).strip()return TranscribeOut(text=text,language=getattr(info, "language", None),duration=getattr(info, "duration", None),)except Exception as e:raise HTTPException(status_code=500, detail=f"Transcription failed: {e}")finally:try:os.remove(tmp_path)except Exception:pass
app.py+36-36