from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.responses import JSONResponse from faster_whisper import WhisperModel import tempfile import os import shutil import logging logging.basicConfig(level=logging.INFO) app = FastAPI( title="Fast Whisper API", version="1.0.0" ) print("Loading Faster Whisper model...") model = WhisperModel( "base", device="cpu", compute_type="int8", cpu_threads=4, num_workers=2 ) print("Model loaded successfully!") @app.get("/") def root(): return { "status": "online", "model": "faster-whisper-base", "languages": [ "Hindi", "English", "Hinglish (Auto Detect)" ] } @app.post("/transcribe") async def transcribe(file: UploadFile = File(...)): if not file.filename: raise HTTPException(400, "No file uploaded.") suffix = os.path.splitext(file.filename)[1] with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp: shutil.copyfileobj(file.file, temp) temp_path = temp.name try: segments, info = model.transcribe( temp_path, beam_size=1, vad_filter=True, word_timestamps=False ) text = " ".join(segment.text.strip() for segment in segments).strip() return JSONResponse( { "success": True, "language": info.language, "language_probability": round(info.language_probability, 3), "text": text } ) except Exception as e: logging.exception(e) raise HTTPException(500, str(e)) finally: if os.path.exists(temp_path): os.remove(temp_path)