Qwen3-ASR / code /scripts /make_demo.py
changh95's picture
tt-model push qwen3-asr (container)
d9f9acd verified
Raw History Blame Contribute Delete
7.68 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Make the card's demo (``### Example output``) from a RUNNING Qwen3-ASR server (standard library only).
python3 code/scripts/make_demo.py --url http://127.0.0.1:20000 --media media \
--short demo_en.mp3,demo_zh.mp3,demo_ko.mp3 --long demo_long_en.mp3 --stream demo_ko.mp3
Every input file is read from ``--media``; the outputs go there too:
* each ``--short`` file: ``POST /v1/audio/transcriptions`` (json) -> transcript, language, client round trip;
* ``--long``: ``response_format=srt`` -> ``<stem>.srt`` (segment cues), and ``verbose_json`` (segments, timings);
* ``--stream``: the WebSocket streaming input at real-time pace (0.1 s PCM16 frames, 2 s chunks): the delay of every
partial transcript after the last frame of its chunk, and the final text; plus the SSE first-delta time of the
same file;
* ``demos.json``: every request, response, timing and the sha256 of every input / output file.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import io
import json
import sys
import threading
import time
import wave
from pathlib import Path
HERE = Path(__file__).resolve().parent
_spec = importlib.util.spec_from_file_location("q3asr_client", HERE.parent / "tt_qwen3_asr" / "server" / "client.py")
qc = importlib.util.module_from_spec(_spec)
sys.modules["q3asr_client"] = qc
_spec.loader.exec_module(qc)
def sha(p: Path) -> str:
return hashlib.sha256(p.read_bytes()).hexdigest()
def get_json(url: str):
import urllib.request
with urllib.request.urlopen(url, timeout=30) as r:
return json.loads(r.read())
def pcm16_of(url: str, audio: bytes) -> bytes:
"""16 kHz mono PCM16 for the WebSocket route: a 16 kHz PCM16 WAV is used as is; any other file (MP3, other rates)
is decoded with soundfile + soxr, as the server does (only this path needs numpy / soundfile / soxr)."""
try:
pcm, sr = qc.wav_to_pcm16(audio)
if sr == 16000:
return pcm
except Exception: # noqa: BLE001
pass
import numpy as np # optional path (MP3 / other rates): soundfile + soxr, as the server
import soundfile as sf
import soxr
x, sr = sf.read(io.BytesIO(audio), dtype="float32", always_2d=False)
if x.ndim == 2:
x = x.mean(-1)
if sr != 16000:
x = soxr.resample(x, sr, 16000, quality="HQ")
return (np.clip(x, -1, 1) * 32767).astype("<i2").tobytes()
def stream_realtime(url: str, pcm: bytes, chunk_s: float = 2.0, frame_s: float = 0.1) -> dict:
ws = qc._WS(url.replace("http://", "ws://").rstrip("/") + "/v1/audio/transcriptions/stream")
msgs, times = [], []
def reader():
while True:
m = ws.recv()
if m is None:
return
msgs.append(json.loads(m))
times.append(time.perf_counter())
if msgs[-1].get("type") in ("final", "error"):
return
ws.send(json.dumps({"format": "pcm16", "sample_rate": 16000, "chunk_size_sec": chunk_s}))
first = json.loads(ws.recv())
if first.get("type") != "ready":
raise RuntimeError(f"WebSocket start refused: {first}")
th = threading.Thread(target=reader, daemon=True)
th.start()
fb = int(frame_s * 16000) * 2
sent_at = [] # time the last frame of every chunk was sent
t0 = time.perf_counter()
per_chunk = int(round(chunk_s / frame_s))
for i, k in enumerate(range(0, len(pcm), fb)):
target = t0 + i * frame_s
time.sleep(max(0.0, target - time.perf_counter()))
ws.send(pcm[k:k + fb], binary=True)
if (i + 1) % per_chunk == 0:
sent_at.append(time.perf_counter())
t_fin = time.perf_counter()
ws.send(json.dumps({"type": "finish"}))
th.join(120)
ws.close()
parts = [(m, t) for m, t in zip(msgs, times) if m.get("type") == "partial"]
delays = [round(1e3 * (t - s), 1) for (m, t), s in zip(parts, sent_at)]
fin = [(m, t) for m, t in zip(msgs, times) if m.get("type") == "final"]
return {"audio_seconds": round(len(pcm) / 32000, 2), "chunk_seconds": chunk_s, "frame_seconds": frame_s,
"partials": [m["text"] for m, _ in parts], "partial_delay_ms": delays,
"final": fin[-1][0]["text"] if fin else None,
"final_after_finish_ms": round(1e3 * (fin[-1][1] - t_fin), 1) if fin else None}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:20000")
ap.add_argument("--media", default="media")
ap.add_argument("--short", default="")
ap.add_argument("--long", default="")
ap.add_argument("--stream", default="")
args = ap.parse_args()
url, media = args.url.rstrip("/"), Path(args.media)
info = get_json(url + "/info")
out = {"server": {k: info.get(k) for k in ("profile", "weights", "device", "engine", "precision", "version")},
"short": [], "long": None, "stream": None}
qc.transcribe(url, (media / args.short.split(",")[0]).read_bytes()) # one untimed request first
for name in [s for s in args.short.split(",") if s]:
p = media / name
t0 = time.perf_counter()
st, body, _ = qc.transcribe(url, p.read_bytes())
ms = 1e3 * (time.perf_counter() - t0)
if st != 200:
raise RuntimeError(f"{name}: HTTP {st} {body}")
out["short"].append({"file": name, "sha256": sha(p), "request": {"file": name},
"language": body["language"], "text": body["text"],
"audio_seconds": body["usage"]["seconds"], "round_trip_ms": round(ms, 1)})
print(f"{name}: {body['language']}: {body['text']} ({ms:.0f} ms)", flush=True)
if args.long:
p = media / args.long
t0 = time.perf_counter()
st, srt, _ = qc.transcribe(url, p.read_bytes(), response_format="srt")
ms = 1e3 * (time.perf_counter() - t0)
if st != 200:
raise RuntimeError(f"{args.long}: HTTP {st} {srt}")
srt_path = media / (Path(args.long).stem + ".srt")
srt_path.write_text(srt)
st, vj, _ = qc.transcribe(url, p.read_bytes(), response_format="verbose_json")
out["long"] = {"file": args.long, "sha256": sha(p), "request": {"file": args.long, "response_format": "srt"},
"srt": srt_path.name, "srt_sha256": sha(srt_path), "round_trip_ms": round(ms, 1),
"duration": vj.get("duration"),
"segments": [{k: s[k] for k in ("id", "start", "end", "text")} for s in vj.get("segments", [])],
"timings": vj.get("timings")}
print(f"{args.long}: {len(out['long']['segments'])} segments, {ms:.0f} ms round trip", flush=True)
if args.stream:
p = media / args.stream
audio = p.read_bytes()
r = stream_realtime(url, pcm16_of(url, audio))
t0 = time.perf_counter()
first = None
for ev in qc.transcribe_stream(url, audio):
if first is None and ev.get("type") == "transcript.text.delta":
first = 1e3 * (time.perf_counter() - t0)
r.update({"file": args.stream, "sha256": sha(p), "sse_first_delta_ms": round(first or -1, 1)})
out["stream"] = r
print(f"stream {args.stream}: {len(r['partials'])} partials, delays {r['partial_delay_ms']} ms, final "
f"{r['final_after_finish_ms']} ms after finish; SSE first delta {r['sse_first_delta_ms']} ms", flush=True)
(media / "demos.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
return 0
if __name__ == "__main__":
sys.exit(main())