Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, UploadFile, File | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import whisper | |
| import tempfile | |
| import os | |
| app = FastAPI(title="Whisper Tiny ASR API") | |
| # Allow all origins so any frontend can call this | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Load model once at startup | |
| model = whisper.load_model("tiny") | |
| def root(): | |
| return {"message": "Whisper Tiny ASR API is running. POST audio to /transcribe"} | |
| async def transcribe(file: UploadFile = File(...)): | |
| # Save uploaded audio to a temp file | |
| suffix = os.path.splitext(file.filename)[-1] or ".wav" | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: | |
| tmp.write(await file.read()) | |
| tmp_path = tmp.name | |
| try: | |
| result = model.transcribe(tmp_path) | |
| return {"text": result["text"], "language": result.get("language", "unknown")} | |
| finally: | |
| os.remove(tmp_path) |