Release TTS-V8: Chinese call-center TTS model with online WAV demos and serving code
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+26
- LICENSE-QWEN.txtAdded+202
- LICENSE.mdAdded+5
- NOTICEAdded+2
- README.mdAdded+110
- SHA256SUMSAdded+61
- config.jsonAdded+166
- data/voices.jsonAdded+38
- data/voices/bank_collection_female.wavAdded+3
- data/voices/bank_collection_male.wavAdded+3
- data/voices/sales_female.wavAdded+3
- data/voices/sales_male.wavAdded+3
- data/voices/service_female.wavAdded+3
- data/voices/service_male.wavAdded+3
- demos/bank_collection_female__offline.wavAdded+3
- demos/bank_collection_female__stream_icl_sentence.wavAdded+3
- demos/bank_collection_female__stream_xvec_token.wavAdded+3
- demos/bank_collection_male__offline.wavAdded+3
- demos/bank_collection_male__stream_icl_sentence.wavAdded+3
- demos/bank_collection_male__stream_xvec_token.wavAdded+3
- demos/demos.jsonAdded+139
- demos/sales_female__offline.wavAdded+3
- demos/sales_female__stream_icl_sentence.wavAdded+3
- demos/sales_female__stream_xvec_token.wavAdded+3
- demos/sales_male__offline.wavAdded+3
- demos/sales_male__stream_icl_sentence.wavAdded+3
- demos/sales_male__stream_xvec_token.wavAdded+3
- demos/service_female__offline.wavAdded+3
- demos/service_female__offline__speed0.8.wavAdded+3
- demos/service_female__offline__speed1.2.wavAdded+3
- demos/service_female__stream_icl_sentence.wavAdded+3
- demos/service_female__stream_xvec_token.wavAdded+3
- demos/service_male__offline.wavAdded+3
- demos/service_male__stream_icl_sentence.wavAdded+3
- demos/service_male__stream_xvec_token.wavAdded+3
- generation_config.jsonAdded+12
- inference.pyAdded+190
- merges.txtAdded
- model.safetensorsAdded+3
- preprocessor_config.jsonAdded+6
- requirements.txtAdded+13
- residual_graph.pyAdded+88
- speech_tokenizer/config.jsonAdded+94
- speech_tokenizer/configuration.jsonAdded+1
- speech_tokenizer/model.safetensorsAdded+3
- speech_tokenizer/preprocessor_config.jsonAdded+10
- speed.pyAdded+111
- stream_client.pyAdded+105
- stream_engine.pyAdded+572
- stream_server.pyAdded+177
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424344454647484950515253545556575859606132 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdata/voices/bank_collection_female.wav filter=lfs diff=lfs merge=lfs -textdata/voices/bank_collection_male.wav filter=lfs diff=lfs merge=lfs -textdata/voices/sales_female.wav filter=lfs diff=lfs merge=lfs -textdata/voices/sales_male.wav filter=lfs diff=lfs merge=lfs -textdata/voices/service_female.wav filter=lfs diff=lfs merge=lfs -textdata/voices/service_male.wav filter=lfs diff=lfs merge=lfs -textdemos/bank_collection_female__offline.wav filter=lfs diff=lfs merge=lfs -textdemos/bank_collection_female__stream_icl_sentence.wav filter=lfs diff=lfs merge=lfs -textdemos/bank_collection_female__stream_xvec_token.wav filter=lfs diff=lfs merge=lfs -textdemos/bank_collection_male__offline.wav filter=lfs diff=lfs merge=lfs -textdemos/bank_collection_male__stream_icl_sentence.wav filter=lfs diff=lfs merge=lfs -textdemos/bank_collection_male__stream_xvec_token.wav filter=lfs diff=lfs merge=lfs -textdemos/sales_female__offline.wav filter=lfs diff=lfs merge=lfs -textdemos/sales_female__stream_icl_sentence.wav filter=lfs diff=lfs merge=lfs -textdemos/sales_female__stream_xvec_token.wav filter=lfs diff=lfs merge=lfs -textdemos/sales_male__offline.wav filter=lfs diff=lfs merge=lfs -textdemos/sales_male__stream_icl_sentence.wav filter=lfs diff=lfs merge=lfs -textdemos/sales_male__stream_xvec_token.wav filter=lfs diff=lfs merge=lfs -textdemos/service_female__offline.wav filter=lfs diff=lfs merge=lfs -textdemos/service_female__offline__speed0.8.wav filter=lfs diff=lfs merge=lfs -textdemos/service_female__offline__speed1.2.wav filter=lfs diff=lfs merge=lfs -textdemos/service_female__stream_icl_sentence.wav filter=lfs diff=lfs merge=lfs -textdemos/service_female__stream_xvec_token.wav filter=lfs diff=lfs merge=lfs -textdemos/service_male__offline.wav filter=lfs diff=lfs merge=lfs -textdemos/service_male__stream_icl_sentence.wav filter=lfs diff=lfs merge=lfs -textdemos/service_male__stream_xvec_token.wav filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345# 许可说明
1. **底座与推理代码**:本模型基于 `Qwen/Qwen3-TTS-12Hz-1.7B-Base`(Apache-2.0 许可,详见 `LICENSE-QWEN.txt`)。2. **参考录音**:`data/voices/` 中的六段内置参考音频仅随本仓库提供用于语音克隆与试听。声音克隆用于业务场景时,请确保符合相关合规与授权要求。3. **示例音频**:`demos/` 中的音频由 TTS-V8 生成,供效果试听与评估。12TTS-V8 is a custom Chinese call-center TTS release built on Qwen3-TTS (Apache-2.0).It is not an official Qwen model release.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110---license: otherlicense_name: mixed-componentslicense_link: LICENSE.mdlanguage: - zhpipeline_tag: text-to-speechtags: - text-to-speech - tts - voice-cloning - streaming - call-center - vllm-omni---
# TTS-V8:呼叫中心中文语音合成模型
TTS-V8 是面向客服、销售、催收等电话外呼与智能语音交互场景的中文 TTS 模型,主打**自然真人通话听感**、**高音色还原度**与**低延迟实时流式输出**。
- **开箱即用:** 完整权重文件,直接加载推理。- **内置 6 种业务音色(3 男 3 女):** 覆盖客服、销售、催收场景,同时支持任意自定义参考音频声音克隆。- **实时流式 & 高并发:** 内置双向流式(支持 LLM 逐字增量输入、首包低至 ~90 ms),并原生支持 **vLLM-Omni** 高并发服务部署。- **语速调节与数字读法优化:** 内置保持音高的语速调节(0.5–2.0 倍),自动处理订单号、卡号、金额、日期等业务话术读法。
---
## 在线试听(点击直接播放或下载 WAV)
以下全部示例使用同一段约 230 字的业务长话术(含订单号、金额、日期与英文),流式示例模拟 LLM 每秒 30 字逐字输入:
> 您好,很抱歉让您久等了。我已经为您查询到,您的订单编号是20261113004567,商品金额为128.50元,优惠券抵扣20元,实际支付108.50元。退款申请已于11月13日提交,预计3个工作日内退回原支付账户。请您打开APP,在订单详情页面查看处理进度。如果您是VIP会员,也可以联系在线客服。如果超过7天仍未到账,请再次联系我们,我们会尽快为您核实。感谢您的耐心等待,祝您生活愉快。
### 六种内置音色试听
| 音色 | 离线整段合成 | 流式·按句(推荐默认,首包约 0.45 s) | 流式·极速首包(首包约 90 ms) ||---|---|---|---|| **客服女** `service_female` | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__offline.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__offline.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__stream_icl_sentence.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__stream_icl_sentence.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__stream_xvec_token.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__stream_xvec_token.wav) || **客服男** `service_male` | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_male__offline.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_male__offline.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_male__stream_icl_sentence.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_male__stream_icl_sentence.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_male__stream_xvec_token.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_male__stream_xvec_token.wav) || **销售女** `sales_female` | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_female__offline.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_female__offline.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_female__stream_icl_sentence.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_female__stream_icl_sentence.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_female__stream_xvec_token.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_female__stream_xvec_token.wav) || **销售男** `sales_male` | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_male__offline.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_male__offline.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_male__stream_icl_sentence.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_male__stream_icl_sentence.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_male__stream_xvec_token.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/sales_male__stream_xvec_token.wav) || **催收男** `bank_collection_male` | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_male__offline.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_male__offline.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_male__stream_icl_sentence.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_male__stream_icl_sentence.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_male__stream_xvec_token.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_male__stream_xvec_token.wav) || **催收女** `bank_collection_female` | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_female__offline.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_female__offline.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_female__stream_icl_sentence.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_female__stream_icl_sentence.wav) | <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_female__stream_xvec_token.wav"></audio><br>[下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/bank_collection_female__stream_xvec_token.wav) |
### 语速调节试听(`service_female`)
- **0.8 倍速(放慢):** <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__offline__speed0.8.wav"></audio> [下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__offline__speed0.8.wav)- **1.2 倍速(加快):** <audio controls preload="none" src="https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__offline__speed1.2.wav"></audio> [下载 WAV](https://huggingface.co/autotrust/TTS-V8/resolve/main/demos/service_female__offline__speed1.2.wav)
---
## 快速测试与接入
### 1. 下载与安装
```bashpip install "huggingface-hub==0.36.2"python -c "from huggingface_hub import snapshot_download; snapshot_download('autotrust/TTS-V8', local_dir='TTS-V8')"cd TTS-V8pip install -r requirements.txt # 需要 CUDA 版 PyTorchpython verify_files.py # 校验文件完整性```
### 2. 命令行快速合成
```bash# 离线合成python synthesize.py --voice service_female \ --text "您好,您本期账单金额是235.60元,请您核对。" --output out.wav
# 流式·按句(推荐用于对接 LLM)python synthesize.py --voice service_female --stream icl --cps 30 \ --text "您好,很抱歉让您久等了。您的退款预计3个工作日内到账。" --output icl.wav
# 流式·极速首包python synthesize.py --voice service_female --stream xvec --cps 30 \ --text "您好,很抱歉让您久等了。您的退款预计3个工作日内到账。" --output xvec.wav
# 调节语速(如 --speed 1.2)或自定义音色(--ref-audio ref.wav --ref-text "参考音频转写")```
### 3. Python 调用
```pythonfrom inference import TTSV8import soundfile as sf
tts = TTSV8(".")wav, sr = tts.synthesize("您好,请您核对一下账单金额。", voice="service_female")sf.write("out.wav", wav, sr)```
### 4. 服务部署
- **单路/双向流式 WebSocket 服务:** ```bash V4_CUDA_GRAPH=1 python stream_server.py --model-dir . --port 8765 ```- **高并发生产部署(vLLM-Omni,OpenAI 兼容接口):** ```bash bash vllm_omni/serve.sh . 8091 python vllm_omni/register_voices.py python vllm_omni/client.py --voice service_female --text "您好,请您核对账单。" --output out.wav ```
---
## 许可
详见 [`LICENSE.md`](LICENSE.md)、[`LICENSE-QWEN.txt`](LICENSE-QWEN.txt) 与 [`NOTICE`](NOTICE)。12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE-QWEN.txt2270dcf3e494b8b5c51a4ab9b0c0ad9f8093e1566c923d877b714d65664290fc LICENSE.mde2acffabf8f82c0afdde88a9ffe7fe6b62e4ed70595ded6beab5626d2726dfcb NOTICE48d0520f0721208b4b14e4d6402c9ab7d8449c648fc54088c49056bc1770dfe4 README.md07764733c96aae337e25904be943f8824ceba2e59d55d1324ff814367ebcb7b4 config.jsona34a17fb29ba392ca62a155b233b11e81bde93523cdb67581b7393cb7765ff67 data/voices.json2e81093d219600f2dc37fda3e8563d6c11d4b2bb939e25ca9ef80805c100b788 data/voices/bank_collection_female.wavd2e4b14e4a11781c59ac7c23445c8eb84d80f590cd3621748a4ba6a1f4f4e8ad data/voices/bank_collection_male.wav2fe2d2b3058c8cd163d3c0171df604d75cf2a223243b9e2d468a860b99c9d9bc data/voices/sales_female.wav2ee8de99a58dd74de71955cf27a7b15d2240a0d078a76ac3c97e3e5f245fe329 data/voices/sales_male.wavda2a78cd6d92c9293257f6ccc94f1ead63a2a26e2c129635cd07934e57c8a1ff data/voices/service_female.wav0f2a8cae70fdd7f917665121f8508f90a3744040bba1ad13c9941d709821d6ed data/voices/service_male.wavc7519bd430abf6d8e164e8ae920c5399b03d2eab469ce3764a14dec813cdf8c4 demos/bank_collection_female__offline.wav4414a744a9baea0470cea6910e9b34b85c1f097fe91f14cfa435735662daaf10 demos/bank_collection_female__stream_icl_sentence.wav223ac06c6bffc4d4e84b24c45e98a6b0270166e2a2cf9801b144c3b9c7161b01 demos/bank_collection_female__stream_xvec_token.wavbfc00c785b85db96f6344ee6f1f4d5e8a5171d24c4594ad00607f1b255a4c356 demos/bank_collection_male__offline.wavd08e3ac72271abeb82217e621946f0d5a324bc3838e56e790f5e788f42da3914 demos/bank_collection_male__stream_icl_sentence.wav09c9e6e2b5c7550db6a4eeff480a6c78335a340b3edd2b098dee917db0456223 demos/bank_collection_male__stream_xvec_token.wav8389a775c72619b589847218667ab70e9211902b650a922834c9a1cda57a083e demos/demos.jsonb209c5c715acc8828be12edd5da0118fcabe1f743cde4b722ccef487cfff9c4a demos/sales_female__offline.wavbf2e378d7d565880b2167379acd42bbf1bb210a3002fa645877db88b25c59868 demos/sales_female__stream_icl_sentence.wav36545e19b5c1f41242e1dfeafbc9d01ebaaac61c8acf14f609d880dbd9e8795d demos/sales_female__stream_xvec_token.wava5c7a21abb4248cd10dbde04e8a760c0c1d9b69ecd6ddd152f7dd073054916e1 demos/sales_male__offline.wav4af9508f588552329ce66092f4f0e338b8c39f1ba95fc63596a443b63c7cd1bb demos/sales_male__stream_icl_sentence.wav11141ddb50d1f1c5a5d866b679d7962a7a8466fcfe89c43b28837fb01a8fffa5 demos/sales_male__stream_xvec_token.wav9c406c98cbadf23815ca9b0a9a20f97e21300afde6327b15755fa0c861278952 demos/service_female__offline.wav7ed0a1a9d1a8c42961d3fd61b1c70157e6655a736face8f1bfd6074f2f0f0e48 demos/service_female__offline__speed0.8.wav3051aa4f66db8cd1fad864186124fc4369a510fc5ab463f75d97c0ef47e1bde7 demos/service_female__offline__speed1.2.wav1cea39c9b1f40b4d4c84d021a13695cd1693e4fdd551c97f79db73cb326d15f0 demos/service_female__stream_icl_sentence.wavcb476f7c1b52581133e5c362ec048c14e7bff980e2ba94a95996e937120089e3 demos/service_female__stream_xvec_token.wav1c591e14c9e31cfee51bc8aff127cd15741edaa093e1e484382c2336bb8c52d1 demos/service_male__offline.wavd4614c2b1b6abda1e4d509305d69aea1d737dfb1c1d07e590c6f7a6d3247102c demos/service_male__stream_icl_sentence.wav5f8afc1f4ef101bdf8b3c0689eb4ef5c3a2e9e2e449118e5ef752252fa00df6a demos/service_male__stream_xvec_token.wavf1b90b4513f3b34c62851049e2492d7b4c5940daf1276f89c82b8ef04127f3aa generation_config.jsona0d069b0243e9bb61390cce2616a5c634adc4e4dcf8b3ce2c0f1e417517769c1 inference.py599bab54075088774b1733fde865d5bd747cbcc7a547c5bc12610e874e26f5e3 merges.txte56d47ca64dbce580baa5c51374d7ab0056d70cafe1aee333bd06042d2376f27 model.safetensorsefdde1022ea9d76928bf7a9cd53139138f5ba2e466e837f08f6105ab1af1c119 preprocessor_config.json92f4166759c21473af703f3b6542f058ec0428e22ab29314203d6cba0d02c002 requirements.txt3e9dcba518efe94db0595d4a47d0d979447c0006d5f1f5e9fa901979c446a4da residual_graph.pyee65bb901c876664ab8707c487157aa1a6ee57c65969b28fb5ec9dc211e68167 speech_tokenizer/config.json6bc26d64eb5024b4d1dab5a52371958b429256d6c9d59787f1f5294a54e0cebd speech_tokenizer/configuration.json836b7b357f5ea43e889936a3709af68dfe3751881acefe4ecf0dbd30ba571258 speech_tokenizer/model.safetensorsfcb3805e597e786d4067706e602f6688524640f8d3396790e2e09b5942fcbdfb speech_tokenizer/preprocessor_config.jsonbb94ae6c176bc8e16f0bb1b98b440063a43163902f679c881d3b4b912b2b801b speed.py06a5aa129166ae7c7053d3874fe9c2d5eb8090073a66096d002392bea22b97d5 stream_client.py35c6d57c2cd29a37f2e1d19ea7d423f77c0e6687edd9d14f8a1f049104f0d435 stream_engine.pyafe829250de54565b628c2b91c0d3678a391814620e70863c7c64476b854e029 stream_server.py7d89a9b723bae24aa96780ee535dedf56a47500a2708e9eb587218b971e08419 streaming_layout.pyf6c618134817329be4a87d56bf4ae2448cfb83c9e0125258b9db40e1fcb8ce0c synthesize.pyf2bb8fc3e090a3ecc9ad512a584f8ee6d58e998d26dcb1ecfe0c6b431e321273 synthesize_batch.pya44e7703da4625e958579c10061f1c8047ede7b31b616c7dceb5c52c0751bf9e text_normalization.pydc3c31c3bdaedd5016382bb3cbe07323026775ad51f5a4fb564505992ae4a670 tokenizer_config.json5bb1136491e42f4d881ca94ea26a5fa0e49e03ac3a0a0a45cb50c8a625c9ebf2 verify_files.py5ede4251137879506564d0b08941e594b7210d36b6f3249919caf7456db0186b vllm_omni/bench.py7c7b8da4777f27f3b38856043bfa01931339a5fc4176435536e18c57562df6af vllm_omni/client.py7ea40e4acd3749a07e7127a7232c531bd4e229b11a4ed477fc05c0b2ce2ee6f0 vllm_omni/register_voices.py28425be9115acd0f32e1010d34c53a039f518b5358bbbecfdad7048fcce8041a vllm_omni/requirements.txt26037c5bb6a9a522a6c4770beb6fb012357cf7c9a44eed259eac9ec4fe3c184d vllm_omni/serve.sh41ab8bb03587c29ee479fe93bab9968781962820db4080c20ca73957e3f4f52d vllm_omni/v8_fused.yamlca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910 vocab.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166{ "architectures": [ "Qwen3TTSForConditionalGeneration" ], "assistant_token_id": 77091, "im_end_token_id": 151645, "im_start_token_id": 151644, "tts_bos_token_id": 151672, "tts_eos_token_id": 151673, "tts_pad_token_id": 151671, "model_type": "qwen3_tts", "tokenizer_type": "qwen3_tts_tokenizer_12hz", "tts_model_size": "1b7", "tts_model_type": "base", "speaker_encoder_config": { "enc_dim": 2048, "sample_rate": 24000 }, "talker_config": { "attention_bias": false, "attention_dropout": 0, "code_predictor_config": { "_name_or_path": "", "add_cross_attention": false, "architectures": null, "attention_bias": false, "attention_dropout": 0, "bad_words_ids": null, "begin_suppress_tokens": null, "bos_token_id": null, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": null, "exponential_decay_length_penalty": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "head_dim": 128, "hidden_act": "silu", "hidden_size": 1024, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "initializer_range": 0.02, "intermediate_size": 3072, "is_decoder": false, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "length_penalty": 1.0, "max_length": 20, "max_position_embeddings": 65536, "max_window_layers": 28, "min_length": 0, "model_type": "qwen3_tts_talker_code_predictor", "no_repeat_ngram_size": 0, "num_attention_heads": 16, "num_beam_groups": 1, "num_beams": 1, "num_code_groups": 16, "num_hidden_layers": 5, "num_key_value_heads": 8, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": null, "prefix": null, "problem_type": null, "pruned_heads": {}, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sep_token_id": null, "sliding_window": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": false, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "dtype": null, "torchscript": false, "typical_p": 1.0, "use_bfloat16": false, "use_cache": true, "use_sliding_window": false, "vocab_size": 2048 }, "codec_bos_id": 2149, "codec_eos_token_id": 2150, "codec_think_id": 2154, "codec_language_id": { "chinese": 2055, "english": 2050, "german": 2053, "italian": 2070, "portuguese": 2071, "spanish": 2054, "japanese": 2058, "korean": 2064, "french": 2061, "russian": 2069 }, "codec_nothink_id": 2155, "codec_pad_id": 2148, "codec_think_bos_id": 2156, "codec_think_eos_id": 2157, "spk_id": {}, "spk_is_dialect": {}, "head_dim": 128, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 6144, "max_position_embeddings": 32768, "model_type": "qwen3_tts_talker", "num_attention_heads": 16, "num_code_groups": 16, "num_hidden_layers": 28, "num_key_value_heads": 8, "position_id_per_seconds": 13, "rms_norm_eps": 1e-06, "rope_scaling": { "interleaved": true, "mrope_section": [ 24, 20, 20 ], "rope_type": "default", "type": "default" }, "rope_theta": 1000000, "sliding_window": null, "text_hidden_size": 2048, "text_vocab_size": 151936, "use_cache": true, "use_sliding_window": false, "vocab_size": 3072 }, "transformers_version": "4.57.3", "_name_or_path": "autotrust/TTS-V8"}1234567891011121314151617181920212223242526272829303132333435363738{ "sales_female": { "audio": "data/voices/sales_female.wav", "text": "他他装修什么呢?应该不是自己自自己买的这个商品房的这种装修吧?", "duration_s": 6.68, "sha256": "2fe2d2b3058c8cd163d3c0171df604d75cf2a223243b9e2d468a860b99c9d9bc" }, "sales_male": { "audio": "data/voices/sales_male.wav", "text": "啊,我这边去确认一下,就是法院有没有扣除那个银行的那个保全费用。", "duration_s": 6.04, "sha256": "2ee8de99a58dd74de71955cf27a7b15d2240a0d078a76ac3c97e3e5f245fe329" }, "service_female": { "audio": "data/voices/service_female.wav", "text": "是因为这笔欠款的逾期时间比较长了,申请方要追回这笔金额,那案件本月初在阳泉市城区人民法院的公众号上面进行公示调解了。", "duration_s": 10.12, "sha256": "da2a78cd6d92c9293257f6ccc94f1ead63a2a26e2c129635cd07934e57c8a1ff" }, "service_male": { "audio": "data/voices/service_male.wav", "text": "我这不是司法所啊,我这边是,呃,山西省阳泉市城区人民法院特邀调解中心的特邀调解员。", "duration_s": 6.2, "sha256": "0f2a8cae70fdd7f917665121f8508f90a3744040bba1ad13c9941d709821d6ed" }, "bank_collection_male": { "audio": "data/voices/bank_collection_male.wav", "text": "可以那个本金还款啊,你等全面冻结以后,他就不可以本金还款了。你这个本金跟总金额差太多了,本金才九千多,总金额两万多。", "duration_s": 8.785, "sha256": "d2e4b14e4a11781c59ac7c23445c8eb84d80f590cd3621748a4ba6a1f4f4e8ad" }, "bank_collection_female": { "audio": "data/voices/bank_collection_female.wav", "text": "我跟你说的是兴业银行的信用卡,先生,你是浦发银行还有信用卡是吧?", "duration_s": 4.85, "sha256": "2e81093d219600f2dc37fda3e8563d6c11d4b2bb939e25ca9ef80805c100b788" }}123version https://git-lfs.github.com/spec/v1oid sha256:2e81093d219600f2dc37fda3e8563d6c11d4b2bb939e25ca9ef80805c100b788size 232844123version https://git-lfs.github.com/spec/v1oid sha256:d2e4b14e4a11781c59ac7c23445c8eb84d80f590cd3621748a4ba6a1f4f4e8adsize 421724123version https://git-lfs.github.com/spec/v1oid sha256:2fe2d2b3058c8cd163d3c0171df604d75cf2a223243b9e2d468a860b99c9d9bcsize 320684123version https://git-lfs.github.com/spec/v1oid sha256:2ee8de99a58dd74de71955cf27a7b15d2240a0d078a76ac3c97e3e5f245fe329size 289964123version https://git-lfs.github.com/spec/v1oid sha256:da2a78cd6d92c9293257f6ccc94f1ead63a2a26e2c129635cd07934e57c8a1ffsize 485804123version https://git-lfs.github.com/spec/v1oid sha256:0f2a8cae70fdd7f917665121f8508f90a3744040bba1ad13c9941d709821d6edsize 297644123version https://git-lfs.github.com/spec/v1oid sha256:c7519bd430abf6d8e164e8ae920c5399b03d2eab469ce3764a14dec813cdf8c4size 1443884123version https://git-lfs.github.com/spec/v1oid sha256:4414a744a9baea0470cea6910e9b34b85c1f097fe91f14cfa435735662daaf10size 1562924123version https://git-lfs.github.com/spec/v1oid sha256:223ac06c6bffc4d4e84b24c45e98a6b0270166e2a2cf9801b144c3b9c7161b01size 1459244123version https://git-lfs.github.com/spec/v1oid sha256:bfc00c785b85db96f6344ee6f1f4d5e8a5171d24c4594ad00607f1b255a4c356size 1493804123version https://git-lfs.github.com/spec/v1oid sha256:d08e3ac72271abeb82217e621946f0d5a324bc3838e56e790f5e788f42da3914size 1528364123version https://git-lfs.github.com/spec/v1oid sha256:09c9e6e2b5c7550db6a4eeff480a6c78335a340b3edd2b098dee917db0456223size 1428524123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139{ "text": "您好,很抱歉让您久等了。我已经为您查询到,您的订单编号是20261113004567,商品金额为128.50元,优惠券抵扣20元,实际支付108.50元。退款申请已于11月13日提交,预计3个工作日内退回原支付账户。请您打开APP,在订单详情页面查看处理进度。如果您是VIP会员,也可以联系在线客服。如果超过7天仍未到账,请再次联系我们,我们会尽快为您核实。感谢您的耐心等待,祝您生活愉快。", "items": [ { "voice": "sales_female", "mode": "offline", "file": "sales_female__offline.wav", "duration_s": 29.76 }, { "voice": "sales_female", "mode": "stream_icl_sentence", "file": "sales_female__stream_icl_sentence.wav", "duration_s": 38.4, "first_audio_ms_from_first_text": 489 }, { "voice": "sales_female", "mode": "stream_xvec_token", "file": "sales_female__stream_xvec_token.wav", "duration_s": 28.08, "first_audio_ms_from_first_text": 92 }, { "voice": "sales_male", "mode": "offline", "file": "sales_male__offline.wav", "duration_s": 29.76 }, { "voice": "sales_male", "mode": "stream_icl_sentence", "file": "sales_male__stream_icl_sentence.wav", "duration_s": 33.12, "first_audio_ms_from_first_text": 450 }, { "voice": "sales_male", "mode": "stream_xvec_token", "file": "sales_male__stream_xvec_token.wav", "duration_s": 28.88, "first_audio_ms_from_first_text": 89 }, { "voice": "service_female", "mode": "offline", "file": "service_female__offline.wav", "duration_s": 32.8 }, { "voice": "service_female", "mode": "stream_icl_sentence", "file": "service_female__stream_icl_sentence.wav", "duration_s": 35.76, "first_audio_ms_from_first_text": 453 }, { "voice": "service_female", "mode": "stream_xvec_token", "file": "service_female__stream_xvec_token.wav", "duration_s": 35.04, "first_audio_ms_from_first_text": 88 }, { "voice": "service_male", "mode": "offline", "file": "service_male__offline.wav", "duration_s": 30.0 }, { "voice": "service_male", "mode": "stream_icl_sentence", "file": "service_male__stream_icl_sentence.wav", "duration_s": 30.24, "first_audio_ms_from_first_text": 449 }, { "voice": "service_male", "mode": "stream_xvec_token", "file": "service_male__stream_xvec_token.wav", "duration_s": 30.8, "first_audio_ms_from_first_text": 88 }, { "voice": "bank_collection_male", "mode": "offline", "file": "bank_collection_male__offline.wav", "duration_s": 31.12 }, { "voice": "bank_collection_male", "mode": "stream_icl_sentence", "file": "bank_collection_male__stream_icl_sentence.wav", "duration_s": 31.84, "first_audio_ms_from_first_text": 448 }, { "voice": "bank_collection_male", "mode": "stream_xvec_token", "file": "bank_collection_male__stream_xvec_token.wav", "duration_s": 29.76, "first_audio_ms_from_first_text": 86 }, { "voice": "bank_collection_female", "mode": "offline", "file": "bank_collection_female__offline.wav", "duration_s": 30.08 }, { "voice": "bank_collection_female", "mode": "stream_icl_sentence", "file": "bank_collection_female__stream_icl_sentence.wav", "duration_s": 32.56, "first_audio_ms_from_first_text": 447 }, { "voice": "bank_collection_female", "mode": "stream_xvec_token", "file": "bank_collection_female__stream_xvec_token.wav", "duration_s": 30.4, "first_audio_ms_from_first_text": 84 }, { "voice": "service_female", "mode": "offline", "speed": 0.8, "file": "service_female__offline__speed0.8.wav", "duration_s": 41.0 }, { "voice": "service_female", "mode": "offline", "speed": 1.2, "file": "service_female__offline__speed1.2.wav", "duration_s": 27.33 } ]}123version https://git-lfs.github.com/spec/v1oid sha256:b209c5c715acc8828be12edd5da0118fcabe1f743cde4b722ccef487cfff9c4asize 1428524123version https://git-lfs.github.com/spec/v1oid sha256:bf2e378d7d565880b2167379acd42bbf1bb210a3002fa645877db88b25c59868size 1843244123version https://git-lfs.github.com/spec/v1oid sha256:36545e19b5c1f41242e1dfeafbc9d01ebaaac61c8acf14f609d880dbd9e8795dsize 1347884123version https://git-lfs.github.com/spec/v1oid sha256:a5c7a21abb4248cd10dbde04e8a760c0c1d9b69ecd6ddd152f7dd073054916e1size 1428524123version https://git-lfs.github.com/spec/v1oid sha256:4af9508f588552329ce66092f4f0e338b8c39f1ba95fc63596a443b63c7cd1bbsize 1589804123version https://git-lfs.github.com/spec/v1oid sha256:11141ddb50d1f1c5a5d866b679d7962a7a8466fcfe89c43b28837fb01a8fffa5size 1386284123version https://git-lfs.github.com/spec/v1oid sha256:9c406c98cbadf23815ca9b0a9a20f97e21300afde6327b15755fa0c861278952size 1574444123version https://git-lfs.github.com/spec/v1oid sha256:7ed0a1a9d1a8c42961d3fd61b1c70157e6655a736face8f1bfd6074f2f0f0e48size 1968044123version https://git-lfs.github.com/spec/v1oid sha256:3051aa4f66db8cd1fad864186124fc4369a510fc5ab463f75d97c0ef47e1bde7size 1312044123version https://git-lfs.github.com/spec/v1oid sha256:1cea39c9b1f40b4d4c84d021a13695cd1693e4fdd551c97f79db73cb326d15f0size 1716524123version https://git-lfs.github.com/spec/v1oid sha256:cb476f7c1b52581133e5c362ec048c14e7bff980e2ba94a95996e937120089e3size 1681964123version https://git-lfs.github.com/spec/v1oid sha256:1c591e14c9e31cfee51bc8aff127cd15741edaa093e1e484382c2336bb8c52d1size 1440044123version https://git-lfs.github.com/spec/v1oid sha256:d4614c2b1b6abda1e4d509305d69aea1d737dfb1c1d07e590c6f7a6d3247102csize 1451564123version https://git-lfs.github.com/spec/v1oid sha256:5f8afc1f4ef101bdf8b3c0689eb4ef5c3a2e9e2e449118e5ef752252fa00df6asize 1478444123456789101112{ "do_sample": true, "repetition_penalty": 1.05, "temperature": 0.9, "top_p": 1.0, "top_k": 50, "subtalker_dosample": true, "subtalker_temperature": 0.9, "subtalker_top_p": 1.0, "subtalker_top_k": 50, "max_new_tokens": 8192}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""Local-only inference for the complete, merged TTS-V4 checkpoint.
tts = TTSV4() # this directory audio, sr = tts.synthesize('您好……', voice='service_female') # offline session = tts.stream(voice='service_female', mode='icl') # bidirectional streaming session.push_text('您好,'); session.push_text('您的账单……'); session.end() for pcm in session.audio(): ... # float32 chunks at 24 kHz"""import jsonimport osfrom pathlib import Path
# Inference never downloads a second model. Download the complete snapshot once.os.environ['HF_HUB_OFFLINE'] = '1'os.environ['TRANSFORMERS_OFFLINE'] = '1'
import numpy as npimport torch
torch.backends.cuda.enable_cudnn_sdp(False) # sporadic cuDNN SDPA failures on shared GPUs
from text_normalization import normalize_text
ROOT = Path(__file__).resolve().parentREQUIRED = ( 'config.json', 'generation_config.json', 'model.safetensors', 'preprocessor_config.json', 'tokenizer_config.json', 'vocab.json', 'merges.txt', 'speech_tokenizer/config.json', 'speech_tokenizer/model.safetensors', 'speech_tokenizer/preprocessor_config.json', 'data/voices.json',)# Sampling used for all published V4 evaluations (see MODEL_CARD.md).DEFAULT_TEMPERATURE = 0.8
class TTSV4: """One complete local model: six reference voices or a custom real reference (audio + transcript)."""
def __init__(self, model_dir=ROOT, device='cuda:0', threads=2): self.root = Path(model_dir).expanduser().resolve() missing = [name for name in REQUIRED if not (self.root / name).is_file()] if missing: raise FileNotFoundError('完整模型目录缺少文件:' + ', '.join(missing)) if device.startswith('cuda') and not torch.cuda.is_available(): raise RuntimeError('CUDA不可用;请安装匹配的PyTorch/CUDA运行环境') torch.set_num_threads(threads) from stream_engine import StreamingTTS self.engine = StreamingTTS(self.root, device=device) self.model = self.engine.tts self.voices = self.engine.voice_info self.prompts = {}
def _prompt(self, voice, ref_audio, ref_text): if voice is not None: if ref_audio is not None or ref_text is not None: raise ValueError('固定voice和自定义参考不能同时指定') if voice not in self.voices: raise ValueError(f'未知voice:{voice};可用:{list(self.voices)}') if voice not in self.prompts: self.prompts[voice] = self.model.create_voice_clone_prompt( ref_audio=str(self.root / 'data/voices' / f'{voice}.wav'), ref_text=self.voices[voice]['text'], x_vector_only_mode=False) return self.prompts[voice] if ref_audio is None or not isinstance(ref_text, str) or not ref_text.strip(): raise ValueError('请指定voice,或同时提供ref_audio和ref_text') path = Path(ref_audio).expanduser().resolve() if not path.is_file(): raise FileNotFoundError(path) return self.model.create_voice_clone_prompt(ref_audio=str(path), ref_text=ref_text, x_vector_only_mode=False)
def synthesize(self, text, voice=None, ref_audio=None, ref_text=None, seed=5000, temperature=DEFAULT_TEMPERATURE, speed=1.0, max_new_tokens=2048): """Offline (whole text known): native non-streaming ICL generation.
speed: pitch-preserving speaking-rate change applied to the output (0.5-2.0, recommended 0.8-1.3). """ if not isinstance(text, str) or not text.strip(): raise ValueError('text不能为空') prompt = self._prompt(voice, ref_audio, ref_text) torch.manual_seed(seed) with self.engine.lock: waves, sample_rate = self.model.generate_voice_clone( text=normalize_text(text), language='Chinese', voice_clone_prompt=prompt, non_streaming_mode=True, max_new_tokens=max_new_tokens, temperature=temperature, subtalker_temperature=temperature) audio = np.asarray(waves[0], dtype=np.float32).reshape(-1) if len(audio) == 0 or not np.isfinite(audio).all(): raise RuntimeError('模型返回空音频或非有限采样值') if speed != 1.0: from speed import change_speed audio = change_speed(audio, sample_rate, speed) return audio, sample_rate
def stream(self, voice=None, ref_audio=None, ref_text=None, mode='icl', segment=None, seed=None, temperature=DEFAULT_TEMPERATURE, speed=1.0, **kw): """Bidirectional streaming session (push_text/end/cancel + audio() generator).
mode='xvec': speaker embedding only; starts after the first text token (lowest latency). mode='icl' : reference audio + transcript (richer acoustic reference; naturalness requires listening). segment='token' : text is fed to the model as it arrives; icl then starts once icl_start_tokens() tokens exist, or when end() is called. segment='sentence': each complete sentence is generated with its full text known; icl starts ~0.2-0.4 s after the first sentence is complete. segment=None : 'sentence' for icl, 'token' for xvec (same default as stream_server.py). speed : pitch-preserving speaking-rate change of the output (0.5-2.0; 1.0 = unchanged). """ if segment is None: segment = 'sentence' if mode == 'icl' else 'token' sampling = dict(temperature=temperature, subtalker_temperature=temperature) return self.engine.session(voice, ref_audio=ref_audio, ref_text=ref_text, mode=mode, segment=segment, speed=speed, seed=seed, sampling=sampling, **kw)
def synthesize_batch(self, texts, voice=None, ref_audio=None, ref_text=None, seed=5000, temperature=DEFAULT_TEMPERATURE, speed=1.0, batch_size=8, max_new_tokens=2048): """Offline GPU batching via native generate_voice_clone(text=list).
Returns (list[float32 ndarray], sample_rate), in input order. voice can be one fixed voice or a list matching texts. Custom ref_audio/ref_text may likewise be scalar or lists. This returns completed audio, not per-request streaming chunks. Batch grouping affects sampled outputs. """ if not isinstance(texts, (list, tuple)) or not texts: raise ValueError('texts必须是非空文本列表') if any(not isinstance(text, str) or not text.strip() for text in texts): raise ValueError('texts中的每项必须是非空字符串') if not isinstance(batch_size, int) or isinstance(batch_size, bool) or batch_size < 1: raise ValueError('batch_size必须是正整数') if not 0.5 <= speed <= 2.0: raise ValueError('speed必须在0.5–2.0之间')
def expand(value, name): if isinstance(value, (list, tuple)): if len(value) != len(texts): raise ValueError(f'{name}列表长度必须与texts一致') return list(value) return [value] * len(texts)
voices = expand(voice, 'voice') audios = expand(ref_audio, 'ref_audio') transcripts = expand(ref_text, 'ref_text') prompts = [self._prompt(v, a, r)[0] for v, a, r in zip(voices, audios, transcripts)] normalized = [normalize_text(text) for text in texts] result = [] sample_rate = self.engine.sample_rate for offset in range(0, len(texts), batch_size): group = normalized[offset:offset + batch_size] with self.engine.lock: if seed is not None: torch.manual_seed(seed + offset) waves, sample_rate = self.model.generate_voice_clone( text=group, language=['Chinese'] * len(group), voice_clone_prompt=prompts[offset:offset + batch_size], non_streaming_mode=True, max_new_tokens=max_new_tokens, temperature=temperature, subtalker_temperature=temperature) if len(waves) != len(group): raise RuntimeError('模型返回音频条数与输入不一致') for wave in waves: pcm = np.asarray(wave, dtype=np.float32).reshape(-1) if not len(pcm) or not np.isfinite(pcm).all(): raise RuntimeError('模型返回空音频或非有限采样值') if speed != 1.0: from speed import change_speed pcm = change_speed(pcm, sample_rate, speed) result.append(pcm) return result, sample_rate
def icl_start_tokens(self, voice=None, ref_audio=None, ref_text=None): """Text tokens an icl stream must receive before its first audio frame (unless end() comes first).""" from streaming_layout import required_target_tokens v = self.engine.voice(voice, ref_audio, ref_text) return required_target_tokens('icl', v.ref_ids, v.ref_codes)
def stream_sentences(self, text_pieces, voice=None, ref_audio=None, ref_text=None, mode='icl', seed=None, temperature=DEFAULT_TEMPERATURE, speed=1.0, max_chars=60): """Convenience: consume an iterable of text pieces (e.g. LLM deltas) in a background thread and yield audio chunks, using segment='sentence'.""" import threading s = self.stream(voice=voice, ref_audio=ref_audio, ref_text=ref_text, mode=mode, seed=seed, temperature=temperature, segment='sentence', speed=speed, max_chars=max_chars)
def reader(): try: for piece in text_pieces: s.push_text(piece or '') finally: s.end() threading.Thread(target=reader, daemon=True).start() yield from s.audio()
TTSV8 = TTSV4123version https://git-lfs.github.com/spec/v1oid sha256:e56d47ca64dbce580baa5c51374d7ab0056d70cafe1aee333bd06042d2376f27size 3857413776123456{ "padding_side": "left", "padding_value": 0.0, "processor_class": "Qwen3TTSProcessor", "return_attention_mask": true}12345678910111213qwen-tts==0.1.1transformers==4.57.3accelerate==1.12.0safetensors>=0.4soundfile>=0.12librosa>=0.10,<0.12numpy>=1.26,<3wetext==0.2.1# streaming server / clientfastapi>=0.110uvicorn>=0.29websockets>=12soxr>=0.312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Capture V4's native 15-codebook predictor loop; keep its sampling settings.
Uses the StaticCache + CUDA Graph strategy documented byhttps://github.com/andimarafioti/faster-qwen3-tts (MIT).This implementation targets V4/qwen-tts 0.1.1 / Transformers 4.57.3."""import torchfrom transformers.cache_utils import StaticCache
class PredictorCache(StaticCache): """Fixed storage, but expose the exact active length in each unrolled step.
Unlike a padded static attention mask, these views preserve the baseline SDPA shapes and mask-free kernels; the predictor always has 2..16 tokens. """ active_length = 2
def update(self, key_states, value_states, layer_idx, cache_kwargs=None): key, value = super().update(key_states, value_states, layer_idx, cache_kwargs) return key[:, :, :self.active_length], value[:, :, :self.active_length]
class ResidualGraph: def __init__(self, engine, sampling): self.engine = engine self.p = engine.predictor self.sampling = dict(sampling) parameter = next(self.p.parameters()) self.device, self.dtype = parameter.device, parameter.dtype self.cache = PredictorCache(config=self.p.config, max_cache_len=16) self.positions = [torch.arange(2, device=self.device)] + [ torch.tensor([j + 1], device=self.device) for j in range(1, 15)] self.token = torch.zeros((), dtype=torch.long, device=self.device) self.hidden = torch.zeros(1, 1, engine.talker.config.hidden_size, dtype=self.dtype, device=self.device) self.output = torch.zeros(16, dtype=torch.long, device=self.device) self.graph = torch.cuda.CUDAGraph() self._capture()
def _sample(self, logits): scores = logits.float()[0] if not self.sampling['subtalker_do_sample']: return scores.argmax().view(1) scores = scores / self.sampling['subtalker_temperature'] k = self.sampling['subtalker_top_k'] if k: cutoff = torch.topk(scores, k).values[-1] scores = scores.masked_fill(scores < cutoff, -float('inf')) return torch.multinomial(scores.softmax(-1), 1)
def _loop(self): last = self.engine.talker.get_input_embeddings()(self.token.view(1, 1)) x = self.p.small_to_mtp_projection(torch.cat([self.hidden, last], dim=1)) self.output[0].copy_(self.token) for j in range(15): pos = self.positions[j] self.cache.active_length = j + 2 out = self.p.model(inputs_embeds=x, past_key_values=self.cache, use_cache=True, cache_position=pos, position_ids=pos[None], attention_mask={'full_attention': None}) code = self._sample(self.p.lm_head[j](out.last_hidden_state[:, -1])) self.output[j + 1].copy_(code[0]) if j < 14: x = self.p.small_to_mtp_projection(self.p.model.get_input_embeddings()[j](code.view(1, 1))) return self.output
@torch.inference_mode() def _capture(self): # Capture is initialization, not part of the request RNG trajectory. with torch.cuda.device(self.device), torch.random.fork_rng(devices=[self.device.index]): stream = torch.cuda.Stream(device=self.device) stream.wait_stream(torch.cuda.current_stream(self.device)) with torch.cuda.stream(stream): for _ in range(3): self._loop() torch.cuda.current_stream(self.device).wait_stream(stream) torch.cuda.synchronize(self.device) with torch.cuda.graph(self.graph, stream=stream): self._loop() torch.cuda.current_stream(self.device).wait_stream(stream) torch.cuda.synchronize(self.device)
@torch.inference_mode() def run(self, token, past_hidden): self.token.copy_(token.reshape(())) self.hidden.copy_(past_hidden) # Causal masks exclude unwritten positions; all used K/V are overwritten. self.graph.replay() return self.output.clone()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394{ "architectures": [ "Qwen3TTSTokenizerV2Model" ], "model_type": "qwen3_tts_tokenizer_12hz", "encoder_valid_num_quantizers": 16, "input_sample_rate": 24000, "output_sample_rate": 24000, "decode_upsample_rate": 1920, "encode_downsample_rate": 1920, "decoder_config": { "attention_bias": false, "attention_dropout": 0.0, "latent_dim": 1024, "codebook_dim": 512, "codebook_size": 2048, "decoder_dim": 1536, "hidden_act": "silu", "hidden_size": 512, "intermediate_size": 1024, "layer_scale_initial_scale": 0.01, "max_position_embeddings": 8000, "head_dim": 64, "num_attention_heads": 16, "num_hidden_layers": 8, "num_key_value_heads": 16, "num_quantizers": 16, "num_semantic_quantizers": 1, "rms_norm_eps": 1e-05, "rope_theta": 10000, "semantic_codebook_size": 4096, "sliding_window": 72, "upsample_rates": [ 8, 5, 4, 3 ], "upsampling_ratios": [ 2, 2 ], "vector_quantization_hidden_dimension": 512 }, "encoder_config": { "_frame_rate": 12.5, "attention_bias": false, "attention_dropout": 0.0, "audio_channels": 1, "codebook_dim": 256, "codebook_size": 2048, "compress": 2, "dilation_growth_rate": 2, "dtype": "float32", "head_dim": 64, "hidden_act": "gelu", "hidden_size": 512, "initializer_range": 0.02, "intermediate_size": 2048, "kernel_size": 7, "last_kernel_size": 3, "layer_scale_initial_scale": 0.01, "max_position_embeddings": 8000, "norm_eps": 1e-05, "normalize": false, "num_attention_heads": 8, "num_filters": 64, "num_hidden_layers": 8, "num_key_value_heads": 8, "num_quantizers": 32, "num_residual_layers": 1, "num_semantic_quantizers": 1, "pad_mode": "constant", "residual_kernel_size": 3, "rope_theta": 10000.0, "sampling_rate": 24000, "sliding_window": 250, "transformers_version": "4.57.0.dev0", "trim_right_ratio": 1.0, "upsample_groups": 512, "upsampling_ratios": [ 8, 6, 5, 4 ], "use_cache": false, "use_causal_conv": true, "use_conv_shortcut": false, "use_streaming": false, "vector_quantization_hidden_dimension": 256 }, "transformers_version": "4.57.3"}1{"framework": "pytorch", "task": "feature-extraction", "allow_remote": true}123version https://git-lfs.github.com/spec/v1oid sha256:836b7b357f5ea43e889936a3709af68dfe3751881acefe4ecf0dbd30ba571258size 68229309212345678910{ "chunk_length_s": null, "feature_extractor_type": "EncodecFeatureExtractor", "feature_size": 1, "overlap": null, "padding_side": "right", "padding_value": 0.0, "return_attention_mask": true, "sampling_rate": 24000}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Pitch-preserving speaking-rate change (WSOLA), usable on whole clips or on a stream.
Qwen3-TTS Base (and therefore TTS-V4) has no speaking-rate input; the generated ratefollows the reference recording. `speed` is applied to the generated audio:speed > 1 is faster, < 1 slower; pitch and timbre are kept.
ts = TimeStretch(1.2, 24000) for chunk in chunks: out = ts.process(chunk) # streaming tail = ts.flush()"""import numpy as np
MIN_SPEED, MAX_SPEED = 0.5, 2.0
class TimeStretch: def __init__(self, speed, sample_rate, frame_ms=30.0, tolerance_ms=10.0): if not MIN_SPEED <= speed <= MAX_SPEED: raise ValueError(f'speed must be within [{MIN_SPEED}, {MAX_SPEED}]') self.speed = float(speed) self.n = int(sample_rate * frame_ms / 1000) // 2 * 2 self.hs = self.n // 2 # synthesis hop self.delta = int(sample_rate * tolerance_ms / 1000) # search tolerance self.window = np.hanning(self.n + 1)[:-1].astype(np.float32) # periodic Hann: sums to 1 at 50 % overlap self.inp = np.zeros(self.delta, np.float32) # leading zeros so frame 0 can search left self.offset = -self.delta # absolute index of inp[0] self.out = np.zeros(self.n, np.float32) # overlap-add accumulator starting at out_pos self.out_pos = 0 self.k = 0 # next frame index self.prev = None # absolute start of previous chosen frame self.total_in = 0 self.emitted = 0
def _frame(self, k): nominal = int(round(k * self.hs * self.speed)) if self.prev is None: return nominal lo, hi = nominal - self.delta, nominal + self.delta lo = max(lo, self.offset) target = self._get(self.prev + self.hs, self.n) region = self._get(lo, hi - lo + self.n) corr = np.correlate(region, target, mode='valid') return lo + int(np.argmax(corr))
def _get(self, start, length): a = start - self.offset seg = self.inp[max(a, 0):a + length] if a < 0: seg = np.concatenate([np.zeros(-a, np.float32), seg]) if len(seg) < length: seg = np.concatenate([seg, np.zeros(length - len(seg), np.float32)]) return seg
def _run(self, final): res = [] end = self.offset + len(self.inp) while True: nominal = int(round(self.k * self.hs * self.speed)) need = nominal + self.delta + self.n if self.prev is not None: need = max(need, self.prev + self.hs + self.n) if not final and need > end: break if final and nominal > self.total_in: break p = self._frame(self.k) pos = self.k * self.hs self.out[pos - self.out_pos:pos - self.out_pos + self.n] += self.window * self._get(p, self.n) self.prev = p self.k += 1 done = self.hs # [out_pos, out_pos + hs) is final now res.append(self.out[:done].copy()) self.out = np.concatenate([self.out[done:], np.zeros(done, np.float32)]) self.out_pos += done keep_from = min(int(round(self.k * self.hs * self.speed)) - self.delta, self.prev + self.hs) - self.offset if keep_from > 0: self.inp = self.inp[keep_from:] self.offset += keep_from return np.concatenate(res) if res else np.zeros(0, np.float32)
def _limit(self, y, final): expected = int(round(self.total_in / self.speed)) if final: y = np.concatenate([y, self.out]) y = y[:max(0, expected - self.emitted)] if final else y self.emitted += len(y) return y
def process(self, chunk): x = np.asarray(chunk, np.float32).reshape(-1) if self.speed == 1.0: self.total_in += len(x) self.emitted += len(x) return x self.inp = np.concatenate([self.inp, x]) self.total_in += len(x) return self._limit(self._run(False), False)
def flush(self): if self.speed == 1.0: return np.zeros(0, np.float32) self.inp = np.concatenate([self.inp, np.zeros(self.n + 2 * self.delta, np.float32)]) return self._limit(self._run(True), True)
def change_speed(audio, sample_rate, speed): """Whole-clip helper.""" if speed == 1.0: return np.asarray(audio, np.float32) ts = TimeStretch(speed, sample_rate) return np.concatenate([ts.process(audio), ts.flush()])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#!/usr/bin/env python3"""Streaming client / latency benchmark for stream_server.py.
Simulates an LLM emitting text at --cps characters per second (0 = all at once)and measures first-audio latency from the first text message, real-time factor,and playback stalls (buffer underruns) assuming playback starts at first audio.
python stream_client.py --voice bank_collection_female --text-file demos/text.txt --cps 15 --output out.wav python stream_client.py --concurrency 4 --cps 15 ..."""import argparseimport asyncioimport jsonimport statisticsimport timefrom pathlib import Path
import numpy as npimport soundfile as sfimport websockets
DEFAULT_TEXT = '您好,很抱歉让您久等了。我已经为您查询到,您的订单编号是20261113004567,商品金额为128.50元,实际支付108.50元。请您打开APP查看处理进度。'
async def one(url, voice, text, cps, sample_rate, seed, output=None, chunk_chars=1, mode='icl', segment=None, speed=1.0): async with websockets.connect(url, max_size=None) as ws: await ws.send(json.dumps(dict(type='start', voice=voice, sample_rate=sample_rate, seed=seed, mode=mode, speed=speed, **({'segment': segment} if segment else {})))) started = json.loads(await ws.recv()) if started.get('type') != 'started': raise RuntimeError(started) t0 = time.perf_counter() arrivals, chunks, done = [], [], None
async def feed(): for i in range(0, len(text), chunk_chars): await ws.send(json.dumps(dict(type='text', text=text[i:i + chunk_chars]))) if cps: await asyncio.sleep(chunk_chars / cps) await ws.send(json.dumps(dict(type='end'))) feeder = asyncio.create_task(feed()) async for message in ws: if isinstance(message, bytes): arrivals.append((time.perf_counter() - t0, len(message) // 2 / sample_rate)) chunks.append(np.frombuffer(message, '<i2')) else: msg = json.loads(message) if msg['type'] == 'done': done = msg['stats'] break if msg['type'] == 'error': raise RuntimeError(msg['message']) await feeder audio = np.concatenate(chunks) if chunks else np.zeros(0, np.int16) if output: sf.write(output, audio, sample_rate, subtype='PCM_16') first = arrivals[0][0] if arrivals else None received, stall = 0.0, 0.0 for t, dur in arrivals: playback = (t - first) - stall if received < playback: stall += playback - received received += dur total = arrivals[-1][0] if arrivals else None return dict(first_audio_ms=None if first is None else round(first * 1000, 1), total_s=total, audio_s=len(audio) / sample_rate, stall_s=round(stall, 3), server=done)
async def main_async(args): text = Path(args.text_file).read_text().strip() if args.text_file else args.text jobs = [one(args.url, args.voice, text, args.cps, args.sample_rate, args.seed + i, (args.output if args.concurrency == 1 else f'{Path(args.output).stem}_{i}.wav') if args.output else None, mode=args.mode, segment=args.segment, speed=args.speed) for i in range(args.concurrency)] results = await asyncio.gather(*jobs) for r in results: print(json.dumps(r, ensure_ascii=False)) firsts = [r['first_audio_ms'] for r in results] summary = dict(mode=args.mode, segment=args.segment or 'server default', concurrency=args.concurrency, cps=args.cps, first_audio_ms_median=statistics.median(firsts), first_audio_ms_max=max(firsts), stall_s_max=max(r['stall_s'] for r in results), server_rtf_median=statistics.median(r['server']['rtf'] for r in results)) print('SUMMARY', json.dumps(summary, ensure_ascii=False)) return summary
def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--url', default='ws://127.0.0.1:8765/v1/tts/stream') ap.add_argument('--voice', default='bank_collection_female') ap.add_argument('--text', default=DEFAULT_TEXT) ap.add_argument('--text-file') ap.add_argument('--cps', type=float, default=15, help='simulated LLM characters/second; 0 = whole text at once') ap.add_argument('--sample-rate', type=int, default=24000) ap.add_argument('--concurrency', type=int, default=1) ap.add_argument('--seed', type=int, default=0) ap.add_argument('--output') ap.add_argument('--mode', choices=['icl', 'xvec'], default='icl') ap.add_argument('--speed', type=float, default=1.0, help='speaking-rate factor (pitch preserved), 0.5-2.0') ap.add_argument('--segment', choices=['sentence', 'token'], help='server default: sentence for icl, token for xvec') args = ap.parse_args() asyncio.run(main_async(args))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572"""Bidirectional streaming inference for TTS-V4 (Qwen3-TTS-12Hz architecture).
Text can be pushed incrementally while audio is produced frame by frame(12.5 frames/s, 80 ms each) and decoded incrementally with the causal audiodecoder. Layouts (streaming_layout.py) are Qwen3-TTS native dual-trackstreaming; V4 is trained on them: mode='icl' - reference audio codes + reference transcript (best cloning and naturalness; starts once about ref_frames - ref_tokens target tokens exist, or when the text ends) mode='xvec' - speaker embedding only (starts after the first text token)
engine = StreamingTTS('/path/to/TTS-V4') # complete local model session = engine.session('bank_collection_female', mode='icl') session.push_text('您好,您的订单金额是'); session.push_text('235.60元。'); session.end() for pcm in session.audio(): # float32 chunks, 24 kHz ..."""import jsonimport queueimport reimport threadingimport timefrom dataclasses import dataclass, fieldfrom pathlib import Path
import librosaimport numpy as npimport torchtorch.backends.cuda.enable_cudnn_sdp(False) # avoid sporadic cuDNN SDPA failures under GPU sharingfrom transformers.cache_utils import DynamicCache
from streaming_layout import PAD, EOS, frame_embeds, prefix_positions, required_target_tokens, stream_prefix, text_embedsfrom text_normalization import normalize_text
EOS_CODE = 2150BOUNDARY = set(',。!?;:、,!?;:\n')ASCII_ALNUM = re.compile(r'[0-9A-Za-z]')
class IncrementalNormalizer: """Commit text only where spoken-form normalization cannot change later.
Commits at punctuation. Long digit-free runs are committed except the last six characters (so keywords like 订单编号 stay attached to their digits). """
def __init__(self): self.buffer = ''
def push(self, text): self.buffer += text cut = max((i + 1 for i, c in enumerate(self.buffer) if c in BOUNDARY), default=0) if cut == 0 and len(self.buffer) >= 12 and not ASCII_ALNUM.search(self.buffer): cut = len(self.buffer) - 6 if cut == 0: return [] segment, self.buffer = self.buffer[:cut], self.buffer[cut:] return [normalize_text(segment)] if segment.strip() else []
def flush(self): segment, self.buffer = self.buffer, '' return [normalize_text(segment)] if segment.strip() else []
@dataclassclass Voice: ref_codes: torch.Tensor speaker: torch.Tensor ref_ids: list
@dataclassclass Stats: t_first_text: float = None t_prefill: float = None t_first_audio: float = None t_done: float = None frames: int = 0 audio_s: float = 0.0 waits_for_text: int = 0 eos: bool = False cancelled: bool = False extra: dict = field(default_factory=dict)
class StreamingTTS: def __init__(self, model_dir, adapter=None, device='cuda:0', voices_json=None): import os os.environ.setdefault('HF_HUB_OFFLINE', '1') from qwen_tts import Qwen3TTSModel self.root = Path(model_dir) self.tts = Qwen3TTSModel.from_pretrained(str(self.root), device_map=device, dtype=torch.bfloat16, attn_implementation='sdpa', local_files_only=True) if adapter: from qwen_v4 import load_adapter load_adapter(self.tts.model, adapter) self.tts.model.eval() self.model = self.tts.model self.talker = self.model.talker self.decoder = self.model.speech_tokenizer.model.decoder self.upsample = int(self.decoder.total_upsample) self.sample_rate = int(self.model.speech_tokenizer.get_output_sample_rate()) self.role_ids = self.tts._tokenize_texts([self.tts._build_assistant_text('好')])[0][0, :3].cpu() self.lock = threading.Lock() with torch.inference_mode(): from streaming_layout import special_embeds _, self.eos_emb, self.pad_emb = special_embeds(self.tts) self.predictor = self.talker.code_predictor self.voices = {} vj = Path(voices_json) if voices_json else self.root / 'data/voices.json' self.voice_info = json.loads(vj.read_text()) if vj.exists() else {} self._residual_graphs = {} self.cuda_graphs_enabled = False if os.environ.get('V4_CUDA_GRAPH') == '1': self.enable_cuda_graphs()
def enable_cuda_graphs(self, sampling=None): """Capture the 15-codebook loop once; applies to this incremental engine.
Call before serving concurrent requests. Native SDK/offline generate is a separate path. Model weights and chunking are unchanged. """ if self.model.device.type != 'cuda': raise ValueError('V4_CUDA_GRAPH requires a CUDA device') settings = dict(DEFAULT_SAMPLING, **(sampling or {})) with self.lock: self._residual_graph(settings) self.cuda_graphs_enabled = True
def _residual_graph(self, sampling): key = (bool(sampling['subtalker_do_sample']), float(sampling['subtalker_temperature']), int(sampling['subtalker_top_k'])) if key not in self._residual_graphs: from residual_graph import ResidualGraph # Bound graph memory if a service permits arbitrary temperatures. if len(self._residual_graphs) >= 4: return None self._residual_graphs[key] = ResidualGraph(self, sampling) return self._residual_graphs[key]
# ------------------------------------------------------------ prompts def tokenize(self, text): return self.tts.processor.tokenizer(text, add_special_tokens=False)['input_ids']
@torch.inference_mode() def voice(self, name=None, ref_audio=None, ref_text=None): key = name or (str(ref_audio), ref_text) if key in self.voices: return self.voices[key] if name is not None: info = self.voice_info[name] local = self.root / 'data/voices' / f'{name}.wav' ref_audio = str(local) if local.exists() else info['audio'] ref_text = info['text'] with self.lock: item = self.tts.create_voice_clone_prompt(ref_audio=str(ref_audio), ref_text=ref_text, x_vector_only_mode=False)[0] ref_ids = self.tts._tokenize_texts([self.tts._build_ref_text(ref_text)])[0][0, 3:-2].tolist() v = Voice(item.ref_code.to(self.model.device), item.ref_spk_embedding, ref_ids) self.voices[key] = v return v
def session(self, voice=None, ref_audio=None, ref_text=None, segment='token', speed=1.0, **kw): """segment='token': text goes to the model as it arrives (Session). segment='sentence': each complete sentence is synthesized with its full text known (SentenceSession). speed: pitch-preserving rate change of the output (1.0 = as generated; >1 faster).""" v = self.voice(voice, ref_audio, ref_text) if segment == 'sentence': session = SentenceSession(self, v, **kw) elif segment == 'token': session = Session(self, v, **kw) else: raise ValueError("segment must be 'token' or 'sentence'") return session if speed == 1.0 else SpeedSession(session, speed, self.sample_rate)
# ------------------------------------------------------------ model steps def _forward(self, embeds, cache, start): pos = torch.arange(start, start + embeds.shape[0], device=embeds.device).view(1, 1, -1).expand(3, 1, -1) out = self.talker.model(inputs_embeds=embeds[None], position_ids=pos, past_key_values=cache, use_cache=True) hidden = out.last_hidden_state return self.talker.codec_head(hidden[:, -1]).float(), hidden[:, -1:]
def _residuals(self, token, past_hidden, sampling): """Residual codebooks 1..15 (same computation as code_predictor.generate, no HF overhead).""" if self.cuda_graphs_enabled: graph = self._residual_graph(sampling) if graph is not None: return graph.run(token, past_hidden) p = self.predictor last = self.talker.get_input_embeddings()(token.view(1, 1)) x = p.small_to_mtp_projection(torch.cat([past_hidden, last], dim=1)) cache = DynamicCache() codes = [token.view(1)] pos = 0 for j in range(15): n = x.shape[1] out = p.model(inputs_embeds=x, past_key_values=cache, use_cache=True, position_ids=torch.arange(pos, pos + n, device=x.device).view(1, -1)) pos += n logits = p.lm_head[j](out.last_hidden_state[:, -1]).float()[0] if sampling['subtalker_do_sample']: logits = logits / sampling['subtalker_temperature'] k = sampling['subtalker_top_k'] if k: kth = torch.topk(logits, k).values[-1] logits = logits.masked_fill(logits < kth, -float('inf')) code = torch.multinomial(logits.softmax(-1), 1) else: code = logits.argmax().view(1) codes.append(code) if j < 14: x = p.small_to_mtp_projection(p.model.get_input_embeddings()[j](code.view(1, 1))) return torch.cat(codes)
def _text_embed(self, element): if element == PAD: return self.pad_emb[None] if element == EOS: return self.eos_emb[None] ids = torch.tensor([[element]], device=self.pad_emb.device) return self.talker.text_projection(self.talker.get_text_embeddings()(ids))[0]
def _decode(self, codes, new): """codes [T,16] (context + new frames) -> float32 samples for the last `new` frames.""" wav = self.decoder(codes.T[None].clamp(min=0)) return wav[0, 0, -new * self.upsample:].float().cpu().numpy()
def _sample(logits, history, step, s): scores = logits[0].clone() if s['repetition_penalty'] != 1.0 and history: idx = torch.tensor(sorted(set(history)), device=scores.device) val = scores[idx] scores[idx] = torch.where(val > 0, val / s['repetition_penalty'], val * s['repetition_penalty']) vocab = scores.shape[0] keep = scores[EOS_CODE].clone() scores[vocab - 1024:] = -float('inf') scores[EOS_CODE] = keep if step >= 2 else -float('inf') if not s['do_sample']: return int(scores.argmax()) scores = scores / s['temperature'] if s['top_k']: kth = torch.topk(scores, s['top_k']).values[-1] scores[scores < kth] = -float('inf') return int(torch.multinomial(scores.softmax(-1), 1))
DEFAULT_SAMPLING = dict(do_sample=True, temperature=0.8, top_k=50, repetition_penalty=1.05, subtalker_do_sample=True, subtalker_temperature=0.8, subtalker_top_k=50, subtalker_top_p=1.0)
class Session: def __init__(self, engine, voice, mode='icl', first_chunk=2, chunk=6, context=25, max_frames=2000, seed=None, sampling=None): if mode not in ('icl', 'xvec'): raise ValueError('mode must be icl or xvec') self.e, self.v, self.mode = engine, voice, mode self.first_chunk, self.chunk, self.context = first_chunk, chunk, context self.max_frames = max_frames self.sampling = dict(DEFAULT_SAMPLING, **(sampling or {})) self.seed = seed self.gap, self.forced_gap = 0, None # forced_gap: layout tests of experimental PAD-gap layout only self.normalizer = IncrementalNormalizer() self.target_ids, self.ended, self.cancelled = [], False, False self.cv = threading.Condition() self.out = queue.Queue() self.stats = Stats() self.thread = None
# ------------------------------------------------------------ text side def push_text(self, text): segments = self.normalizer.push(text) self._append(segments)
def end(self): self._append(self.normalizer.flush(), end=True)
def _append(self, segments, end=False): ids = [t for s in segments for t in self.e.tokenize(s)] with self.cv: if self.stats.t_first_text is None and (ids or end): self.stats.t_first_text = time.perf_counter() self.target_ids.extend(ids) self.ended = self.ended or end self.cv.notify_all() if self.thread is None: self.thread = threading.Thread(target=self._run, daemon=True) self.thread.start()
def push_ids(self, ids, end=False): """Test hook: push already tokenized target ids.""" with self.cv: if self.stats.t_first_text is None: self.stats.t_first_text = time.perf_counter() self.target_ids.extend(ids) self.ended = self.ended or end self.cv.notify_all() if self.thread is None: self.thread = threading.Thread(target=self._run, daemon=True) self.thread.start()
def cancel(self): with self.cv: self.cancelled = True self.cv.notify_all()
# ------------------------------------------------------------ audio side def audio(self): while True: item = self.out.get() if item is None: return if isinstance(item, Exception): raise item yield item
def _wait_for(self, count): """Block until `count` target ids exist or text ended; False if cancelled.""" with self.cv: while not self.cancelled and not self.ended and len(self.target_ids) < count: self.stats.waits_for_text += 1 self.cv.wait() return not self.cancelled
def _track_element(self, position): offset = len(self.v.ref_ids) + self.gap if self.mode == 'icl' else 0 index = position - offset # index into target ids if index < 0: return self.v.ref_ids[position] if not self._wait_for(index + 1): return None with self.cv: if index < len(self.target_ids): return self.target_ids[index] return EOS if index == len(self.target_ids) else PAD
@torch.inference_mode() def _run(self): try: self._generate() except Exception as error: # surface to consumer self.out.put(error) finally: self.stats.t_done = time.perf_counter() self.out.put(None)
def _generate(self, forced_frames=None, collect_logits=None): e, v, s = self.e, self.v, self.sampling if self.seed is not None: torch.manual_seed(self.seed) n_ref = prefix_positions(self.mode, v.ref_codes) # icl: native layout needs about (reference frames - reference tokens) target tokens # (or the end of the text) before the first frame; xvec needs one token. need = required_target_tokens(self.mode, v.ref_ids, v.ref_codes) if not self._wait_for(need): self.stats.cancelled = True return with self.cv: ids, ended = list(self.target_ids), self.ended self.gap = self.forced_gap or 0 self.stats.extra['start_tokens'] = len(ids) cache = DynamicCache() with e.lock: prefix, _ = stream_prefix(e.tts, self.mode, v.speaker, e.role_ids, v.ref_ids, v.ref_codes, ids, ended, self.gap) logits, past_hidden = e._forward(prefix, cache, 0) self.stats.t_prefill = time.perf_counter() cur = prefix.shape[0] history, frames, emitted = [], [], 0 for k in range(self.max_frames): if self.cancelled: self.stats.cancelled = True return if collect_logits is not None: collect_logits.append(logits) with e.lock: if forced_frames is not None: if k >= len(forced_frames): return frame = forced_frames[k].to(logits.device) else: token = _sample(logits, history, k, s) if token == EOS_CODE: self.stats.eos = True break history.append(token) frame = e._residuals(torch.tensor(token, device=logits.device), past_hidden, s) frames.append(frame) ready = len(frames) - emitted if forced_frames is None and ready >= (self.first_chunk if emitted == 0 else self.chunk): self._emit(frames, emitted, ready) emitted = len(frames) element = self._track_element(n_ref + k) if element is None: self.stats.cancelled = True return with e.lock: emb = frame_embeds(e.tts, frame[None]) + e._text_embed(element) logits, past_hidden = e._forward(emb, cache, cur) cur += 1 if forced_frames is None and len(frames) > emitted: self._emit(frames, emitted, len(frames) - emitted) self.stats.frames = len(frames)
def _emit(self, frames, emitted, new): e = self.e gen = torch.stack(frames) ctx_ref = self.v.ref_codes allc = torch.cat([ctx_ref, gen], dim=0) start = max(0, allc.shape[0] - new - self.context) with e.lock: pcm = e._decode(allc[start:], new) if self.stats.t_first_audio is None: self.stats.t_first_audio = time.perf_counter() self.stats.audio_s += len(pcm) / e.sample_rate self.out.put(pcm)
# ------------------------------------------------------------ validation hook @torch.inference_mode() def teacher_force(self, target_ids, frames, gap=None): """Return per-step logits when the given frames are forced (for layout tests).""" self.target_ids, self.ended, self.forced_gap = list(target_ids), True, gap logits = [] self._generate(forced_frames=frames, collect_logits=logits) return torch.cat(logits)
SENTENCE_END = set('。!?;!?;\n')CLAUSE_END = set(',,、::')
class SentenceSession: """Same interface as Session (push_text / end / cancel / audio / stats), but text is cut into sentences and every sentence is generated with its whole text known.
With mode='icl' this removes icl's start condition (enough text tokens to cover the reference): audio starts about 0.1-0.25 s after the first sentence is complete. A worker thread generates the sentences one after another as soon as each is complete, independent of how fast audio() is consumed, so a consumer that plays in real time hears no gaps. A sentence longer than `max_chars` without an end mark is cut at its last comma. """
def __init__(self, engine, voice, max_chars=60, seed=None, **kw): self.e, self.v, self.kw, self.seed, self.max_chars = engine, voice, kw, seed, max_chars if kw.get('mode', 'icl') not in ('icl', 'xvec'): raise ValueError('mode must be icl or xvec') self.buffer, self.sentences, self.out = '', queue.Queue(), queue.Queue() self.cancelled, self.current, self.thread = False, None, None self.stats = Stats() self.lock = threading.Lock()
def _start(self): if self.thread is None: self.thread = threading.Thread(target=self._worker, daemon=True) self.thread.start()
def push_text(self, text): with self.lock: if self.stats.t_first_text is None and text: self.stats.t_first_text = time.perf_counter() self.buffer += text while True: cut = next((i + 1 for i, c in enumerate(self.buffer) if c in SENTENCE_END), 0) if not cut and len(self.buffer) > self.max_chars: cut = max((i + 1 for i, c in enumerate(self.buffer) if c in CLAUSE_END), default=len(self.buffer)) if not cut: break sentence, self.buffer = self.buffer[:cut], self.buffer[cut:] if sentence.strip(): self.sentences.put(sentence) self._start()
def end(self): with self.lock: if self.stats.t_first_text is None: self.stats.t_first_text = time.perf_counter() if self.buffer.strip(): self.sentences.put(self.buffer) self.buffer = '' self.sentences.put(None) self._start()
def cancel(self): self.cancelled = True current = self.current if current is not None: current.cancel() self.sentences.put(None)
def _worker(self): st, n, eos = self.stats, 0, True try: while not self.cancelled: sentence = self.sentences.get() if sentence is None or self.cancelled: break seed = None if self.seed is None else self.seed + n self.current = Session(self.e, self.v, seed=seed, **self.kw) self.current.push_text(sentence) self.current.end() for pcm in self.current.audio(): if st.t_first_audio is None: st.t_first_audio = time.perf_counter() st.t_prefill = self.current.stats.t_prefill st.audio_s += len(pcm) / self.e.sample_rate self.out.put(pcm) st.frames += self.current.stats.frames eos = eos and self.current.stats.eos n += 1 except Exception as error: self.out.put(error) finally: st.eos, st.cancelled = eos and not self.cancelled, self.cancelled st.extra['sentences'] = n st.t_done = time.perf_counter() self.out.put(None)
def audio(self): while True: item = self.out.get() if item is None: return if isinstance(item, Exception): raise item yield item
class SpeedSession: """Wraps a Session/SentenceSession and changes the speaking rate of its audio (WSOLA)."""
def __init__(self, inner, speed, sample_rate): from speed import TimeStretch self.inner, self.ts = inner, TimeStretch(speed, sample_rate) self.stats = inner.stats self.stats.extra['speed'] = speed
def push_text(self, text): self.inner.push_text(text)
def end(self): self.inner.end()
def cancel(self): self.inner.cancel()
def audio(self): for pcm in self.inner.audio(): out = self.ts.process(pcm) if len(out): yield out if not self.stats.cancelled: tail = self.ts.flush() if len(tail): yield tail
def synthesize_stream_to_array(engine, voice, text, chars_per_second=None, **kw): """Convenience: optionally simulate incremental text, return (audio, sr, stats).""" session = engine.session(voice, **kw)
def feed(): if chars_per_second: for ch in text: session.push_text(ch) time.sleep(1.0 / chars_per_second) else: session.push_text(text) session.end() feeder = threading.Thread(target=feed, daemon=True) feeder.start() chunks = list(session.audio()) feeder.join() audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32) return audio, engine.sample_rate, session.stats123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177#!/usr/bin/env python3"""WebSocket bidirectional-streaming TTS server for TTS-V4.
python stream_server.py --model-dir /path/to/TTS-V4 --port 8765
Protocol (ws://host:port/v1/tts/stream): client -> {"type":"start","voice":"bank_collection_female","sample_rate":8000|16000|24000, "mode":"icl"|"xvec","segment":"sentence"|"token","speed":1.0,"temperature":0.8,"seed":0} (or "ref_audio_b64" + "ref_text" instead of "voice" for a custom real reference) client -> {"type":"text","text":"..."} (any number, any granularity, e.g. LLM tokens) client -> {"type":"end"} (no more text) | {"type":"cancel"} (barge-in) server -> {"type":"started","sample_rate":..,"format":"pcm_s16le","channels":1} server -> binary audio chunks (PCM 16-bit little endian mono) server -> {"type":"done","stats":{...}} | {"type":"error","message":...}"""import argparseimport asyncioimport base64import jsonimport osimport tempfileimport threadingimport time
import numpy as npimport soxrimport uvicornfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect
from stream_engine import StreamingTTS
app = FastAPI()ENGINE = NoneARGS = None
@app.get('/health')def health(): return dict(status='ok' if ENGINE else 'loading', voices=sorted(ENGINE.voice_info) if ENGINE else [], sample_rate=ENGINE.sample_rate if ENGINE else None)
def pcm16(x): return (np.clip(x, -1, 1) * 32767).astype('<i2').tobytes()
@app.websocket('/v1/tts/stream')async def stream(ws: WebSocket): await ws.accept() loop = asyncio.get_running_loop() session, temp = None, None try: start = json.loads(await ws.receive_text()) if start.get('type') != 'start': raise ValueError('first message must be {"type":"start",...}') sr = int(start.get('sample_rate', ENGINE.sample_rate)) if sr not in (8000, 16000, 24000): raise ValueError('sample_rate must be 8000, 16000 or 24000') mode = start.get('mode', 'icl') if mode not in ('icl', 'xvec'): raise ValueError('mode must be icl or xvec') t = float(start.get('temperature', ARGS.temperature)) segment = start.get('segment', 'sentence' if mode == 'icl' else 'token') speed = float(start.get('speed', 1.0)) if not 0.5 <= speed <= 2.0: raise ValueError('speed must be within [0.5, 2.0]') kwargs = dict(seed=start.get('seed'), mode=mode, segment=segment, speed=speed, sampling=dict(temperature=t, subtalker_temperature=t)) if 'ref_audio_b64' in start: temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False) temp.write(base64.b64decode(start['ref_audio_b64'])) temp.close() session = ENGINE.session(ref_audio=temp.name, ref_text=start['ref_text'], **kwargs) else: voice = start.get('voice') if voice not in ENGINE.voice_info: raise ValueError(f'unknown voice {voice!r}; available {sorted(ENGINE.voice_info)}') session = ENGINE.session(voice, **kwargs) resampler = soxr.ResampleStream(ENGINE.sample_rate, sr, 1, dtype='float32') if sr != ENGINE.sample_rate else None await ws.send_text(json.dumps(dict(type='started', sample_rate=sr, format='pcm_s16le', channels=1))) audio_q = asyncio.Queue()
def pump(): try: for chunk in session.audio(): if resampler is not None: chunk = resampler.resample_chunk(chunk) if len(chunk): loop.call_soon_threadsafe(audio_q.put_nowait, pcm16(chunk)) if resampler is not None: tail = resampler.resample_chunk(np.zeros(0, np.float32), last=True) if len(tail): loop.call_soon_threadsafe(audio_q.put_nowait, pcm16(tail)) loop.call_soon_threadsafe(audio_q.put_nowait, None) except Exception as error: loop.call_soon_threadsafe(audio_q.put_nowait, error)
threading.Thread(target=pump, daemon=True).start()
async def sender(): while True: item = await audio_q.get() if item is None: return if isinstance(item, Exception): raise item await ws.send_bytes(item)
send_task = asyncio.create_task(sender())
async def receiver(): while True: msg = json.loads(await ws.receive_text()) kind = msg.get('type') if kind == 'text': await asyncio.to_thread(session.push_text, msg.get('text', '')) elif kind == 'end': await asyncio.to_thread(session.end) return elif kind == 'cancel': session.cancel() return recv_task = asyncio.create_task(receiver()) done, _ = await asyncio.wait({send_task, recv_task}, return_when=asyncio.FIRST_EXCEPTION) for task in done: if task.exception(): raise task.exception() await send_task st = session.stats t0 = st.t_first_text await ws.send_text(json.dumps(dict(type='done', stats=dict( mode=mode, segment=segment, speed=speed, start_tokens=st.extra.get('start_tokens'), sentences=st.extra.get('sentences'), first_audio_ms=None if st.t_first_audio is None or t0 is None else round(1000 * (st.t_first_audio - t0), 1), prefill_ms=None if st.t_prefill is None or t0 is None else round(1000 * (st.t_prefill - t0), 1), frames=st.frames, audio_s=round(st.audio_s, 3), eos=st.eos, cancelled=st.cancelled, waits_for_text=st.waits_for_text, rtf=None if not st.audio_s or st.t_done is None or st.t_prefill is None else round((st.t_done - st.t_prefill) / st.audio_s, 3))))) except WebSocketDisconnect: if session: session.cancel() except Exception as error: if session: session.cancel() try: await ws.send_text(json.dumps(dict(type='error', message=repr(error)))) except Exception: pass finally: if temp is not None: os.unlink(temp.name) try: await ws.close() except Exception: pass
def main(): global ENGINE, ARGS ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('--model-dir', default=os.path.dirname(os.path.abspath(__file__))) ap.add_argument('--adapter', help='development only: V4 adapter on a base checkpoint') ap.add_argument('--voices-json') ap.add_argument('--host', default='0.0.0.0') ap.add_argument('--port', type=int, default=8765) ap.add_argument('--device', default='cuda:0') ap.add_argument('--temperature', type=float, default=0.8) ARGS = ap.parse_args() ENGINE = StreamingTTS(ARGS.model_dir, adapter=ARGS.adapter, device=ARGS.device, voices_json=ARGS.voices_json) for name in ENGINE.voice_info: # warm reference prompts ENGINE.voice(name) s = ENGINE.session(next(iter(ENGINE.voice_info)), seed=0) s.push_text('您好。'); s.end(); list(s.audio()) uvicorn.run(app, host=ARGS.host, port=ARGS.port, log_level='warning')
if __name__ == '__main__': main().gitattributes+26
LICENSE-QWEN.txtAdded+202
LICENSE.mdAdded+5
NOTICEAdded+2
README.mdAdded+110
SHA256SUMSAdded+61
config.jsonAdded+166
data/voices.jsonAdded+38
data/voices/bank_collection_female.wavAdded+3
data/voices/bank_collection_male.wavAdded+3
data/voices/sales_female.wavAdded+3
data/voices/sales_male.wavAdded+3
data/voices/service_female.wavAdded+3
data/voices/service_male.wavAdded+3
demos/bank_collection_female__offline.wavAdded+3
demos/bank_collection_female__stream_icl_sentence.wavAdded+3
demos/bank_collection_female__stream_xvec_token.wavAdded+3
demos/bank_collection_male__offline.wavAdded+3
demos/bank_collection_male__stream_icl_sentence.wavAdded+3
demos/bank_collection_male__stream_xvec_token.wavAdded+3
demos/demos.jsonAdded+139
demos/sales_female__offline.wavAdded+3
demos/sales_female__stream_icl_sentence.wavAdded+3
demos/sales_female__stream_xvec_token.wavAdded+3
demos/sales_male__offline.wavAdded+3
demos/sales_male__stream_icl_sentence.wavAdded+3
demos/sales_male__stream_xvec_token.wavAdded+3
demos/service_female__offline.wavAdded+3
demos/service_female__offline__speed0.8.wavAdded+3
demos/service_female__offline__speed1.2.wavAdded+3
demos/service_female__stream_icl_sentence.wavAdded+3
demos/service_female__stream_xvec_token.wavAdded+3
demos/service_male__offline.wavAdded+3
demos/service_male__stream_icl_sentence.wavAdded+3
demos/service_male__stream_xvec_token.wavAdded+3
generation_config.jsonAdded+12
inference.pyAdded+190
merges.txtAdded
model.safetensorsAdded+3
preprocessor_config.jsonAdded+6
requirements.txtAdded+13
residual_graph.pyAdded+88
speech_tokenizer/config.jsonAdded+94
speech_tokenizer/configuration.jsonAdded+1
speech_tokenizer/model.safetensorsAdded+3
speech_tokenizer/preprocessor_config.jsonAdded+10
speed.pyAdded+111
stream_client.pyAdded+105
stream_engine.pyAdded+572
stream_server.pyAdded+177