Spaces:
Running
Running
Restore CPU demo while resolving ZeroGPU hardware migration
Browse files- LICENSE.md +1 -1
- README.md +4 -7
- app.py +298 -207
- index.html +1 -1
- inference_core.py +0 -332
- licenses/gradio-client-Apache-2.0.txt +0 -201
- requirements.txt +5 -1
- server_runtime/asr_semantic.py +7 -2
- server_runtime/clap_sound_router.py +5 -12
- server_runtime/typed_runtime.py +0 -1
- ui.js +13 -13
- vendor/gradio-client.min.js +0 -8
LICENSE.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# License and third-party notices
|
| 2 |
|
| 3 |
-
This public demo includes model artifacts derived from Qwen3-ASR-0.6B and CLAP (Apache-2.0) and ModernBERT-Ja-30M and ModernBERT-Ja-130M (MIT). The corresponding license texts and notices are included under `licenses/`. The
|
| 4 |
|
| 5 |
The original model heads, routing components, and interface created by mocomoco inc. are © 2026 mocomoco inc. No separate redistribution license for those original components is granted by this Space. This does not limit rights provided by the upstream licenses for upstream-derived material.
|
|
|
|
| 1 |
# License and third-party notices
|
| 2 |
|
| 3 |
+
This public demo includes model artifacts derived from Qwen3-ASR-0.6B and CLAP (Apache-2.0) and ModernBERT-Ja-30M and ModernBERT-Ja-130M (MIT). The corresponding license texts and notices are included under `licenses/`. The LINE Seed JP font is covered by the license in `licenses/LINE-Seed-OFL.txt`. Sample audio attribution is recorded in `examples/ATTRIBUTION.json`.
|
| 4 |
|
| 5 |
The original model heads, routing components, and interface created by mocomoco inc. are © 2026 mocomoco inc. No separate redistribution license for those original components is granted by this Space. This does not limit rights provided by the upstream licenses for upstream-derived material.
|
README.md
CHANGED
|
@@ -3,11 +3,8 @@ title: Audio Decision Model (inspired by Jev)
|
|
| 3 |
emoji: 🎧
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: blue
|
| 6 |
-
sdk:
|
| 7 |
-
|
| 8 |
-
app_file: app.py
|
| 9 |
-
python_version: 3.12
|
| 10 |
-
suggested_hardware: zero-a10g
|
| 11 |
pinned: false
|
| 12 |
---
|
| 13 |
|
|
@@ -19,7 +16,7 @@ Inspired by [TypeSafe AI’s Jev](https://typesafe.ai/blog/introducing-system-on
|
|
| 19 |
|
| 20 |
音声と質問を入力すると、`Noul`(Yes / No)・`Choice`(選択)・`Score`(数値)の構造化JSONで答えます。予約の取り消しやキーワード、音楽や動物の鳴き声など、発話内容と周囲の音について質問できます。
|
| 21 |
|
| 22 |
-
質問と選択肢は画面上で編集できます。Cloudは
|
| 23 |
|
| 24 |
[モデルファイル](https://huggingface.co/spaces/mocomoco-inc/AudioDecisionModel/tree/main) · [mocomoco inc.](https://mocomoco.ai)
|
| 25 |
|
|
@@ -41,6 +38,6 @@ Inspired by [TypeSafe AI’s Jev](https://typesafe.ai/blog/introducing-system-on
|
|
| 41 |
|
| 42 |
## English
|
| 43 |
|
| 44 |
-
Audio Decision Model takes an audio clip and editable natural-language questions and returns structured JSON with Yes/No, choice, or ordinal score answers. You can record audio, upload a file, or try a sample. Cloud mode
|
| 45 |
|
| 46 |
In a fixed 240-item evaluation of reservation/order intent and speech act together, both answers were correct for 88.75% of items. Accuracy for arbitrary new questions and speech-plus-background-audio questions remains under evaluation. See [LICENSE.md](LICENSE.md) and the [Space files](https://huggingface.co/spaces/mocomoco-inc/AudioDecisionModel/tree/main) for model details and notices. The design draws inspiration from [Jev / TypeSafe AI](https://typesafe.ai/blog/introducing-system-one-models-and-jev) and [OpenJev / SemIf](https://github.com/TheoLeeCJ/SemIf).
|
|
|
|
| 3 |
emoji: 🎧
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
|
|
|
|
|
|
|
|
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
|
|
|
| 16 |
|
| 17 |
音声と質問を入力すると、`Noul`(Yes / No)・`Choice`(選択)・`Score`(数値)の構造化JSONで答えます。予約の取り消しやキーワード、音楽や動物の鳴き声など、発話内容と周囲の音について質問できます。
|
| 18 |
|
| 19 |
+
質問と選択肢は画面上で編集できます。Cloudは[Qwen/Qwen3-ASR-0.6B](https://huggingface.co/Qwen/Qwen3-ASR-0.6B)、[sbintuitions/modernbert-ja-30m](https://huggingface.co/sbintuitions/modernbert-ja-30m)・[sbintuitions/modernbert-ja-130m](https://huggingface.co/sbintuitions/modernbert-ja-130m)、[laion/clap-htsat-unfused](https://huggingface.co/laion/clap-htsat-unfused)を組み合わせて処理します。Edge AIは量子化したONNXモデルをブラウザ上で実行し、入力データをクラウドへ送りません。
|
| 20 |
|
| 21 |
[モデルファイル](https://huggingface.co/spaces/mocomoco-inc/AudioDecisionModel/tree/main) · [mocomoco inc.](https://mocomoco.ai)
|
| 22 |
|
|
|
|
| 38 |
|
| 39 |
## English
|
| 40 |
|
| 41 |
+
Audio Decision Model takes an audio clip and editable natural-language questions and returns structured JSON with Yes/No, choice, or ordinal score answers. You can record audio, upload a file, or try a sample. Cloud mode combines [Qwen/Qwen3-ASR-0.6B](https://huggingface.co/Qwen/Qwen3-ASR-0.6B), [sbintuitions/modernbert-ja-30m](https://huggingface.co/sbintuitions/modernbert-ja-30m), [sbintuitions/modernbert-ja-130m](https://huggingface.co/sbintuitions/modernbert-ja-130m), and [laion/clap-htsat-unfused](https://huggingface.co/laion/clap-htsat-unfused); Edge AI runs quantized ONNX models in your browser without sending your audio or questions to the cloud.
|
| 42 |
|
| 43 |
In a fixed 240-item evaluation of reservation/order intent and speech act together, both answers were correct for 88.75% of items. Accuracy for arbitrary new questions and speech-plus-background-audio questions remains under evaluation. See [LICENSE.md](LICENSE.md) and the [Space files](https://huggingface.co/spaces/mocomoco-inc/AudioDecisionModel/tree/main) for model details and notices. The design draws inspiration from [Jev / TypeSafe AI](https://typesafe.ai/blog/introducing-system-one-models-and-jev) and [OpenJev / SemIf](https://github.com/TheoLeeCJ/SemIf).
|
app.py
CHANGED
|
@@ -1,230 +1,321 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 5 |
import json
|
| 6 |
-
import math
|
| 7 |
import os
|
| 8 |
-
import time
|
| 9 |
from pathlib import Path
|
|
|
|
| 10 |
|
| 11 |
import gradio as gr
|
| 12 |
-
import numpy as np
|
| 13 |
-
from fastapi.responses import FileResponse
|
| 14 |
-
from fastapi.staticfiles import StaticFiles
|
| 15 |
-
from scipy.signal import resample_poly
|
| 16 |
-
import spaces
|
| 17 |
-
import torch
|
| 18 |
-
from huggingface_hub import snapshot_download
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
ROOT = Path(__file__).resolve().parent
|
| 22 |
-
FRONTEND = ROOT
|
| 23 |
-
MODEL_REPO = "mocomoco-inc/AudioJev-AudioDecisionModel"
|
| 24 |
-
MODEL_REVISION = "ff07066f5e19538f0ee1b6d39a1c9a1c36ba78a3"
|
| 25 |
-
|
| 26 |
-
# ZeroGPU's CUDA emulation is active during module import. Place the models on
|
| 27 |
-
# CUDA here so inference does not load or transfer weights inside a GPU lease.
|
| 28 |
-
semantic_snapshot = Path(snapshot_download(
|
| 29 |
-
MODEL_REPO,
|
| 30 |
-
revision=MODEL_REVISION,
|
| 31 |
-
allow_patterns=[
|
| 32 |
-
"cloud/semantic_v8/semantic_head.pt",
|
| 33 |
-
"cloud/semantic_v8/text_encoder/*",
|
| 34 |
-
],
|
| 35 |
-
))
|
| 36 |
-
os.environ["AUDIO_JEV_SEMANTIC_DIR"] = str(semantic_snapshot / "cloud" / "semantic_v8")
|
| 37 |
-
os.environ["AUDIO_JEV_DEVICE"] = "cuda"
|
| 38 |
-
|
| 39 |
-
import inference_core as core # noqa: E402
|
| 40 |
-
|
| 41 |
-
bundle = core.get_model()
|
| 42 |
-
bundle.typed_predictor()
|
| 43 |
-
bundle.sound._load_base()
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
INTENT_QUESTION = {
|
| 47 |
-
"intent": {
|
| 48 |
-
"type": "choice",
|
| 49 |
-
"instructions": "話者が伝えたい用件は何ですか?",
|
| 50 |
-
"criteria": {
|
| 51 |
-
"none": "用件が特定できない",
|
| 52 |
-
"reservation": "予約をしたい",
|
| 53 |
-
"order": "注文をしたい",
|
| 54 |
-
"change": "予約や注文を変更したい",
|
| 55 |
-
"cancel": "予約や注文を取り消したい",
|
| 56 |
-
},
|
| 57 |
-
}
|
| 58 |
-
}
|
| 59 |
-
DOG_QUESTION = {
|
| 60 |
-
"dog": {
|
| 61 |
-
"type": "noul",
|
| 62 |
-
"instructions": "犬の鳴き声が聞こえますか?",
|
| 63 |
-
"criteria": {"false": "犬の鳴き声は聞こえない", "true": "犬の鳴き声が聞こえる"},
|
| 64 |
-
}
|
| 65 |
-
}
|
| 66 |
-
MUSIC_QUESTION = {
|
| 67 |
-
"music": {
|
| 68 |
-
"type": "noul",
|
| 69 |
-
"instructions": "音楽が流れていますか?",
|
| 70 |
-
"criteria": {"false": "音楽は流れていない", "true": "音楽が流れている"},
|
| 71 |
-
}
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def prepare_audio(audio: tuple[int, np.ndarray] | None) -> np.ndarray:
|
| 76 |
-
if audio is None:
|
| 77 |
-
raise gr.Error("音声を録音・アップロードするか、サンプルを選んでください。")
|
| 78 |
-
sample_rate, values = audio
|
| 79 |
-
if sample_rate <= 0:
|
| 80 |
-
raise gr.Error("音声のサンプルレートが不正です。")
|
| 81 |
-
wave = np.asarray(values)
|
| 82 |
-
if wave.ndim == 2:
|
| 83 |
-
wave = wave.astype(np.float32).mean(axis=1)
|
| 84 |
-
if wave.ndim != 1:
|
| 85 |
-
raise gr.Error("モノラルまたはステレオ音声を指定してください。")
|
| 86 |
-
if np.issubdtype(wave.dtype, np.integer):
|
| 87 |
-
wave = wave.astype(np.float32) / 32768.0
|
| 88 |
-
else:
|
| 89 |
-
wave = wave.astype(np.float32)
|
| 90 |
-
if not np.isfinite(wave).all():
|
| 91 |
-
raise gr.Error("音声に無効な値が含まれています。")
|
| 92 |
-
divisor = math.gcd(int(sample_rate), 16000)
|
| 93 |
-
wave = resample_poly(wave, 16000 // divisor, int(sample_rate) // divisor).astype(np.float32)
|
| 94 |
-
if not 4000 <= len(wave) <= 480000:
|
| 95 |
-
raise gr.Error("0.25〜30秒の音声を指定してください。")
|
| 96 |
-
return np.clip(wave, -1.0, 1.0)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
@spaces.GPU(duration=90)
|
| 100 |
-
def analyze_gradio(audio: tuple[int, np.ndarray] | None, context: str, questions_json: str):
|
| 101 |
-
started = time.perf_counter()
|
| 102 |
-
wave = prepare_audio(audio)
|
| 103 |
-
try:
|
| 104 |
-
questions = json.loads(questions_json)
|
| 105 |
-
except json.JSONDecodeError as error:
|
| 106 |
-
raise gr.Error(f"質問JSONを読み取れません: {error.msg}") from error
|
| 107 |
-
if not isinstance(questions, dict):
|
| 108 |
-
raise gr.Error("質問JSONは、質問名をキーにしたオブジェクトにしてください。")
|
| 109 |
-
try:
|
| 110 |
-
payload = core.AnalyzeRequest(
|
| 111 |
-
samples=wave.tolist(), context=context or "", questions=questions,
|
| 112 |
-
)
|
| 113 |
-
result = core.analyze(payload)
|
| 114 |
-
except ValueError as error:
|
| 115 |
-
raise gr.Error(str(error)) from error
|
| 116 |
-
device = torch.cuda.get_device_name(0)
|
| 117 |
-
result["execution"]["gpu_device"] = device
|
| 118 |
-
elapsed = time.perf_counter() - started
|
| 119 |
-
return result, f"**GPU:** {device} · **推論:** {elapsed:.2f}秒(キュー待ちを除く)"
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
@spaces.GPU(duration=90)
|
| 123 |
-
def analyze_web(request: dict):
|
| 124 |
-
"""The public demo's JSON contract, executed through Gradio's GPU queue."""
|
| 125 |
-
if not isinstance(request, dict):
|
| 126 |
-
raise gr.Error("解析リクエストの形式が正しくありません。")
|
| 127 |
-
torch.cuda.synchronize()
|
| 128 |
-
gpu_started = time.perf_counter()
|
| 129 |
-
try:
|
| 130 |
-
wave = np.asarray(request.get("samples"), dtype=np.float32)
|
| 131 |
-
if wave.ndim != 1 or not 4000 <= len(wave) <= 480000 or not np.isfinite(wave).all():
|
| 132 |
-
raise ValueError("0.25〜30秒の有効な音声を指定してください���")
|
| 133 |
-
payload = core.AnalyzeRequest(
|
| 134 |
-
samples=wave.tolist(),
|
| 135 |
-
context=request.get("context") or "",
|
| 136 |
-
questions=request.get("questions"),
|
| 137 |
-
)
|
| 138 |
-
result = core.analyze(payload)
|
| 139 |
-
except ValueError as error:
|
| 140 |
-
raise gr.Error(str(error)) from error
|
| 141 |
-
result["execution"]["gpu_device"] = torch.cuda.get_device_name(0)
|
| 142 |
-
torch.cuda.synchronize()
|
| 143 |
-
result["latency_ms"]["gpu_function"] = (time.perf_counter() - gpu_started) * 1000
|
| 144 |
-
return result
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
with gr.Blocks(title="Audio Decision Model") as demo:
|
| 148 |
-
gr.Markdown(
|
| 149 |
-
"# Audio Decision Model\n"
|
| 150 |
-
"音声と言語・非言語の質問を入力すると、構造化JSONで返します。"
|
| 151 |
-
)
|
| 152 |
-
with gr.Row():
|
| 153 |
-
with gr.Column(scale=1):
|
| 154 |
-
audio_input = gr.Audio(
|
| 155 |
-
label="音声", sources=["microphone", "upload"], type="numpy",
|
| 156 |
-
)
|
| 157 |
-
context_input = gr.Textbox(label="文脈(任意)", lines=2)
|
| 158 |
-
questions_input = gr.Code(
|
| 159 |
-
label="質問JSON", language="json", lines=15,
|
| 160 |
-
value=json.dumps(INTENT_QUESTION, ensure_ascii=False, indent=2),
|
| 161 |
-
)
|
| 162 |
-
run_button = gr.Button("ZeroGPUで解析", variant="primary")
|
| 163 |
-
with gr.Column(scale=1):
|
| 164 |
-
timing_output = gr.Markdown("結果はここに表示されます。")
|
| 165 |
-
result_output = gr.JSON(label="結果JSON")
|
| 166 |
-
gr.Examples(
|
| 167 |
-
examples=[
|
| 168 |
-
[str(ROOT / "examples" / "irodori-reservation.wav"), json.dumps(INTENT_QUESTION, ensure_ascii=False, indent=2)],
|
| 169 |
-
[str(ROOT / "examples" / "animal-dog-birds-238688.wav"), json.dumps(DOG_QUESTION, ensure_ascii=False, indent=2)],
|
| 170 |
-
[str(ROOT / "examples" / "music-acoustic-loop-848704.wav"), json.dumps(MUSIC_QUESTION, ensure_ascii=False, indent=2)],
|
| 171 |
-
],
|
| 172 |
-
inputs=[audio_input, questions_input],
|
| 173 |
-
cache_examples=False,
|
| 174 |
-
)
|
| 175 |
-
run_button.click(
|
| 176 |
-
analyze_gradio,
|
| 177 |
-
inputs=[audio_input, context_input, questions_input],
|
| 178 |
-
outputs=[result_output, timing_output],
|
| 179 |
-
api_name="analyze",
|
| 180 |
-
)
|
| 181 |
-
web_request = gr.JSON(visible=False)
|
| 182 |
-
web_result = gr.JSON(visible=False)
|
| 183 |
-
web_trigger = gr.Button(visible=False)
|
| 184 |
-
web_trigger.click(
|
| 185 |
-
analyze_web,
|
| 186 |
-
inputs=[web_request],
|
| 187 |
-
outputs=[web_result],
|
| 188 |
-
api_name="analyze_web",
|
| 189 |
-
)
|
| 190 |
|
| 191 |
-
demo.queue(default_concurrency_limit=1, max_size=10)
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
demo.launch(prevent_thread_lock=True, ssr_mode=False, show_api=False)
|
| 196 |
-
app = demo.app
|
| 197 |
-
original_route_count = len(app.router.routes)
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
return {"ready": True, "readiness": "ready", "backend": "ZeroGPU"}
|
| 208 |
|
| 209 |
|
| 210 |
-
def
|
| 211 |
-
|
| 212 |
-
return FileResponse(FRONTEND / filename)
|
| 213 |
|
| 214 |
-
return respond
|
| 215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
for asset in (
|
| 218 |
-
"styles.css", "ui.js", "audio-player.js", "audio-recorder.js",
|
| 219 |
-
"inference.js", "inference-worker.js", "favicon.svg", "mocomoco-inc-logo.svg",
|
| 220 |
-
):
|
| 221 |
-
app.add_api_route(f"/{asset}", serve_asset(asset), methods=["GET"], include_in_schema=False)
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
app.router.routes[:] = app.router.routes[original_route_count:] + app.router.routes[:original_route_count]
|
| 228 |
|
| 229 |
if __name__ == "__main__":
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private Hugging Face Space UI for the Mocovoice Audio Jev research demo."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
+
import importlib
|
| 6 |
import json
|
|
|
|
| 7 |
import os
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
|
| 11 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
|
|
|
| 13 |
|
| 14 |
+
SPACE_ROOT = Path(__file__).resolve().parent
|
| 15 |
+
CATALOG_PATH = SPACE_ROOT / "examples" / "catalog.json"
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
DEFAULT_QUESTIONS = {
|
| 18 |
+
"本人確認": {
|
| 19 |
+
"type": "noul",
|
| 20 |
+
"instructions": "話者が本人確認に必要な情報を明確に述べているか確認してください。",
|
| 21 |
+
"criteria": {
|
| 22 |
+
"false": "必要な情報が不足している、または聞き取れません。",
|
| 23 |
+
"true": "必要な情報を明確に述べています。",
|
| 24 |
+
},
|
| 25 |
+
},
|
| 26 |
+
"聞き取りやすさ": {
|
| 27 |
+
"type": "score",
|
| 28 |
+
"instructions": "発話の明瞭さを評価してください。",
|
| 29 |
+
"criteria": ["聞き取りにくい", "一部聞き取りにくい", "概ね明瞭", "明瞭"],
|
| 30 |
+
},
|
| 31 |
+
}
|
| 32 |
|
| 33 |
+
PRESETS: dict[str, tuple[str, dict[str, Any]]] = {
|
| 34 |
+
"本人確認": (
|
| 35 |
+
"本人確認の会話です。氏名、生年月日など必要な情報が音声に含まれているか確認します。",
|
| 36 |
+
DEFAULT_QUESTIONS,
|
| 37 |
+
),
|
| 38 |
+
"応対品質": (
|
| 39 |
+
"顧客応対の通話です。応対内容と話し方を評価します。",
|
| 40 |
+
{
|
| 41 |
+
"要件の確認": {
|
| 42 |
+
"type": "noul",
|
| 43 |
+
"instructions": "依頼・質問の要点を確認できているか評価してください。",
|
| 44 |
+
"criteria": {"false": "要点を確認できていません。", "true": "要点を確認できています。"},
|
| 45 |
+
},
|
| 46 |
+
"応対評価": {
|
| 47 |
+
"type": "score",
|
| 48 |
+
"instructions": "丁寧で分かりやすい応対か評価してください。",
|
| 49 |
+
"criteria": ["改善が必要", "やや不十分", "適切", "非常に良い"],
|
| 50 |
+
},
|
| 51 |
+
},
|
| 52 |
+
),
|
| 53 |
+
"選択肢の分類": (
|
| 54 |
+
"この音声を、定義した選択肢のいずれかに分類します。",
|
| 55 |
+
{
|
| 56 |
+
"お問い合わせ種別": {
|
| 57 |
+
"type": "choice",
|
| 58 |
+
"instructions": "主なお問い合わせ内容を一つ選んでください。",
|
| 59 |
+
"criteria": {
|
| 60 |
+
"契約": "契約内容、変更、解約に関する問い合わせ",
|
| 61 |
+
"請求": "料金、請求、支払いに関する問い合わせ",
|
| 62 |
+
"技術": "利用方法や不具合に関する問い合わせ",
|
| 63 |
+
},
|
| 64 |
+
}
|
| 65 |
+
},
|
| 66 |
+
),
|
| 67 |
+
}
|
| 68 |
|
| 69 |
|
| 70 |
+
def _pretty(value: Any) -> str:
|
| 71 |
+
return json.dumps(value, ensure_ascii=False, indent=2)
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
+
def _user_error(message: str) -> None:
|
| 75 |
+
raise gr.Error(message)
|
|
|
|
| 76 |
|
|
|
|
| 77 |
|
| 78 |
+
def _parse_json(value: str, label: str, *, allow_empty: bool = False) -> Any:
|
| 79 |
+
if not value or not value.strip():
|
| 80 |
+
if allow_empty:
|
| 81 |
+
return None
|
| 82 |
+
_user_error(f"{label}を入力してください。")
|
| 83 |
+
try:
|
| 84 |
+
return json.loads(value)
|
| 85 |
+
except json.JSONDecodeError as exc:
|
| 86 |
+
_user_error(f"{label}は有効なJSONにしてください({exc.msg})。")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _validate_questions(raw: Any) -> dict[str, dict[str, Any]]:
|
| 90 |
+
if not isinstance(raw, dict) or not raw:
|
| 91 |
+
_user_error("質問JSONは、質問名をキーにした1件以上のオブジェクトにしてください。")
|
| 92 |
+
validated: dict[str, dict[str, Any]] = {}
|
| 93 |
+
for name, question in raw.items():
|
| 94 |
+
if not isinstance(name, str) or not name.strip():
|
| 95 |
+
_user_error("質問名は空でない文字列にしてください。")
|
| 96 |
+
if not isinstance(question, dict):
|
| 97 |
+
_user_error(f"「{name}」はオブジェクトにしてください。")
|
| 98 |
+
kind = question.get("type")
|
| 99 |
+
instructions = question.get("instructions")
|
| 100 |
+
criteria = question.get("criteria")
|
| 101 |
+
if kind not in {"noul", "choice", "score"}:
|
| 102 |
+
_user_error(f"「{name}」のtypeは noul / choice / score のいずれかにしてください。")
|
| 103 |
+
if not isinstance(instructions, str) or not instructions.strip():
|
| 104 |
+
_user_error(f"「{name}」のinstructionsを入力してください。")
|
| 105 |
+
if kind == "noul":
|
| 106 |
+
if criteria is None:
|
| 107 |
+
criteria = {"false": "該当しません。", "true": "該当します。"}
|
| 108 |
+
if not isinstance(criteria, dict) or set(criteria) != {"false", "true"}:
|
| 109 |
+
_user_error(f"「{name}」のnoul criteriaは false と true を持つオブジェクトにしてください。")
|
| 110 |
+
elif kind == "choice":
|
| 111 |
+
if not isinstance(criteria, dict) or not 2 <= len(criteria) <= 32:
|
| 112 |
+
_user_error(f"「{name}」のchoice criteriaは2〜32件の選択肢オブジェクトにしてください。")
|
| 113 |
+
else:
|
| 114 |
+
if not isinstance(criteria, list) or not 2 <= len(criteria) <= 10:
|
| 115 |
+
_user_error(f"「{name}」のscore criteriaは2〜10件の順序付きリストにしてください。")
|
| 116 |
+
validated[name.strip()] = {"type": kind, "instructions": instructions.strip(), "criteria": criteria}
|
| 117 |
+
return validated
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _questions_from_text(questions_text: str) -> dict[str, dict[str, Any]]:
|
| 121 |
+
return _validate_questions(_parse_json(questions_text, "質問JSON"))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _criteria_hint(kind: str) -> str:
|
| 125 |
+
if kind == "noul":
|
| 126 |
+
return _pretty({"false": "該当しません", "true": "該当します"})
|
| 127 |
+
if kind == "choice":
|
| 128 |
+
return _pretty({"選択肢A": "説明", "選択肢B": "説明"})
|
| 129 |
+
return _pretty(["低い", "高い"])
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _set_criteria_hint(kind: str) -> str:
|
| 133 |
+
return _criteria_hint(kind)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _edit_question(
|
| 137 |
+
questions_text: str, name: str, kind: str, instructions: str, criteria_text: str, action: str
|
| 138 |
+
) -> tuple[str, str, str, str]:
|
| 139 |
+
questions = _questions_from_text(questions_text)
|
| 140 |
+
clean_name = name.strip()
|
| 141 |
+
if not clean_name:
|
| 142 |
+
_user_error("質問名を入力してください。")
|
| 143 |
+
if action == "remove":
|
| 144 |
+
if clean_name not in questions:
|
| 145 |
+
_user_error(f"「{clean_name}」は質問JSONにありません。")
|
| 146 |
+
del questions[clean_name]
|
| 147 |
+
if not questions:
|
| 148 |
+
_user_error("最後の質問は削除できません。代わりに内容を更新してください。")
|
| 149 |
+
return _pretty(questions), "", "", _criteria_hint("noul")
|
| 150 |
+
|
| 151 |
+
criteria = _parse_json(criteria_text, "基準") if criteria_text.strip() else None
|
| 152 |
+
candidate = {clean_name: {"type": kind, "instructions": instructions, "criteria": criteria}}
|
| 153 |
+
normalized = _validate_questions(candidate)[clean_name]
|
| 154 |
+
questions[clean_name] = normalized
|
| 155 |
+
return _pretty(questions), "", "", _criteria_hint(kind)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _load_preset(name: str) -> tuple[str, str]:
|
| 159 |
+
context, questions = PRESETS[name]
|
| 160 |
+
return context, _pretty(questions)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _catalog_examples() -> list[list[Any]]:
|
| 164 |
+
if not CATALOG_PATH.is_file():
|
| 165 |
+
return []
|
| 166 |
+
try:
|
| 167 |
+
records = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
|
| 168 |
+
examples: list[list[Any]] = []
|
| 169 |
+
for record in records:
|
| 170 |
+
if not all(key in record for key in ("name", "audio", "context", "questions")):
|
| 171 |
+
continue
|
| 172 |
+
audio = SPACE_ROOT / str(record["audio"])
|
| 173 |
+
if audio.is_file():
|
| 174 |
+
examples.append([str(audio), str(record["context"]), _pretty(record["questions"])])
|
| 175 |
+
return examples
|
| 176 |
+
except (OSError, json.JSONDecodeError, TypeError):
|
| 177 |
+
return []
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _backend() -> Any:
|
| 181 |
+
try:
|
| 182 |
+
return importlib.import_module("demo_backend")
|
| 183 |
+
except Exception:
|
| 184 |
+
_user_error("デモの実行準備がまだ完了していません。少し待ってから再度お試しください。")
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _summary(result: Any) -> str:
|
| 188 |
+
if not isinstance(result, dict):
|
| 189 |
+
return "結果を受け取りました。下のJSONで詳細を確認してください。"
|
| 190 |
+
lines = ["### 読みやすい結果"]
|
| 191 |
+
transcript = result.get("transcript") or result.get("text")
|
| 192 |
+
if isinstance(transcript, str) and transcript.strip():
|
| 193 |
+
lines.append(f"**文字起こし** \\n{transcript.strip()}")
|
| 194 |
+
answers = result.get("answers") or result.get("results") or result.get("decisions")
|
| 195 |
+
if isinstance(answers, dict):
|
| 196 |
+
for name, answer in answers.items():
|
| 197 |
+
if isinstance(answer, dict):
|
| 198 |
+
value = answer.get("value", answer.get("answer", answer.get("label", answer)))
|
| 199 |
+
rationale = answer.get("reason") or answer.get("rationale")
|
| 200 |
+
lines.append(f"- **{name}**: {value}" + (f" — {rationale}" if rationale else ""))
|
| 201 |
+
else:
|
| 202 |
+
lines.append(f"- **{name}**: {answer}")
|
| 203 |
+
elif not transcript:
|
| 204 |
+
lines.append("下のJSONで結果を確認してください。")
|
| 205 |
+
return "\n".join(lines)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _analyze(audio_path: str | None, context: str, questions_text: str) -> tuple[Any, str]:
|
| 209 |
+
if not audio_path:
|
| 210 |
+
_user_error("音声ファイルをアップロードするか、マイクで録音してください。")
|
| 211 |
+
questions = _questions_from_text(questions_text)
|
| 212 |
+
try:
|
| 213 |
+
result = _backend().analyze(str(audio_path), context or "", _pretty(questions))
|
| 214 |
+
except gr.Error:
|
| 215 |
+
raise
|
| 216 |
+
except Exception:
|
| 217 |
+
_user_error("解析に失敗しました。音声と質問の内容を確認して、もう一度お試しください。")
|
| 218 |
+
return result, _summary(result)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _export_sample(
|
| 222 |
+
audio_path: str | None, context: str, questions_text: str, expected_text: str, result: Any
|
| 223 |
+
) -> str:
|
| 224 |
+
if not audio_path:
|
| 225 |
+
_user_error("サンプルを保存するには音声を指定してください。")
|
| 226 |
+
questions = _questions_from_text(questions_text)
|
| 227 |
+
expected = _parse_json(expected_text, "期待する回答", allow_empty=True)
|
| 228 |
+
result_json = result if isinstance(result, dict) else None
|
| 229 |
+
try:
|
| 230 |
+
return _backend().export_sample(str(audio_path), context or "", _pretty(questions), _pretty(expected) if expected is not None else "", result_json)
|
| 231 |
+
except gr.Error:
|
| 232 |
+
raise
|
| 233 |
+
except Exception:
|
| 234 |
+
_user_error("サンプルZIPを作成できませんでした。入力内容を確認して再度お試しください。")
|
| 235 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
def _model_status() -> str:
|
| 238 |
+
try:
|
| 239 |
+
return str(_backend().model_status())
|
| 240 |
+
except gr.Error:
|
| 241 |
+
return "準備状況を確認できません。"
|
| 242 |
+
except Exception:
|
| 243 |
+
return "準備状況を確認できません。"
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def build_app() -> gr.Blocks:
|
| 247 |
+
css = """
|
| 248 |
+
.gradio-container { max-width: 1120px !important; }
|
| 249 |
+
#hero { padding: 1.2rem 0 .4rem; }
|
| 250 |
+
#notice { border-left: 4px solid #e0a42b; padding: .7rem 1rem; background: #fff8e8; border-radius: 6px; }
|
| 251 |
+
"""
|
| 252 |
+
with gr.Blocks(title="Mocovoice Audio Jev", css=css) as demo:
|
| 253 |
+
gr.Markdown("# Mocovoice Audio Jev", elem_id="hero")
|
| 254 |
+
gr.Markdown(
|
| 255 |
+
"音声と文脈から、定義した質問への回答を試す研究プロトタイプです。"
|
| 256 |
+
"新しい業務・質問への精度は検証されていません。結果は確認用であり、自動処理は行いません。",
|
| 257 |
+
elem_id="notice",
|
| 258 |
+
)
|
| 259 |
+
with gr.Row():
|
| 260 |
+
with gr.Column(scale=1):
|
| 261 |
+
audio = gr.Audio(label="音声", sources=["upload", "microphone"], type="filepath")
|
| 262 |
+
context = gr.Textbox(label="文脈・補足", lines=5, placeholder="例:この通話は契約変更についてのお問い合わせです。")
|
| 263 |
+
preset = gr.Dropdown(label="プリセット", choices=list(PRESETS), value="本人確認")
|
| 264 |
+
load_preset = gr.Button("プリセットを読��込む")
|
| 265 |
+
with gr.Column(scale=1):
|
| 266 |
+
questions = gr.Textbox(label="質問JSON", value=_pretty(DEFAULT_QUESTIONS), lines=18)
|
| 267 |
+
with gr.Accordion("質問をフォームで編集", open=False):
|
| 268 |
+
gr.Markdown("質問名が同じ場合は更新します。削除は質問名を指定して行います。")
|
| 269 |
+
question_name = gr.Textbox(label="質問名")
|
| 270 |
+
question_type = gr.Radio(["noul", "choice", "score"], value="noul", label="回答タイプ")
|
| 271 |
+
question_instructions = gr.Textbox(label="指示", lines=3)
|
| 272 |
+
question_criteria = gr.Textbox(label="基準JSON", value=_criteria_hint("noul"), lines=5)
|
| 273 |
+
with gr.Row():
|
| 274 |
+
add_update = gr.Button("追加・更新", variant="secondary")
|
| 275 |
+
remove = gr.Button("削除", variant="stop")
|
| 276 |
+
|
| 277 |
+
with gr.Row():
|
| 278 |
+
analyze = gr.Button("解析する", variant="primary", scale=1)
|
| 279 |
+
status_button = gr.Button("準備状況を確認", scale=0)
|
| 280 |
+
status = gr.Textbox(label="モデルの準備状況", interactive=False, value="解析時にモデルを読み込みます。")
|
| 281 |
+
|
| 282 |
+
with gr.Row():
|
| 283 |
+
with gr.Column():
|
| 284 |
+
summary = gr.Markdown("解析すると、ここに読みやすい結果を表示します。")
|
| 285 |
+
with gr.Column():
|
| 286 |
+
result = gr.JSON(label="結果JSON")
|
| 287 |
+
|
| 288 |
+
with gr.Accordion("評価サンプルを保存", open=False):
|
| 289 |
+
gr.Markdown("解析を待たずに、音声・文脈・質問をデータセット用ZIPとして保存できます。期待する回答は任意です。")
|
| 290 |
+
expected = gr.Textbox(label="期待する回答JSON(任意)", lines=7, placeholder='例:{"本人確認": true}')
|
| 291 |
+
export = gr.Button("サンプルZIPを作成")
|
| 292 |
+
download = gr.File(label="サンプルZIP")
|
| 293 |
+
|
| 294 |
+
examples = _catalog_examples()
|
| 295 |
+
if examples:
|
| 296 |
+
gr.Examples(examples=examples, inputs=[audio, context, questions], label="収録済みの例")
|
| 297 |
+
|
| 298 |
+
load_preset.click(_load_preset, inputs=preset, outputs=[context, questions])
|
| 299 |
+
question_type.change(_set_criteria_hint, inputs=question_type, outputs=question_criteria)
|
| 300 |
+
add_update.click(
|
| 301 |
+
lambda q, n, t, i, c: _edit_question(q, n, t, i, c, "upsert"),
|
| 302 |
+
inputs=[questions, question_name, question_type, question_instructions, question_criteria],
|
| 303 |
+
outputs=[questions, question_name, question_instructions, question_criteria],
|
| 304 |
+
)
|
| 305 |
+
remove.click(
|
| 306 |
+
lambda q, n, t, i, c: _edit_question(q, n, t, i, c, "remove"),
|
| 307 |
+
inputs=[questions, question_name, question_type, question_instructions, question_criteria],
|
| 308 |
+
outputs=[questions, question_name, question_instructions, question_criteria],
|
| 309 |
+
)
|
| 310 |
+
analyze.click(_analyze, inputs=[audio, context, questions], outputs=[result, summary])
|
| 311 |
+
status_button.click(_model_status, outputs=status)
|
| 312 |
+
export.click(_export_sample, inputs=[audio, context, questions, expected, result], outputs=download)
|
| 313 |
+
return demo.queue(default_concurrency_limit=1)
|
| 314 |
|
|
|
|
| 315 |
|
| 316 |
if __name__ == "__main__":
|
| 317 |
+
build_app().launch(
|
| 318 |
+
server_name="0.0.0.0",
|
| 319 |
+
server_port=int(os.environ.get("PORT", "7860")),
|
| 320 |
+
share=False,
|
| 321 |
+
)
|
index.html
CHANGED
|
@@ -34,4 +34,4 @@
|
|
| 34 |
</div>
|
| 35 |
<aside class="output"><div class="section-heading"><h2>結果</h2><span id="inference-time" class="inference-time" hidden></span></div><div class="run-bar"><button id="analyze" class="primary">実行する</button><span id="analysis-status" role="status">音声を選んでください。</span></div><div id="summary" class="summary is-empty">音声を選んで解析すると、ここに結果が表示されます。</div><details class="result-details" open><summary>結果 JSON</summary><pre id="result-json">{}</pre></details>
|
| 36 |
</aside>
|
| 37 |
-
</div></main><footer class="site-footer"><div class="operator-block"><div class="operator"><span>企業情報</span><a class="operator-logo" href="https://mocomoco.ai" target="_blank" rel="noopener noreferrer"><img src="./mocomoco-inc-logo.svg" alt="mocomoco inc." width="217" height="33" loading="lazy"></a></div><p class="references">inspired by <a href="https://docs.typesafe.ai/introduction" target="_blank" rel="noopener noreferrer">Jev / TypeSafe AI</a> · <a href="https://github.com/TheoLeeCJ/SemIf" target="_blank" rel="noopener noreferrer">OpenJev / SemIf</a></p></div><a class="hf-link" href="https://huggingface.co/spaces/mocomoco-inc/AudioDecisionModel/tree/main" target="_blank" rel="noopener noreferrer"><span aria-hidden="true">🤗</span>Available on Hugging Face<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M8 5h11v11M19 5 5 19"/></svg></a></footer><dialog id="edge-intro" class="edge-intro" aria-labelledby="edge-intro-title" aria-describedby="edge-intro-description"><button id="edge-intro-close" class="dialog-close" type="button" aria-label="説明を閉じる" autofocus><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button><svg class="edge-intro-illustration" viewBox="0 0 280 110" fill="none" role="img" aria-label="音声を端末の中で処理し、外へ送信しないイメージ"><rect x="65" y="12" width="150" height="78" rx="9" fill="#162d40" stroke="#7293aa" stroke-width="2"/><rect x="74" y="21" width="132" height="60" rx="4" fill="#101b2a"/><path d="M53 91h174l-8 9H61l-8-9Z" fill="#203c51" stroke="#7293aa" stroke-width="2" stroke-linejoin="round"/><path d="M128 94h24" stroke="#7293aa" stroke-width="2" stroke-linecap="round"/><g stroke="#69d2ff" stroke-width="3" stroke-linecap="round"><path d="M91 47v10m7-18v26m7-31v36m7-27v18m7-13v8"/></g><path d="M132 52h20m-5-5 5 5-5 5" stroke="#7293aa" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><rect x="163" y="45" width="27" height="22" rx="5" fill="#25485e" stroke="#69d2ff" stroke-width="2"/><path d="M170 45v-6a6.5 6.5 0 0 1 13 0v6" stroke="#69d2ff" stroke-width="2"/><path d="m171 56 4 4 7-8" stroke="#a0e4ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg><h2 id="edge-intro-title">Edge AI</h2><div id="edge-intro-description"><p>データをクラウドに送らず、この端末内でJevを実行します。外部送信不要で、オフラインでも利用できます。初回のみ「モデルを読み込む」からモデルをダウンロードします。</p></div></dialog><script type="module" src="./ui.js?v=20260921-
|
|
|
|
| 34 |
</div>
|
| 35 |
<aside class="output"><div class="section-heading"><h2>結果</h2><span id="inference-time" class="inference-time" hidden></span></div><div class="run-bar"><button id="analyze" class="primary">実行する</button><span id="analysis-status" role="status">音声を選んでください。</span></div><div id="summary" class="summary is-empty">音声を選んで解析すると、ここに結果が表示されます。</div><details class="result-details" open><summary>結果 JSON</summary><pre id="result-json">{}</pre></details>
|
| 36 |
</aside>
|
| 37 |
+
</div></main><footer class="site-footer"><div class="operator-block"><div class="operator"><span>企業情報</span><a class="operator-logo" href="https://mocomoco.ai" target="_blank" rel="noopener noreferrer"><img src="./mocomoco-inc-logo.svg" alt="mocomoco inc." width="217" height="33" loading="lazy"></a></div><p class="references">inspired by <a href="https://docs.typesafe.ai/introduction" target="_blank" rel="noopener noreferrer">Jev / TypeSafe AI</a> · <a href="https://github.com/TheoLeeCJ/SemIf" target="_blank" rel="noopener noreferrer">OpenJev / SemIf</a></p></div><a class="hf-link" href="https://huggingface.co/spaces/mocomoco-inc/AudioDecisionModel/tree/main" target="_blank" rel="noopener noreferrer"><span aria-hidden="true">🤗</span>Available on Hugging Face<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M8 5h11v11M19 5 5 19"/></svg></a></footer><dialog id="edge-intro" class="edge-intro" aria-labelledby="edge-intro-title" aria-describedby="edge-intro-description"><button id="edge-intro-close" class="dialog-close" type="button" aria-label="説明を閉じる" autofocus><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button><svg class="edge-intro-illustration" viewBox="0 0 280 110" fill="none" role="img" aria-label="音声を端末の中で処理し、外へ送信しないイメージ"><rect x="65" y="12" width="150" height="78" rx="9" fill="#162d40" stroke="#7293aa" stroke-width="2"/><rect x="74" y="21" width="132" height="60" rx="4" fill="#101b2a"/><path d="M53 91h174l-8 9H61l-8-9Z" fill="#203c51" stroke="#7293aa" stroke-width="2" stroke-linejoin="round"/><path d="M128 94h24" stroke="#7293aa" stroke-width="2" stroke-linecap="round"/><g stroke="#69d2ff" stroke-width="3" stroke-linecap="round"><path d="M91 47v10m7-18v26m7-31v36m7-27v18m7-13v8"/></g><path d="M132 52h20m-5-5 5 5-5 5" stroke="#7293aa" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><rect x="163" y="45" width="27" height="22" rx="5" fill="#25485e" stroke="#69d2ff" stroke-width="2"/><path d="M170 45v-6a6.5 6.5 0 0 1 13 0v6" stroke="#69d2ff" stroke-width="2"/><path d="m171 56 4 4 7-8" stroke="#a0e4ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg><h2 id="edge-intro-title">Edge AI</h2><div id="edge-intro-description"><p>データをクラウドに送らず、この端末内でJevを実行します。外部送信不要で、オフラインでも利用できます。初回のみ「モデルを読み込む」からモデルをダウンロードします。</p></div></dialog><script type="module" src="./ui.js?v=20260921-inference-time-v2"></script></body></html>
|
inference_core.py
DELETED
|
@@ -1,332 +0,0 @@
|
|
| 1 |
-
"""Inference core for the Audio Decision Model ZeroGPU Space.
|
| 2 |
-
|
| 3 |
-
The model files are local to the Space. Requests are never written to disk.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from __future__ import annotations
|
| 7 |
-
|
| 8 |
-
import asyncio
|
| 9 |
-
import json
|
| 10 |
-
import math
|
| 11 |
-
import os
|
| 12 |
-
import threading
|
| 13 |
-
import time
|
| 14 |
-
from pathlib import Path
|
| 15 |
-
from typing import Any
|
| 16 |
-
|
| 17 |
-
import numpy as np
|
| 18 |
-
from fastapi import FastAPI, HTTPException, Request
|
| 19 |
-
from fastapi.concurrency import run_in_threadpool
|
| 20 |
-
from fastapi.responses import FileResponse, PlainTextResponse
|
| 21 |
-
from pydantic import BaseModel, ValidationError
|
| 22 |
-
import torch
|
| 23 |
-
|
| 24 |
-
from server_runtime.typed_runtime import TypedAudioPredictor
|
| 25 |
-
from server_runtime.asr_semantic import (
|
| 26 |
-
ASR_ADAPTATION_SHA256,
|
| 27 |
-
ASR_VARIANT,
|
| 28 |
-
QwenASRSemanticPredictor,
|
| 29 |
-
fixed_semantic_task,
|
| 30 |
-
)
|
| 31 |
-
from server_runtime.transcript_keyword import (
|
| 32 |
-
answer_keyword_questions,
|
| 33 |
-
classify_keyword_question,
|
| 34 |
-
)
|
| 35 |
-
from server_runtime.language_id import (
|
| 36 |
-
answer_language_questions,
|
| 37 |
-
classify_language_question,
|
| 38 |
-
)
|
| 39 |
-
from server_runtime.clap_sound_router import (
|
| 40 |
-
ClapSoundRouter,
|
| 41 |
-
sound_answer,
|
| 42 |
-
)
|
| 43 |
-
from server_runtime.learned_modality_router import (
|
| 44 |
-
LearnedModalityRouter,
|
| 45 |
-
learned_fuse_answers,
|
| 46 |
-
)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
ROOT = Path(__file__).resolve().parent
|
| 50 |
-
CHECKPOINT = ROOT / "server_runtime" / "checkpoint.pt"
|
| 51 |
-
# A full 30-second JSON array of 480,000 float samples is around 10 MiB.
|
| 52 |
-
MAX_BODY_BYTES = 12 * 1024 * 1024
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
class AnalyzeRequest(BaseModel):
|
| 56 |
-
samples: list[float]
|
| 57 |
-
context: str
|
| 58 |
-
questions: dict[str, Any]
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
class ModelBundle:
|
| 62 |
-
def __init__(self, device: str = "cpu") -> None:
|
| 63 |
-
self.device = device
|
| 64 |
-
torch.set_num_threads(max(1, min(8, int(os.environ.get("JEV_TORCH_THREADS", "2")))))
|
| 65 |
-
semantic_dir = Path(os.environ.get("AUDIO_JEV_SEMANTIC_DIR", ROOT / "server_runtime" / "semantic_v8"))
|
| 66 |
-
self.semantic = QwenASRSemanticPredictor(semantic_dir, device=device)
|
| 67 |
-
self._predictor: TypedAudioPredictor | None = None
|
| 68 |
-
self._predictor_lock = threading.Lock()
|
| 69 |
-
self.sound = ClapSoundRouter(ROOT / "server_runtime", device=device)
|
| 70 |
-
self.router = LearnedModalityRouter(ROOT / "models")
|
| 71 |
-
|
| 72 |
-
def typed_predictor(self) -> TypedAudioPredictor:
|
| 73 |
-
# The generic option scorer remains available for turn state and user
|
| 74 |
-
# schemas. Avoid its second Qwen audio-tower copy until it is needed.
|
| 75 |
-
if self._predictor is None:
|
| 76 |
-
with self._predictor_lock:
|
| 77 |
-
if self._predictor is None:
|
| 78 |
-
self._predictor = TypedAudioPredictor(CHECKPOINT, device=self.device)
|
| 79 |
-
return self._predictor
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
_model: ModelBundle | None = None
|
| 83 |
-
_load_lock = threading.Lock()
|
| 84 |
-
_request_lock = asyncio.Lock()
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
def get_model() -> ModelBundle:
|
| 88 |
-
global _model
|
| 89 |
-
if _model is None:
|
| 90 |
-
with _load_lock:
|
| 91 |
-
if _model is None:
|
| 92 |
-
_model = ModelBundle(device=os.environ.get("AUDIO_JEV_DEVICE", "cpu"))
|
| 93 |
-
return _model
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def status() -> dict[str, Any]:
|
| 97 |
-
bundle = _model
|
| 98 |
-
return {
|
| 99 |
-
"ready": bundle is not None,
|
| 100 |
-
"backend": "zerogpu-cuda" if bundle and bundle.device == "cuda" else "server-cpu",
|
| 101 |
-
"precision": "mixed bfloat16/float32" if bundle and bundle.device == "cuda" else "float32",
|
| 102 |
-
"model_revision": "cloud-unified-qwen06-ja-adapt-semantic-v8-clap-learned-router-v7",
|
| 103 |
-
"model": "Adapted Qwen3-ASR-0.6B and CLAP with learned sparse routing ensemble and option-weighted fusion",
|
| 104 |
-
"asr_adaptation": {"candidate": ASR_VARIANT, "sha256": ASR_ADAPTATION_SHA256},
|
| 105 |
-
"on_device": False,
|
| 106 |
-
"audio_sent_to_server": True,
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def fail(message: str) -> None:
|
| 111 |
-
raise ValueError(message)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def options_for(question: Any) -> list[tuple[str, str]]:
|
| 115 |
-
if not isinstance(question, dict) or not isinstance(question.get("instructions"), str) or not question["instructions"].strip():
|
| 116 |
-
fail("各質問にinstructions(質問文)を指定してください。")
|
| 117 |
-
if len(question["instructions"]) > 2000:
|
| 118 |
-
fail("質問文は2000文字以内にしてください。")
|
| 119 |
-
kind = question.get("type")
|
| 120 |
-
if kind == "noul":
|
| 121 |
-
criteria = question.get("criteria", {"false": "いいえ。その条件を満たさない。", "true": "はい。その条件を満たす。"})
|
| 122 |
-
if not isinstance(criteria, dict) or set(criteria) != {"false", "true"}:
|
| 123 |
-
fail("Noulのcriteriaにはfalseとtrueを指定してください。")
|
| 124 |
-
pairs = [("false", criteria["false"]), ("true", criteria["true"])]
|
| 125 |
-
elif kind == "choice":
|
| 126 |
-
criteria = question.get("criteria")
|
| 127 |
-
if not isinstance(criteria, dict):
|
| 128 |
-
fail("Choiceのcriteriaは候補IDと説明のオブジェクトです。")
|
| 129 |
-
pairs = list(criteria.items())
|
| 130 |
-
if not 2 <= len(pairs) <= 32:
|
| 131 |
-
fail("Choiceの候補数は2〜32個です。")
|
| 132 |
-
elif kind == "score":
|
| 133 |
-
criteria = question.get("criteria")
|
| 134 |
-
if not isinstance(criteria, list) or not 2 <= len(criteria) <= 10:
|
| 135 |
-
fail("Scoreのcriteriaは2〜10段階の説明を順に並べた配列です。")
|
| 136 |
-
pairs = [(str(i), value) for i, value in enumerate(criteria)]
|
| 137 |
-
else:
|
| 138 |
-
fail("typeはnoul・choice・scoreのいずれかです。")
|
| 139 |
-
if any(not key or not isinstance(value, str) or not value.strip() or len(value) > 1000 for key, value in pairs):
|
| 140 |
-
fail("各候補には空でない説明を1000文字以内で指定してください。")
|
| 141 |
-
return pairs
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def waveform_windows(samples: np.ndarray) -> list[np.ndarray]:
|
| 145 |
-
last = max(0, len(samples) - 80000)
|
| 146 |
-
starts = list(range(0, last + 1, 40000))
|
| 147 |
-
if starts[-1] != last:
|
| 148 |
-
starts.append(last)
|
| 149 |
-
return [samples[start : min(start + 80000, len(samples))] for start in starts]
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
def normalize(wave: np.ndarray) -> np.ndarray:
|
| 153 |
-
# Match JS accumulation semantics closely; both use observed-population variance.
|
| 154 |
-
mean = sum(float(value) for value in wave) / len(wave)
|
| 155 |
-
variance = sum((float(value) - mean) ** 2 for value in wave) / len(wave)
|
| 156 |
-
return np.asarray([(float(value) - mean) / math.sqrt(variance + 1e-7) for value in wave], dtype=np.float32)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
def analyze(payload: AnalyzeRequest) -> dict[str, Any]:
|
| 160 |
-
began = time.perf_counter()
|
| 161 |
-
samples = np.asarray(payload.samples, dtype=np.float32)
|
| 162 |
-
if samples.ndim != 1 or len(samples) < 4000 or len(samples) > 480000 or not np.isfinite(samples).all():
|
| 163 |
-
fail("音声は0.25秒〜30秒の範囲で入力してください。")
|
| 164 |
-
if len(payload.context) > 2000:
|
| 165 |
-
fail("文脈は2000文字以内にしてください。")
|
| 166 |
-
entries = list(payload.questions.items())
|
| 167 |
-
if not 1 <= len(entries) <= 16:
|
| 168 |
-
fail("質問数は1〜16個にしてください。")
|
| 169 |
-
# Validate with the browser-visible Japanese error contract before model work.
|
| 170 |
-
for _, question in entries:
|
| 171 |
-
options_for(question)
|
| 172 |
-
bundle = get_model()
|
| 173 |
-
# Question names and lexical aliases never enter this gate. ModernBERT
|
| 174 |
-
# embeddings produce continuous speech/non-verbal/joint weights, followed
|
| 175 |
-
# by sparse top-1 or two-expert execution.
|
| 176 |
-
routes = bundle.router.route_all(payload.context, payload.questions)
|
| 177 |
-
language_questions = {name: question for name, question in payload.questions.items()
|
| 178 |
-
if routes[name].mode in ("language", "joint")}
|
| 179 |
-
language_id_questions = {name: question for name, question in language_questions.items()
|
| 180 |
-
if classify_language_question(question) is not None}
|
| 181 |
-
fixed_questions = {name: question for name, question in language_questions.items()
|
| 182 |
-
if name not in language_id_questions and fixed_semantic_task(question) is not None}
|
| 183 |
-
keyword_questions = {name: question for name, question in language_questions.items()
|
| 184 |
-
if name not in language_id_questions and fixed_semantic_task(question) is None
|
| 185 |
-
and classify_keyword_question(question) is not None}
|
| 186 |
-
generic_questions = {name: question for name, question in language_questions.items()
|
| 187 |
-
if name not in language_id_questions and name not in fixed_questions
|
| 188 |
-
and name not in keyword_questions}
|
| 189 |
-
needs_sound = any(selected.mode in ("sound", "joint") for selected in routes.values())
|
| 190 |
-
sound_scores = bundle.sound.score(samples) if needs_sound else None
|
| 191 |
-
result = {"transcript": None, "answers": {}, "action_executable": False,
|
| 192 |
-
"evidence": {"audio_duration_ms": len(samples) / 16, "sample_rate_hz": 16_000,
|
| 193 |
-
"language_experts": {}}, "latency_ms": {}}
|
| 194 |
-
auto_transcription = None
|
| 195 |
-
if language_id_questions:
|
| 196 |
-
asr_began = time.perf_counter()
|
| 197 |
-
auto_transcription = bundle.semantic.transcribe_result(samples, detect_language=True)
|
| 198 |
-
result["latency_ms"]["language_asr"] = (time.perf_counter() - asr_began) * 1000
|
| 199 |
-
result["transcript"] = auto_transcription.text
|
| 200 |
-
result["answers"].update(answer_language_questions(
|
| 201 |
-
auto_transcription.language, language_id_questions
|
| 202 |
-
))
|
| 203 |
-
result["evidence"]["language_experts"]["native_language_id"] = {
|
| 204 |
-
"model": f"Qwen/Qwen3-ASR-0.6B + {ASR_VARIANT}",
|
| 205 |
-
"detected_language": auto_transcription.language or "unknown",
|
| 206 |
-
"decoder": "one automatic-language ASR decode shared with transcript tasks",
|
| 207 |
-
"adaptation_sha256": ASR_ADAPTATION_SHA256,
|
| 208 |
-
"tasks": {name: classify_language_question(question).task
|
| 209 |
-
for name, question in language_id_questions.items()},
|
| 210 |
-
}
|
| 211 |
-
if fixed_questions:
|
| 212 |
-
fixed_result = bundle.semantic.predict(
|
| 213 |
-
samples, payload.context, fixed_questions, transcription=auto_transcription
|
| 214 |
-
)
|
| 215 |
-
result["transcript"] = fixed_result["transcript"]
|
| 216 |
-
result["answers"].update(fixed_result["answers"])
|
| 217 |
-
result["evidence"]["language_experts"]["fixed_semantics"] = fixed_result["evidence"]
|
| 218 |
-
result["latency_ms"].update({f"fixed_{key}": value for key, value in fixed_result["latency_ms"].items()})
|
| 219 |
-
if keyword_questions:
|
| 220 |
-
if result["transcript"] is None:
|
| 221 |
-
asr_began = time.perf_counter()
|
| 222 |
-
result["transcript"] = bundle.semantic.transcribe(samples)
|
| 223 |
-
result["latency_ms"]["keyword_asr"] = (time.perf_counter() - asr_began) * 1000
|
| 224 |
-
result["answers"].update(answer_keyword_questions(result["transcript"], keyword_questions))
|
| 225 |
-
result["evidence"]["language_experts"]["transcript_keyword"] = {
|
| 226 |
-
"model": f"Qwen/Qwen3-ASR-0.6B + {ASR_VARIANT}",
|
| 227 |
-
"selection": "clean-v3 validation; frozen surface-reading-lemma matcher, threshold 0.60, minimum fuzzy length 2",
|
| 228 |
-
"adaptation_sha256": ASR_ADAPTATION_SHA256,
|
| 229 |
-
"tasks": {name: classify_keyword_question(question).task
|
| 230 |
-
for name, question in keyword_questions.items()},
|
| 231 |
-
}
|
| 232 |
-
if generic_questions:
|
| 233 |
-
generic_result = bundle.typed_predictor().predict(samples, payload.context, generic_questions)
|
| 234 |
-
result["answers"].update(generic_result["answers"])
|
| 235 |
-
result["evidence"]["language_experts"]["generic_typed"] = generic_result["evidence"]
|
| 236 |
-
result["latency_ms"].update({f"generic_{key}": value for key, value in generic_result["latency_ms"].items()})
|
| 237 |
-
for name, question in payload.questions.items():
|
| 238 |
-
selected = routes[name]
|
| 239 |
-
if selected.mode == "sound":
|
| 240 |
-
result["answers"][name] = sound_answer(question, sound_scores)
|
| 241 |
-
elif selected.mode == "joint":
|
| 242 |
-
acoustic_answer = sound_answer(question, sound_scores)
|
| 243 |
-
result["answers"][name] = learned_fuse_answers(
|
| 244 |
-
question, result["answers"][name], acoustic_answer, selected
|
| 245 |
-
)
|
| 246 |
-
result["answers"] = {name: result["answers"][name] for name in payload.questions}
|
| 247 |
-
result.setdefault("evidence", {})["question_routing"] = {name: selected.public() for name, selected in routes.items()}
|
| 248 |
-
result.setdefault("latency_ms", {})["total"] = (time.perf_counter() - began) * 1000
|
| 249 |
-
result["model"] = "mocovoice-audio-jev-cloud-unified-qwen06-ja-adapt-semantic-v8-clap-learned-router-v7"
|
| 250 |
-
result["execution"] = status()
|
| 251 |
-
result["warnings"] = []
|
| 252 |
-
result["scope"] = "研究用試作。未知タスクへの正確さと確率校正は未検証。"
|
| 253 |
-
return result
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
@app.on_event("startup")
|
| 260 |
-
async def load_models_at_startup() -> None:
|
| 261 |
-
# The status endpoint is usable as a readiness probe, so load before serving.
|
| 262 |
-
await run_in_threadpool(get_model)
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
async def read_json_limited(request: Request) -> dict[str, Any]:
|
| 266 |
-
content_length = request.headers.get("content-length")
|
| 267 |
-
if content_length is not None:
|
| 268 |
-
try:
|
| 269 |
-
if int(content_length) > MAX_BODY_BYTES:
|
| 270 |
-
raise HTTPException(status_code=413, detail="Request body must be 12 MiB or smaller.")
|
| 271 |
-
except ValueError as error:
|
| 272 |
-
raise HTTPException(status_code=400, detail="Invalid Content-Length.") from error
|
| 273 |
-
chunks: list[bytes] = []
|
| 274 |
-
received = 0
|
| 275 |
-
async for chunk in request.stream():
|
| 276 |
-
received += len(chunk)
|
| 277 |
-
if received > MAX_BODY_BYTES:
|
| 278 |
-
raise HTTPException(status_code=413, detail="Request body must be 12 MiB or smaller.")
|
| 279 |
-
chunks.append(chunk)
|
| 280 |
-
try:
|
| 281 |
-
body = json.loads(b"".join(chunks))
|
| 282 |
-
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
| 283 |
-
raise HTTPException(status_code=400, detail="Request body must be valid JSON.") from error
|
| 284 |
-
if not isinstance(body, dict):
|
| 285 |
-
raise HTTPException(status_code=400, detail="Request body must be a JSON object.")
|
| 286 |
-
return body
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
@app.get("/api/status")
|
| 290 |
-
async def api_status() -> dict[str, Any]:
|
| 291 |
-
return status()
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
@app.post("/api/analyze")
|
| 295 |
-
async def api_analyze(request: Request) -> dict[str, Any]:
|
| 296 |
-
try:
|
| 297 |
-
payload = AnalyzeRequest.model_validate(await read_json_limited(request))
|
| 298 |
-
except ValidationError as error:
|
| 299 |
-
raise HTTPException(status_code=400, detail="Invalid analyze request.") from error
|
| 300 |
-
async with _request_lock:
|
| 301 |
-
try:
|
| 302 |
-
return await run_in_threadpool(analyze, payload)
|
| 303 |
-
except ValueError as error:
|
| 304 |
-
raise HTTPException(status_code=400, detail=str(error)) from error
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
_EXACT_STATIC = {
|
| 308 |
-
"index.html", "styles.css", "ui.js", "inference.js", "inference-worker.js",
|
| 309 |
-
"audio-recorder.js", "audio-player.js", "README.md", "mocomoco-inc-logo.svg", "favicon.svg",
|
| 310 |
-
}
|
| 311 |
-
_STATIC_PREFIXES = ("models/", "vendor/", "fonts/", "examples/", "licenses/")
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
@app.get("/")
|
| 315 |
-
async def home() -> FileResponse:
|
| 316 |
-
return FileResponse(ROOT / "index.html", headers={"Cache-Control": "private, no-store"})
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
@app.get("/{asset_path:path}")
|
| 320 |
-
async def static_asset(asset_path: str) -> FileResponse:
|
| 321 |
-
"""Serve only browser assets; source and server checkpoints are never files."""
|
| 322 |
-
candidate = (ROOT / asset_path).resolve()
|
| 323 |
-
try:
|
| 324 |
-
relative = candidate.relative_to(ROOT).as_posix()
|
| 325 |
-
except ValueError:
|
| 326 |
-
return PlainTextResponse("Not found.", status_code=404)
|
| 327 |
-
# Authorize the resolved path, never the untrusted URL string. This makes
|
| 328 |
-
# ``models/../server.py`` and encoded dot-segment variants unavailable.
|
| 329 |
-
allowed = relative in _EXACT_STATIC or relative.startswith(_STATIC_PREFIXES)
|
| 330 |
-
if not allowed or not candidate.is_file():
|
| 331 |
-
return PlainTextResponse("Not found.", status_code=404)
|
| 332 |
-
return FileResponse(candidate)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
licenses/gradio-client-Apache-2.0.txt
DELETED
|
@@ -1,201 +0,0 @@
|
|
| 1 |
-
Apache License
|
| 2 |
-
Version 2.0, January 2004
|
| 3 |
-
http://www.apache.org/licenses/
|
| 4 |
-
|
| 5 |
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
-
|
| 7 |
-
1. Definitions.
|
| 8 |
-
|
| 9 |
-
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
-
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
-
|
| 12 |
-
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
-
the copyright owner that is granting the License.
|
| 14 |
-
|
| 15 |
-
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
-
other entities that control, are controlled by, or are under common
|
| 17 |
-
control with that entity. For the purposes of this definition,
|
| 18 |
-
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
-
direction or management of such entity, whether by contract or
|
| 20 |
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
-
|
| 23 |
-
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
-
exercising permissions granted by this License.
|
| 25 |
-
|
| 26 |
-
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
-
including but not limited to software source code, documentation
|
| 28 |
-
source, and configuration files.
|
| 29 |
-
|
| 30 |
-
"Object" form shall mean any form resulting from mechanical
|
| 31 |
-
transformation or translation of a Source form, including but
|
| 32 |
-
not limited to compiled object code, generated documentation,
|
| 33 |
-
and conversions to other media types.
|
| 34 |
-
|
| 35 |
-
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
-
Object form, made available under the License, as indicated by a
|
| 37 |
-
copyright notice that is included in or attached to the work
|
| 38 |
-
(an example is provided in the Appendix below).
|
| 39 |
-
|
| 40 |
-
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
-
form, that is based on (or derived from) the Work and for which the
|
| 42 |
-
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
-
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
-
of this License, Derivative Works shall not include works that remain
|
| 45 |
-
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
-
the Work and Derivative Works thereof.
|
| 47 |
-
|
| 48 |
-
"Contribution" shall mean any work of authorship, including
|
| 49 |
-
the original version of the Work and any modifications or additions
|
| 50 |
-
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
-
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
-
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
-
means any form of electronic, verbal, or written communication sent
|
| 55 |
-
to the Licensor or its representatives, including but not limited to
|
| 56 |
-
communication on electronic mailing lists, source code control systems,
|
| 57 |
-
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
-
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
-
excluding communication that is conspicuously marked or otherwise
|
| 60 |
-
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
-
|
| 62 |
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
-
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
-
subsequently incorporated within the Work.
|
| 65 |
-
|
| 66 |
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
-
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
-
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
-
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
-
Work and such Derivative Works in Source or Object form.
|
| 72 |
-
|
| 73 |
-
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
-
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
-
(except as stated in this section) patent license to make, have made,
|
| 77 |
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
-
where such license applies only to those patent claims licensable
|
| 79 |
-
by such Contributor that are necessarily infringed by their
|
| 80 |
-
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
-
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
-
institute patent litigation against any entity (including a
|
| 83 |
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
-
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
-
or contributory patent infringement, then any patent licenses
|
| 86 |
-
granted to You under this License for that Work shall terminate
|
| 87 |
-
as of the date such litigation is filed.
|
| 88 |
-
|
| 89 |
-
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
-
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
-
modifications, and in Source or Object form, provided that You
|
| 92 |
-
meet the following conditions:
|
| 93 |
-
|
| 94 |
-
(a) You must give any other recipients of the Work or
|
| 95 |
-
Derivative Works a copy of this License; and
|
| 96 |
-
|
| 97 |
-
(b) You must cause any modified files to carry prominent notices
|
| 98 |
-
stating that You changed the files; and
|
| 99 |
-
|
| 100 |
-
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
-
that You distribute, all copyright, patent, trademark, and
|
| 102 |
-
attribution notices from the Source form of the Work,
|
| 103 |
-
excluding those notices that do not pertain to any part of
|
| 104 |
-
the Derivative Works; and
|
| 105 |
-
|
| 106 |
-
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
-
distribution, then any Derivative Works that You distribute must
|
| 108 |
-
include a readable copy of the attribution notices contained
|
| 109 |
-
within such NOTICE file, excluding those notices that do not
|
| 110 |
-
pertain to any part of the Derivative Works, in at least one
|
| 111 |
-
of the following places: within a NOTICE text file distributed
|
| 112 |
-
as part of the Derivative Works; within the Source form or
|
| 113 |
-
documentation, if provided along with the Derivative Works; or,
|
| 114 |
-
within a display generated by the Derivative Works, if and
|
| 115 |
-
wherever such third-party notices normally appear. The contents
|
| 116 |
-
of the NOTICE file are for informational purposes only and
|
| 117 |
-
do not modify the License. You may add Your own attribution
|
| 118 |
-
notices within Derivative Works that You distribute, alongside
|
| 119 |
-
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
-
that such additional attribution notices cannot be construed
|
| 121 |
-
as modifying the License.
|
| 122 |
-
|
| 123 |
-
You may add Your own copyright statement to Your modifications and
|
| 124 |
-
may provide additional or different license terms and conditions
|
| 125 |
-
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
-
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
-
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
-
the conditions stated in this License.
|
| 129 |
-
|
| 130 |
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
-
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
-
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
-
this License, without any additional terms or conditions.
|
| 134 |
-
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
-
the terms of any separate license agreement you may have executed
|
| 136 |
-
with Licensor regarding such Contributions.
|
| 137 |
-
|
| 138 |
-
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
-
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
-
except as required for reasonable and customary use in describing the
|
| 141 |
-
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
-
|
| 143 |
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
-
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
-
implied, including, without limitation, any warranties or conditions
|
| 148 |
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
-
appropriateness of using or redistributing the Work and assume any
|
| 151 |
-
risks associated with Your exercise of permissions under this License.
|
| 152 |
-
|
| 153 |
-
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
-
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
-
unless required by applicable law (such as deliberate and grossly
|
| 156 |
-
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
-
liable to You for damages, including any direct, indirect, special,
|
| 158 |
-
incidental, or consequential damages of any character arising as a
|
| 159 |
-
result of this License or out of the use or inability to use the
|
| 160 |
-
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
-
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
-
other commercial damages or losses), even if such Contributor
|
| 163 |
-
has been advised of the possibility of such damages.
|
| 164 |
-
|
| 165 |
-
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
-
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
-
or other liability obligations and/or rights consistent with this
|
| 169 |
-
License. However, in accepting such obligations, You may act only
|
| 170 |
-
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
-
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
-
defend, and hold each Contributor harmless for any liability
|
| 173 |
-
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
-
of your accepting any such warranty or additional liability.
|
| 175 |
-
|
| 176 |
-
END OF TERMS AND CONDITIONS
|
| 177 |
-
|
| 178 |
-
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
-
|
| 180 |
-
To apply the Apache License to your work, attach the following
|
| 181 |
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
-
replaced with your own identifying information. (Don't include
|
| 183 |
-
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
-
comment syntax for the file format. We also recommend that a
|
| 185 |
-
file or class name and description of purpose be included on the
|
| 186 |
-
same "printed page" as the copyright notice for easier
|
| 187 |
-
identification within third-party archives.
|
| 188 |
-
|
| 189 |
-
Copyright [yyyy] [name of copyright owner]
|
| 190 |
-
|
| 191 |
-
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
-
you may not use this file except in compliance with the License.
|
| 193 |
-
You may obtain a copy of the License at
|
| 194 |
-
|
| 195 |
-
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
-
|
| 197 |
-
Unless required by applicable law or agreed to in writing, software
|
| 198 |
-
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
-
See the License for the specific language governing permissions and
|
| 201 |
-
limitations under the License.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
|
|
|
|
|
| 1 |
numpy==2.5.2
|
| 2 |
-
|
| 3 |
transformers==4.57.6
|
|
|
|
|
|
|
| 4 |
onnxruntime==1.30.0
|
| 5 |
SudachiPy==0.6.11
|
| 6 |
SudachiDict-core==20260428
|
|
|
|
| 1 |
+
fastapi==0.141.1
|
| 2 |
+
uvicorn==0.53.0
|
| 3 |
numpy==2.5.2
|
| 4 |
+
torch==2.9.1
|
| 5 |
transformers==4.57.6
|
| 6 |
+
huggingface_hub==0.36.2
|
| 7 |
+
scipy==1.17.1
|
| 8 |
onnxruntime==1.30.0
|
| 9 |
SudachiPy==0.6.11
|
| 10 |
SudachiDict-core==20260428
|
server_runtime/asr_semantic.py
CHANGED
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
| 4 |
from dataclasses import dataclass
|
| 5 |
import hashlib
|
| 6 |
import time
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
import re
|
| 9 |
from typing import Any
|
|
@@ -21,6 +22,8 @@ from .typed_audio import question_options, typed_answer
|
|
| 21 |
|
| 22 |
MODEL_ID = "Qwen/Qwen3-ASR-0.6B"
|
| 23 |
REVISION = "5eb144179a02acc5e5ba31e748d22b0cf3e303b0"
|
|
|
|
|
|
|
| 24 |
ASR_VARIANT = "hybrid_channel-alpha050"
|
| 25 |
ASR_ADAPTATION = Path(__file__).with_name("qwen06_asr_ja_keyword_alpha050.safetensors")
|
| 26 |
ASR_ADAPTATION_SHA256 = "776d9ff19aff2cce4b5a59dacf56e747c5d2945b06f19970844a875e7f803533"
|
|
@@ -95,7 +98,10 @@ class QwenASRSemanticPredictor:
|
|
| 95 |
|
| 96 |
semantic_dir = Path(semantic_dir)
|
| 97 |
if not (semantic_dir / "text_encoder/model.safetensors").is_file():
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
| 99 |
encoder_dir = semantic_dir / "text_encoder"
|
| 100 |
self.tokenizer = PreTrainedTokenizerFast(
|
| 101 |
tokenizer_file=str(encoder_dir / "tokenizer.json"),
|
|
@@ -106,7 +112,6 @@ class QwenASRSemanticPredictor:
|
|
| 106 |
encoder_dir, local_files_only=True, torch_dtype=torch.float32,
|
| 107 |
attn_implementation="sdpa",
|
| 108 |
).to(self.device).eval()
|
| 109 |
-
self.semantic.config.reference_compile = False
|
| 110 |
self.head = nn.Linear(self.semantic.config.hidden_size, len(ACTS) + len(INTENTS)).to(self.device).eval()
|
| 111 |
self.head.load_state_dict(torch.load(semantic_dir / "semantic_head.pt", map_location=self.device,
|
| 112 |
weights_only=True), strict=True)
|
|
|
|
| 4 |
from dataclasses import dataclass
|
| 5 |
import hashlib
|
| 6 |
import time
|
| 7 |
+
import os
|
| 8 |
from pathlib import Path
|
| 9 |
import re
|
| 10 |
from typing import Any
|
|
|
|
| 22 |
|
| 23 |
MODEL_ID = "Qwen/Qwen3-ASR-0.6B"
|
| 24 |
REVISION = "5eb144179a02acc5e5ba31e748d22b0cf3e303b0"
|
| 25 |
+
SEMANTIC_REPO_ID = "gojiteji/mocovoice-audio-jev-semantic-v8"
|
| 26 |
+
SEMANTIC_REVISION = "23779177e4f8abe672cef0d59812e7ee63bb1095"
|
| 27 |
ASR_VARIANT = "hybrid_channel-alpha050"
|
| 28 |
ASR_ADAPTATION = Path(__file__).with_name("qwen06_asr_ja_keyword_alpha050.safetensors")
|
| 29 |
ASR_ADAPTATION_SHA256 = "776d9ff19aff2cce4b5a59dacf56e747c5d2945b06f19970844a875e7f803533"
|
|
|
|
| 98 |
|
| 99 |
semantic_dir = Path(semantic_dir)
|
| 100 |
if not (semantic_dir / "text_encoder/model.safetensors").is_file():
|
| 101 |
+
semantic_dir = Path(snapshot_download(
|
| 102 |
+
SEMANTIC_REPO_ID, revision=SEMANTIC_REVISION,
|
| 103 |
+
token=os.environ.get("AUDIO_JEV_MODEL_TOKEN"),
|
| 104 |
+
))
|
| 105 |
encoder_dir = semantic_dir / "text_encoder"
|
| 106 |
self.tokenizer = PreTrainedTokenizerFast(
|
| 107 |
tokenizer_file=str(encoder_dir / "tokenizer.json"),
|
|
|
|
| 112 |
encoder_dir, local_files_only=True, torch_dtype=torch.float32,
|
| 113 |
attn_implementation="sdpa",
|
| 114 |
).to(self.device).eval()
|
|
|
|
| 115 |
self.head = nn.Linear(self.semantic.config.hidden_size, len(ACTS) + len(INTENTS)).to(self.device).eval()
|
| 116 |
self.head.load_state_dict(torch.load(semantic_dir / "semantic_head.pt", map_location=self.device,
|
| 117 |
weights_only=True), strict=True)
|
server_runtime/clap_sound_router.py
CHANGED
|
@@ -15,7 +15,6 @@ import re
|
|
| 15 |
|
| 16 |
import numpy as np
|
| 17 |
import torch
|
| 18 |
-
from huggingface_hub import snapshot_download
|
| 19 |
from scipy.signal import resample_poly
|
| 20 |
from transformers import ClapAudioModelWithProjection, ClapFeatureExtractor
|
| 21 |
|
|
@@ -274,24 +273,18 @@ class _ClapHead:
|
|
| 274 |
|
| 275 |
|
| 276 |
class ClapSoundRouter:
|
| 277 |
-
"""CLAP
|
| 278 |
-
def __init__(self, root: str | Path | None = None
|
| 279 |
directory = Path(root) if root is not None else Path(__file__).resolve().parent
|
| 280 |
-
self.device = torch.device(device)
|
| 281 |
self.broad = _ClapHead(directory / "clap_sound_v1.pt", BROAD + ("dog", "cat", "bird", "insect"), animal8=False)
|
| 282 |
self.animal8 = _ClapHead(directory / "clap_animal8_oof_v1.pt", ANIMAL8, animal8=True)
|
| 283 |
-
for group in (self.broad, self.animal8):
|
| 284 |
-
group.head = group.head.to(self.device)
|
| 285 |
-
group.mean = group.mean.to(self.device)
|
| 286 |
-
group.std = group.std.to(self.device)
|
| 287 |
self.extractor = None
|
| 288 |
self.encoder = None
|
| 289 |
|
| 290 |
def _load_base(self) -> None:
|
| 291 |
if self.encoder is None:
|
| 292 |
-
|
| 293 |
-
self.
|
| 294 |
-
self.encoder = ClapAudioModelWithProjection.from_pretrained(snapshot, local_files_only=True).to(self.device).eval()
|
| 295 |
|
| 296 |
@staticmethod
|
| 297 |
def _feature(wave16k: np.ndarray, extractor, encoder) -> torch.Tensor:
|
|
@@ -301,7 +294,7 @@ class ClapSoundRouter:
|
|
| 301 |
values = []
|
| 302 |
with torch.inference_mode():
|
| 303 |
for start in starts:
|
| 304 |
-
inputs = extractor(wave[start:start + 480_000], sampling_rate=48_000, return_tensors="pt")
|
| 305 |
values.append(encoder(**inputs).audio_embeds[0].float())
|
| 306 |
stacked = torch.stack(values)
|
| 307 |
return torch.cat((stacked.mean(0), stacked.max(0).values)).unsqueeze(0)
|
|
|
|
| 15 |
|
| 16 |
import numpy as np
|
| 17 |
import torch
|
|
|
|
| 18 |
from scipy.signal import resample_poly
|
| 19 |
from transformers import ClapAudioModelWithProjection, ClapFeatureExtractor
|
| 20 |
|
|
|
|
| 273 |
|
| 274 |
|
| 275 |
class ClapSoundRouter:
|
| 276 |
+
"""Lazy CPU CLAP loader; call only when at least one route uses sound."""
|
| 277 |
+
def __init__(self, root: str | Path | None = None) -> None:
|
| 278 |
directory = Path(root) if root is not None else Path(__file__).resolve().parent
|
|
|
|
| 279 |
self.broad = _ClapHead(directory / "clap_sound_v1.pt", BROAD + ("dog", "cat", "bird", "insect"), animal8=False)
|
| 280 |
self.animal8 = _ClapHead(directory / "clap_animal8_oof_v1.pt", ANIMAL8, animal8=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
self.extractor = None
|
| 282 |
self.encoder = None
|
| 283 |
|
| 284 |
def _load_base(self) -> None:
|
| 285 |
if self.encoder is None:
|
| 286 |
+
self.extractor = ClapFeatureExtractor.from_pretrained(MODEL, revision=REVISION, local_files_only=True)
|
| 287 |
+
self.encoder = ClapAudioModelWithProjection.from_pretrained(MODEL, revision=REVISION, local_files_only=True).cpu().eval()
|
|
|
|
| 288 |
|
| 289 |
@staticmethod
|
| 290 |
def _feature(wave16k: np.ndarray, extractor, encoder) -> torch.Tensor:
|
|
|
|
| 294 |
values = []
|
| 295 |
with torch.inference_mode():
|
| 296 |
for start in starts:
|
| 297 |
+
inputs = extractor(wave[start:start + 480_000], sampling_rate=48_000, return_tensors="pt")
|
| 298 |
values.append(encoder(**inputs).audio_embeds[0].float())
|
| 299 |
stacked = torch.stack(values)
|
| 300 |
return torch.cat((stacked.mean(0), stacked.max(0).values)).unsqueeze(0)
|
server_runtime/typed_runtime.py
CHANGED
|
@@ -60,7 +60,6 @@ class TypedAudioPredictor:
|
|
| 60 |
# Training text caches were computed in float32. Keep that contract.
|
| 61 |
self.text = AutoModel.from_pretrained(text_id, revision=text_revision, torch_dtype=torch.float32,
|
| 62 |
attn_implementation="sdpa").to(device).eval()
|
| 63 |
-
self.text.config.reference_compile = False
|
| 64 |
self.text_cache = OrderedDict(); self.window_cache = OrderedDict()
|
| 65 |
|
| 66 |
def _sync(self):
|
|
|
|
| 60 |
# Training text caches were computed in float32. Keep that contract.
|
| 61 |
self.text = AutoModel.from_pretrained(text_id, revision=text_revision, torch_dtype=torch.float32,
|
| 62 |
attn_implementation="sdpa").to(device).eval()
|
|
|
|
| 63 |
self.text_cache = OrderedDict(); self.window_cache = OrderedDict()
|
| 64 |
|
| 65 |
def _sync(self):
|
ui.js
CHANGED
|
@@ -18,7 +18,6 @@ let serverReady = false;
|
|
| 18 |
let edgeIntroShown = false;
|
| 19 |
let exampleRecords = [];
|
| 20 |
let selectedExampleId = null;
|
| 21 |
-
let gradioClientPromise = null;
|
| 22 |
|
| 23 |
async function dismissStartupScreen() {
|
| 24 |
const screen = $('startup-screen');
|
|
@@ -68,10 +67,10 @@ function status(message, error = false) { const node = $("analysis-status"); nod
|
|
| 68 |
function clearResult() { inputRevision++; latestResult = null; $("result-json").textContent = "{}"; $("summary").classList.add("is-empty"); $("summary").textContent = "解析結果がここに表示されます。"; $("inference-time").hidden = true; updateAnalyzeButton(); }
|
| 69 |
function renderInferenceTime(result) {
|
| 70 |
const node = $("inference-time");
|
| 71 |
-
const
|
| 72 |
-
if (!
|
| 73 |
-
node.textContent = `
|
| 74 |
-
node.title = "
|
| 75 |
node.hidden = false;
|
| 76 |
}
|
| 77 |
function getContext() { const value = $("context").value; if ([...value].length > 2000) throw new Error("文脈・補足は2000文字以内にしてください。"); return value; }
|
|
@@ -341,15 +340,16 @@ async function analyze() {
|
|
| 341 |
}
|
| 342 |
|
| 343 |
async function analyzeOnServer(samples, context, questions) {
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
}
|
| 349 |
-
|
| 350 |
-
const response = await client.predict('/analyze_web', [{samples: Array.from(samples), context, questions}]);
|
| 351 |
-
if (!response?.data?.[0]) throw new Error('クラウドで解析できませんでした。');
|
| 352 |
-
return response.data[0];
|
| 353 |
}
|
| 354 |
|
| 355 |
function updateCount() { $("context-count").textContent = [...$("context").value].length; }
|
|
|
|
| 18 |
let edgeIntroShown = false;
|
| 19 |
let exampleRecords = [];
|
| 20 |
let selectedExampleId = null;
|
|
|
|
| 21 |
|
| 22 |
async function dismissStartupScreen() {
|
| 23 |
const screen = $('startup-screen');
|
|
|
|
| 67 |
function clearResult() { inputRevision++; latestResult = null; $("result-json").textContent = "{}"; $("summary").classList.add("is-empty"); $("summary").textContent = "解析結果がここに表示されます。"; $("inference-time").hidden = true; updateAnalyzeButton(); }
|
| 68 |
function renderInferenceTime(result) {
|
| 69 |
const node = $("inference-time");
|
| 70 |
+
const totalMs = Number(result?.latency_ms?.total);
|
| 71 |
+
if (!Number.isFinite(totalMs) || totalMs < 0) { node.hidden = true; return; }
|
| 72 |
+
node.textContent = `推論: ${(totalMs / 1000).toFixed(2)}秒${isServerMode() ? "(キュー待ちを除く)" : "(モデル取得を除く)"}`;
|
| 73 |
+
node.title = isServerMode() ? "モデル処理時間。通信時間は含みません。" : "モデル処理時間。初回のモデル取得は含みません。";
|
| 74 |
node.hidden = false;
|
| 75 |
}
|
| 76 |
function getContext() { const value = $("context").value; if ([...value].length > 2000) throw new Error("文脈・補足は2000文字以内にしてください。"); return value; }
|
|
|
|
| 340 |
}
|
| 341 |
|
| 342 |
async function analyzeOnServer(samples, context, questions) {
|
| 343 |
+
const response = await fetch("/api/analyze", {
|
| 344 |
+
method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" },
|
| 345 |
+
body: JSON.stringify({ samples: Array.from(samples), context, questions })
|
| 346 |
+
});
|
| 347 |
+
if (!response.ok) {
|
| 348 |
+
let message = "クラウドで解析できませんでした。";
|
| 349 |
+
try { message = (await response.json()).detail || message; } catch { /* Keep a clear client-facing message. */ }
|
| 350 |
+
throw new Error(message);
|
| 351 |
}
|
| 352 |
+
return response.json();
|
|
|
|
|
|
|
|
|
|
| 353 |
}
|
| 354 |
|
| 355 |
function updateCount() { $("context-count").textContent = [...$("context").value].length; }
|
vendor/gradio-client.min.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
/**
|
| 2 |
-
* Minified by jsDelivr using Terser v5.37.0.
|
| 3 |
-
* Original file: /npm/@gradio/client@1.13.1/dist/index.js
|
| 4 |
-
*
|
| 5 |
-
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
| 6 |
-
*/
|
| 7 |
-
var _currentLine,__defProp=Object.defineProperty,__defNormalProp=(e,t,s)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,__publicField=(e,t,s)=>(__defNormalProp(e,"symbol"!=typeof t?t+"":t,s),s),__accessCheck=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},__privateGet=(e,t,s)=>(__accessCheck(e,t,"read from private field"),s?s.call(e):t.get(e)),__privateAdd=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},__privateSet=(e,t,s,n)=>(__accessCheck(e,t,"write to private field"),n?n.call(e,s):t.set(e,s),s),fn=new Intl.Collator(0,{numeric:1}).compare;function semiver(e,t,s){return e=e.split("."),t=t.split("."),fn(e[0],t[0])||fn(e[1],t[1])||(t[2]=t.slice(2).join("."),(s=/[.-]/.test(e[2]=e.slice(2).join(".")))==/[.-]/.test(t[2])?fn(e[2],t[2]):s?-1:1)}const HOST_URL="host",SSE_URL="queue/data",SSE_DATA_URL="queue/join",UPLOAD_URL="upload",LOGIN_URL="login",CONFIG_URL="config",API_INFO_URL="info",RUNTIME_URL="runtime",SLEEPTIME_URL="sleeptime",HEARTBEAT_URL="heartbeat",COMPONENT_SERVER_URL="component_server",RESET_URL="reset",CANCEL_URL="cancel",SPACE_FETCHER_URL="https://gradio-space-api-fetcher-v2.hf.space/api",QUEUE_FULL_MSG="This application is currently busy. Please try again. ",BROKEN_CONNECTION_MSG="Connection errored out. ",CONFIG_ERROR_MSG="Could not resolve app config. ",SPACE_STATUS_ERROR_MSG="Could not get space status. ",API_INFO_ERROR_MSG="Could not get API info. ",SPACE_METADATA_ERROR_MSG="Space metadata could not be loaded. ",INVALID_URL_MSG="Invalid URL. A full URL path is required.",UNAUTHORIZED_MSG="Not authorized to access this space. ",INVALID_CREDENTIALS_MSG="Invalid credentials. Could not login. ",MISSING_CREDENTIALS_MSG="Login credentials are required to access this space.",NODEJS_FS_ERROR_MSG="File system access is only available in Node.js environments",ROOT_URL_ERROR_MSG="Root URL not found in client config",FILE_PROCESSING_ERROR_MSG="Error uploading file";function resolve_root(e,t,s){return t.startsWith("http://")||t.startsWith("https://")?s?e:t:e+t}async function get_jwt(e,t,s){try{const n=await fetch(`https://huggingface.co/api/spaces/${e}/jwt`,{headers:{Authorization:`Bearer ${t}`,...s?{Cookie:s}:{}}});return(await n.json()).token||!1}catch(e){return!1}}function map_names_to_ids(e){let t={};return e.forEach((({api_name:e,id:s})=>{e&&(t[e]=s)})),t}async function resolve_config(e){var t;const s=this.options.hf_token?{Authorization:`Bearer ${this.options.hf_token}`}:{};if(s["Content-Type"]="application/json","undefined"!=typeof window&&window.gradio_config&&"http://localhost:9876"!==location.origin&&!window.gradio_config.dev_mode){const t=window.gradio_config.root,s=window.gradio_config;let n=resolve_root(e,s.root,!1);return s.root=n,{...s,path:t}}if(e){const n=join_urls(e,"config"),i=await this.fetch(n,{headers:s,credentials:"include"});if(401===(null==i?void 0:i.status)&&!this.options.auth)throw new Error(MISSING_CREDENTIALS_MSG);if(401===(null==i?void 0:i.status)&&this.options.auth)throw new Error(INVALID_CREDENTIALS_MSG);if(200===(null==i?void 0:i.status)){let s=await i.json();return s.path=s.path??"",s.root=e,null==(t=s.dependencies)||t.forEach(((e,t)=>{void 0===e.id&&(e.id=t)})),s}if(401===(null==i?void 0:i.status))throw new Error(UNAUTHORIZED_MSG);throw new Error(CONFIG_ERROR_MSG)}throw new Error(CONFIG_ERROR_MSG)}async function resolve_cookies(){const{http_protocol:e,host:t}=await process_endpoint(this.app_reference,this.options.hf_token);try{if(this.options.auth){const s=await get_cookie_header(e,t,this.options.auth,this.fetch,this.options.hf_token);s&&this.set_cookies(s)}}catch(e){throw Error(e.message)}}async function get_cookie_header(e,t,s,n,i){const a=new FormData;a.append("username",null==s?void 0:s[0]),a.append("password",null==s?void 0:s[1]);let o={};i&&(o.Authorization=`Bearer ${i}`);const r=await n(`${e}//${t}/login`,{headers:o,method:"POST",body:a,credentials:"include"});if(200===r.status)return r.headers.get("set-cookie");throw 401===r.status?new Error(INVALID_CREDENTIALS_MSG):new Error(SPACE_METADATA_ERROR_MSG)}function determine_protocol(e){if(e.startsWith("http")){const{protocol:t,host:s,pathname:n}=new URL(e);return{ws_protocol:"https:"===t?"wss":"ws",http_protocol:t,host:s+("/"!==n?n:"")}}return e.startsWith("file:")?{ws_protocol:"ws",http_protocol:"http:",host:"lite.local"}:{ws_protocol:"wss",http_protocol:"https:",host:new URL(e).host}}const parse_and_set_cookies=e=>{let t=[];return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e=>{const[s,n]=e.split(";")[0].split("=");s&&n&&t.push(`${s.trim()}=${n.trim()}`)})),t},RE_SPACE_NAME=/^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/,RE_SPACE_DOMAIN=/.*hf\.space\/{0,1}.*$/;async function process_endpoint(e,t){const s={};t&&(s.Authorization=`Bearer ${t}`);const n=e.trim().replace(/\/$/,"");if(RE_SPACE_NAME.test(n))try{const t=await fetch(`https://huggingface.co/api/spaces/${n}/host`,{headers:s});return{space_id:e,...determine_protocol((await t.json()).host)}}catch(e){throw new Error(SPACE_METADATA_ERROR_MSG)}if(RE_SPACE_DOMAIN.test(n)){const{ws_protocol:e,http_protocol:t,host:s}=determine_protocol(n);return{space_id:s.split("/")[0].replace(".hf.space",""),ws_protocol:e,http_protocol:t,host:s}}return{space_id:!1,...determine_protocol(n)}}const join_urls=(...e)=>{try{return e.reduce(((e,t)=>(e=e.replace(/\/+$/,""),t=t.replace(/^\/+/,""),new URL(t,e+"/").toString())))}catch(e){throw new Error(INVALID_URL_MSG)}};function transform_api_info(e,t,s){const n={named_endpoints:{},unnamed_endpoints:{}};return Object.keys(e).forEach((i=>{"named_endpoints"!==i&&"unnamed_endpoints"!==i||(n[i]={},Object.entries(e[i]).forEach((([e,{parameters:a,returns:o}])=>{var r,c,l,p;const d=(null==(r=t.dependencies.find((t=>t.api_name===e||t.api_name===e.replace("/",""))))?void 0:r.id)||s[e.replace("/","")]||-1,u=-1!==d?null==(c=t.dependencies.find((e=>e.id==d)))?void 0:c.types:{generator:!1,cancel:!1};if(-1!==d&&(null==(p=null==(l=t.dependencies.find((e=>e.id==d)))?void 0:l.inputs)?void 0:p.length)!==a.length){const e=t.dependencies.find((e=>e.id==d)).inputs.map((e=>{var s;return null==(s=t.components.find((t=>t.id===e)))?void 0:s.type}));try{e.forEach(((e,t)=>{if("state"===e){const e={component:"state",example:null,parameter_default:null,parameter_has_default:!0,parameter_name:null,hidden:!0};a.splice(t,0,e)}}))}catch(e){console.error(e)}}const _=(e,t,s,n)=>({...e,description:get_description(null==e?void 0:e.type,s),type:get_type(null==e?void 0:e.type,t,s,n)||""});n[i][e]={parameters:a.map((e=>_(e,null==e?void 0:e.component,null==e?void 0:e.serializer,"parameter"))),returns:o.map((e=>_(e,null==e?void 0:e.component,null==e?void 0:e.serializer,"return"))),type:u}})))})),n}function get_type(e,t,s,n){if("Api"===t)return e.type;switch(null==e?void 0:e.type){case"string":return"string";case"boolean":return"boolean";case"number":return"number"}return"JSONSerializable"===s||"StringSerializable"===s?"any":"ListStringSerializable"===s?"string[]":"Image"===t?"parameter"===n?"Blob | File | Buffer":"string":"FileSerializable"===s?"array"===(null==e?void 0:e.type)?"parameter"===n?"(Blob | File | Buffer)[]":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]":"parameter"===n?"Blob | File | Buffer":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}":"GallerySerializable"===s?"parameter"===n?"[(Blob | File | Buffer), (string | null)][]":"[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]":void 0}function get_description(e,t){return"GallerySerializable"===t?"array of [file, label] tuples":"ListStringSerializable"===t?"array of strings":"FileSerializable"===t?"array of files or single file":null==e?void 0:e.description}function handle_message(e,t){const s=!0;switch(e.msg){case"send_data":return{type:"data"};case"send_hash":return{type:"hash"};case"queue_full":return{type:"update",status:{queue:s,message:QUEUE_FULL_MSG,stage:"error",code:e.code,success:e.success}};case"heartbeat":return{type:"heartbeat"};case"unexpected_error":return{type:"unexpected_error",status:{queue:s,message:e.message,stage:"error",success:!1}};case"estimation":return{type:"update",status:{queue:s,stage:t||"pending",code:e.code,size:e.queue_size,position:e.rank,eta:e.rank_eta,success:e.success}};case"progress":return{type:"update",status:{queue:s,stage:"pending",code:e.code,progress_data:e.progress_data,success:e.success}};case"log":return{type:"log",data:e};case"process_generating":return{type:"generating",status:{queue:s,message:e.success?null:e.output.error,stage:e.success?"generating":"error",code:e.code,progress_data:e.progress_data,eta:e.average_duration,changed_state_ids:e.success?e.output.changed_state_ids:void 0},data:e.success?e.output:null};case"process_streaming":return{type:"streaming",status:{queue:s,message:e.output.error,stage:"streaming",time_limit:e.time_limit,code:e.code,progress_data:e.progress_data,eta:e.eta},data:e.output};case"process_completed":return"error"in e.output?{type:"update",status:{queue:s,title:e.output.title,message:e.output.error,visible:e.output.visible,duration:e.output.duration,stage:"error",code:e.code,success:e.success}}:{type:"complete",status:{queue:s,message:e.success?void 0:e.output.error,stage:e.success?"complete":"error",code:e.code,progress_data:e.progress_data,changed_state_ids:e.success?e.output.changed_state_ids:void 0},data:e.success?e.output:null};case"process_starts":return{type:"update",status:{queue:s,stage:"pending",code:e.code,size:e.rank,position:0,success:e.success,eta:e.eta},original_msg:"process_starts"}}return{type:"none",status:{stage:"error",queue:s}}}const map_data_to_params=(e=[],t)=>{const s=t?t.parameters:[];if(Array.isArray(e))return e.length>s.length&&console.warn("Too many arguments provided for the endpoint."),e;const n=[],i=Object.keys(e);return s.forEach(((t,s)=>{if(e.hasOwnProperty(t.parameter_name))n[s]=e[t.parameter_name];else{if(!t.parameter_has_default)throw new Error(`No value provided for required parameter: ${t.parameter_name}`);n[s]=t.parameter_default}})),i.forEach((e=>{if(!s.some((t=>t.parameter_name===e)))throw new Error(`Parameter \`${e}\` is not a valid keyword argument. Please refer to the API for usage.`)})),n.forEach(((e,t)=>{if(void 0===e&&!s[t].parameter_has_default)throw new Error(`No value provided for required parameter: ${s[t].parameter_name}`)})),n};async function view_api(){if(this.api_info)return this.api_info;const{hf_token:e}=this.options,{config:t}=this,s={"Content-Type":"application/json"};if(e&&(s.Authorization=`Bearer ${e}`),t)try{let e,n;if("undefined"!=typeof window&&window.gradio_api_info)n=window.gradio_api_info;else{if(semiver((null==t?void 0:t.version)||"2.0.0","3.30")<0)e=await this.fetch(SPACE_FETCHER_URL,{method:"POST",body:JSON.stringify({serialize:!1,config:JSON.stringify(t)}),headers:s,credentials:"include"});else{const n=join_urls(t.root,this.api_prefix,"info");e=await this.fetch(n,{headers:s,credentials:"include"})}if(!e.ok)throw new Error(BROKEN_CONNECTION_MSG);n=await e.json()}return"api"in n&&(n=n.api),n.named_endpoints["/predict"]&&!n.unnamed_endpoints[0]&&(n.unnamed_endpoints[0]=n.named_endpoints["/predict"]),transform_api_info(n,t,this.api_map)}catch(e){e.message}}async function upload_files(e,t,s){var n;const i={};(null==(n=null==this?void 0:this.options)?void 0:n.hf_token)&&(i.Authorization=`Bearer ${this.options.hf_token}`);const a=[];let o;for(let n=0;n<t.length;n+=1e3){const r=t.slice(n,n+1e3),c=new FormData;r.forEach((e=>{c.append("files",e)}));try{const t=s?`${e}${this.api_prefix}/upload?upload_id=${s}`:`${e}${this.api_prefix}/upload`;o=await this.fetch(t,{method:"POST",body:c,headers:i,credentials:"include"})}catch(e){throw new Error(BROKEN_CONNECTION_MSG+e.message)}if(!o.ok){const e=await o.text();return{error:`HTTP ${o.status}: ${e}`}}const l=await o.json();l&&a.push(...l)}return{files:a}}async function upload(e,t,s,n){let i=(Array.isArray(e)?e:[e]).map((e=>e.blob));const a=i.filter((e=>e.size>(n??1/0)));if(a.length)throw new Error(`File size exceeds the maximum allowed size of ${n} bytes: ${a.map((e=>e.name)).join(", ")}`);return await Promise.all(await this.upload_files(t,i,s).then((async s=>{if(s.error)throw new Error(s.error);return s.files?s.files.map(((s,n)=>new FileData({...e[n],path:s,url:`${t}${this.api_prefix}/file=${s}`}))):[]})))}async function prepare_files(e,t){return e.map((e=>new FileData({path:e.name,orig_name:e.name,blob:e,size:e.size,mime_type:e.type,is_stream:t})))}class FileData{constructor({path:e,url:t,orig_name:s,size:n,blob:i,is_stream:a,mime_type:o,alt_text:r,b64:c}){__publicField(this,"path"),__publicField(this,"url"),__publicField(this,"orig_name"),__publicField(this,"size"),__publicField(this,"blob"),__publicField(this,"is_stream"),__publicField(this,"mime_type"),__publicField(this,"alt_text"),__publicField(this,"b64"),__publicField(this,"meta",{_type:"gradio.FileData"}),this.path=e,this.url=t,this.orig_name=s,this.size=n,this.blob=t?void 0:i,this.is_stream=a,this.mime_type=o,this.alt_text=r,this.b64=c}}class Command{constructor(e,t){__publicField(this,"type"),__publicField(this,"command"),__publicField(this,"meta"),__publicField(this,"fileData"),this.type="command",this.command=e,this.meta=t}}const is_node="undefined"!=typeof process&&process.versions&&process.versions.node;function update_object(e,t,s){for(;s.length>1;){const t=s.shift();if("string"!=typeof t&&"number"!=typeof t)throw new Error("Invalid key type");e=e[t]}const n=s.shift();if("string"!=typeof n&&"number"!=typeof n)throw new Error("Invalid key type");e[n]=t}async function walk_and_store_blobs(e,t=void 0,s=[],n=!1,i=void 0){if(Array.isArray(e)){let a=[];return await Promise.all(e.map((async(o,r)=>{var c;let l=s.slice();l.push(String(r));const p=await walk_and_store_blobs(e[r],n?(null==(c=null==i?void 0:i.parameters[r])?void 0:c.component)||void 0:t,l,!1,i);a=a.concat(p)}))),a}if(globalThis.Buffer&&e instanceof globalThis.Buffer||e instanceof Blob)return[{path:s,blob:new Blob([e]),type:t}];if("object"==typeof e&&null!==e){let t=[];for(const n of Object.keys(e)){const a=[...s,n],o=e[n];t=t.concat(await walk_and_store_blobs(o,void 0,a,!1,i))}return t}return[]}function skip_queue(e,t){var s,n;let i=null==(n=null==(s=null==t?void 0:t.dependencies)?void 0:s.find((t=>t.id==e)))?void 0:n.queue;return null!=i?!i:!t.enable_queue}function post_message(e,t){return new Promise(((s,n)=>{const i=new MessageChannel;i.port1.onmessage=({data:e})=>{i.port1.close(),s(e)},window.parent.postMessage(e,t,[i.port2])}))}function handle_file(e){if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://"))return{path:e,url:e,orig_name:e.split("/").pop()??"unknown",meta:{_type:"gradio.FileData"}};if(is_node)return new Command("upload_file",{path:e,name:e,orig_path:e})}else{if("undefined"!=typeof File&&e instanceof File)return new Blob([e]);if(e instanceof Buffer)return new Blob([e]);if(e instanceof Blob)return e}throw new Error("Invalid input: must be a URL, File, Blob, or Buffer object.")}function handle_payload(e,t,s,n,i=!1){if("input"===n&&!i)throw new Error("Invalid code path. Cannot skip state inputs for input.");if("output"===n&&i)return e;let a=[],o=0;const r="input"===n?t.inputs:t.outputs;for(let t=0;t<r.length;t++){const n=r[t],c=s.find((e=>e.id===n));if("state"!==(null==c?void 0:c.type)){const t=e[o];a.push(t),o++}else{if(!i){o++;continue}if(e.length===r.length){const t=e[o];a.push(t),o++}else a.push(null)}}return a}async function handle_blob(e,t,s){const n=this;await process_local_file_commands(n,t);const i=await walk_and_store_blobs(t,void 0,[],!0,s);return(await Promise.all(i.map((async({path:t,blob:s,type:i})=>{if(!s)return{path:t,type:i};const a=await n.upload_files(e,[s]);return{path:t,file_url:a.files&&a.files[0],type:i,name:"undefined"!=typeof File&&s instanceof File?null==s?void 0:s.name:void 0}})))).forEach((({path:e,file_url:s,type:n,name:i})=>{if("Gallery"===n)update_object(t,s,e);else if(s){const n=new FileData({path:s,orig_name:i});update_object(t,n,e)}})),t}async function process_local_file_commands(e,t){var s,n;if(!((null==(s=e.config)?void 0:s.root)||(null==(n=e.config)?void 0:n.root_url)))throw new Error(ROOT_URL_ERROR_MSG);await recursively_process_commands(e,t)}async function recursively_process_commands(e,t,s=[]){for(const n in t)t[n]instanceof Command?await process_single_command(e,t,n):"object"==typeof t[n]&&null!==t[n]&&await recursively_process_commands(e,t[n],[...s,n])}async function process_single_command(e,t,s){var n,i;let a=t[s];const o=(null==(n=e.config)?void 0:n.root)||(null==(i=e.config)?void 0:i.root_url);if(!o)throw new Error(ROOT_URL_ERROR_MSG);try{let n,i;if("undefined"==typeof process||!process.versions||!process.versions.node)throw new Error(NODEJS_FS_ERROR_MSG);{const e=await import("fs/promises");i=(await import("path")).resolve(process.cwd(),a.meta.path),n=await e.readFile(i)}const r=new Blob([n],{type:"application/octet-stream"}),c=await e.upload_files(o,[r]),l=c.files&&c.files[0];if(l){const e=new FileData({path:l,orig_name:a.meta.name||""});t[s]=e}}catch(e){console.error("Error uploading file",e)}}async function post_data(e,t,s){const n={"Content-Type":"application/json"};this.options.hf_token&&(n.Authorization=`Bearer ${this.options.hf_token}`);try{var i=await this.fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...n,...s},credentials:"include"})}catch(e){return[{error:BROKEN_CONNECTION_MSG},500]}let a,o;try{a=await i.json(),o=i.status}catch(e){a={error:`Could not parse server response: ${e}`},o=500}return[a,o]}async function predict(e,t={}){let s=!1,n=!1;if(!this.config)throw new Error("Could not resolve app config");if("number"==typeof e)this.config.dependencies.find((t=>t.id==e));else{const t=e.replace(/^\//,"");this.config.dependencies.find((e=>e.id==this.api_map[t]))}return new Promise((async(i,a)=>{const o=this.submit(e,t,null,null,!0);let r;for await(const e of o)"data"===e.type&&(n&&i(r),s=!0,r=e),"status"===e.type&&("error"===e.stage&&a(e),"complete"===e.stage&&(n=!0,s&&i(r)))}))}async function check_space_status(e,t,s){let n,i,a="subdomain"===t?`https://huggingface.co/api/spaces/by-subdomain/${e}`:`https://huggingface.co/api/spaces/${e}`;try{if(n=await fetch(a),i=n.status,200!==i)throw new Error;n=await n.json()}catch(e){return void s({status:"error",load_status:"error",message:SPACE_STATUS_ERROR_MSG,detail:"NOT_FOUND"})}if(!n||200!==i)return;const{runtime:{stage:o},id:r}=n;switch(o){case"STOPPED":case"SLEEPING":s({status:"sleeping",load_status:"pending",message:"Space is asleep. Waking it up...",detail:o}),setTimeout((()=>{check_space_status(e,t,s)}),1e3);break;case"PAUSED":s({status:"paused",load_status:"error",message:"This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",detail:o,discussions_enabled:await discussions_enabled(r)});break;case"RUNNING":case"RUNNING_BUILDING":s({status:"running",load_status:"complete",message:"Space is running.",detail:o});break;case"BUILDING":s({status:"building",load_status:"pending",message:"Space is building...",detail:o}),setTimeout((()=>{check_space_status(e,t,s)}),1e3);break;case"APP_STARTING":s({status:"starting",load_status:"pending",message:"Space is starting...",detail:o}),setTimeout((()=>{check_space_status(e,t,s)}),1e3);break;default:s({status:"space_error",load_status:"error",message:"This space is experiencing an issue.",detail:o,discussions_enabled:await discussions_enabled(r)})}}const check_and_wake_space=async(e,t)=>{let s=0;return new Promise((n=>{check_space_status(e,RE_SPACE_NAME.test(e)?"space_name":"subdomain",(i=>{t(i),"running"===i.status||"error"===i.status||"paused"===i.status||"space_error"===i.status?n():"sleeping"!==i.status&&"building"!==i.status||(s<12?(s++,setTimeout((()=>{check_and_wake_space(e,t).then(n)}),5e3)):n())}))}))},RE_DISABLED_DISCUSSION=/^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;async function discussions_enabled(e){try{const t=await fetch(`https://huggingface.co/api/spaces/${e}/discussions`,{method:"HEAD"}),s=t.headers.get("x-error-message");return!(!t.ok||s&&RE_DISABLED_DISCUSSION.test(s))}catch(e){return!1}}async function get_space_hardware(e,t){const s={};t&&(s.Authorization=`Bearer ${t}`);try{const t=await fetch(`https://huggingface.co/api/spaces/${e}/runtime`,{headers:s});if(200!==t.status)throw new Error("Space hardware could not be obtained.");const{hardware:n}=await t.json();return n.current}catch(e){throw new Error(e.message)}}async function set_space_timeout(e,t,s){const n={};s&&(n.Authorization=`Bearer ${s}`);const i={seconds:t};try{const t=await fetch(`https://huggingface.co/api/spaces/${e}/sleeptime`,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(i)});if(200!==t.status)throw new Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges.");return await t.json()}catch(e){throw new Error(e.message)}}const hardware_types=["cpu-basic","cpu-upgrade","cpu-xl","t4-small","t4-medium","a10g-small","a10g-large","a10g-largex2","a10g-largex4","a100-large","zero-a10g","h100","h100x8"];async function duplicate(e,t){const{hf_token:s,private:n,hardware:i,timeout:a,auth:o}=t;if(i&&!hardware_types.includes(i))throw new Error(`Invalid hardware type provided. Valid types are: ${hardware_types.map((e=>`"${e}"`)).join(",")}.`);const{http_protocol:r,host:c}=await process_endpoint(e,s);let l=null;if(o){const e=await get_cookie_header(r,c,o,fetch);e&&(l=parse_and_set_cookies(e))}const p={Authorization:`Bearer ${s}`,"Content-Type":"application/json",...l?{Cookie:l.join("; ")}:{}},d=(await(await fetch("https://huggingface.co/api/whoami-v2",{headers:p})).json()).name,u=e.split("/")[1],_={repository:`${d}/${u}`};let h;n&&(_.private=!0);try{i||(h=await get_space_hardware(e,s))}catch(e){throw Error(SPACE_METADATA_ERROR_MSG+e.message)}const f=i||h||"cpu-basic";_.hardware=f;try{const n=await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`,{method:"POST",headers:p,body:JSON.stringify(_)});if(409===n.status)try{return await Client.connect(`${d}/${u}`,t)}catch(e){throw console.error("Failed to connect Client instance:",e),e}else if(200!==n.status)throw new Error(n.statusText);const i=await n.json();return await set_space_timeout(`${d}/${u}`,a||300,s),await Client.connect(get_space_reference(i.url),t)}catch(e){throw new Error(e)}}function get_space_reference(e){const t=e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/);if(t)return t[1]}class TextLineStream extends TransformStream{constructor(e={allowCR:!1}){super({transform:(t,s)=>{for(t=__privateGet(this,_currentLine)+t;;){const n=t.indexOf("\n"),i=e.allowCR?t.indexOf("\r"):-1;if(-1!==i&&i!==t.length-1&&(-1===n||n-1>i)){s.enqueue(t.slice(0,i)),t=t.slice(i+1);continue}if(-1===n)break;const a="\r"===t[n-1]?n-1:n;s.enqueue(t.slice(0,a)),t=t.slice(n+1)}__privateSet(this,_currentLine,t)},flush:t=>{if(""===__privateGet(this,_currentLine))return;const s=e.allowCR&&__privateGet(this,_currentLine).endsWith("\r")?__privateGet(this,_currentLine).slice(0,-1):__privateGet(this,_currentLine);t.enqueue(s)}}),__privateAdd(this,_currentLine,"")}}function stream$1(e){let t=new TextDecoderStream,s=new TextLineStream({allowCR:!0});return e.pipeThrough(t).pipeThrough(s)}function split(e){let t=/[:]\s*/.exec(e),s=t&&t.index;if(s)return[e.substring(0,s),e.substring(s+t[0].length)]}function fallback(e,t,s){e.get(t)||e.set(t,s)}async function*events(e,t){if(!e.body)return;let s,n,i=stream$1(e.body).getReader();for(;;){if(t&&t.aborted)return i.cancel();if(s=await i.read(),s.done)return;if(!s.value){n&&(yield n),n=void 0;continue}let[e,a]=split(s.value)||[];e&&("data"===e?(n||(n={}),n[e]=n[e]?n[e]+"\n"+a:a):"event"===e?(n||(n={}),n[e]=a):"id"===e?(n||(n={}),n[e]=+a||a):"retry"===e&&(n||(n={}),n[e]=+a||void 0))}}async function stream(e,t){let s=new Request(e,t);fallback(s.headers,"Accept","text/event-stream"),fallback(s.headers,"Content-Type","application/json");let n=await fetch(s);if(!n.ok)throw n;return events(n,s.signal)}async function open_stream(){let{event_callbacks:e,unclosed_events:t,pending_stream_messages:s,stream_status:n,config:i,jwt:a}=this;const o=this;if(!i)throw new Error("Could not resolve app config");n.open=!0;let r=null,c=new URLSearchParams({session_hash:this.session_hash}).toString(),l=new URL(`${i.root}${this.api_prefix}/${SSE_URL}?${c}`);a&&l.searchParams.set("__sign",a),r=this.stream(l),r?(r.onmessage=async function(a){let r=JSON.parse(a.data);if("close_stream"===r.msg)return void close_stream(n,o.abort_controller);const c=r.event_id;if(c)if(e[c]&&i){"process_completed"===r.msg&&["sse","sse_v1","sse_v2","sse_v2.1","sse_v3"].includes(i.protocol)&&t.delete(c);let s=e[c];"undefined"!=typeof window&&"undefined"!=typeof document?setTimeout(s,0,r):s(r)}else s[c]||(s[c]=[]),s[c].push(r);else await Promise.all(Object.keys(e).map((t=>e[t](r))))},r.onerror=async function(){await Promise.all(Object.keys(e).map((t=>e[t]({msg:"unexpected_error",message:BROKEN_CONNECTION_MSG}))))}):console.warn("Cannot connect to SSE endpoint: "+l.toString())}function close_stream(e,t){e&&(e.open=!1,null==t||t.abort())}function apply_diff_stream(e,t,s){!e[t]?(e[t]=[],s.data.forEach(((s,n)=>{e[t][n]=s}))):s.data.forEach(((n,i)=>{let a=apply_diff(e[t][i],n);e[t][i]=a,s.data[i]=a}))}function apply_diff(e,t){return t.forEach((([t,s,n])=>{e=apply_edit(e,s,t,n)})),e}function apply_edit(e,t,s,n){if(0===t.length){if("replace"===s)return n;if("append"===s)return e+n;throw new Error(`Unsupported action: ${s}`)}let i=e;for(let e=0;e<t.length-1;e++)i=i[t[e]];const a=t[t.length-1];switch(s){case"replace":i[a]=n;break;case"append":i[a]+=n;break;case"add":Array.isArray(i)?i.splice(Number(a),0,n):i[a]=n;break;case"delete":Array.isArray(i)?i.splice(Number(a),1):delete i[a];break;default:throw new Error(`Unknown action: ${s}`)}return e}function readable_stream(e,t={}){const s={close:()=>{console.warn("Method not implemented.")},onerror:null,onmessage:null,onopen:null,readyState:0,url:e.toString(),withCredentials:!1,CONNECTING:0,OPEN:1,CLOSED:2,addEventListener:()=>{throw new Error("Method not implemented.")},dispatchEvent:()=>{throw new Error("Method not implemented.")},removeEventListener:()=>{throw new Error("Method not implemented.")}};return stream(e,t).then((async e=>{s.readyState=s.OPEN;try{for await(const t of e)s.onmessage&&s.onmessage(t);s.readyState=s.CLOSED}catch(e){s.onerror&&s.onerror(e),s.readyState=s.CLOSED}})).catch((e=>{console.error(e),s.onerror&&s.onerror(e),s.readyState=s.CLOSED})),s}function submit(e,t={},s,n,i){var a;try{let r=function(e){(i||z[e.type])&&d(e)},c=function(){for(J=!0;K.length>0;)K.shift()({value:void 0,done:!0})},l=function(e){J||(K.length>0?K.shift()(e):H.push(e))},p=function(e){l(thenable_reject(e)),c()},d=function(e){l({value:e,done:!1})},u=function(){return H.length>0?Promise.resolve(H.shift()):J?Promise.resolve({value:void 0,done:!0}):new Promise((e=>K.push(e)))};const{hf_token:_}=this.options,{fetch:h,app_reference:f,config:m,session_hash:g,api_info:w,api_map:y,stream_status:b,pending_stream_messages:v,pending_diff_streams:E,event_callbacks:S,unclosed_events:R,post_data:O,options:N,api_prefix:k}=this,C=this;if(!w)throw new Error("No API found");if(!m)throw new Error("Could not resolve app config");let A,F,{fn_index:T,endpoint_info:$,dependency:x}=get_endpoint_info(w,e,y,m),L=map_data_to_params(t,$),D=m.protocol??"ws",I="",G=()=>I;const P="number"==typeof e?"/predict":e;let U,j=null,M=!1,q={},B="undefined"!=typeof window&&"undefined"!=typeof document?new URLSearchParams(window.location.search).toString():"";const z=(null==(a=null==N?void 0:N.events)?void 0:a.reduce(((e,t)=>(e[t]=!0,e)),{}))||{};const W=async e=>{await this._resolve_hearbeat(e)};async function o(e){if(!m)return;let t=e.render_id;m.components=[...m.components.filter((e=>e.props.rendered_in!==t)),...e.components],m.dependencies=[...m.dependencies.filter((e=>e.rendered_in!==t)),...e.dependencies];const s=m.components.some((e=>"state"===e.type)),n=m.dependencies.some((e=>e.targets.some((e=>"unload"===e[1]))));m.connect_heartbeat=s||n,await W(m),r({type:"render",data:e,endpoint:P,fn_index:T})}this.handle_blob(m.root,L,$).then((async e=>{var t;let i=handle_payload(e,x,m.components,"input",!0);if(U={data:i||[],event_data:s,fn_index:T,trigger_id:n},skip_queue(T,m))r({type:"status",endpoint:P,stage:"pending",queue:!1,fn_index:T,time:new Date}),O(`${m.root}${k}/run${P.startsWith("/")?P:`/${P}`}${B?"?"+B:""}`,{...U,session_hash:g}).then((([e,t])=>{const i=e.data;200==t?(r({type:"data",endpoint:P,fn_index:T,data:handle_payload(i,x,m.components,"output",N.with_null_state),time:new Date,event_data:s,trigger_id:n}),e.render_config&&o(e.render_config),r({type:"status",endpoint:P,fn_index:T,stage:"complete",eta:e.average_duration,queue:!1,time:new Date})):r({type:"status",stage:"error",endpoint:P,fn_index:T,message:e.error,queue:!1,time:new Date})})).catch((e=>{r({type:"status",stage:"error",message:e.message,endpoint:P,fn_index:T,queue:!1,time:new Date})}));else if("ws"==D){const{ws_protocol:e,host:t}=await process_endpoint(f,_);r({type:"status",stage:"pending",queue:!0,endpoint:P,fn_index:T,time:new Date});let i=new URL(`${e}://${resolve_root(t,m.path,!0)}/queue/join${B?"?"+B:""}`);this.jwt&&i.searchParams.set("__sign",this.jwt),A=new WebSocket(i),A.onclose=e=>{e.wasClean||r({type:"status",stage:"error",broken:!0,message:BROKEN_CONNECTION_MSG,queue:!0,endpoint:P,fn_index:T,time:new Date})},A.onmessage=function(e){const t=JSON.parse(e.data),{type:i,status:a,data:o}=handle_message(t,q[T]);if("update"===i&&a&&!M)r({type:"status",endpoint:P,fn_index:T,time:new Date,...a}),"error"===a.stage&&A.close();else{if("hash"===i)return void A.send(JSON.stringify({fn_index:T,session_hash:g}));"data"===i?A.send(JSON.stringify({...U,session_hash:g})):"complete"===i?M=a:"log"===i?r({type:"log",title:o.title,log:o.log,level:o.level,endpoint:P,duration:o.duration,visible:o.visible,fn_index:T}):"generating"===i&&r({type:"status",time:new Date,...a,stage:null==a?void 0:a.stage,queue:!0,endpoint:P,fn_index:T})}o&&(r({type:"data",time:new Date,data:handle_payload(o.data,x,m.components,"output",N.with_null_state),endpoint:P,fn_index:T,event_data:s,trigger_id:n}),M&&(r({type:"status",time:new Date,...M,stage:null==a?void 0:a.stage,queue:!0,endpoint:P,fn_index:T}),A.close()))},semiver(m.version||"2.0.0","3.6")<0&&addEventListener("open",(()=>A.send(JSON.stringify({hash:g}))))}else if("sse"==D){r({type:"status",stage:"pending",queue:!0,endpoint:P,fn_index:T,time:new Date});var a=new URLSearchParams({fn_index:T.toString(),session_hash:g}).toString();let e=new URL(`${m.root}${k}/${SSE_URL}?${B?B+"&":""}${a}`);if(this.jwt&&e.searchParams.set("__sign",this.jwt),F=this.stream(e),!F)return Promise.reject(new Error("Cannot connect to SSE endpoint: "+e.toString()));F.onmessage=async function(e){const t=JSON.parse(e.data),{type:i,status:a,data:o}=handle_message(t,q[T]);if("update"===i&&a&&!M)r({type:"status",endpoint:P,fn_index:T,time:new Date,...a}),"error"===a.stage&&(null==F||F.close(),c());else if("data"===i){let[e,t]=await O(`${m.root}${k}/queue/data`,{...U,session_hash:g,event_id:j});200!==t&&(r({type:"status",stage:"error",message:BROKEN_CONNECTION_MSG,queue:!0,endpoint:P,fn_index:T,time:new Date}),null==F||F.close(),c())}else"complete"===i?M=a:"log"===i?r({type:"log",title:o.title,log:o.log,level:o.level,endpoint:P,duration:o.duration,visible:o.visible,fn_index:T}):"generating"!==i&&"streaming"!==i||r({type:"status",time:new Date,...a,stage:null==a?void 0:a.stage,queue:!0,endpoint:P,fn_index:T});o&&(r({type:"data",time:new Date,data:handle_payload(o.data,x,m.components,"output",N.with_null_state),endpoint:P,fn_index:T,event_data:s,trigger_id:n}),M&&(r({type:"status",time:new Date,...M,stage:null==a?void 0:a.stage,queue:!0,endpoint:P,fn_index:T}),null==F||F.close(),c()))}}else if("sse_v1"==D||"sse_v2"==D||"sse_v2.1"==D||"sse_v3"==D){r({type:"status",stage:"pending",queue:!0,endpoint:P,fn_index:T,time:new Date});let e="";"undefined"!=typeof window&&"undefined"!=typeof document&&(e=null==(t=null==window?void 0:window.location)?void 0:t.hostname);let s="dev.spaces.huggingface.tech";const n=e.includes(".dev.")?`https://moon-${e.split(".")[1]}.${s}`:"https://huggingface.co";("undefined"!=typeof window&&"undefined"!=typeof document&&window.parent!=window&&window.supports_zerogpu_headers?post_message("zerogpu-headers",n):Promise.resolve(null)).then((e=>O(`${m.root}${k}/queue/join?${B}`,{...U,session_hash:g},e))).then((async([e,t])=>{if(503===t)r({type:"status",stage:"error",message:QUEUE_FULL_MSG,queue:!0,endpoint:P,fn_index:T,time:new Date});else if(200!==t)r({type:"status",stage:"error",message:BROKEN_CONNECTION_MSG,queue:!0,endpoint:P,fn_index:T,time:new Date});else{j=e.event_id,I=j;let t=async function(e){try{const{type:t,status:s,data:n,original_msg:i}=handle_message(e,q[T]);if("heartbeat"==t)return;if("update"===t&&s&&!M)r({type:"status",endpoint:P,fn_index:T,time:new Date,original_msg:i,...s});else if("complete"===t)M=s;else if("unexpected_error"==t)console.error("Unexpected error",null==s?void 0:s.message),r({type:"status",stage:"error",message:(null==s?void 0:s.message)||"An Unexpected Error Occurred!",queue:!0,endpoint:P,fn_index:T,time:new Date});else{if("log"===t)return void r({type:"log",title:n.title,log:n.log,level:n.level,endpoint:P,duration:n.duration,visible:n.visible,fn_index:T});"generating"!==t&&"streaming"!==t||(r({type:"status",time:new Date,...s,stage:null==s?void 0:s.stage,queue:!0,endpoint:P,fn_index:T}),n&&"stream"!==x.connection&&["sse_v2","sse_v2.1","sse_v3"].includes(D)&&apply_diff_stream(E,j,n))}n&&(r({type:"data",time:new Date,data:handle_payload(n.data,x,m.components,"output",N.with_null_state),endpoint:P,fn_index:T}),n.render_config&&await o(n.render_config),M&&(r({type:"status",time:new Date,...M,stage:null==s?void 0:s.stage,queue:!0,endpoint:P,fn_index:T}),c())),"complete"!==(null==s?void 0:s.stage)&&"error"!==(null==s?void 0:s.stage)||(S[j]&&delete S[j],j in E&&delete E[j])}catch(e){console.error("Unexpected client exception",e),r({type:"status",stage:"error",message:"An Unexpected Error Occurred!",queue:!0,endpoint:P,fn_index:T,time:new Date}),["sse_v2","sse_v2.1","sse_v3"].includes(D)&&(close_stream(b,C.abort_controller),b.open=!1,c())}};j in v&&(v[j].forEach((e=>t(e))),delete v[j]),S[j]=t,R.add(j),b.open||await this.open_stream()}}))}}));let J=!1;const H=[],K=[],V={[Symbol.asyncIterator]:()=>V,next:u,throw:async e=>(p(e),u()),return:async()=>(c(),u()),cancel:async function(){const e={stage:"complete",queue:!1,time:new Date};M=e,r({...e,type:"status",endpoint:P,fn_index:T});let t={},s={};"ws"===D?(A&&0===A.readyState?A.addEventListener("open",(()=>{A.close()})):A.close(),t={fn_index:T,session_hash:g}):(close_stream(b,C.abort_controller),c(),t={event_id:j},s={event_id:j,session_hash:g,fn_index:T});try{if(!m)throw new Error("Could not resolve app config");"event_id"in s&&await h(`${m.root}${k}/cancel`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(s)}),await h(`${m.root}${k}/reset`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(t)})}catch(e){console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.")}},event_id:G};return V}catch(Z){throw console.error("Submit function encountered an error:",Z),Z}}function thenable_reject(e){return{then:(t,s)=>s(e)}}function get_endpoint_info(e,t,s,n){let i,a,o;if("number"==typeof t)i=t,a=e.unnamed_endpoints[i],o=n.dependencies.find((e=>e.id==t));else{const r=t.replace(/^\//,"");i=s[r],a=e.named_endpoints[t.trim()],o=n.dependencies.find((e=>e.id==s[r]))}if("number"!=typeof i)throw new Error("There is no endpoint matching that name of fn_index matching that number.");return{fn_index:i,endpoint_info:a,dependency:o}}_currentLine=new WeakMap;class Client{constructor(e,t={events:["data"]}){__publicField(this,"app_reference"),__publicField(this,"options"),__publicField(this,"config"),__publicField(this,"api_prefix",""),__publicField(this,"api_info"),__publicField(this,"api_map",{}),__publicField(this,"session_hash",Math.random().toString(36).substring(2)),__publicField(this,"jwt",!1),__publicField(this,"last_status",{}),__publicField(this,"cookies",null),__publicField(this,"stream_status",{open:!1}),__publicField(this,"closed",!1),__publicField(this,"pending_stream_messages",{}),__publicField(this,"pending_diff_streams",{}),__publicField(this,"event_callbacks",{}),__publicField(this,"unclosed_events",new Set),__publicField(this,"heartbeat_event",null),__publicField(this,"abort_controller",null),__publicField(this,"stream_instance",null),__publicField(this,"current_payload"),__publicField(this,"ws_map",{}),__publicField(this,"view_api"),__publicField(this,"upload_files"),__publicField(this,"upload"),__publicField(this,"handle_blob"),__publicField(this,"post_data"),__publicField(this,"submit"),__publicField(this,"predict"),__publicField(this,"open_stream"),__publicField(this,"resolve_config"),__publicField(this,"resolve_cookies"),this.app_reference=e,t.events||(t.events=["data"]),this.options=t,this.current_payload={},this.view_api=view_api.bind(this),this.upload_files=upload_files.bind(this),this.handle_blob=handle_blob.bind(this),this.post_data=post_data.bind(this),this.submit=submit.bind(this),this.predict=predict.bind(this),this.open_stream=open_stream.bind(this),this.resolve_config=resolve_config.bind(this),this.resolve_cookies=resolve_cookies.bind(this),this.upload=upload.bind(this),this.fetch=this.fetch.bind(this),this.handle_space_success=this.handle_space_success.bind(this),this.stream=this.stream.bind(this)}get_url_config(e=null){if(!this.config)throw new Error(CONFIG_ERROR_MSG);null===e&&(e=window.location.href);const t=e=>e.replace(/^\/+|\/+$/g,"");let s,n=t(new URL(this.config.root).pathname),i=t(new URL(e).pathname);return s=i.startsWith(n)?t(i.substring(n.length)):"",this.get_page_config(s)}get_page_config(e){if(!this.config)throw new Error(CONFIG_ERROR_MSG);let t=this.config;return e in t.page||(e=""),{...t,current_page:e,layout:t.page[e].layout,components:t.components.filter((s=>t.page[e].components.includes(s.id))),dependencies:this.config.dependencies.filter((s=>t.page[e].dependencies.includes(s.id)))}}fetch(e,t){const s=new Headers((null==t?void 0:t.headers)||{});if(this&&this.cookies&&s.append("Cookie",this.cookies),this&&this.options.headers)for(const e in this.options.headers)s.append(e,this.options.headers[e]);return fetch(e,{...t,headers:s})}stream(e){const t=new Headers;if(this&&this.cookies&&t.append("Cookie",this.cookies),this&&this.options.headers)for(const e in this.options.headers)t.append(e,this.options.headers[e]);return this.abort_controller=new AbortController,this.stream_instance=readable_stream(e.toString(),{credentials:"include",headers:t,signal:this.abort_controller.signal}),this.stream_instance}async init(){var e;if(!("undefined"!=typeof window&&"WebSocket"in window||global.WebSocket)){const e=await import("./wrapper-CviSselG.js");global.WebSocket=e.WebSocket}this.options.auth&&await this.resolve_cookies(),await this._resolve_config().then((({config:e})=>this._resolve_hearbeat(e))),this.api_info=await this.view_api(),this.api_map=map_names_to_ids((null==(e=this.config)?void 0:e.dependencies)||[])}async _resolve_hearbeat(e){if(e&&(this.config=e,this.api_prefix=e.api_prefix||"",this.config&&this.config.connect_heartbeat&&this.config.space_id&&this.options.hf_token&&(this.jwt=await get_jwt(this.config.space_id,this.options.hf_token,this.cookies))),e.space_id&&this.options.hf_token&&(this.jwt=await get_jwt(e.space_id,this.options.hf_token)),this.config&&this.config.connect_heartbeat){const e=new URL(`${this.config.root}${this.api_prefix}/heartbeat/${this.session_hash}`);this.jwt&&e.searchParams.set("__sign",this.jwt),this.heartbeat_event||(this.heartbeat_event=this.stream(e))}}static async connect(e,t={events:["data"]}){const s=new this(e,t);return await s.init(),s}close(){this.closed=!0,close_stream(this.stream_status,this.abort_controller)}set_current_payload(e){this.current_payload=e}static async duplicate(e,t={events:["data"]}){return duplicate(e,t)}async _resolve_config(){const{http_protocol:e,host:t,space_id:s}=await process_endpoint(this.app_reference,this.options.hf_token),{status_callback:n}=this.options;let i;s&&n&&await check_and_wake_space(s,n);try{if(i=await this.resolve_config(`${e}//${t}`),!i)throw new Error(CONFIG_ERROR_MSG);return this.config_success(i)}catch(e){if(!s||!n)throw n&&n({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),Error(e);check_space_status(s,RE_SPACE_NAME.test(s)?"space_name":"subdomain",this.handle_space_success)}}async config_success(e){if(this.config=e,this.api_prefix=e.api_prefix||"","undefined"!=typeof window&&"undefined"!=typeof document&&"https:"===window.location.protocol&&(this.config.root=this.config.root.replace("http://","https://")),this.config.auth_required)return this.prepare_return_obj();try{this.api_info=await this.view_api()}catch(e){console.error(API_INFO_ERROR_MSG+e.message)}return this.prepare_return_obj()}async handle_space_success(e){var t;if(!this)throw new Error(CONFIG_ERROR_MSG);const{status_callback:s}=this.options;if(s&&s(e),"running"===e.status)try{if(this.config=await this._resolve_config(),this.api_prefix=(null==(t=null==this?void 0:this.config)?void 0:t.api_prefix)||"",!this.config)throw new Error(CONFIG_ERROR_MSG);return await this.config_success(this.config)}catch(e){throw s&&s({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),e}}async component_server(e,t,s){var n;if(!this.config)throw new Error(CONFIG_ERROR_MSG);const i={},{hf_token:a}=this.options,{session_hash:o}=this;let r;a&&(i.Authorization=`Bearer ${this.options.hf_token}`);let c,l=this.config.components.find((t=>t.id===e));if(r=(null==(n=null==l?void 0:l.props)?void 0:n.root_url)?l.props.root_url:this.config.root,"binary"in s){c=new FormData;for(const e in s.data)"binary"!==e&&c.append(e,s.data[e]);c.set("component_id",e.toString()),c.set("fn_name",t),c.set("session_hash",o)}else c=JSON.stringify({data:s,component_id:e,fn_name:t,session_hash:o}),i["Content-Type"]="application/json";a&&(i.Authorization=`Bearer ${a}`);try{const e=await this.fetch(`${r}${this.api_prefix}/component_server/`,{method:"POST",body:c,headers:i,credentials:"include"});if(!e.ok)throw new Error("Could not connect to component server: "+e.statusText);return await e.json()}catch(e){console.warn(e)}}set_cookies(e){this.cookies=parse_and_set_cookies(e).join("; ")}prepare_return_obj(){return{config:this.config,predict:this.predict,submit:this.submit,view_api:this.view_api,component_server:this.component_server}}async connect_ws(e){return new Promise(((t,s)=>{let n;try{n=new WebSocket(e)}catch(t){return void(this.ws_map[e]="failed")}n.onopen=()=>{t()},n.onerror=s=>{console.error("WebSocket error:",s),this.close_ws(e),this.ws_map[e]="failed",t()},n.onclose=()=>{delete this.ws_map[e],this.ws_map[e]="failed"},n.onmessage=e=>{},this.ws_map[e]=n}))}async send_ws_message(e,t){e in this.ws_map||await this.connect_ws(e);const s=this.ws_map[e];s instanceof WebSocket?s.send(JSON.stringify(t)):this.post_data(e,t)}async close_ws(e){if(e in this.ws_map){const t=this.ws_map[e];t instanceof WebSocket&&(t.close(),delete this.ws_map[e])}}}async function client(e,t={events:["data"]}){return await Client.connect(e,t)}async function duplicate_space(e,t){return await Client.duplicate(e,t)}export{Client,FileData,client,duplicate_space as duplicate,handle_file,predict,prepare_files,submit,upload,upload_files};
|
| 8 |
-
//# sourceMappingURL=/sm/cb356b6300b7138d14860ae177383ea54067ebdf57f14068a69b8e792f497fba.map
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|