Download app.py from SubLabAI/Subflow: direct link, hf CLI and curl.
- Browser
- Download file 3.16 kB
-
https://huggingface.co/spaces/SubLabAI/Subflow/resolve/79ef2f0b8d67d1b9387ba28eff59f89ee665f0be/app.py
- Command line
-
hf download hf://spaces/SubLabAI/Subflow@79ef2f0b8d67d1b9387ba28eff59f89ee665f0be/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SubLabAI/Subflow/resolve/79ef2f0b8d67d1b9387ba28eff59f89ee665f0be/app.py
3.16 kB
| import os | |
| import tempfile | |
| import asyncio | |
| from fastapi import FastAPI, WebSocket, WebSocketDisconnect | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from faster_whisper import WhisperModel | |
| 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 ─────────────────────────────────────────────────────────────────── | |
| async def health(): | |
| return {"status": "ok", "message": "SubFlow backend is running"} | |
| # ─── 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, info = model.transcribe( | |
| tmp_path, | |
| language="en", | |
| word_timestamps=True, | |
| vad_filter=True, | |
| ) | |
| # مرحله ۴ — ساخت SRT | |
| await websocket.send_json({"status": "processing"}) | |
| srt_entries = [] | |
| index = 1 | |
| for segment in segments: | |
| words = list(segment.words) | |
| if not words: | |
| continue | |
| start = words[0].start | |
| end = words[-1].end | |
| text = segment.text.strip() | |
| srt_entries.append({ | |
| "index": index, | |
| "start": start, | |
| "end": end, | |
| "text": text, | |
| "words": [{"word": w.word, "start": w.start, "end": w.end} for w in words] | |
| }) | |
| index += 1 | |
| # مرحله ۵ — ارسال نتیجه | |
| await websocket.send_json({ | |
| "status": "done", | |
| "segments": srt_entries, | |
| "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() |