|
21 | 21 | import os |
22 | 22 | import re |
23 | 23 | import hashlib |
| 24 | +import json |
24 | 25 | import random |
25 | 26 | import tempfile |
| 27 | +import time |
| 28 | +import asyncio |
| 29 | +from contextlib import suppress |
26 | 30 | from typing import List, Optional |
27 | 31 |
|
28 | 32 | import requests |
29 | | -from fastapi import FastAPI, File, UploadFile |
| 33 | +from fastapi import FastAPI, File, UploadFile, WebSocket, WebSocketDisconnect |
30 | 34 | from fastapi.middleware.cors import CORSMiddleware |
31 | 35 | from pydantic import BaseModel |
32 | 36 |
|
@@ -183,3 +187,120 @@ def api_transcribe(file: UploadFile = File(...), authorization: Optional[str] = |
183 | 187 | segments, info = model.transcribe(tmp.name, beam_size=5) |
184 | 188 | text = "".join(seg.text for seg in segments).strip() |
185 | 189 | return {"text": text, "language": getattr(info, "language", None)} |
| 190 | + |
| 191 | + |
| 192 | +# ---------------- 流式 Whisper(WebSocket,边录边出字,类似 WhisperLiveKit) ---------------- |
| 193 | +# |
| 194 | +# 协议: |
| 195 | +# App 连接 ws://<host>:8000/ws/transcribe?lang=zh|en|yue(lang 可省略 → 自动检测) |
| 196 | +# 客户端 → 服务端:二进制帧 = 16kHz/16bit/单声道 PCM 原始字节 |
| 197 | +# 客户端 → 服务端:文本帧 "flush" = 停止并返回最终转写;"close" = 直接断开 |
| 198 | +# 服务端 → 客户端:JSON 文本帧 |
| 199 | +# {"type":"interim","text":"..."} 滚动中间结果(每积累约 3s 新音频) |
| 200 | +# {"type":"final","text":"...","language":"en"} 最终完整转写 |
| 201 | +# {"type":"error","message":"..."} |
| 202 | + |
| 203 | +STREAM_INTERVAL_SEC = 3.0 # 每隔这么多秒的"新音频"做一次中间转写 |
| 204 | +STREAM_WINDOW_SEC = 15.0 # 中间转写只看最近这么多秒(滚动窗口) |
| 205 | +STREAM_MAX_SEC = 300.0 # 缓冲上限(5 分钟),防止长录音内存无限增长 |
| 206 | +_STREAM_BYTES_PER_SEC = 32000 # 16kHz × 16bit / 8 = 32000 B/s |
| 207 | + |
| 208 | +def _pcm_to_float(raw_pcm: bytes): |
| 209 | + import numpy as np |
| 210 | + return np.frombuffer(raw_pcm, dtype=np.int16).astype(np.float32) / 32768.0 |
| 211 | + |
| 212 | +def _transcribe_audio(model, raw_pcm: bytes, lang: str = ""): |
| 213 | + """把 PCM 字节交给 Whisper 转写,返回 (text, language)。""" |
| 214 | + audio = _pcm_to_float(raw_pcm) |
| 215 | + if audio.size == 0: |
| 216 | + return "", None |
| 217 | + language = lang or None |
| 218 | + segments, info = model.transcribe( |
| 219 | + audio, language=language, beam_size=1, vad_filter=True, |
| 220 | + condition_on_previous_text=False, |
| 221 | + ) |
| 222 | + text = "".join(seg.text for seg in segments).strip() |
| 223 | + return text, (info.language if language is None else language) |
| 224 | + |
| 225 | +@app.websocket("/ws/transcribe") |
| 226 | +async def ws_transcribe(websocket: WebSocket, lang: str = ""): |
| 227 | + await websocket.accept() |
| 228 | + auth = websocket.headers.get("authorization", "") |
| 229 | + if AUTH_TOKEN and auth != f"Bearer {AUTH_TOKEN}": |
| 230 | + await websocket.send_text(json.dumps({"type": "error", "message": "AUTH_TOKEN 不匹配"})) |
| 231 | + await websocket.close(code=4001) |
| 232 | + return |
| 233 | + try: |
| 234 | + model = await asyncio.to_thread(_get_whisper_model) |
| 235 | + except Exception as e: |
| 236 | + await websocket.send_text(json.dumps({"type": "error", "message": f"faster-whisper 未安装或加载失败: {e}"})) |
| 237 | + await websocket.close(code=4002) |
| 238 | + return |
| 239 | + |
| 240 | + buffer = bytearray() |
| 241 | + lock = asyncio.Lock() |
| 242 | + last_len = 0 |
| 243 | + |
| 244 | + async def stream_loop(): |
| 245 | + nonlocal last_len |
| 246 | + last_run = time.monotonic() |
| 247 | + try: |
| 248 | + while True: |
| 249 | + await asyncio.sleep(0.5) |
| 250 | + last_len = min(last_len, len(buffer)) |
| 251 | + now = time.monotonic() |
| 252 | + if now - last_run >= STREAM_INTERVAL_SEC and len(buffer) > last_len: |
| 253 | + last_len = len(buffer) |
| 254 | + last_run = now |
| 255 | + window = bytes(buffer[-int(STREAM_WINDOW_SEC * _STREAM_BYTES_PER_SEC):]) |
| 256 | + try: |
| 257 | + async with lock: |
| 258 | + text, _ = await asyncio.to_thread(_transcribe_audio, model, window, lang) |
| 259 | + except Exception as e: |
| 260 | + text = "" |
| 261 | + if text: |
| 262 | + try: |
| 263 | + await websocket.send_text(json.dumps({"type": "interim", "text": text})) |
| 264 | + except Exception: |
| 265 | + return |
| 266 | + except asyncio.CancelledError: |
| 267 | + raise |
| 268 | + except Exception: |
| 269 | + pass |
| 270 | + |
| 271 | + loop_task = asyncio.create_task(stream_loop()) |
| 272 | + try: |
| 273 | + while True: |
| 274 | + msg = await websocket.receive() |
| 275 | + if msg["type"] == "websocket.receive_bytes": |
| 276 | + buffer.extend(msg["bytes"]) |
| 277 | + max_bytes = int(STREAM_MAX_SEC * _STREAM_BYTES_PER_SEC) |
| 278 | + if len(buffer) > max_bytes + int(STREAM_WINDOW_SEC * _STREAM_BYTES_PER_SEC): |
| 279 | + del buffer[: len(buffer) - max_bytes] |
| 280 | + elif msg["type"] == "websocket.receive_text": |
| 281 | + txt = msg.get("text", "").strip() |
| 282 | + if txt == "flush": |
| 283 | + loop_task.cancel() |
| 284 | + with suppress(asyncio.CancelledError): |
| 285 | + await loop_task |
| 286 | + async with lock: |
| 287 | + final_text, language = await asyncio.to_thread( |
| 288 | + _transcribe_audio, model, bytes(buffer), lang |
| 289 | + ) |
| 290 | + try: |
| 291 | + await websocket.send_text(json.dumps({ |
| 292 | + "type": "final", "text": final_text, "language": language, |
| 293 | + })) |
| 294 | + except Exception: |
| 295 | + pass |
| 296 | + break |
| 297 | + elif txt == "close": |
| 298 | + break |
| 299 | + except WebSocketDisconnect: |
| 300 | + pass |
| 301 | + finally: |
| 302 | + loop_task.cancel() |
| 303 | + with suppress(asyncio.CancelledError): |
| 304 | + await loop_task |
| 305 | + with suppress(Exception): |
| 306 | + await websocket.close() |
0 commit comments