import os import tempfile from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.middleware.cors import CORSMiddleware from faster_whisper import WhisperModel from pipeline.postprocess import process app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # ─── Model Load ─────────────────────────────────────────────────────────────── print("Loading Whisper model...") model = WhisperModel("large-v3", device="cpu", compute_type="int8") print("Whisper model ready!") # ─── Health ─────────────────────────────────────────────────────────────────── @app.get("/health") async def health(): return {"status": "ok", "message": "SubFlow backend is running"} # ─── WebSocket Transcribe ───────────────────────────────────────────────────── @app.websocket("/transcribe") async def transcribe(websocket: WebSocket): await websocket.accept() tmp_path = None try: # مرحله ۱ — دریافت فایل صوتی await websocket.send_json({"status": "receiving"}) audio_bytes = await websocket.receive_bytes() # مرحله ۲ — ذخیره موقت روی دیسک with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp: tmp.write(audio_bytes) tmp_path = tmp.name # مرحله ۳ — transcription await websocket.send_json({"status": "transcribing"}) segments_raw, info = model.transcribe( tmp_path, language="en", word_timestamps=True, vad_filter=True, ) # مرحله ۴ — تبدیل به لیست قابل پردازش await websocket.send_json({"status": "processing"}) segments = [] for seg in segments_raw: words = list(seg.words) if not words: continue segments.append({ "text": seg.text.strip(), "start": words[0].start, "end": words[-1].end, "words": [ {"word": w.word, "start": w.start, "end": w.end} for w in words ], }) # مرحله ۵ — Post-Processing (اون ۲۰٪ طلایی) srt_content = process(segments) # مرحله ۶ — ارسال نتیجه await websocket.send_json({ "status": "done", "srt": srt_content, "language": info.language, "duration": info.duration, }) except WebSocketDisconnect: pass except Exception as e: await websocket.send_json({"status": "error", "message": str(e)}) finally: if tmp_path and os.path.exists(tmp_path): os.remove(tmp_path) await websocket.close()