Subflow / app.py
AliJabbarpour's picture
Update app.py
79ef2f0 verified
Raw History Blame
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 ───────────────────────────────────────────────────────────────────
@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, 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()