CoolFace
Apppublic

adiharel30/HebrewTranscriber

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py44 linesDownload Raw Back to root
1from fastapi import FastAPI, Request2from fastapi.responses import JSONResponse3import os4from pydub import AudioSegment5import aiofiles6import faster_whisper7 8# Initialize the FastAPI app9app = FastAPI()10 11# Initialize the model with GPU support12model = faster_whisper.WhisperModel('ivrit-ai/faster-whisper-v2-d4')13 14# Define file paths15TEMP_FILE_PATH = "temp_audio_file.m4a"16WAV_FILE_PATH = "temp_audio_file.wav"17 18@app.post("/transcribe")19async def transcribe(request: Request):20    # Stream the file directly to a temporary file on disk21    async with aiofiles.open(TEMP_FILE_PATH, 'wb') as out_file:22        async for chunk in request.stream():23            await out_file.write(chunk)24    print("File saved successfully.")25 26    # Convert M4A to WAV27    try:28        audio = AudioSegment.from_file(TEMP_FILE_PATH, format="m4a")29        audio.export(WAV_FILE_PATH, format="wav")30        print("Conversion to WAV successful.")31    except Exception as e:32        print("Error during conversion:", e)33        return JSONResponse({"detail": "Error in audio conversion"}, status_code=400)34 35    # Transcribe the WAV audio file36    segments, _ = model.transcribe(WAV_FILE_PATH, language='he')37    transcribed_text = ' '.join([s.text for s in segments])38 39    # Clean up temporary files40    os.remove(TEMP_FILE_PATH)41    os.remove(WAV_FILE_PATH)42 43    return JSONResponse({"transcribed_text": transcribed_text})44