Gaadwhin/speech_to_text_api
1
1import whisper2import tempfile3import os4from fastapi import FastAPI, UploadFile, File, HTTPException5from fastapi.middleware.cors import CORSMiddleware6 7app = FastAPI()8 9# ✅ CORS for frontend10app.add_middleware(11 CORSMiddleware,12 allow_origins=["https://godwin015.github.io"],13 allow_credentials=True,14 allow_methods=["*"],15 allow_headers=["*"],16)17 18# IMPORTANT: Change CACHE_DIR to /tmp for Hugging Face Spaces19# Hugging Face Spaces typically restrict write access to /data,20# but /tmp is generally writable for temporary files and model caches.21CACHE_DIR = "/tmp" 22 23# Ensure the cache directory exists.24# This will create /tmp if it doesn't exist, which it usually does.25os.makedirs(CACHE_DIR, exist_ok=True)26 27# ✅ Load Whisper model with custom cache dir28# The model will now download and cache to the writable /tmp directory.29model = whisper.load_model("tiny", download_root=CACHE_DIR)30 31@app.get("/")32def read_root():33 """34 Root endpoint to confirm the backend is running.35 """36 return {"message": "Whisper transcription backend is up."}37 38@app.post("/api/transcribe")39async def transcribe(audio: UploadFile = File(...), language: str = "en"):40 """41 Transcribes an uploaded audio file using the Whisper model.42 43 Args:44 audio (UploadFile): The audio file to transcribe.45 language (str): The language to transcribe in (e.g., "en" for English).46 47 Returns:48 dict: A dictionary containing the transcription text and detected language.49 50 Raises:51 HTTPException: If the uploaded file is not a valid audio file or if an52 error occurs during transcription.53 """54 # Validate that the uploaded file is an audio file55 if not audio.content_type.startswith("audio/"):56 raise HTTPException(status_code=400, detail="Please upload a valid audio file.")57 58 try:59 # Create a temporary file to save the uploaded audio60 # Using tempfile.NamedTemporaryFile ensures a unique file name61 # and handles cleanup (though we explicitly remove it later).62 # It defaults to the system's temp directory, which is usually /tmp.63 with tempfile.NamedTemporaryFile(delete=False, suffix=".webm") as tmp:64 tmp.write(await audio.read()) # Write the uploaded audio content to the temp file65 tmp_path = tmp.name # Get the path of the temporary file66 67 # Perform the transcription using the Whisper model68 result = model.transcribe(tmp_path, language=language)69 70 # Clean up the temporary audio file after transcription71 os.remove(tmp_path)72 73 # Return the transcription result74 return {75 "transcription": result["text"],76 "language_detected": result.get("language", "unknown")77 }78 except Exception as e:79 # Catch any exceptions during the process and return a 500 error80 # This helps in debugging by providing the error message.81 raise HTTPException(status_code=500, detail=str(e))