v2: + YodaLingua data, 2-step IntMeanFlow fast mode (cfm2), new previews
Browse filesFiles changed (30)
- NOTICE+4-2
- README.md+12-7
- config.json+7-1
- onnx/cfm.onnx+1-1
- onnx/cfm2.onnxAdded+3
- onnx/enc.onnx+1-1
- samples/tra-da-nam-tram_ke-chuyen.wav+2-2
- samples/tra-da-nam_ban-tin.wav+2-2
- samples/tra-da-nam_tong-dai.wav+2-2
- samples/tra-da-nu-am_tong-dai.wav+2-2
- samples/tra-da-nu_chao-hoi.wav+2-2
- samples/tra-da-nu_ke-chuyen.wav+2-2
- scripts/export_onnx.py+16
- trada-tts-10m-2step.safetensorsAdded+3
- trada-tts-10m.safetensors+1-1
- trada_tts/__main__.py+2-1
- trada_tts/infer.py+29-6
- trada_tts/model.py+7-3
- voices/ban-hang-nu.wav+2-2
- voices/ban-tin-nu.wav+2-2
- voices/game-nam.wav+2-2
- voices/ke-chuyen-nam.wav+2-2
- voices/review-phim-nam.wav+2-2
- voices/tra-da-nam-tram.wav+2-2
- voices/tra-da-nam.wav+2-2
- voices/tra-da-nu-am.wav+2-2
- voices/tra-da-nu.wav+2-2
- web/app.js+14-8
- web/index.html+14-3
- web/tts.js+21-10
12345678Trà Đá TTS==========Code (trada_tts/, scripts/, web/*.js, web/*.html, web/serve.py): Apache License 2.0 (see LICENSE).Model weights (trada-tts-10m.safetensors, onnx/enc.onnx, onnx/cfm.onnx, onnx/dec.onnx, voices/): CC BY-NC-SA 4.0,because they are trained only on the viVoice dataset (capleaf/viVoice, CC BY-NC-SA 4.0).https://creativecommons.org/licenses/by-nc-sa/4.0/ -- non-commercial use, attribution, share-alike.Third-party components12345678910Trà Đá TTS==========Code (trada_tts/, scripts/, web/*.js, web/*.html, web/serve.py): Apache License 2.0 (see LICENSE).Model weights (trada-tts-10m.safetensors, trada-tts-10m-2step.safetensors, onnx/enc.onnx, onnx/cfm.onnx, onnx/cfm2.onnx,onnx/dec.onnx, voices/): CC BY-NC-SA 4.0, because they are trained on the viVoice dataset (capleaf/viVoice, CC BY-NC-SA 4.0).They are also trained on about 61 hours of YodaLingua-Vietnamese (Thomcles/YodaLingua-Vietnamese), which its publisherlists as CC BY 4.0. Its transcripts were re-labelled with the ChunkFormer ASR model (khanhld/chunkformer-large-vie).https://creativecommons.org/licenses/by-nc-sa/4.0/ -- non-commercial use, attribution, share-alike.Third-party components
12 unmodified lines13141516171819202122234 unmodified lines2829303132333425 unmodified lines6061626364656667686950 unmodified lines12012112212312412512612712812913013124 unmodified lines15615715815916016116212 unmodified lines- on-devicedatasets:- capleaf/viVoice---# Trà Đá TTS 10M (`trada-tts-10m`)**Trà Đá** is a small Vietnamese text-to-speech model: **9.8M parameters**, 24 kHz output, about **16× faster than real time on 4 CPU threads**. It supports **zero-shot voice cloning** from a 5–15 s recording, and runs in PyTorch, in ONNX Runtime (no PyTorch needed) and **in the browser with WebGPU**, so text and voice never leave the device.> Trà Đá là mô hình đọc tiếng Việt 9,8 triệu tham số, hỗ trợ nhân bản giọng từ 5–15 giây ghi âm. Chạy được bằng PyTorch, ONNX Runtime, hoặc ngay trong trình duyệt bằng WebGPU. Có 4 giọng mẫu tổng hợp và nhân bản giọng từ 5–15 giây ghi âm.4 unmodified lines| Input | Vietnamese text: numbers, dates, units and currency are normalised automatically || Voices | 9 synthetic voices (4 presets + 5 TikTok-style) + zero-shot cloning from a 5–15 s reference || Runtimes | PyTorch · ONNX Runtime (CPU/GPU) · ONNX Runtime Web (WebGPU, WASM fallback) || Training data | viVoice only (CC BY-NC-SA 4.0) || License | weights **CC BY-NC-SA 4.0** (non-commercial); code Apache-2.0 |## Samples25 unmodified linesaudio = tts.synthesize("Đây là giọng của tôi.", voice="my_voice.wav") # zero-shot clone from 5-15 s of audio````synthesize(text, voice, cfg_weight=3.0, steps=16, speed=1.0, seed=0, min_syllable_ms=160)`:- `voice`: a voice id (`tra-da-nu`, `tra-da-nu-am`, `tra-da-nam`, `tra-da-nam-tram`, `review-phim-nam`, `ke-chuyen-nam`, `ban-tin-nu`, `game-nam`, `ban-hang-nu`), a path to a reference recording, or a 192-d speaker embedding.- `cfg_weight`: text guidance. Higher is clearer; lower is looser and more natural, but makes more mistakes.- `steps`: flow-matching steps. 8 is faster and slightly rougher.- Long text is split into sentences automatically.- `min_syllable_ms` (default 160): every syllable lasts at least this long. Without it the model sometimes rushes long numbers until syllables get swallowed. On number-heavy text, word errors drop from 10.0% to 6.0%, while ordinary text stays the same and only 2% slower. Set it to 0 to disable.50 unmodified lines| | Result ||---|---|| Syllable error rate, viVoice test (80 utterances, Whisper large-v3-turbo) | **16.0%**. The real recordings score 18.1% under the same ASR, because the test set is noisy YouTube audio. || Same test, 15M parent model | 16.1% (the 10M model is not measurably worse) || DNSMOS OVRL of the samples above | 3.22–3.45 || CPU speed, ONNX Runtime, 4 threads (server Xeon) | RTF 0.063 (16× real time); first sentence in 0.14 s (median) || Browser, WASM, 8 threads (headless Chromium on a shared server) | about 2× real time || Zero-shot cloning, unseen speakers | speaker similarity 0.71 and 0.60, against 0.89 and 0.86 for real clips of the same speakers (CAM++ cosine) |WebGPU output was checked for correctness (it matches WASM), but its speed was not benchmarked on real GPU hardware. Expect it to be much faster than WASM on a discrete or Apple GPU.24 unmodified lines## License and responsible use- **Weights** (`trada-tts-10m.safetensors`, `onnx/enc|cfm|dec.onnx`, `voices/`) are trained only on [viVoice](https://huggingface.co/datasets/capleaf/viVoice) and are released under **[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)**: non-commercial use, with attribution and share-alike.- **Code** is Apache-2.0.- **Third-party components** are listed in [`NOTICE`](NOTICE): CAM++ (Apache-2.0), misaki (Apache-2.0) and ONNX Runtime Web (MIT).12 unmodified lines1314151617181920212223244 unmodified lines293031323334353625 unmodified lines626364656667686970717250 unmodified lines12312412512612712812913013113213313413513624 unmodified lines16116216316416516616712 unmodified lines- on-devicedatasets:- capleaf/viVoice- Thomcles/YodaLingua-Vietnamese---# Trà Đá TTS 10M (`trada-tts-10m`)**Trà Đá** is a small Vietnamese text-to-speech model: **9.8M parameters**, 24 kHz output, about **16× faster than real time on 4 CPU threads**, or about 30× in the 2-step fast mode. It supports **zero-shot voice cloning** from a 5–15 s recording, and runs in PyTorch, in ONNX Runtime (no PyTorch needed) and **in the browser with WebGPU**, so text and voice never leave the device.> Trà Đá là mô hình đọc tiếng Việt 9,8 triệu tham số, hỗ trợ nhân bản giọng từ 5–15 giây ghi âm. Chạy được bằng PyTorch, ONNX Runtime, hoặc ngay trong trình duyệt bằng WebGPU. Có 4 giọng mẫu tổng hợp và nhân bản giọng từ 5–15 giây ghi âm.4 unmodified lines| Input | Vietnamese text: numbers, dates, units and currency are normalised automatically || Voices | 9 synthetic voices (4 presets + 5 TikTok-style) + zero-shot cloning from a 5–15 s reference || Runtimes | PyTorch · ONNX Runtime (CPU/GPU) · ONNX Runtime Web (WebGPU, WASM fallback) || Training data | viVoice (CC BY-NC-SA 4.0) + 61 h of YodaLingua-Vietnamese (CC BY 4.0), transcripts re-labelled with ChunkFormer || Fast mode | 2-step flow distilled with IntMeanFlow (`fast=True`), about 8× fewer flow compute than 16 steps || License | weights **CC BY-NC-SA 4.0** (non-commercial); code Apache-2.0 |## Samples25 unmodified linesaudio = tts.synthesize("Đây là giọng của tôi.", voice="my_voice.wav") # zero-shot clone from 5-15 s of audio````synthesize(text, voice, cfg_weight=3.0, steps=16, speed=1.0, seed=0, min_syllable_ms=160, fast=False)`:- `voice`: a voice id (`tra-da-nu`, `tra-da-nu-am`, `tra-da-nam`, `tra-da-nam-tram`, `review-phim-nam`, `ke-chuyen-nam`, `ban-tin-nu`, `game-nam`, `ban-hang-nu`), a path to a reference recording, or a 192-d speaker embedding.- `cfg_weight`: text guidance. Higher is clearer; lower is looser and more natural, but makes more mistakes.- `steps`: flow-matching steps. 8 is faster and slightly rougher.- `fast=True`: use the 2-step distilled flow (`trada-tts-10m-2step.safetensors`, `onnx/cfm2.onnx`). Text guidance is built in, so `cfg_weight` is ignored. Quality is close to 16 steps (see Evaluation). The web demo uses it by default.- Long text is split into sentences automatically.- `min_syllable_ms` (default 160): every syllable lasts at least this long. Without it the model sometimes rushes long numbers until syllables get swallowed. On number-heavy text, word errors drop from 10.0% to 6.0%, while ordinary text stays the same and only 2% slower. Set it to 0 to disable.50 unmodified lines| | Result ||---|---|| Syllable error rate, viVoice test (80 utterances, Whisper large-v3-turbo) | **17.0%**; the viVoice-only release scored 16.6% in the same run (difference not significant, 95% CI −0.5 to +1.3 points). The real recordings score 18.1% under the same ASR, because the test set is noisy YouTube audio. || Syllable error rate, 4 preset voices × 48 sentences | 16 steps **4.8%** · 2-step fast mode **5.1%** · 16-step model run at 2 steps without distillation 5.3% || DNSMOS OVRL, same 48 sentences | 16 steps 3.28 (min 3.00) · fast mode 3.25 (min 2.90) || Voice similarity, fast mode vs 16 steps | 0.973 (CAM++ cosine) || DNSMOS OVRL of the samples above | 3.22–3.45 || CPU speed, ONNX Runtime, 4 threads (server Xeon) | RTF 0.063 (16× real time); first sentence in 0.14 s (median) || Browser, WASM, 8 threads (headless Chromium on a shared server) | about 2× real time || Zero-shot cloning, unseen speakers | speaker similarity 0.71 and 0.63, against 0.89 and 0.86 for real clips of the same speakers (CAM++ cosine) |WebGPU output was checked for correctness (it matches WASM), but its speed was not benchmarked on real GPU hardware. Expect it to be much faster than WASM on a discrete or Apple GPU.24 unmodified lines## License and responsible use- **Weights** (`trada-tts-10m.safetensors`, `trada-tts-10m-2step.safetensors`, `onnx/enc|cfm|cfm2|dec.onnx`, `voices/`) are trained on [viVoice](https://huggingface.co/datasets/capleaf/viVoice) (CC BY-NC-SA 4.0) and [YodaLingua-Vietnamese](https://huggingface.co/datasets/Thomcles/YodaLingua-Vietnamese) (CC BY 4.0, as stated by its publisher), and are released under **[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)**: non-commercial use, with attribution and share-alike.- **Code** is Apache-2.0.- **Third-party components** are listed in [`NOTICE`](NOTICE): CAM++ (Apache-2.0), misaki (Apache-2.0) and ONNX Runtime Web (MIT).
87 unmodified lines888990919287 unmodified lines"steps": 16,"speed": 1.0},"default_voice": "tra-da-nu"}87 unmodified lines888990919293949596979887 unmodified lines"steps": 16,"speed": 1.0},"default_voice": "tra-da-nu","fast": {"weights": "trada-tts-10m-2step.safetensors","steps": 2,"onnx": "cfm2.onnx","note": "IntMeanFlow-distilled flow decoder: average velocity over [t, r], text CFG baked in"}}
123version https://git-lfs.github.com/spec/v1oid sha256:8dd5d9383caa927f9ca9664f4a8d5182e10d7badf8ea94081eb39da73cb8f2e9size 23069257123version https://git-lfs.github.com/spec/v1oid sha256:4d8520668de0d29741b608c8125dffb69f15b589f8d896a3512425152399626asize 23069257
123version https://git-lfs.github.com/spec/v1oid sha256:033c2cb1bd8f99ad97d7388778b878dbbc832ff02e09bcb5585681f9370e2641size 23746651123version https://git-lfs.github.com/spec/v1oid sha256:8be5a9fcd49c4ca2033d716fd74ea0fcb87e153c827c3bce203c622e5fb42f1esize 10023026123version https://git-lfs.github.com/spec/v1oid sha256:49f579ca76544b99e132f7bcbcef239a8dc39f78221c9a64028681971316e62fsize 10023026
123version https://git-lfs.github.com/spec/v1oid sha256:595a77e576d16625ae5fe047fe3d98ce20b7d6f454117cd436193dce4151b3desize 342284123version https://git-lfs.github.com/spec/v1oid sha256:10693c45f95f85a87331798feffe98b3e4c2f2e4918fdcde7f213e7142c68bcbsize 357644
123version https://git-lfs.github.com/spec/v1oid sha256:c5cb5cc87808d1c19ba9a3e8d69f0d86a7873280288ed93c095c027192028897size 340844123version https://git-lfs.github.com/spec/v1oid sha256:dd4461dabbe7a175d2b3e83eb491adf091bca5eb82eb3d922bed302b0c7f467esize 358124
123version https://git-lfs.github.com/spec/v1oid sha256:3aa50089980292bb936a8ffe98885fdad74f9622b660a837e6265ce74e78a570size 311084123version https://git-lfs.github.com/spec/v1oid sha256:4686f0ef8013c1859e16bb6c5918fec794ebf7e9ad28b5696eca5cfc904a8a0esize 307244
123version https://git-lfs.github.com/spec/v1oid sha256:f6353eacb690cfea4b8e3c7a780efceb4fdf3ef729c99a0989a953725a40ae4bsize 320684123version https://git-lfs.github.com/spec/v1oid sha256:b0c342bafcfd3dcf67ea4f25ecfe70d9b93c591f4158b19ab5b6e62b06f77b53size 345644
123version https://git-lfs.github.com/spec/v1oid sha256:3f8e2c7d467f94a62a7083ebfec4690aab066f924bff90139a542fac9917e29dsize 290444123version https://git-lfs.github.com/spec/v1oid sha256:5f81d1d07d52510e868b9837099c03682c15ae0abeb645c7a58a521296987ba2size 296204
123version https://git-lfs.github.com/spec/v1oid sha256:f89f313cc122d2b73d4a7480ea81aed894164239f98d6a2f7134a8a7f3ede5c4size 361484123version https://git-lfs.github.com/spec/v1oid sha256:60357e652aaa8a7637318bfd1dd54d5659c1a24b60321e991c8d7cd6ee8dca0csize 371084
22 unmodified lines23242526272818 unmodified lines4748495051527 unmodified lines60616263646522 unmodified linesdef forward(s, x, cond, t, spk, w): return s.n.velocity_cfg(x, cond, t, spk, w)class Dec(nn.Module):def __init__(s, n): super().__init__(); s.n = ndef forward(s, z): return s.n.decode(z)18 unmodified linestorch.onnx.export(dec, (z,), f"{a.out}/dec.onnx", input_names=["z"], output_names=["mag", "phase"],dynamic_axes={"z": {2: "T"}, "mag": {2: "T2"}, "phase": {2: "T2"}}, **kw)import onnxruntime as ortworst = {}def chk(name, feeds, ref):7 unmodified linesx, cond, z = torch.randn(1, L, T2), torch.randn(1, C, T2), torch.randn(1, L, T2)chk("cfm.onnx", {"x": x.numpy(), "cond": cond.numpy(), "t": t.numpy(), "spk": spk.numpy(), "w": w.numpy()}, [cfm(x, cond, t, spk, w)])chk("dec.onnx", {"z": z.numpy()}, dec(z))for k, v in worst.items(): print(f"{k:12s} max rel |onnx - torch| {v:.1e}")assert max(worst.values()) < 1e-3, worstprint({f: round(os.path.getsize(f"{a.out}/{f}") / 1e6, 1) for f in sorted(os.listdir(a.out)) if f.endswith(".onnx")})22 unmodified lines23242526272829303132333418 unmodified lines53545556575859606162636465667 unmodified lines747576777879808122 unmodified linesdef forward(s, x, cond, t, spk, w): return s.n.velocity_cfg(x, cond, t, spk, w)class CFM2(nn.Module):"""2-step IntMeanFlow flow: average velocity over [t, r], CFG baked in (no w input)"""def __init__(s, f): super().__init__(); s.f = fdef forward(s, x, cond, t, r, spk): return s.f(x, cond, t, spk, r)class Dec(nn.Module):def __init__(s, n): super().__init__(); s.n = ndef forward(s, z): return s.n.decode(z)18 unmodified linestorch.onnx.export(dec, (z,), f"{a.out}/dec.onnx", input_names=["z"], output_names=["mag", "phase"],dynamic_axes={"z": {2: "T"}, "mag": {2: "T2"}, "phase": {2: "T2"}}, **kw)fast = cfg.get("fast"); cfm2 = Noneif fast and os.path.exists(os.path.join(ROOT, fast["weights"])):from trada_tts.model import FlowDecoderA = cfg["arch"]; f2 = FlowDecoder(A["latent_dim"], A["enc_dim"], A["cfm_dim"], A["cfm_blocks"], interval=True).eval()f2.load_state_dict({k[5:]: v for k, v in load_file(os.path.join(ROOT, fast["weights"])).items()}); cfm2 = CFM2(f2).eval()torch.onnx.export(cfm2, (x, cond, t, torch.tensor([0.5]), spk), f"{a.out}/cfm2.onnx", input_names=["x", "cond", "t", "r", "spk"], output_names=["v"],dynamic_axes={"x": {2: "T"}, "cond": {2: "T"}, "v": {2: "T"}}, **kw)import onnxruntime as ortworst = {}def chk(name, feeds, ref):7 unmodified linesx, cond, z = torch.randn(1, L, T2), torch.randn(1, C, T2), torch.randn(1, L, T2)chk("cfm.onnx", {"x": x.numpy(), "cond": cond.numpy(), "t": t.numpy(), "spk": spk.numpy(), "w": w.numpy()}, [cfm(x, cond, t, spk, w)])chk("dec.onnx", {"z": z.numpy()}, dec(z))if cfm2 is not None:r = torch.tensor([0.5]); chk("cfm2.onnx", {"x": x.numpy(), "cond": cond.numpy(), "t": torch.tensor([0.0]).numpy(), "r": r.numpy(), "spk": spk.numpy()}, [cfm2(x, cond, torch.tensor([0.0]), r, spk)])for k, v in worst.items(): print(f"{k:12s} max rel |onnx - torch| {v:.1e}")assert max(worst.values()) < 1e-3, worstprint({f: round(os.path.getsize(f"{a.out}/{f}") / 1e6, 1) for f in sorted(os.listdir(a.out)) if f.endswith(".onnx")})
123version https://git-lfs.github.com/spec/v1oid sha256:a22bb3da9930c656248490c7c808e48701c615039e3b3a8e5521e5c3657d8ecesize 23725888123version https://git-lfs.github.com/spec/v1oid sha256:d551f4aba895e797056265d97a8490bd0691faa44cce9a8bbcac127243af016csize 39223468123version https://git-lfs.github.com/spec/v1oid sha256:302b31188fecfce3012f572e037e81ba5f0250f8ad85d8512ffe53e4df6dd923size 39223468
15 unmodified lines1617181920214 unmodified lines2627282930313215 unmodified linesap.add_argument("--steps", type=int, default=16, help="flow sampling steps (default 16)")ap.add_argument("--speed", type=float, default=1.0)ap.add_argument("--seed", type=int, default=0)ap.add_argument("--list-voices", action="store_true")a = ap.parse_args()import os4 unmodified linesprint("\n".join(tts.voices)); returntext = a.text or (open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read())t0 = time.time()y = tts.synthesize(text, voice=a.ref or a.voice, cfg_weight=a.cfg, steps=a.steps, speed=a.speed, seed=a.seed)dt = time.time() - t0tts.save(y, a.out)print(f"{a.out}: {len(y) / 24000:.2f} s audio in {dt:.2f} s ({a.backend})")15 unmodified lines161718192021224 unmodified lines2728293031323315 unmodified linesap.add_argument("--steps", type=int, default=16, help="flow sampling steps (default 16)")ap.add_argument("--speed", type=float, default=1.0)ap.add_argument("--seed", type=int, default=0)ap.add_argument("--fast", action="store_true", help="2-step distilled flow (~8x faster flow, same quality)")ap.add_argument("--list-voices", action="store_true")a = ap.parse_args()import os4 unmodified linesprint("\n".join(tts.voices)); returntext = a.text or (open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read())t0 = time.time()y = tts.synthesize(text, voice=a.ref or a.voice, cfg_weight=a.cfg, steps=a.steps, speed=a.speed, seed=a.seed, fast=a.fast)dt = time.time() - t0tts.save(y, a.out)print(f"{a.out}: {len(y) / 24000:.2f} s audio in {dt:.2f} s ({a.backend})")
58 unmodified lines59606162636465666 unmodified lines737475767778793 unmodified lines838485868788899091929394959616 unmodified lines11311411511611711811913 unmodified lines1331341351361371389 unmodified lines1481491501511521531546 unmodified lines16116216316416516658 unmodified lines# ---- synthesis ----def synthesize_chunk(self, norm, spk, cfg_weight=3.0, steps=16, speed=1.0, seed=0, return_timeline=False, breaks=None,min_syllable_ms=160):"""breaks: {syllable word index: "join" | "," | "."} = manual phrasing at the boundary before that word."""breaks = {**T.joins_of(norm), **(breaks or {})} # "_" joins from the textids, tones, words, w2c = T.encode(norm)ids, tones, words, w2c, bound = T.apply_breaks(ids, tones, words, w2c, breaks)6 unmodified linescond = np.repeat(h, dur, axis=2).astype(np.float32)x = np.random.default_rng(seed).standard_normal((1, self.config["latent_dim"], cond.shape[2])).astype(np.float32)for k in range(steps): # Euler, uniform t in [0, 1)x = x + self._velocity(x, cond, k / steps, spk[None], cfg_weight) / stepsaudio = self._decode(x)if not return_timeline:return audio3 unmodified linestl.append(dict(text=w, start=f * FRAME_S, end=(f + d) * FRAME_S, frames=d, bound=b)); f += dreturn audio, tldef synthesize(self, text, voice=None, cfg_weight=3.0, steps=16, speed=1.0, seed=0, pause_s=0.25, min_syllable_ms=160):"""raw Vietnamese text -> float32 waveform @24 kHz. Long text is split into sentences."""spk = self.speaker_embedding(voice if voice is not None else self.config["default_voice"])parts = []for i, chunk in enumerate(T.split_sentences(T.normalize(text))):if parts:parts.append(np.zeros(int(pause_s * SR), np.float32))parts.append(self.synthesize_chunk(chunk, spk, cfg_weight, steps, speed, seed + i, min_syllable_ms=min_syllable_ms))return np.concatenate(parts) if parts else np.zeros(0, np.float32)@staticmethod16 unmodified linesc = self.configself.net = TradaTTSModel(n_symbols=len(c["symbols"]), n_tones=c["num_tones"], **c["arch"])self.net.load_state_dict(load_file(os.path.join(root, c["weights"])))self.net.eval().to(self.device)self.window = torch.hann_window(N_FFT, device=self.device)@classmethod13 unmodified linestt = self.torch.tensor([t], dtype=self.torch.float32, device=self.device)return self.net.velocity_cfg(self._t(x), self._t(cond), tt, self._t(spk), w).cpu().numpy()def _decode(self, z):with self.torch.inference_mode():mag, ph = self.net.decode(self._t(z))9 unmodified linesimport onnxruntime as ortso = ort.SessionOptions(); so.intra_op_num_threads = threads; so.inter_op_num_threads = 1pv = providers or ["CPUExecutionProvider"]self.s = {k: ort.InferenceSession(os.path.join(root, "onnx", f"{k}.onnx"), sess_options=so, providers=pv) for k in ("enc", "cfm", "dec")}@classmethoddef from_pretrained(cls, path_or_repo, **kw):6 unmodified linesreturn self.s["cfm"].run(None, {"x": x, "cond": cond, "t": np.array([t], np.float32), "spk": spk.astype(np.float32),"w": np.array([w], np.float32)})[0]def _decode(self, z):mag, ph = self.s["dec"].run(None, {"z": z})return istft_np(mag[0], ph[0])58 unmodified lines5960616263646566676869706 unmodified lines77787980818283843 unmodified lines88899091929394959697989910010116 unmodified lines11811912012112212312412512612712812913013113 unmodified lines1451461471481491501511521531541559 unmodified lines1651661671681691701711721736 unmodified lines18018118218318418518618718818958 unmodified lines# ---- synthesis ----def synthesize_chunk(self, norm, spk, cfg_weight=3.0, steps=16, speed=1.0, seed=0, return_timeline=False, breaks=None,min_syllable_ms=160, fast=False):"""breaks: {syllable word index: "join" | "," | "."} = manual phrasing at the boundary before that word.fast=True: the IntMeanFlow-distilled 2-step flow (CFG baked in; cfg_weight is ignored, steps defaults to 2)."""if fast:if not self.has_fast: raise ValueError("this model folder has no 2-step weights (config.json 'fast')")steps = self.config["fast"]["steps"] if steps in (None, 16) else stepsbreaks = {**T.joins_of(norm), **(breaks or {})} # "_" joins from the textids, tones, words, w2c = T.encode(norm)ids, tones, words, w2c, bound = T.apply_breaks(ids, tones, words, w2c, breaks)6 unmodified linescond = np.repeat(h, dur, axis=2).astype(np.float32)x = np.random.default_rng(seed).standard_normal((1, self.config["latent_dim"], cond.shape[2])).astype(np.float32)for k in range(steps): # Euler, uniform t in [0, 1)if fast: x = x + self._velocity_fast(x, cond, k / steps, (k + 1) / steps, spk[None]) / steps # average velocityelse: x = x + self._velocity(x, cond, k / steps, spk[None], cfg_weight) / stepsaudio = self._decode(x)if not return_timeline:return audio3 unmodified linestl.append(dict(text=w, start=f * FRAME_S, end=(f + d) * FRAME_S, frames=d, bound=b)); f += dreturn audio, tldef synthesize(self, text, voice=None, cfg_weight=3.0, steps=16, speed=1.0, seed=0, pause_s=0.25, min_syllable_ms=160, fast=False):"""raw Vietnamese text -> float32 waveform @24 kHz. Long text is split into sentences."""spk = self.speaker_embedding(voice if voice is not None else self.config["default_voice"])parts = []for i, chunk in enumerate(T.split_sentences(T.normalize(text))):if parts:parts.append(np.zeros(int(pause_s * SR), np.float32))parts.append(self.synthesize_chunk(chunk, spk, cfg_weight, steps, speed, seed + i, min_syllable_ms=min_syllable_ms, fast=fast))return np.concatenate(parts) if parts else np.zeros(0, np.float32)@staticmethod16 unmodified linesc = self.configself.net = TradaTTSModel(n_symbols=len(c["symbols"]), n_tones=c["num_tones"], **c["arch"])self.net.load_state_dict(load_file(os.path.join(root, c["weights"])))fw = os.path.join(root, c["fast"]["weights"]) if "fast" in c else Noneself.has_fast = bool(fw and os.path.exists(fw))if self.has_fast: # optional 2-step (IntMeanFlow) flow decoderfrom .model import FlowDecodera = c["arch"]; self.cfm2 = FlowDecoder(a["latent_dim"], a["enc_dim"], a["cfm_dim"], a["cfm_blocks"], interval=True)self.cfm2.load_state_dict({k[5:]: v for k, v in load_file(fw).items()}); self.cfm2.eval()self.net.eval().to(self.device)if self.has_fast: self.cfm2.to(self.device)self.window = torch.hann_window(N_FFT, device=self.device)@classmethod13 unmodified linestt = self.torch.tensor([t], dtype=self.torch.float32, device=self.device)return self.net.velocity_cfg(self._t(x), self._t(cond), tt, self._t(spk), w).cpu().numpy()def _velocity_fast(self, x, cond, t, r, spk):with self.torch.inference_mode():f = lambda v: self.torch.tensor([v], dtype=self.torch.float32, device=self.device)return self.cfm2(self._t(x), self._t(cond), f(t), self._t(spk), f(r)).cpu().numpy()def _decode(self, z):with self.torch.inference_mode():mag, ph = self.net.decode(self._t(z))9 unmodified linesimport onnxruntime as ortso = ort.SessionOptions(); so.intra_op_num_threads = threads; so.inter_op_num_threads = 1pv = providers or ["CPUExecutionProvider"]names = ["enc", "cfm", "dec"] + (["cfm2"] if os.path.exists(os.path.join(root, "onnx", "cfm2.onnx")) else [])self.s = {k: ort.InferenceSession(os.path.join(root, "onnx", f"{k}.onnx"), sess_options=so, providers=pv) for k in names}self.has_fast = "cfm2" in self.s@classmethoddef from_pretrained(cls, path_or_repo, **kw):6 unmodified linesreturn self.s["cfm"].run(None, {"x": x, "cond": cond, "t": np.array([t], np.float32), "spk": spk.astype(np.float32),"w": np.array([w], np.float32)})[0]def _velocity_fast(self, x, cond, t, r, spk):return self.s["cfm2"].run(None, {"x": x, "cond": cond, "t": np.array([t], np.float32), "r": np.array([r], np.float32),"spk": spk.astype(np.float32)})[0]def _decode(self, z):mag, ph = self.s["dec"].run(None, {"z": z})return istft_np(mag[0], ph[0])
66 unmodified lines6768697071727374753 unmodified lines79808182838485868788899066 unmodified linesclass FlowDecoder(nn.Module):"""Velocity network v(x_t, cond, t, spk) over the normalised latent."""def __init__(self, latent_dim, cond_dim, dim, n_blocks):super().__init__()self.spk_in = nn.Linear(SPK_DIM, SPK_FEAT)self.inp = nn.Conv1d(latent_dim + cond_dim + SPK_FEAT, dim, 1)self.tmlp = nn.Sequential(nn.Linear(128, dim), nn.GELU(), nn.Linear(dim, dim))3 unmodified linesself.norm = nn.LayerNorm(dim)self.out = nn.Conv1d(dim, latent_dim, 1)def forward(self, xt, cond, t, spk):T = xt.size(-1)x = self.inp(torch.cat([xt, cond, self.spk_in(spk).unsqueeze(-1).expand(-1, -1, T)], 1))scale, shift = self.film(spk).chunk(2, -1)x = x * (1 + scale).unsqueeze(-1) + shift.unsqueeze(-1)g = self.tmlp(timestep_embed(t)) + self.spk_g(spk)for b in self.blocks:x = b(x, g)return self.out(self.norm(x.transpose(1, 2)).transpose(1, 2))66 unmodified lines67686970717273747576773 unmodified lines818283848586878889909192939466 unmodified linesclass FlowDecoder(nn.Module):"""Velocity network v(x_t, cond, t, spk) over the normalised latent. With interval=True (the 2-step "fast" model,IntMeanFlow-distilled) it also takes the end time r and predicts the AVERAGE velocity over [t, r], CFG baked in."""def __init__(self, latent_dim, cond_dim, dim, n_blocks, interval=False):super().__init__()self.rmlp = nn.Sequential(nn.Linear(128, dim), nn.GELU(), nn.Linear(dim, dim)) if interval else Noneself.spk_in = nn.Linear(SPK_DIM, SPK_FEAT)self.inp = nn.Conv1d(latent_dim + cond_dim + SPK_FEAT, dim, 1)self.tmlp = nn.Sequential(nn.Linear(128, dim), nn.GELU(), nn.Linear(dim, dim))3 unmodified linesself.norm = nn.LayerNorm(dim)self.out = nn.Conv1d(dim, latent_dim, 1)def forward(self, xt, cond, t, spk, r=None):T = xt.size(-1)x = self.inp(torch.cat([xt, cond, self.spk_in(spk).unsqueeze(-1).expand(-1, -1, T)], 1))scale, shift = self.film(spk).chunk(2, -1)x = x * (1 + scale).unsqueeze(-1) + shift.unsqueeze(-1)g = self.tmlp(timestep_embed(t)) + self.spk_g(spk)if self.rmlp is not None and r is not None:g = g + self.rmlp(timestep_embed(r))for b in self.blocks:x = b(x, g)return self.out(self.norm(x.transpose(1, 2)).transpose(1, 2))
123version https://git-lfs.github.com/spec/v1oid sha256:c103a0977f8058fb3c110da258f8aeb92ce98851284499f1dce14224cbcbebbasize 212204123version https://git-lfs.github.com/spec/v1oid sha256:658c2361088f2f4df16340b0d24959b18c4972c45ca586a18c20f59b649356c5size 214124
123version https://git-lfs.github.com/spec/v1oid sha256:c64757e8a4f50d57b7dff11ebb38c94dcb912f884170b2813841817dda5ac23esize 173324123version https://git-lfs.github.com/spec/v1oid sha256:126a6e8c82862186deb68bd91a9aeaa0997bce56bfa1d5d4656285d7287db41fsize 179084
123version https://git-lfs.github.com/spec/v1oid sha256:339498d389ada180b471669790227f8b03b1238f37d7b282ccc978b118ea3223size 169964123version https://git-lfs.github.com/spec/v1oid sha256:8aa3cebc76e905c555a4360717cdc107970b2bbe5020cfb2f62f7ed49758291asize 166124
123version https://git-lfs.github.com/spec/v1oid sha256:928fccf3d4e71a0e819f37fdaab07d9c181562a09a94c93b2b843a18c54631f6size 229484123version https://git-lfs.github.com/spec/v1oid sha256:c07f6f8c2035a50cbb8eea2ecbcce1bac7803f480909833aa7497356a7746564size 219884
123version https://git-lfs.github.com/spec/v1oid sha256:7631c7c94f249f776a1bd20274b217ac8476b0cee535c31296b8821c4caf9417size 202604123version https://git-lfs.github.com/spec/v1oid sha256:05ded99f87a0488b4909df7a18d3ac75e563f460c5fc936209165a3d56cd9b33size 189164
123version https://git-lfs.github.com/spec/v1oid sha256:b2001fa189ea4ca21d0fd9f311983a148570ae375a8332612b87617f225ed677size 188684123version https://git-lfs.github.com/spec/v1oid sha256:f996caba54beeed30e42c79fa6e6a258862b145a54b2e45f163b60a32830968csize 182924
123version https://git-lfs.github.com/spec/v1oid sha256:cb857b51b534712eca651e55f3d4d79ee7e2467b3ed8dbfa64766b7030e6ff37size 169484123version https://git-lfs.github.com/spec/v1oid sha256:51ecd9b2b50a1f61e825e88f7c2011986f2059b1dfec434382ab184a2a62cfabsize 175244
123version https://git-lfs.github.com/spec/v1oid sha256:7f05fdaceef069362051d15ac33f1a602ae25a45c8cb95d17fd76008ccd28065size 217964123version https://git-lfs.github.com/spec/v1oid sha256:97ed4710de305f219fd4611fcdc592bf6213bb92986cb9ce7892d269bfff66aesize 244844
123version https://git-lfs.github.com/spec/v1oid sha256:2c9b6769ad7243d49c41d581787401351bfff6bd66f9df54f4879d0baefa9f62size 181004123version https://git-lfs.github.com/spec/v1oid sha256:9a7c40727442f23248e80647b594b7a698a85a8ac70792956fc743d34c1d8587size 184844
123456710 unmodified lines18192021222324320 unmodified lines3453463473483493503516 unmodified lines35835936036136236336436536636736836937037111 unmodified lines38338438538638738839 unmodified lines428429430431432433434import * as ort from './ort/ort.webgpu.min.mjs';import { TradaTTS, normalize, normalizePart, JOIN, isAlnum } from './tts.js?v=11202031';import { resample, kaldiFbank } from './audio.js?v=11202031';const VER = '11202031';// model repo root (config.json, onnx/, voices/): the page's parent folder, or window.TRADA_ROOT (e.g. a Hugging Face resolve URL)const ROOT = (window.TRADA_ROOT || new URL('..', import.meta.url).href).replace(/\/$/, '');10 unmodified lines['Kể chuyện', 'Chiều hôm ấy, mưa rơi lất phất trên con phố nhỏ. Bà cụ bán trà đá vẫn ngồi đó, rót cho khách quen một cốc, rồi kể chuyện ngày xưa.'],];const STORE = 'trada-tts.voices.v1', THEME = 'trada-tts.theme';const S = { tts: null, camp: null, presets: [], saved: [], sel: null, backend: 'wasm', take: null, takes: [], pending: null, selG: -1, stopAt: null };// ---------------- iSTFT on WebGPU (WGSL; validated against torch.istft) ----------------const N = 1920, H = 480, FB = 961, MT = 2048;320 unmodified lines// ---------------- generate ----------------async function generate({ replace = false, autoplay = true } = {}) {const text = $('text').value.trim(); if (!text || !S.tts || $('go').disabled) return;const v = current(), opts = { w: +$('w').value, steps: +$('steps').value, speed: +$('speed').value, seed: +$('seed').value };$('go').disabled = true; $('goLabel').textContent = 'Đang pha…'; $('status').classList.remove('err'); $('status').textContent = '';setFill(0); brewing(true);const t0 = performance.now();6 unmodified lineselse { S.takes.unshift(take); if (S.takes.length > 6) URL.revokeObjectURL(S.takes.pop().url); }if (!replace) S.selG = -1;showTake(take); renderHist(); selectBoundary(S.selG); if (autoplay) $('player').play().catch(() => {});$('status').textContent = `${S.backend === 'webgpu' ? 'WebGPU' : 'CPU (WASM)'} · CFG ${opts.w} · ${opts.steps} bước · seed ${opts.seed}`;} catch (e) { console.error(e); $('status').classList.add('err'); $('status').textContent = `Lỗi: ${e.message}. Thử câu ngắn hơn hoặc tải lại trang.`; }brewing(false); $('go').disabled = false; $('goLabel').textContent = 'Đọc';}// ---------------- init ----------------function setPill(id, cls, text) { const p = $(id); p.className = 'pill ' + cls; p.lastElementChild.textContent = text; }const PARTS = { enc: 'lp-enc', cfm: 'lp-cfm', dec: 'lp-dec' };async function init() {try { const th = localStorage.getItem(THEME); if (th) document.documentElement.dataset.theme = th; } catch {}for (const el of document.querySelectorAll('svg.glass')) el.innerHTML = GLASS;11 unmodified linesfor (const [id, out, f] of [['w', 'oW', v => (+v).toFixed(2)], ['steps', 'oSteps', v => v], ['speed', 'oSpeed', v => (+v).toFixed(2) + '×']]) { $(id).oninput = () => $(out).textContent = f($(id).value); $(id).oninput(); }$('dice').onclick = () => { $('seed').value = Math.floor(Math.random() * 100000); };$('go').onclick = () => generate();$('brkSeg').querySelectorAll('button').forEach(b => b.onclick = () => setBoundary(b.dataset.v));$('brkPlay').onclick = playBoundary;$('brkClose').onclick = () => selectBoundary(-1);39 unmodified linesconst prog = (a, b, got, size) => {const f = b ? a / b : 0; scene?.setProgress(f);$('lMB').textContent = `${(a / 1e6).toFixed(0)} / ${((b || 39e6) / 1e6).toFixed(0)} MB`; $('lBar').style.width = (100 * f).toFixed(1) + '%';for (const [n, id] of Object.entries(PARTS)) $(id).className = size[n] && got[n] >= size[n] ? 'done' : got[n] ? 'going' : '';if (b && a >= b) $('lSub').textContent = S.backend === 'webgpu' ? 'Đang khởi động WebGPU…' : 'Đang khởi động…';};let gpu = false;123456710 unmodified lines18192021222324320 unmodified lines3453463473483493503513523536 unmodified lines36036136236336436536636736836937037137237311 unmodified lines38538638738838939039139239339439 unmodified lines434435436437438439440import * as ort from './ort/ort.webgpu.min.mjs';import { TradaTTS, normalize, normalizePart, JOIN, isAlnum } from './tts.js?v=11220100';import { resample, kaldiFbank } from './audio.js?v=11220100';const VER = '11220100';// model repo root (config.json, onnx/, voices/): the page's parent folder, or window.TRADA_ROOT (e.g. a Hugging Face resolve URL)const ROOT = (window.TRADA_ROOT || new URL('..', import.meta.url).href).replace(/\/$/, '');10 unmodified lines['Kể chuyện', 'Chiều hôm ấy, mưa rơi lất phất trên con phố nhỏ. Bà cụ bán trà đá vẫn ngồi đó, rót cho khách quen một cốc, rồi kể chuyện ngày xưa.'],];const STORE = 'trada-tts.voices.v1', THEME = 'trada-tts.theme';const S = { tts: null, camp: null, presets: [], saved: [], sel: null, backend: 'wasm', take: null, takes: [], pending: null, selG: -1, stopAt: null, fast: true };// ---------------- iSTFT on WebGPU (WGSL; validated against torch.istft) ----------------const N = 1920, H = 480, FB = 961, MT = 2048;320 unmodified lines// ---------------- generate ----------------async function generate({ replace = false, autoplay = true } = {}) {const text = $('text').value.trim(); if (!text || !S.tts || $('go').disabled) return;const fast = S.fast && S.tts.hasFast;const v = current(), opts = { w: +$('w').value, steps: +$('steps').value, speed: +$('speed').value, seed: +$('seed').value, fast };if (!fast && !S.tts.s.cfm) $('status').textContent = 'Đang tải model 16 bước (23 MB)…';$('go').disabled = true; $('goLabel').textContent = 'Đang pha…'; $('status').classList.remove('err'); $('status').textContent = '';setFill(0); brewing(true);const t0 = performance.now();6 unmodified lineselse { S.takes.unshift(take); if (S.takes.length > 6) URL.revokeObjectURL(S.takes.pop().url); }if (!replace) S.selG = -1;showTake(take); renderHist(); selectBoundary(S.selG); if (autoplay) $('player').play().catch(() => {});$('status').textContent = `${S.backend === 'webgpu' ? 'WebGPU' : 'CPU (WASM)'} · ` + (fast ? `Nhanh · 2 bước` : `CFG ${opts.w} · ${opts.steps} bước`) + ` · seed ${opts.seed}`;} catch (e) { console.error(e); $('status').classList.add('err'); $('status').textContent = `Lỗi: ${e.message}. Thử câu ngắn hơn hoặc tải lại trang.`; }brewing(false); $('go').disabled = false; $('goLabel').textContent = 'Đọc';}// ---------------- init ----------------function setPill(id, cls, text) { const p = $(id); p.className = 'pill ' + cls; p.lastElementChild.textContent = text; }const PARTS = { enc: 'lp-enc', cfm: 'lp-cfm', dec: 'lp-dec', cfm2: 'lp-cfm' };async function init() {try { const th = localStorage.getItem(THEME); if (th) document.documentElement.dataset.theme = th; } catch {}for (const el of document.querySelectorAll('svg.glass')) el.innerHTML = GLASS;11 unmodified linesfor (const [id, out, f] of [['w', 'oW', v => (+v).toFixed(2)], ['steps', 'oSteps', v => v], ['speed', 'oSpeed', v => (+v).toFixed(2) + '×']]) { $(id).oninput = () => $(out).textContent = f($(id).value); $(id).oninput(); }$('dice').onclick = () => { $('seed').value = Math.floor(Math.random() * 100000); };$('go').onclick = () => generate();const setMode = fast => { S.fast = fast; $('mFast').setAttribute('aria-checked', String(fast)); $('mStd').setAttribute('aria-checked', String(!fast));for (const id of ['setW', 'setSteps']) { $(id).classList.toggle('off', fast); $(id).querySelector('input').disabled = fast; }$('modeHint').textContent = fast ? 'Nhanh hơn khoảng 8 lần ở bước sinh âm, chất lượng tương đương.' : 'Bản gốc: 16 bước, có chỉnh độ bám chữ (CFG).'; };$('mFast').onclick = () => setMode(true); $('mStd').onclick = () => setMode(false); setMode(true);$('brkSeg').querySelectorAll('button').forEach(b => b.onclick = () => setBoundary(b.dataset.v));$('brkPlay').onclick = playBoundary;$('brkClose').onclick = () => selectBoundary(-1);39 unmodified linesconst prog = (a, b, got, size) => {const f = b ? a / b : 0; scene?.setProgress(f);$('lMB').textContent = `${(a / 1e6).toFixed(0)} / ${((b || 39e6) / 1e6).toFixed(0)} MB`; $('lBar').style.width = (100 * f).toFixed(1) + '%';for (const [n, id] of Object.entries(PARTS)) if (n in size) $(id).className = size[n] && got[n] >= size[n] ? 'done' : got[n] ? 'going' : '';if (b && a >= b) $('lSub').textContent = S.backend === 'webgpu' ? 'Đang khởi động WebGPU…' : 'Đang khởi động…';};let gpu = false;
81 unmodified lines828384858687200 unmodified lines28828929029129229329429529676 unmodified lines37337437537637737881 unmodified lines.set .lv{display:flex;justify-content:space-between;gap:6px}.set output{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums}.set input[type=range]{width:100%;accent-color:var(--tea);margin:4px 0 0}.seed{display:flex;gap:6px}.seed input{width:100%;min-width:0;border:1px solid var(--line);border-radius:8px;background:var(--surface);padding:4px 8px;font-variant-numeric:tabular-nums}.foot{display:flex;align-items:center;gap:14px;border-top:1px solid var(--line);padding:12px 18px;flex-wrap:wrap}200 unmodified lines</div><div class="chips" id="examples"></div><div class="settings"><label class="set"><span class="lv"><span>Tốc độ</span><output id="oSpeed"></output></span><input type="range" id="speed" min="0.7" max="1.4" step="0.05" value="1"></label><label class="set" title="Cao hơn: phát âm rõ hơn. Thấp hơn: tự nhiên hơn nhưng dễ đọc sai."><span class="lv"><span>Độ bám chữ</span><output id="oW"></output></span><input type="range" id="w" min="1" max="4" step="0.25" value="3"></label><label class="set" title="Ít bước: nhanh hơn, giọng thô hơn."><span class="lv"><span>Số bước</span><output id="oSteps"></output></span><input type="range" id="steps" min="4" max="32" step="1" value="16"></label><div class="set"><label for="seed">Seed</label><div class="seed"><input type="number" id="seed" value="0" min="0"><button class="btn sq" id="dice" aria-label="Seed ngẫu nhiên">⟳</button></div></div></div><div class="foot">76 unmodified lines<span>Các giọng mẫu là giọng tổng hợp (trộn nhiều người nói), không phải giọng của một người thật.</span></footer></div><script type="module" src="app.js?v=11202031"></script></body></html>81 unmodified lines82838485868788899091929394200 unmodified lines29529629729829930030130230330430530630776 unmodified lines38438538638738838981 unmodified lines.set .lv{display:flex;justify-content:space-between;gap:6px}.set output{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums}.set input[type=range]{width:100%;accent-color:var(--tea);margin:4px 0 0}.set.off{opacity:.45}.mode{grid-column:1/-1;display:flex;align-items:center;gap:12px;flex-wrap:wrap}.mode .seg2{display:inline-grid;grid-template-columns:1fr 1fr;border:1px solid var(--line);border-radius:10px;overflow:hidden;background:var(--surface)}.mode .seg2 button{border:0;background:transparent;padding:7px 14px;font-size:13.5px;cursor:pointer;min-height:38px}.mode .seg2 button+button{border-left:1px solid var(--line)}.mode .seg2 button[aria-checked="true"]{background:var(--tea);color:var(--on-tea);font-weight:600}.mode .hint{font-size:12px;color:var(--muted)}.seed{display:flex;gap:6px}.seed input{width:100%;min-width:0;border:1px solid var(--line);border-radius:8px;background:var(--surface);padding:4px 8px;font-variant-numeric:tabular-nums}.foot{display:flex;align-items:center;gap:14px;border-top:1px solid var(--line);padding:12px 18px;flex-wrap:wrap}200 unmodified lines</div><div class="chips" id="examples"></div><div class="settings"><div class="mode"><span class="set" style="flex-direction:row;align-items:center;gap:8px"><span>Chế độ</span></span><span class="seg2" role="radiogroup" aria-label="Chế độ sinh"><button role="radio" id="mFast" aria-checked="true">Nhanh · 2 bước</button><button role="radio" id="mStd" aria-checked="false">Chuẩn · 16 bước</button></span><span class="hint" id="modeHint">Nhanh hơn khoảng 8 lần ở bước sinh âm, chất lượng tương đương.</span></div><label class="set"><span class="lv"><span>Tốc độ</span><output id="oSpeed"></output></span><input type="range" id="speed" min="0.7" max="1.4" step="0.05" value="1"></label><label class="set" id="setW" title="Cao hơn: phát âm rõ hơn. Thấp hơn: tự nhiên hơn nhưng dễ đọc sai."><span class="lv"><span>Độ bám chữ</span><output id="oW"></output></span><input type="range" id="w" min="1" max="4" step="0.25" value="3"></label><label class="set" id="setSteps" title="Ít bước: nhanh hơn, giọng thô hơn."><span class="lv"><span>Số bước</span><output id="oSteps"></output></span><input type="range" id="steps" min="4" max="32" step="1" value="16"></label><div class="set"><label for="seed">Seed</label><div class="seed"><input type="number" id="seed" value="0" min="0"><button class="btn sq" id="dice" aria-label="Seed ngẫu nhiên">⟳</button></div></div></div><div class="foot">76 unmodified lines<span>Các giọng mẫu là giọng tổng hợp (trộn nhiều người nói), không phải giọng của một người thật.</span></footer></div><script type="module" src="app.js?v=11220100"></script></body></html>
1234567120 unmodified lines1281291301311321331341351361371381391401416 unmodified lines14814915015115215315415515615716 unmodified lines174175176177178179180181// Trà Đá TTS inference in JavaScript, backend-agnostic: pass an `ort` module (onnxruntime-web in the browser,// onnxruntime-node in tests). Mirrors trada_tts/text.py + trada_tts/infer.py.import { textNormalize } from './vi_normalize.js?v=11202031';import { fixNumbers } from './vi_fix.js?v=11202031';const TONE_MARK = { '̀': 2, '́': 3, '̉': 4, '̃': 5, '̣': 6 };const WORD_RE = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]/gu; // == Python re r"\w+|[^\w\s]" on NFC text120 unmodified lines}export class TradaTTS {constructor(ort, sessions, config, istft = null) {this.ort = ort; this.s = sessions; this.cfg = config; this.sr = config.sample_rate;this.istft = istft || (async (m, p, T) => istftCPU(m, p, T));}// root = repo root URL (holds config.json and onnx/)static async load(ort, root, opts = {}, istft = null, onProgress = null) {const cfg = await (await fetch(`${root}/config.json`)).json();const names = ['enc', 'cfm', 'dec'], bufs = {}, got = {}, size = {};const report = () => { if (!onProgress) return; // total = real sizes once every file has answeredconst a = names.reduce((s, n) => s + (got[n] || 0), 0), known = names.every(n => size[n]);onProgress(a, known ? names.reduce((s, n) => s + size[n], 0) : Math.max(a + 1, 39.3e6), { ...got }, { ...size }); };6 unmodified lines}));const s = {};for (const n of names) s[n] = await ort.InferenceSession.create(bufs[n], opts);return new TradaTTS(ort, s, cfg, istft);}// one chunk of NORMALISED text -> Float32Array @24 kHzasync synthChunk(norm, spk, { w = 3.0, steps = 16, speed = 1.0, seed = 0, noise = null, breaks = null, minSyllableMs = 160, onStep = null, onTiming = null } = {}) {const { ort, s, cfg } = this, C = cfg.enc_dim, L = cfg.latent_dim;const enc0 = encodeText(norm, cfg.symbols); breaks = { ...enc0.joins, ...(breaks || {}) }; // "_" joins from the textconst E = applyBreaks(enc0, breaks, cfg.symbols), { ids, tones, words, w2c, bound } = E; const N = ids.length;16 unmodified linesif (noise) x = Float32Array.from(noise.subarray(0, L * T)); // editing one word leaves the noise of earlier frames unchangedelse { const g = rng(seed); x = new Float32Array(L * T); for (let t = 0; t < T; t++) for (let l = 0; l < L; l++) x[l * T + t] = g(); }const condT = new ort.Tensor('float32', cond, [1, C, T]), wT = new ort.Tensor('float32', new Float32Array([w]), [1]);for (let k = 0; k < steps; k++) {const v = (await s.cfm.run({ x: new ort.Tensor('float32', x, [1, L, T]), cond: condT, t: new ort.Tensor('float32', new Float32Array([k / steps]), [1]), spk: spkT, w: wT })).v.data;for (let i = 0; i < x.length; i++) x[i] += v[i] / steps;if (onStep) onStep(k + 1, steps);}1234567120 unmodified lines1281291301311321331341351361371381391401411421431441451461471486 unmodified lines15515615715815916016116216316416 unmodified lines181182183184185186187188189190191192// Trà Đá TTS inference in JavaScript, backend-agnostic: pass an `ort` module (onnxruntime-web in the browser,// onnxruntime-node in tests). Mirrors trada_tts/text.py + trada_tts/infer.py.import { textNormalize } from './vi_normalize.js?v=11220100';import { fixNumbers } from './vi_fix.js?v=11220100';const TONE_MARK = { '̀': 2, '́': 3, '̉': 4, '̃': 5, '̣': 6 };const WORD_RE = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]/gu; // == Python re r"\w+|[^\w\s]" on NFC text120 unmodified lines}export class TradaTTS {constructor(ort, sessions, config, istft = null, root = null, opts = {}) {this.ort = ort; this.s = sessions; this.cfg = config; this.sr = config.sample_rate; this.root = root; this.opts = opts;this.istft = istft || (async (m, p, T) => istftCPU(m, p, T));this.hasFast = !!config.fast;}// load one more ONNX graph on demand (e.g. the 16-step flow when the user leaves fast mode)async ensure(name) {if (!this.s[name]) this.s[name] = await this.ort.InferenceSession.create(new Uint8Array(await (await fetch(`${this.root}/onnx/${name}.onnx`)).arrayBuffer()), this.opts);return this.s[name];}// root = repo root URL (holds config.json and onnx/). flow: 'cfm2' (2-step, default when available) or 'cfm' (16-step)static async load(ort, root, opts = {}, istft = null, onProgress = null, flow = 'auto') {const cfg = await (await fetch(`${root}/config.json`)).json();if (flow === 'auto') flow = cfg.fast ? 'cfm2' : 'cfm';const names = ['enc', flow, 'dec'], bufs = {}, got = {}, size = {};const report = () => { if (!onProgress) return; // total = real sizes once every file has answeredconst a = names.reduce((s, n) => s + (got[n] || 0), 0), known = names.every(n => size[n]);onProgress(a, known ? names.reduce((s, n) => s + size[n], 0) : Math.max(a + 1, 39.3e6), { ...got }, { ...size }); };6 unmodified lines}));const s = {};for (const n of names) s[n] = await ort.InferenceSession.create(bufs[n], opts);return new TradaTTS(ort, s, cfg, istft, root, opts);}// one chunk of NORMALISED text -> Float32Array @24 kHzasync synthChunk(norm, spk, { w = 3.0, steps = 16, speed = 1.0, seed = 0, noise = null, breaks = null, minSyllableMs = 160, fast = false, onStep = null, onTiming = null } = {}) {const { ort, s, cfg } = this, C = cfg.enc_dim, L = cfg.latent_dim;const enc0 = encodeText(norm, cfg.symbols); breaks = { ...enc0.joins, ...(breaks || {}) }; // "_" joins from the textconst E = applyBreaks(enc0, breaks, cfg.symbols), { ids, tones, words, w2c, bound } = E; const N = ids.length;16 unmodified linesif (noise) x = Float32Array.from(noise.subarray(0, L * T)); // editing one word leaves the noise of earlier frames unchangedelse { const g = rng(seed); x = new Float32Array(L * T); for (let t = 0; t < T; t++) for (let l = 0; l < L; l++) x[l * T + t] = g(); }const condT = new ort.Tensor('float32', cond, [1, C, T]), wT = new ort.Tensor('float32', new Float32Array([w]), [1]);if (fast) steps = cfg.fast.steps; // 2-step IntMeanFlow flow: average velocity over [t, r], CFG baked inconst flow = await this.ensure(fast ? 'cfm2' : 'cfm');for (let k = 0; k < steps; k++) {const t = new ort.Tensor('float32', new Float32Array([k / steps]), [1]), xT = new ort.Tensor('float32', x, [1, L, T]);const v = (await flow.run(fast ? { x: xT, cond: condT, t, r: new ort.Tensor('float32', new Float32Array([(k + 1) / steps]), [1]), spk: spkT }: { x: xT, cond: condT, t, spk: spkT, w: wT })).v.data;for (let i = 0; i < x.length; i++) x[i] += v[i] / steps;if (onStep) onStep(k + 1, steps);}
NOTICE+4-2
README.md+12-7
config.json+7-1
onnx/cfm.onnx+1-1
onnx/cfm2.onnxAdded+3
onnx/enc.onnx+1-1
samples/tra-da-nam-tram_ke-chuyen.wav+2-2
samples/tra-da-nam_ban-tin.wav+2-2
samples/tra-da-nam_tong-dai.wav+2-2
samples/tra-da-nu-am_tong-dai.wav+2-2
samples/tra-da-nu_chao-hoi.wav+2-2
samples/tra-da-nu_ke-chuyen.wav+2-2
scripts/export_onnx.py+16
trada-tts-10m-2step.safetensorsAdded+3
trada-tts-10m.safetensors+1-1
trada_tts/__main__.py+2-1
trada_tts/infer.py+29-6
trada_tts/model.py+7-3
voices/ban-hang-nu.wav+2-2
voices/ban-tin-nu.wav+2-2
voices/game-nam.wav+2-2
voices/ke-chuyen-nam.wav+2-2
voices/review-phim-nam.wav+2-2
voices/tra-da-nam-tram.wav+2-2
voices/tra-da-nam.wav+2-2
voices/tra-da-nu-am.wav+2-2
voices/tra-da-nu.wav+2-2
web/app.js+14-8
web/index.html+14-3
web/tts.js+21-10