File size: 5,673 Bytes
8d5c18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Render the demo audio of the model card from a RUNNING server of this package (standard library only).

    python3 code/scripts/make_demo.py --url http://127.0.0.1:20000 --out media

Sends the fixed demo requests of the served profile (CustomVoice: English, Chinese, Korean and, on 1.7B, an
instruction; VoiceDesign: a designed voice; Base: a clone of the shipped reference clip) to ``POST /tts`` and writes
``<out>/demo_<name>.wav`` (24 kHz, 16-bit) plus ``<out>/demos.json``: per demo the profile, the exact request JSON (the
reference clip by its path in this repo), the response headers (frames, seed, stop reason, timing) and the WAV's
sha256. Existing entries of other profiles in ``demos.json`` are kept.
"""
from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import sys
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent
PKG = HERE.parent / "tt_qwen3_tts"


def _client():
    spec = importlib.util.spec_from_file_location("q3_client", PKG / "server" / "client.py")
    mod = importlib.util.module_from_spec(spec)
    sys.modules["q3_client"] = mod
    spec.loader.exec_module(mod)
    return mod


DEMOS = {
    "custom_voice": [
        ("cv_en", {"text": "Hello! I'm Ryan, one of the nine preset voices. Every word you hear was generated on a "
                           "single accelerator card, faster than real time.", "speaker": "ryan", "language": "English",
                   "seed": 7}),
        ("cv_zh", {"text": "ไฝ ๅฅฝ๏ผŒๆˆ‘ๆ˜ฏ่–‡่–‡ๅฎ‰ใ€‚่ฟ™ๆฎต่ฏญ้Ÿณๆ˜ฏๅœจไธ€ๅผ ๅŠ ้€ŸๅกไธŠๅฎžๆ—ถ็”Ÿๆˆ็š„ใ€‚", "speaker": "vivian",
                   "language": "Chinese", "seed": 11}),
        ("cv_ko", {"text": "์•ˆ๋…•ํ•˜์„ธ์š”, ์ €๋Š” ์†Œํฌ์˜ˆ์š”. ์ด ๋ชฉ์†Œ๋ฆฌ๋Š” ํ…์Šคํ† ๋ ŒํŠธ ์นด๋“œ์—์„œ ์‹ค์‹œ๊ฐ„์œผ๋กœ ๋งŒ๋“ค์–ด์กŒ์–ด์š”.",
                   "speaker": "sohee", "language": "Korean", "seed": 5}),
    ],
    "custom_voice_instruct": [
        ("cv_en_instruct", {"text": "We did it! The whole model runs on one card, and it answers faster than I can "
                                    "blink.", "speaker": "aiden", "language": "English",
                            "instruct": "Speak with great excitement and joy, a little faster than usual.",
                            "seed": 3}),
    ],
    "voice_design": [
        ("vd_en", {"text": "Once upon a time, in a quiet village by the sea, there lived a clockmaker who never "
                           "slept.", "language": "English",
                   "instruct": "A warm, calm elderly woman's voice, speaking slowly and gently, like a bedtime "
                               "story.", "seed": 21}),
    ],
    "base": [
        ("base_clone", {"text": "This voice was cloned from a seven second reference clip, and now it reads a "
                                "sentence it has never heard before.", "language": "English", "seed": 13,
                        "voice": "demo_ryan"}),
    ],
}


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--url", default="http://127.0.0.1:20000")
    ap.add_argument("--out", type=Path, default=Path("media"))
    a = ap.parse_args()
    qc = _client()
    c = qc.Client(a.url, timeout=600)
    info = c.get_json("/info")
    v = info["variant"]
    kind, profile = v["kind"], v["profile"]
    demos = list(DEMOS[kind])
    if kind == "custom_voice" and v.get("instruct"):
        demos += DEMOS["custom_voice_instruct"]
    a.out.mkdir(parents=True, exist_ok=True)
    index_path = a.out / "demos.json"
    index = json.loads(index_path.read_text()) if index_path.is_file() else {}
    if kind == "base":
        sample = PKG / "samples" / "ref_ryan_en"
        meta = json.loads((sample / "sample.json").read_text())
        try:
            c.delete("/voices/demo_ryan")
        except qc.HTTPError:
            pass
        reg = c.register_voice("demo_ryan", (sample / meta["file"]).read_bytes(), meta["ref_text"])
        print(f"registered demo_ryan: {reg.get('ref_frames')} reference frames", flush=True)
    for name, req in demos:
        body = dict(req, response_format="wav", stream=False)
        t0 = time.perf_counter()
        h, wav = c.speech(body)
        dt = time.perf_counter() - t0
        p = a.out / f"demo_{name}.wav"
        p.write_bytes(wav)
        rec = {"profile": profile, "route": "POST /tts", "request": body,
               "response": {k: h.get(k) for k in ("x-frames", "x-audio-seconds", "x-seed", "x-stop-reason",
                                                    "x-timing-ms", "x-model")},
               "client_round_trip_s": round(dt, 3), "file": p.name,
               "sha256": hashlib.sha256(wav).hexdigest(), "made": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
               "device": {k: (info.get("device") or {}).get(k) for k in ("dispatch", "grid")},
               "engines": info.get("engines"), "precision": info.get("precision")}
        if kind == "base":
            rec["voice"] = {"id": "demo_ryan", "registered_with": "POST /voices",
                            "ref_audio": "code/tt_qwen3_tts/samples/ref_ryan_en/reference.wav",
                            "ref_text": meta["ref_text"]}
        index[name] = rec
        print(f"{name}: {h.get('x-frames')} frames, {h.get('x-audio-seconds')} s, stop {h.get('x-stop-reason')}, "
              f"{dt:.2f} s round trip -> {p}", flush=True)
    index_path.write_text(json.dumps(index, indent=1, ensure_ascii=False) + "\n")
    return 0


if __name__ == "__main__":
    sys.exit(main())