openspeechapi 0.2.21__tar.gz → 0.2.22__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/PKG-INFO +1 -1
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/base.py +14 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/model_hub.py +13 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/dispatcher.py +36 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/gemma4.py +33 -6
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/qwen3_omni_stt.py +1 -29
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/app.py +2 -0
- openspeechapi-0.2.22/openspeechapi/server/model_downloads.py +191 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/routes/management.py +44 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/routes/stt.py +38 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/routes/webui.py +10 -2
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/webui/app.js +135 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/webui/index.html +2 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/webui/styles.css +48 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/ws/stt_stream.py +28 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/pyproject.toml +1 -1
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/.gitignore +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/README.md +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/__main__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/cli.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/client/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/client/client.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/config.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/enums.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/models.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/registry.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/core/settings.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/demo.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/aim_provision.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/context.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/executors/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/executors/base.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/executors/in_process.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/executors/remote.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/executors/subprocess_exec.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/fanout.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/filters.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/lifecycle.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/dispatch/watcher.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/engine_catalog.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/engine_registry.yaml +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/exceptions.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/factory.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/aim_resolver.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/backends/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/backends/docker_backend.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/backends/native_backend.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/base.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/engines/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/engines/faster_whisper.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/engines/fish_speech.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/engines/sherpa_onnx.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/engines/whisper.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/engines/whisperlivekit.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/isolated_venv.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/manager.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/models.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/progress.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/registry.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/task_store.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/local_engines/tasks.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/logging_config.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/base.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/debug.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/latency.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/metrics.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/tracing.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/observe/usage.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/_template.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/_local_audio.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/alibaba.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/assemblyai.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/azure_speech.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/baidu.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/canary_qwen_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/deepgram.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/dolphin_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/elevenlabs.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/faster_whisper.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/fireredasr_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/funasr_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/google_cloud.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/iflytek.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/kimi_audio_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/macos_speech.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/mlx_whisper_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/mms_languages.json +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/mms_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/moonshine_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/openai.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/paraformer.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/parakeet_mlx_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/phi4_multimodal_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/qwen3_asr.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/sensevoice.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/sherpa_onnx.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/tencent.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/volcengine.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/vosk_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/voxtral_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/wenet_stt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/whisper.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/whisperlivekit.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/stt/windows_speech.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/alibaba.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/azure_speech.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/baidu.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/coqui.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/cosyvoice.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/deepgram.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/elevenlabs.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/fish_speech.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/google_cloud.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/iflytek.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/macos_say.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/minimax.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/openai.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/piper.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/tencent.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/volcengine.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/providers/tts/windows_sapi.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/auth.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/extras_installer.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/middleware.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/native_installer.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/routes/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/routes/tts.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/system_metrics.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/ws/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/server/ws/tts_stream.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/telemetry/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/telemetry/perf.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/utils/__init__.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/utils/audio_converter.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/utils/audio_playback.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/openspeechapi/vendor_registry.yaml +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/providers.example.yaml +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/aim_adopt.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/aim_consumers.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/cloud/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/faster-whisper/native/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/fish-speech/native/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/macos-stt/_bundle.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/macos-stt/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/macos-stt/macos_stt.swift +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/macos-stt/request_auth.swift +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/sherpa-onnx/native/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/sherpa-onnx/native/run_streaming_server.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/whisper/native/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/engines/whisperlivekit/native/install.sh +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/gen_mms_languages.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/preload_stt_model.py +0 -0
- {openspeechapi-0.2.21 → openspeechapi-0.2.22}/scripts/release.sh +0 -0
|
@@ -94,6 +94,20 @@ class SpeechProvider(ABC):
|
|
|
94
94
|
"""
|
|
95
95
|
return None
|
|
96
96
|
|
|
97
|
+
@classmethod
|
|
98
|
+
def expected_local_repo(cls, settings) -> str | None: # noqa: ANN001
|
|
99
|
+
"""该引擎在本机会从本地缓存加载的 HF repo id(用于「是否已下载」预检)。
|
|
100
|
+
|
|
101
|
+
在 **server 进程** 里调用以判断本地模型是否已缓存 —— 因此本方法及其所有 override
|
|
102
|
+
必须是 **纯字符串逻辑**:绝不 import torch / transformers / mlx 等重依赖,绝不加载
|
|
103
|
+
模型(重依赖只在 worker 进程)。``settings`` 可能是 dataclass 实例或 dict。默认取
|
|
104
|
+
``model`` 字段;不是 ``org/name`` 形式的 HF id(本地路径、单段名等)则返回 None,
|
|
105
|
+
预检随即跳过(无法判断是否已下载 → 不拦截)。平台会重映射 repo 的引擎(如 gemma4)
|
|
106
|
+
应 override 返回本平台实际加载的那个 id。"""
|
|
107
|
+
model = settings.get("model") if isinstance(settings, dict) else getattr(settings, "model", None)
|
|
108
|
+
model = (model or "").strip()
|
|
109
|
+
return model if "/" in model else None
|
|
110
|
+
|
|
97
111
|
def _resolve_model(
|
|
98
112
|
self, repo: str, *, hub: str = "", model_path: str = "",
|
|
99
113
|
ms_repo_map: "dict[str, str] | None" = None, custom_url: str = "",
|
|
@@ -410,6 +410,19 @@ def local_model_path(repo: str, ms_repo_map: Mapping[str, str] | None = None) ->
|
|
|
410
410
|
return _hf_local(repo) or _ms_local(ms_repo)
|
|
411
411
|
|
|
412
412
|
|
|
413
|
+
def model_is_cached(repo: str, ms_repo_map: Mapping[str, str] | None = None) -> bool:
|
|
414
|
+
"""True 表示 repo 的【完整】本地副本已存在(部分/未完成下载算 False)。
|
|
415
|
+
|
|
416
|
+
用于 STT 转写/流式的「是否已下载」预检 —— 未下载时路由层立即返回 409 引导去下载,
|
|
417
|
+
而不是在请求里现下大模型导致 300s 超时。委托给 ``local_model_path``(对不完整下载返回
|
|
418
|
+
None,正合需要;完成度由 ``_hf_local`` 的 snapshot 校验 + ``_dir_has_model_weights``
|
|
419
|
+
把关)。任何异常都当作「未缓存」处理,绝不让预检本身抛错阻塞请求。"""
|
|
420
|
+
try:
|
|
421
|
+
return local_model_path(repo, ms_repo_map) is not None
|
|
422
|
+
except Exception: # noqa: BLE001 - 预检失败时退回「未缓存」,不阻断/不误报
|
|
423
|
+
return False
|
|
424
|
+
|
|
425
|
+
|
|
413
426
|
def build_aim_spec(model: str, hub: str, ms_repo_map: Mapping[str, str] | None = None,
|
|
414
427
|
category: str = "asr/model") -> AimModelSpec | None:
|
|
415
428
|
"""Shared ``aim_model_spec`` body for HF⇄ModelScope-mirrored models.
|
|
@@ -452,6 +452,42 @@ class ServiceDispatcher:
|
|
|
452
452
|
raise ProviderNotFoundError(alias)
|
|
453
453
|
return self._handles[alias]
|
|
454
454
|
|
|
455
|
+
# Local execution modes: the model is loaded/downloaded on THIS box (so a
|
|
456
|
+
# missing local model means an in-request download). Remote/cloud engines
|
|
457
|
+
# download nothing locally → never pre-checked.
|
|
458
|
+
_LOCAL_EXEC_MODES = frozenset({"subprocess", "local", "in_process"})
|
|
459
|
+
|
|
460
|
+
def expected_repo_for(self, alias: str, model_override: str | None = None) -> str | None:
|
|
461
|
+
"""本地引擎在本机预期加载的 HF repo id;远程/云引擎或取不到时返回 None。
|
|
462
|
+
|
|
463
|
+
给路由层的「模型是否已下载」预检用:仅对本地类引擎(subprocess/local/in_process,
|
|
464
|
+
排除 remote)返回 repo,远程引擎一律 None(不在本机下载模型)。委托给 provider 类的
|
|
465
|
+
``expected_local_repo``(纯字符串、不加载模型、不 import 重依赖)。
|
|
466
|
+
|
|
467
|
+
``model_override`` 非空时(Lab Advanced Options 的按请求 model 覆盖),解析的是**被覆盖
|
|
468
|
+
的** model(保留 backend 等其它配置),这样预检对照的是该请求实际会加载的模型,而非引擎
|
|
469
|
+
静态配置。任何异常/找不到都返回 None —— 预检宁可放行也不误拦。"""
|
|
470
|
+
handle = self._handles.get(alias)
|
|
471
|
+
if handle is None:
|
|
472
|
+
return None
|
|
473
|
+
exec_mode = (
|
|
474
|
+
handle.exec_mode.value
|
|
475
|
+
if hasattr(handle.exec_mode, "value")
|
|
476
|
+
else str(handle.exec_mode)
|
|
477
|
+
)
|
|
478
|
+
if str(exec_mode).strip().lower() not in self._LOCAL_EXEC_MODES:
|
|
479
|
+
return None
|
|
480
|
+
try:
|
|
481
|
+
settings = getattr(handle, "settings_dict", None)
|
|
482
|
+
if settings is None:
|
|
483
|
+
settings = getattr(handle, "settings", None) or {}
|
|
484
|
+
if model_override:
|
|
485
|
+
base = settings if isinstance(settings, dict) else (getattr(settings, "__dict__", {}) or {})
|
|
486
|
+
settings = {**base, "model": model_override}
|
|
487
|
+
return handle.provider_cls.expected_local_repo(settings)
|
|
488
|
+
except Exception: # noqa: BLE001 - 预检取 repo 失败 → 当作无法判断,放行
|
|
489
|
+
return None
|
|
490
|
+
|
|
455
491
|
async def _negotiate_audio_format(
|
|
456
492
|
self, handle: "_ProviderHandle", audio: AudioData
|
|
457
493
|
) -> AudioData:
|
|
@@ -143,19 +143,46 @@ class Gemma4STT(STTProvider):
|
|
|
143
143
|
"google/gemma-4-E2B-it": "mlx-community/gemma-4-E2B-it-8bit",
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
146
|
+
@classmethod
|
|
147
|
+
def _resolve_repo_for_platform(cls, model: str, backend: str) -> tuple[str, str]:
|
|
148
|
+
"""Pure-string (backend, model) resolver — NO torch/mlx import, NO model load.
|
|
149
|
+
'auto' picks by platform (Apple Silicon→mlx, else→cuda) and remaps the model to
|
|
150
|
+
that backend's repo namespace when they disagree. Shared by the instance
|
|
151
|
+
``_resolve_backend_and_model`` (worker) and the classmethod ``expected_local_repo``
|
|
152
|
+
(server-process download pre-check), so both agree on the id this box loads."""
|
|
153
|
+
b = (backend or "auto").strip().lower()
|
|
150
154
|
if b == "auto":
|
|
151
155
|
import sys
|
|
152
156
|
b = "mlx" if sys.platform == "darwin" else "cuda"
|
|
153
157
|
if b == "mlx" and model.startswith("google/"):
|
|
154
|
-
model =
|
|
158
|
+
model = cls._HF_TO_MLX.get(model, model)
|
|
155
159
|
elif b == "cuda" and model.startswith("mlx-community/"):
|
|
156
|
-
model =
|
|
160
|
+
model = cls._MLX_TO_HF.get(model, model)
|
|
157
161
|
return b, model
|
|
158
162
|
|
|
163
|
+
def _resolve_backend_and_model(self, model: str) -> tuple[str, str]:
|
|
164
|
+
"""(backend, model): 'auto' picks by platform (Apple Silicon→mlx, else→cuda) and
|
|
165
|
+
remaps the model to that backend's repo namespace when they disagree."""
|
|
166
|
+
return self._resolve_repo_for_platform(model, self.settings.backend)
|
|
167
|
+
|
|
168
|
+
@classmethod
|
|
169
|
+
def expected_local_repo(cls, settings) -> str | None: # noqa: ANN001
|
|
170
|
+
"""The HF repo this box actually loads from cache — i.e. the **remapped** id, so
|
|
171
|
+
the «is it downloaded» pre-check looks for the right copy (e.g. on Linux/CUDA the
|
|
172
|
+
configured MLX ``mlx-community/gemma-4-E4B-it-8bit`` maps to ``google/gemma-4-E4B-it``,
|
|
173
|
+
which is what ``_load_cuda`` would download). Reuses the pure-string platform/backend
|
|
174
|
+
mapping (no torch/mlx import). Local paths / non-HF ids → None (pre-check skipped)."""
|
|
175
|
+
if isinstance(settings, dict):
|
|
176
|
+
model = (settings.get("model") or "").strip()
|
|
177
|
+
backend = settings.get("backend") or "auto"
|
|
178
|
+
else:
|
|
179
|
+
model = (getattr(settings, "model", None) or "").strip()
|
|
180
|
+
backend = getattr(settings, "backend", None) or "auto"
|
|
181
|
+
if "/" not in model:
|
|
182
|
+
return None
|
|
183
|
+
_backend, resolved = cls._resolve_repo_for_platform(model, backend)
|
|
184
|
+
return resolved if "/" in resolved else None
|
|
185
|
+
|
|
159
186
|
def aim_model_spec(self) -> AimModelSpec | None:
|
|
160
187
|
"""Let aim (ai-model-manager) download + manage the model, per CLAUDE.md's aim
|
|
161
188
|
rule. Resolve the backend first so the source targets the repo this box runs
|
|
@@ -72,27 +72,6 @@ class Qwen3OmniSTT(STTProvider):
|
|
|
72
72
|
async def health_check(self) -> bool:
|
|
73
73
|
return self._model is not None
|
|
74
74
|
|
|
75
|
-
@staticmethod
|
|
76
|
-
def _resolve_device_map(device_map: str) -> str:
|
|
77
|
-
"""Resolve the configured device_map to a concrete placement.
|
|
78
|
-
|
|
79
|
-
device_map="auto" mis-reads unified-memory GPUs (DGX/GB10, Jetson) whose free
|
|
80
|
-
VRAM reports as N/A → accelerate concludes nothing "fits" and offloads the whole
|
|
81
|
-
30B model to CPU (~20x slower). Pin the GPU when CUDA is present (mirrors gemma4's
|
|
82
|
-
_load_cuda fix); fall back to CPU only when there's no CUDA at all. Explicit
|
|
83
|
-
"cuda"/"cpu" are user overrides and pass through untouched (no torch probe).
|
|
84
|
-
|
|
85
|
-
NOTE: pinning "cuda" places the whole model on a single device — correct for the
|
|
86
|
-
unified-memory targets this engine is gated to (GB10 128GB / Jetson). True
|
|
87
|
-
multi-GPU sharding of the 30B MoE would need a separate explicit option (e.g.
|
|
88
|
-
"balanced"), not "auto".
|
|
89
|
-
"""
|
|
90
|
-
dm = (device_map or "auto").strip().lower()
|
|
91
|
-
if dm != "auto":
|
|
92
|
-
return dm
|
|
93
|
-
import torch
|
|
94
|
-
return "cuda" if torch.cuda.is_available() else "cpu"
|
|
95
|
-
|
|
96
75
|
async def _ensure_model(self, s: "Qwen3OmniSTTSettings") -> None:
|
|
97
76
|
key = (s.model.strip(), s.dtype.strip(), s.device_map.strip(), s.attn_implementation.strip())
|
|
98
77
|
if self._model is not None and self._loaded_key == key:
|
|
@@ -108,16 +87,9 @@ class Qwen3OmniSTT(STTProvider):
|
|
|
108
87
|
"pip install 'openspeechapi[qwen3-omni-stt]'"
|
|
109
88
|
) from exc
|
|
110
89
|
|
|
111
|
-
# Resolve device placement on THIS (event-loop) thread, before the heavy load is
|
|
112
|
-
# offloaded to a worker. Probing CUDA imports torch, and the FIRST torch import in
|
|
113
|
-
# an asyncio worker thread segfaults on macOS; resolving here also avoids relying on
|
|
114
|
-
# transformers having already pre-imported torch. _load() then loads with a concrete
|
|
115
|
-
# device only.
|
|
116
|
-
device_map = self._resolve_device_map(s.device_map)
|
|
117
|
-
|
|
118
90
|
def _load() -> tuple[Any, Any]:
|
|
119
91
|
model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
|
|
120
|
-
s.model, dtype=s.dtype, device_map=device_map,
|
|
92
|
+
s.model, dtype=s.dtype, device_map=s.device_map,
|
|
121
93
|
attn_implementation=s.attn_implementation,
|
|
122
94
|
)
|
|
123
95
|
processor = Qwen3OmniMoeProcessor.from_pretrained(s.model)
|
|
@@ -14,6 +14,7 @@ from openspeechapi.dispatch.watcher import ConfigWatcher
|
|
|
14
14
|
from openspeechapi.local_engines import EngineManager
|
|
15
15
|
from openspeechapi.logging_config import ensure_configured, logger
|
|
16
16
|
from openspeechapi.server.middleware import RequestContextMiddleware
|
|
17
|
+
from openspeechapi.server.model_downloads import ModelDownloadManager
|
|
17
18
|
from openspeechapi.server.routes import stt, tts, management, webui
|
|
18
19
|
from openspeechapi.server.system_metrics import SystemMonitor
|
|
19
20
|
from openspeechapi.server.ws import stt_stream, tts_stream
|
|
@@ -137,6 +138,7 @@ def create_app(config_path: Path, registry: ProviderRegistry) -> FastAPI:
|
|
|
137
138
|
app.state.registry = registry
|
|
138
139
|
app.state.server_config = config.server
|
|
139
140
|
app.state.engine_manager = EngineManager()
|
|
141
|
+
app.state.model_downloads = ModelDownloadManager(endpoint=config.server.hf_endpoint)
|
|
140
142
|
|
|
141
143
|
# Request-scoped logging context (request_id + route timing) — added first
|
|
142
144
|
# so that auth-middleware rejections still get logged with a request_id.
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Background model-weight downloads with progress (decoupled from request timeouts).
|
|
2
|
+
|
|
3
|
+
Downloading a big model (e.g. gemma-4-E4B ~tens of GB) on a slow mirror takes far longer than the
|
|
4
|
+
per-request invoke timeout (300s) — doing it inline in a transcribe request times out and leaves a
|
|
5
|
+
partial download. This runs the download in a **background thread**, tracks progress (downloaded /
|
|
6
|
+
total bytes), appends progress to the server log, and exposes it via poll + SSE so the WebUI stays
|
|
7
|
+
responsive. Reuses the ``ProgressEmitter`` used by engine installs.
|
|
8
|
+
|
|
9
|
+
Downloads land in the standard HF cache via ``huggingface_hub.snapshot_download`` honouring
|
|
10
|
+
``HF_ENDPOINT`` (set from ``server.hf_endpoint``, e.g. hf-mirror); once cached, the engine loads
|
|
11
|
+
from disk instantly with no further download.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import uuid
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from openspeechapi.local_engines.models import TaskStatus
|
|
23
|
+
from openspeechapi.local_engines.progress import ProgressEmitter, ProgressEvent
|
|
24
|
+
from openspeechapi.logging_config import logger
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class DownloadTask:
|
|
29
|
+
"""State of one background model download (snapshot of progress for poll/SSE)."""
|
|
30
|
+
task_id: str
|
|
31
|
+
repo: str
|
|
32
|
+
status: TaskStatus = TaskStatus.QUEUED
|
|
33
|
+
progress: float | None = None # 0..100, or None when the total size is unknown
|
|
34
|
+
downloaded_mb: float = 0.0
|
|
35
|
+
total_mb: float | None = None
|
|
36
|
+
message: str = ""
|
|
37
|
+
error: str | None = None
|
|
38
|
+
created_at: float = 0.0
|
|
39
|
+
updated_at: float = 0.0
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict[str, Any]:
|
|
42
|
+
return {
|
|
43
|
+
"task_id": self.task_id,
|
|
44
|
+
"repo": self.repo,
|
|
45
|
+
"status": self.status.value,
|
|
46
|
+
"progress": self.progress,
|
|
47
|
+
"downloaded_mb": round(self.downloaded_mb, 1),
|
|
48
|
+
"total_mb": round(self.total_mb, 1) if self.total_mb is not None else None,
|
|
49
|
+
"message": self.message,
|
|
50
|
+
"error": self.error,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _dir_size_bytes(path: str) -> int:
|
|
55
|
+
total = 0
|
|
56
|
+
for root, _dirs, files in os.walk(path):
|
|
57
|
+
for f in files:
|
|
58
|
+
try:
|
|
59
|
+
total += os.path.getsize(os.path.join(root, f))
|
|
60
|
+
except OSError:
|
|
61
|
+
continue
|
|
62
|
+
return total
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ModelDownloadManager:
|
|
66
|
+
"""Runs model downloads in background threads with progress events (poll + SSE)."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, *, endpoint: str = "", poll_interval: float = 2.0,
|
|
69
|
+
now: Any = time.time) -> None:
|
|
70
|
+
self.emitter = ProgressEmitter()
|
|
71
|
+
self._endpoint = endpoint or None
|
|
72
|
+
self._poll = max(0.5, float(poll_interval))
|
|
73
|
+
self._now = now
|
|
74
|
+
self._tasks: dict[str, DownloadTask] = {}
|
|
75
|
+
self._by_repo: dict[str, str] = {} # repo -> task_id (de-dupe in-flight)
|
|
76
|
+
self._threads: dict[str, threading.Thread] = {}
|
|
77
|
+
self._lock = threading.Lock()
|
|
78
|
+
|
|
79
|
+
# ── public API ───────────────────────────────────────────────────────────
|
|
80
|
+
def start(self, repo: str) -> DownloadTask:
|
|
81
|
+
"""Start (or return the in-flight) download for *repo*. Returns immediately."""
|
|
82
|
+
repo = repo.strip()
|
|
83
|
+
with self._lock:
|
|
84
|
+
existing_id = self._by_repo.get(repo)
|
|
85
|
+
if existing_id is not None:
|
|
86
|
+
existing = self._tasks.get(existing_id)
|
|
87
|
+
if existing and existing.status in (TaskStatus.QUEUED, TaskStatus.RUNNING):
|
|
88
|
+
return existing # de-dupe: same repo already downloading
|
|
89
|
+
t = self._now()
|
|
90
|
+
task = DownloadTask(task_id=uuid.uuid4().hex[:12], repo=repo,
|
|
91
|
+
status=TaskStatus.QUEUED, message="queued",
|
|
92
|
+
created_at=t, updated_at=t)
|
|
93
|
+
self._tasks[task.task_id] = task
|
|
94
|
+
self._by_repo[repo] = task.task_id
|
|
95
|
+
th = threading.Thread(target=self._run, args=(task,), daemon=True,
|
|
96
|
+
name=f"model-dl-{task.task_id}")
|
|
97
|
+
self._threads[task.task_id] = th
|
|
98
|
+
th.start()
|
|
99
|
+
return task
|
|
100
|
+
|
|
101
|
+
def get(self, task_id: str) -> DownloadTask | None:
|
|
102
|
+
with self._lock:
|
|
103
|
+
return self._tasks.get(task_id)
|
|
104
|
+
|
|
105
|
+
def list(self) -> list[DownloadTask]:
|
|
106
|
+
with self._lock:
|
|
107
|
+
return list(self._tasks.values())
|
|
108
|
+
|
|
109
|
+
def active_for(self, repo: str) -> DownloadTask | None:
|
|
110
|
+
"""The in-flight (PENDING/RUNNING) task for *repo*, if any."""
|
|
111
|
+
with self._lock:
|
|
112
|
+
tid = self._by_repo.get(repo.strip())
|
|
113
|
+
task = self._tasks.get(tid) if tid else None
|
|
114
|
+
if task and task.status in (TaskStatus.QUEUED, TaskStatus.RUNNING):
|
|
115
|
+
return task
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
# ── internals ────────────────────────────────────────────────────────────
|
|
119
|
+
def _emit(self, task: DownloadTask, phase: str) -> None:
|
|
120
|
+
task.updated_at = self._now()
|
|
121
|
+
self.emitter.emit(ProgressEvent(
|
|
122
|
+
task_id=task.task_id, engine=task.repo, action="download", runtime="hf",
|
|
123
|
+
phase=phase, message=task.message, status=task.status, progress=task.progress,
|
|
124
|
+
metadata={"downloaded_mb": round(task.downloaded_mb, 1),
|
|
125
|
+
"total_mb": round(task.total_mb, 1) if task.total_mb is not None else None},
|
|
126
|
+
))
|
|
127
|
+
|
|
128
|
+
def _resolve_total_mb(self, repo: str) -> float | None:
|
|
129
|
+
"""Total download size (MB) via the HF API, for a % progress. None if unavailable."""
|
|
130
|
+
try:
|
|
131
|
+
from huggingface_hub import HfApi
|
|
132
|
+
info = HfApi(endpoint=self._endpoint).model_info(repo, files_metadata=True)
|
|
133
|
+
total = sum(s.size for s in (info.siblings or []) if getattr(s, "size", None))
|
|
134
|
+
return total / 1048576 if total else None
|
|
135
|
+
except Exception as exc: # noqa: BLE001 - best-effort; fall back to byte counter
|
|
136
|
+
logger.debug("model download: could not get total size for {}: {}", repo, exc)
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
def _target_dir(self, repo: str) -> str:
|
|
140
|
+
from huggingface_hub.constants import HF_HUB_CACHE
|
|
141
|
+
return os.path.join(HF_HUB_CACHE, "models--" + repo.replace("/", "--"))
|
|
142
|
+
|
|
143
|
+
def _run(self, task: DownloadTask) -> None:
|
|
144
|
+
task.status = TaskStatus.RUNNING
|
|
145
|
+
task.message = "resolving size"
|
|
146
|
+
task.total_mb = self._resolve_total_mb(task.repo)
|
|
147
|
+
self._emit(task, "starting")
|
|
148
|
+
target = self._target_dir(task.repo)
|
|
149
|
+
|
|
150
|
+
stop = threading.Event()
|
|
151
|
+
last_log = [0.0, -10.0] # [last_ts, last_pct] for throttled log lines
|
|
152
|
+
|
|
153
|
+
def poll() -> None:
|
|
154
|
+
while not stop.is_set():
|
|
155
|
+
cur_mb = _dir_size_bytes(target) / 1048576 if os.path.isdir(target) else 0.0
|
|
156
|
+
task.downloaded_mb = cur_mb
|
|
157
|
+
task.progress = (min(99.9, cur_mb / task.total_mb * 100)
|
|
158
|
+
if task.total_mb else None)
|
|
159
|
+
task.message = "downloading"
|
|
160
|
+
self._emit(task, "downloading")
|
|
161
|
+
# throttle log: every +5% or every 10s
|
|
162
|
+
now = self._now()
|
|
163
|
+
pct = task.progress if task.progress is not None else 0.0
|
|
164
|
+
if now - last_log[0] >= 10 or pct - last_log[1] >= 5:
|
|
165
|
+
last_log[0], last_log[1] = now, pct
|
|
166
|
+
logger.info("model download {}: {:.0f}MB{} ({})", task.repo, cur_mb,
|
|
167
|
+
f"/{task.total_mb:.0f}MB {pct:.0f}%" if task.total_mb else "",
|
|
168
|
+
task.status.value)
|
|
169
|
+
stop.wait(self._poll)
|
|
170
|
+
|
|
171
|
+
poller = threading.Thread(target=poll, daemon=True, name=f"dl-poll-{task.task_id}")
|
|
172
|
+
poller.start()
|
|
173
|
+
try:
|
|
174
|
+
from huggingface_hub import snapshot_download
|
|
175
|
+
snapshot_download(repo_id=task.repo, endpoint=self._endpoint)
|
|
176
|
+
stop.set()
|
|
177
|
+
poller.join(timeout=2)
|
|
178
|
+
task.downloaded_mb = (_dir_size_bytes(target) / 1048576
|
|
179
|
+
if os.path.isdir(target) else task.downloaded_mb)
|
|
180
|
+
task.status = TaskStatus.SUCCEEDED
|
|
181
|
+
task.progress = 100.0
|
|
182
|
+
task.message = "completed"
|
|
183
|
+
self._emit(task, "completed")
|
|
184
|
+
logger.info("model download {} completed: {:.0f}MB", task.repo, task.downloaded_mb)
|
|
185
|
+
except Exception as exc: # noqa: BLE001 - surface the failure on the task
|
|
186
|
+
stop.set()
|
|
187
|
+
task.status = TaskStatus.FAILED
|
|
188
|
+
task.error = str(exc)
|
|
189
|
+
task.message = f"failed: {exc}"
|
|
190
|
+
self._emit(task, "failed")
|
|
191
|
+
logger.warning("model download {} failed: {}", task.repo, exc)
|
|
@@ -1243,3 +1243,47 @@ async def cancel_engine_task(request: Request, task_id: str):
|
|
|
1243
1243
|
if task is None:
|
|
1244
1244
|
raise HTTPException(status_code=404, detail=f"Task not found: {task_id}")
|
|
1245
1245
|
return {"task": _task_snapshot(task)}
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
# ── background model-weight downloads (decoupled from the request timeout) ─────
|
|
1249
|
+
|
|
1250
|
+
@router.post("/models/download")
|
|
1251
|
+
async def start_model_download(request: Request):
|
|
1252
|
+
"""Start a background download of a model's weights; returns immediately with a task id.
|
|
1253
|
+
|
|
1254
|
+
Body: ``{"repo": "<hf id>"}`` (explicit) or ``{"engine": "<alias>"}`` (download that engine's
|
|
1255
|
+
configured model). The download runs in a background thread (no request/invoke timeout); poll
|
|
1256
|
+
``GET /v1/models/download/{task_id}`` for progress. Once cached, the engine loads instantly."""
|
|
1257
|
+
try:
|
|
1258
|
+
body = await request.json()
|
|
1259
|
+
except Exception: # noqa: BLE001 - empty/invalid body → no args
|
|
1260
|
+
body = {}
|
|
1261
|
+
repo = str(body.get("repo") or "").strip()
|
|
1262
|
+
engine = str(body.get("engine") or "").strip()
|
|
1263
|
+
if not repo and engine:
|
|
1264
|
+
# Resolve the repo the engine will ACTUALLY load on this box (aim-resolved /
|
|
1265
|
+
# hub-mapped), not the raw display_info.model config value — so the download
|
|
1266
|
+
# warms the exact cache the engine reads from. Remote/cloud engines (and any
|
|
1267
|
+
# engine we can't resolve) return None here → 404 below, as before.
|
|
1268
|
+
repo = str(request.app.state.dispatcher.expected_repo_for(engine) or "").strip()
|
|
1269
|
+
if not repo:
|
|
1270
|
+
raise HTTPException(
|
|
1271
|
+
status_code=404,
|
|
1272
|
+
detail=f"engine '{engine}' not found or has no model to download")
|
|
1273
|
+
if not repo:
|
|
1274
|
+
raise HTTPException(status_code=400, detail="provide 'repo' (HF id) or 'engine'")
|
|
1275
|
+
task = request.app.state.model_downloads.start(repo)
|
|
1276
|
+
return task.to_dict()
|
|
1277
|
+
|
|
1278
|
+
|
|
1279
|
+
@router.get("/models/downloads")
|
|
1280
|
+
async def list_model_downloads(request: Request):
|
|
1281
|
+
return {"downloads": [t.to_dict() for t in request.app.state.model_downloads.list()]}
|
|
1282
|
+
|
|
1283
|
+
|
|
1284
|
+
@router.get("/models/download/{task_id}")
|
|
1285
|
+
async def get_model_download(request: Request, task_id: str):
|
|
1286
|
+
task = request.app.state.model_downloads.get(task_id)
|
|
1287
|
+
if task is None:
|
|
1288
|
+
raise HTTPException(status_code=404, detail=f"download task not found: {task_id}")
|
|
1289
|
+
return task.to_dict()
|
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
from fastapi import APIRouter, Depends, File, Form, Request, UploadFile, HTTPException
|
|
4
4
|
from openspeechapi.core.models import AudioData, STTOptions
|
|
5
|
+
from openspeechapi.core.model_hub import model_is_cached
|
|
5
6
|
from openspeechapi.dispatch.fanout import FirstCompleted, HighestConfidence, CollectAll
|
|
7
|
+
from openspeechapi.dispatch.lifecycle import ProviderState
|
|
6
8
|
from openspeechapi.exceptions import AudioConversionError, ProviderNotFoundError, FanOutAllFailedError
|
|
7
9
|
from openspeechapi.server.system_metrics import thermal_guard
|
|
8
10
|
from openspeechapi.utils.audio_converter import AudioConverter
|
|
@@ -16,6 +18,32 @@ STRATEGY_MAP = {
|
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
|
|
21
|
+
def model_download_gate(request, alias: str, model_override: str | None = None) -> tuple[str, str] | None: # noqa: ANN001
|
|
22
|
+
"""本地模型「未下载」预检 —— 返回 ``(message, repo)`` 表示应拦截(用于 409),None 表示放行。
|
|
23
|
+
|
|
24
|
+
``request`` 是 FastAPI ``Request``(REST)或 ``WebSocket``(流式)—— 两者都有
|
|
25
|
+
``.app.state.dispatcher`` / ``.app.state.model_downloads``,故同一套逻辑通用。
|
|
26
|
+
|
|
27
|
+
仅拦截:本地引擎(``expected_repo_for`` 非空)+ 模型未完整缓存 + 引擎当前不是已加载
|
|
28
|
+
(READY)状态。已 READY 的引擎模型必然已就绪,直接放行;云引擎/远程引擎 ``expected_repo_for``
|
|
29
|
+
返回 None,不受影响。已在后台下载中则给出「正在后台下载(进度)」提示,否则提示去 Engines 页
|
|
30
|
+
点〖下载模型〗。这样避免在转写/流式请求里现下大模型导致 300s 超时。"""
|
|
31
|
+
dispatcher = request.app.state.dispatcher
|
|
32
|
+
repo = dispatcher.expected_repo_for(alias, model_override=model_override)
|
|
33
|
+
if not repo or model_is_cached(repo):
|
|
34
|
+
return None
|
|
35
|
+
# 已加载(READY)→ 模型必然已就绪,跳过(覆盖 model_is_cached 看不到的 model_path 等情形)。
|
|
36
|
+
if dispatcher._lifecycle.get_state(alias) == ProviderState.READY:
|
|
37
|
+
return None
|
|
38
|
+
downloads = getattr(request.app.state, "model_downloads", None)
|
|
39
|
+
dl = downloads.active_for(repo) if downloads is not None else None
|
|
40
|
+
if dl is not None:
|
|
41
|
+
pct = getattr(dl, "progress", None)
|
|
42
|
+
progress = f"{pct:.0f}%" if isinstance(pct, (int, float)) else "进行中"
|
|
43
|
+
return (f"模型 {repo} 正在后台下载({progress}),请稍候再试", repo)
|
|
44
|
+
return (f"模型 {repo} 未下载 —— 请在 Engines 页点〖下载模型〗,后台下载完成后再试", repo)
|
|
45
|
+
|
|
46
|
+
|
|
19
47
|
@router.post("/transcribe", dependencies=[Depends(thermal_guard)])
|
|
20
48
|
async def transcribe(
|
|
21
49
|
request: Request,
|
|
@@ -60,6 +88,16 @@ async def transcribe(
|
|
|
60
88
|
overrides=overrides,
|
|
61
89
|
)
|
|
62
90
|
|
|
91
|
+
# Pre-check: a local engine whose model isn't fully downloaded yet would
|
|
92
|
+
# otherwise try to fetch a large model inline → 300s invoke timeout. Return
|
|
93
|
+
# 409 immediately so the WebUI can guide the user to the download button.
|
|
94
|
+
gate = model_download_gate(
|
|
95
|
+
request, provider,
|
|
96
|
+
model_override=model or (overrides.get("model") if overrides else None),
|
|
97
|
+
)
|
|
98
|
+
if gate is not None:
|
|
99
|
+
raise HTTPException(status_code=409, detail=gate[0])
|
|
100
|
+
|
|
63
101
|
try:
|
|
64
102
|
result = await dispatcher.stt.transcribe(provider, audio_data, opts)
|
|
65
103
|
except AudioConversionError as e:
|
|
@@ -4,7 +4,9 @@ from __future__ import annotations
|
|
|
4
4
|
from pathlib import Path
|
|
5
5
|
|
|
6
6
|
from fastapi import APIRouter, HTTPException
|
|
7
|
-
from fastapi.responses import FileResponse
|
|
7
|
+
from fastapi.responses import FileResponse, HTMLResponse
|
|
8
|
+
|
|
9
|
+
from openspeechapi import __version__
|
|
8
10
|
|
|
9
11
|
router = APIRouter()
|
|
10
12
|
|
|
@@ -22,7 +24,13 @@ async def webui_index():
|
|
|
22
24
|
index = _WEBUI_DIR / "index.html"
|
|
23
25
|
if not index.exists():
|
|
24
26
|
raise HTTPException(status_code=404, detail="WebUI is not available")
|
|
25
|
-
|
|
27
|
+
# Cache-bust app.js/styles.css with the package version: a deploy changes the URL, so the
|
|
28
|
+
# browser always fetches the new frontend (stronger than revalidation alone — survives
|
|
29
|
+
# heuristic/proxy caches, no hard refresh needed). The asset route ignores the query string.
|
|
30
|
+
html = index.read_text(encoding="utf-8")
|
|
31
|
+
html = html.replace("/ui/app.js", f"/ui/app.js?v={__version__}")
|
|
32
|
+
html = html.replace("/ui/styles.css", f"/ui/styles.css?v={__version__}")
|
|
33
|
+
return HTMLResponse(html, headers=_NO_CACHE)
|
|
26
34
|
|
|
27
35
|
|
|
28
36
|
@router.get("/ui/{asset_name}")
|