File size: 7,682 Bytes
d9f9acd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | #!/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())
|