fcyai commited on
Commit
d8fce5c
1 Parent(s): bb02bb0
ChatTTS/.gitattributes DELETED
@@ -1,2 +0,0 @@
1
- # ignore jupyter notebooks in the language bar on github
2
- **/*.ipynb linguist-vendored
 
 
 
ChatTTS/.github/workflows/checksum.yml DELETED
@@ -1,45 +0,0 @@
1
- name: Calculate and Sync SHA256
2
- on:
3
- push:
4
- branches:
5
- - main
6
- - dev
7
- jobs:
8
- checksum:
9
- runs-on: ubuntu-latest
10
- steps:
11
- - uses: actions/checkout@master
12
-
13
- - name: Setup Go Environment
14
- uses: actions/setup-go@master
15
-
16
- - name: Run RVC-Models-Downloader
17
- run: |
18
- wget https://github.com/fumiama/RVC-Models-Downloader/releases/download/v0.2.5/rvcmd_linux_amd64.deb
19
- sudo apt -y install ./rvcmd_linux_amd64.deb
20
- rm -f ./rvcmd_linux_amd64.deb
21
- rvcmd -notrs -w 1 -notui assets/chtts
22
-
23
- - name: Calculate all Checksums
24
- run: go run tools/checksum/*.go
25
-
26
- - name: Commit back
27
- if: ${{ !github.head_ref }}
28
- id: commitback
29
- continue-on-error: true
30
- run: |
31
- git config --local user.name 'github-actions[bot]'
32
- git config --local user.email 'github-actions[bot]@users.noreply.github.com'
33
- git add --all
34
- git commit -m "chore(env): sync checksum on ${{github.ref_name}}"
35
-
36
- - name: Create Pull Request
37
- if: steps.commitback.outcome == 'success'
38
- continue-on-error: true
39
- uses: peter-evans/create-pull-request@v5
40
- with:
41
- delete-branch: true
42
- body: "Automatically sync checksum in .env"
43
- title: "chore(env): sync checksum on ${{github.ref_name}}"
44
- commit-message: "chore(env): sync checksum on ${{github.ref_name}}"
45
- branch: checksum-${{github.ref_name}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/.gitignore DELETED
@@ -1,171 +0,0 @@
1
- # Byte-compiled / optimized / DLL files
2
- __pycache__/
3
- *.py[cod]
4
- *$py.class
5
- *.ckpt
6
- # C extensions
7
- *.so
8
- *.pt
9
-
10
- # Distribution / packaging
11
- .Python
12
- outputs/
13
- build/
14
- develop-eggs/
15
- dist/
16
- downloads/
17
- eggs/
18
- .eggs/
19
- lib/
20
- lib64/
21
- parts/
22
- sdist/
23
- var/
24
- wheels/
25
- share/python-wheels/
26
- *.egg-info/
27
- asset/*
28
- .installed.cfg
29
- *.egg
30
- MANIFEST
31
-
32
- # PyInstaller
33
- # Usually these files are written by a python script from a template
34
- # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
- *.manifest
36
- *.spec
37
-
38
- # Installer logs
39
- pip-log.txt
40
- pip-delete-this-directory.txt
41
-
42
- # Unit test / coverage reports
43
- htmlcov/
44
- .tox/
45
- .nox/
46
- .coverage
47
- .coverage.*
48
- .cache
49
- nosetests.xml
50
- coverage.xml
51
- *.cover
52
- *.py,cover
53
- .hypothesis/
54
- .pytest_cache/
55
- cover/
56
-
57
- # Translations
58
- *.mo
59
- *.pot
60
-
61
- # Django stuff:
62
- *.log
63
- local_settings.py
64
- db.sqlite3
65
- db.sqlite3-journal
66
-
67
- # Flask stuff:
68
- instance/
69
- .webassets-cache
70
-
71
- # Scrapy stuff:
72
- .scrapy
73
-
74
- # Sphinx documentation
75
- docs/_build/
76
-
77
- # PyBuilder
78
- .pybuilder/
79
- target/
80
-
81
- # Jupyter Notebook
82
- .ipynb_checkpoints
83
-
84
- # IPython
85
- profile_default/
86
- ipython_config.py
87
-
88
- # pyenv
89
- # For a library or package, you might want to ignore these files since the code is
90
- # intended to run in multiple environments; otherwise, check them in:
91
- # .python-version
92
-
93
- # pipenv
94
- # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
- # However, in case of collaboration, if having platform-specific dependencies or dependencies
96
- # having no cross-platform support, pipenv may install dependencies that don't work, or not
97
- # install all needed dependencies.
98
- #Pipfile.lock
99
-
100
- # poetry
101
- # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
102
- # This is especially recommended for binary packages to ensure reproducibility, and is more
103
- # commonly ignored for libraries.
104
- # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
105
- #poetry.lock
106
-
107
- # pdm
108
- # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
109
- #pdm.lock
110
- # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
111
- # in version control.
112
- # https://pdm.fming.dev/#use-with-ide
113
- .pdm.toml
114
-
115
- # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
- __pypackages__/
117
-
118
- # Celery stuff
119
- celerybeat-schedule
120
- celerybeat.pid
121
-
122
- # SageMath parsed files
123
- *.sage.py
124
-
125
- # Environments
126
- .env
127
- .venv
128
- env/
129
- venv/
130
- ENV/
131
- env.bak/
132
- venv.bak/
133
-
134
- # Spyder project settings
135
- .spyderproject
136
- .spyproject
137
-
138
- # Rope project settings
139
- .ropeproject
140
-
141
- # mkdocs documentation
142
- /site
143
-
144
- # mypy
145
- .mypy_cache/
146
- .dmypy.json
147
- dmypy.json
148
-
149
- # Pyre type checker
150
- .pyre/
151
-
152
- # pytype static type analyzer
153
- .pytype/
154
-
155
- # Cython debug symbols
156
- cython_debug/
157
-
158
- # PyCharm
159
- # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
- # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
- # and can be added to the global gitignore or merged into this file. For a more nuclear
162
- # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
- #.idea/
164
-
165
- # assets and configs of ChatTTS
166
-
167
- /asset
168
- /config
169
-
170
- # inferred result
171
- *.wav
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/LICENSE DELETED
@@ -1,407 +0,0 @@
1
- Attribution-NonCommercial 4.0 International
2
-
3
- =======================================================================
4
-
5
- Creative Commons Corporation ("Creative Commons") is not a law firm and
6
- does not provide legal services or legal advice. Distribution of
7
- Creative Commons public licenses does not create a lawyer-client or
8
- other relationship. Creative Commons makes its licenses and related
9
- information available on an "as-is" basis. Creative Commons gives no
10
- warranties regarding its licenses, any material licensed under their
11
- terms and conditions, or any related information. Creative Commons
12
- disclaims all liability for damages resulting from their use to the
13
- fullest extent possible.
14
-
15
- Using Creative Commons Public Licenses
16
-
17
- Creative Commons public licenses provide a standard set of terms and
18
- conditions that creators and other rights holders may use to share
19
- original works of authorship and other material subject to copyright
20
- and certain other rights specified in the public license below. The
21
- following considerations are for informational purposes only, are not
22
- exhaustive, and do not form part of our licenses.
23
-
24
- Considerations for licensors: Our public licenses are
25
- intended for use by those authorized to give the public
26
- permission to use material in ways otherwise restricted by
27
- copyright and certain other rights. Our licenses are
28
- irrevocable. Licensors should read and understand the terms
29
- and conditions of the license they choose before applying it.
30
- Licensors should also secure all rights necessary before
31
- applying our licenses so that the public can reuse the
32
- material as expected. Licensors should clearly mark any
33
- material not subject to the license. This includes other CC-
34
- licensed material, or material used under an exception or
35
- limitation to copyright. More considerations for licensors:
36
- wiki.creativecommons.org/Considerations_for_licensors
37
-
38
- Considerations for the public: By using one of our public
39
- licenses, a licensor grants the public permission to use the
40
- licensed material under specified terms and conditions. If
41
- the licensor's permission is not necessary for any reason--for
42
- example, because of any applicable exception or limitation to
43
- copyright--then that use is not regulated by the license. Our
44
- licenses grant only permissions under copyright and certain
45
- other rights that a licensor has authority to grant. Use of
46
- the licensed material may still be restricted for other
47
- reasons, including because others have copyright or other
48
- rights in the material. A licensor may make special requests,
49
- such as asking that all changes be marked or described.
50
- Although not required by our licenses, you are encouraged to
51
- respect those requests where reasonable. More considerations
52
- for the public:
53
- wiki.creativecommons.org/Considerations_for_licensees
54
-
55
- =======================================================================
56
-
57
- Creative Commons Attribution-NonCommercial 4.0 International Public
58
- License
59
-
60
- By exercising the Licensed Rights (defined below), You accept and agree
61
- to be bound by the terms and conditions of this Creative Commons
62
- Attribution-NonCommercial 4.0 International Public License ("Public
63
- License"). To the extent this Public License may be interpreted as a
64
- contract, You are granted the Licensed Rights in consideration of Your
65
- acceptance of these terms and conditions, and the Licensor grants You
66
- such rights in consideration of benefits the Licensor receives from
67
- making the Licensed Material available under these terms and
68
- conditions.
69
-
70
-
71
- Section 1 -- Definitions.
72
-
73
- a. Adapted Material means material subject to Copyright and Similar
74
- Rights that is derived from or based upon the Licensed Material
75
- and in which the Licensed Material is translated, altered,
76
- arranged, transformed, or otherwise modified in a manner requiring
77
- permission under the Copyright and Similar Rights held by the
78
- Licensor. For purposes of this Public License, where the Licensed
79
- Material is a musical work, performance, or sound recording,
80
- Adapted Material is always produced where the Licensed Material is
81
- synched in timed relation with a moving image.
82
-
83
- b. Adapter's License means the license You apply to Your Copyright
84
- and Similar Rights in Your contributions to Adapted Material in
85
- accordance with the terms and conditions of this Public License.
86
-
87
- c. Copyright and Similar Rights means copyright and/or similar rights
88
- closely related to copyright including, without limitation,
89
- performance, broadcast, sound recording, and Sui Generis Database
90
- Rights, without regard to how the rights are labeled or
91
- categorized. For purposes of this Public License, the rights
92
- specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
- Rights.
94
- d. Effective Technological Measures means those measures that, in the
95
- absence of proper authority, may not be circumvented under laws
96
- fulfilling obligations under Article 11 of the WIPO Copyright
97
- Treaty adopted on December 20, 1996, and/or similar international
98
- agreements.
99
-
100
- e. Exceptions and Limitations means fair use, fair dealing, and/or
101
- any other exception or limitation to Copyright and Similar Rights
102
- that applies to Your use of the Licensed Material.
103
-
104
- f. Licensed Material means the artistic or literary work, database,
105
- or other material to which the Licensor applied this Public
106
- License.
107
-
108
- g. Licensed Rights means the rights granted to You subject to the
109
- terms and conditions of this Public License, which are limited to
110
- all Copyright and Similar Rights that apply to Your use of the
111
- Licensed Material and that the Licensor has authority to license.
112
-
113
- h. Licensor means the individual(s) or entity(ies) granting rights
114
- under this Public License.
115
-
116
- i. NonCommercial means not primarily intended for or directed towards
117
- commercial advantage or monetary compensation. For purposes of
118
- this Public License, the exchange of the Licensed Material for
119
- other material subject to Copyright and Similar Rights by digital
120
- file-sharing or similar means is NonCommercial provided there is
121
- no payment of monetary compensation in connection with the
122
- exchange.
123
-
124
- j. Share means to provide material to the public by any means or
125
- process that requires permission under the Licensed Rights, such
126
- as reproduction, public display, public performance, distribution,
127
- dissemination, communication, or importation, and to make material
128
- available to the public including in ways that members of the
129
- public may access the material from a place and at a time
130
- individually chosen by them.
131
-
132
- k. Sui Generis Database Rights means rights other than copyright
133
- resulting from Directive 96/9/EC of the European Parliament and of
134
- the Council of 11 March 1996 on the legal protection of databases,
135
- as amended and/or succeeded, as well as other essentially
136
- equivalent rights anywhere in the world.
137
-
138
- l. You means the individual or entity exercising the Licensed Rights
139
- under this Public License. Your has a corresponding meaning.
140
-
141
-
142
- Section 2 -- Scope.
143
-
144
- a. License grant.
145
-
146
- 1. Subject to the terms and conditions of this Public License,
147
- the Licensor hereby grants You a worldwide, royalty-free,
148
- non-sublicensable, non-exclusive, irrevocable license to
149
- exercise the Licensed Rights in the Licensed Material to:
150
-
151
- a. reproduce and Share the Licensed Material, in whole or
152
- in part, for NonCommercial purposes only; and
153
-
154
- b. produce, reproduce, and Share Adapted Material for
155
- NonCommercial purposes only.
156
-
157
- 2. Exceptions and Limitations. For the avoidance of doubt, where
158
- Exceptions and Limitations apply to Your use, this Public
159
- License does not apply, and You do not need to comply with
160
- its terms and conditions.
161
-
162
- 3. Term. The term of this Public License is specified in Section
163
- 6(a).
164
-
165
- 4. Media and formats; technical modifications allowed. The
166
- Licensor authorizes You to exercise the Licensed Rights in
167
- all media and formats whether now known or hereafter created,
168
- and to make technical modifications necessary to do so. The
169
- Licensor waives and/or agrees not to assert any right or
170
- authority to forbid You from making technical modifications
171
- necessary to exercise the Licensed Rights, including
172
- technical modifications necessary to circumvent Effective
173
- Technological Measures. For purposes of this Public License,
174
- simply making modifications authorized by this Section 2(a)
175
- (4) never produces Adapted Material.
176
-
177
- 5. Downstream recipients.
178
-
179
- a. Offer from the Licensor -- Licensed Material. Every
180
- recipient of the Licensed Material automatically
181
- receives an offer from the Licensor to exercise the
182
- Licensed Rights under the terms and conditions of this
183
- Public License.
184
-
185
- b. No downstream restrictions. You may not offer or impose
186
- any additional or different terms or conditions on, or
187
- apply any Effective Technological Measures to, the
188
- Licensed Material if doing so restricts exercise of the
189
- Licensed Rights by any recipient of the Licensed
190
- Material.
191
-
192
- 6. No endorsement. Nothing in this Public License constitutes or
193
- may be construed as permission to assert or imply that You
194
- are, or that Your use of the Licensed Material is, connected
195
- with, or sponsored, endorsed, or granted official status by,
196
- the Licensor or others designated to receive attribution as
197
- provided in Section 3(a)(1)(A)(i).
198
-
199
- b. Other rights.
200
-
201
- 1. Moral rights, such as the right of integrity, are not
202
- licensed under this Public License, nor are publicity,
203
- privacy, and/or other similar personality rights; however, to
204
- the extent possible, the Licensor waives and/or agrees not to
205
- assert any such rights held by the Licensor to the limited
206
- extent necessary to allow You to exercise the Licensed
207
- Rights, but not otherwise.
208
-
209
- 2. Patent and trademark rights are not licensed under this
210
- Public License.
211
-
212
- 3. To the extent possible, the Licensor waives any right to
213
- collect royalties from You for the exercise of the Licensed
214
- Rights, whether directly or through a collecting society
215
- under any voluntary or waivable statutory or compulsory
216
- licensing scheme. In all other cases the Licensor expressly
217
- reserves any right to collect such royalties, including when
218
- the Licensed Material is used other than for NonCommercial
219
- purposes.
220
-
221
-
222
- Section 3 -- License Conditions.
223
-
224
- Your exercise of the Licensed Rights is expressly made subject to the
225
- following conditions.
226
-
227
- a. Attribution.
228
-
229
- 1. If You Share the Licensed Material (including in modified
230
- form), You must:
231
-
232
- a. retain the following if it is supplied by the Licensor
233
- with the Licensed Material:
234
-
235
- i. identification of the creator(s) of the Licensed
236
- Material and any others designated to receive
237
- attribution, in any reasonable manner requested by
238
- the Licensor (including by pseudonym if
239
- designated);
240
-
241
- ii. a copyright notice;
242
-
243
- iii. a notice that refers to this Public License;
244
-
245
- iv. a notice that refers to the disclaimer of
246
- warranties;
247
-
248
- v. a URI or hyperlink to the Licensed Material to the
249
- extent reasonably practicable;
250
-
251
- b. indicate if You modified the Licensed Material and
252
- retain an indication of any previous modifications; and
253
-
254
- c. indicate the Licensed Material is licensed under this
255
- Public License, and include the text of, or the URI or
256
- hyperlink to, this Public License.
257
-
258
- 2. You may satisfy the conditions in Section 3(a)(1) in any
259
- reasonable manner based on the medium, means, and context in
260
- which You Share the Licensed Material. For example, it may be
261
- reasonable to satisfy the conditions by providing a URI or
262
- hyperlink to a resource that includes the required
263
- information.
264
-
265
- 3. If requested by the Licensor, You must remove any of the
266
- information required by Section 3(a)(1)(A) to the extent
267
- reasonably practicable.
268
-
269
- 4. If You Share Adapted Material You produce, the Adapter's
270
- License You apply must not prevent recipients of the Adapted
271
- Material from complying with this Public License.
272
-
273
-
274
- Section 4 -- Sui Generis Database Rights.
275
-
276
- Where the Licensed Rights include Sui Generis Database Rights that
277
- apply to Your use of the Licensed Material:
278
-
279
- a. for the avoidance of doubt, Section 2(a)(1) grants You the right
280
- to extract, reuse, reproduce, and Share all or a substantial
281
- portion of the contents of the database for NonCommercial purposes
282
- only;
283
-
284
- b. if You include all or a substantial portion of the database
285
- contents in a database in which You have Sui Generis Database
286
- Rights, then the database in which You have Sui Generis Database
287
- Rights (but not its individual contents) is Adapted Material; and
288
-
289
- c. You must comply with the conditions in Section 3(a) if You Share
290
- all or a substantial portion of the contents of the database.
291
-
292
- For the avoidance of doubt, this Section 4 supplements and does not
293
- replace Your obligations under this Public License where the Licensed
294
- Rights include other Copyright and Similar Rights.
295
-
296
-
297
- Section 5 -- Disclaimer of Warranties and Limitation of Liability.
298
-
299
- a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
300
- EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
301
- AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
302
- ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
303
- IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
304
- WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
305
- PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
306
- ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
307
- KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
308
- ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
309
-
310
- b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
311
- TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
312
- NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
313
- INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
314
- COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
315
- USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
316
- ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
317
- DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
318
- IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
319
-
320
- c. The disclaimer of warranties and limitation of liability provided
321
- above shall be interpreted in a manner that, to the extent
322
- possible, most closely approximates an absolute disclaimer and
323
- waiver of all liability.
324
-
325
-
326
- Section 6 -- Term and Termination.
327
-
328
- a. This Public License applies for the term of the Copyright and
329
- Similar Rights licensed here. However, if You fail to comply with
330
- this Public License, then Your rights under this Public License
331
- terminate automatically.
332
-
333
- b. Where Your right to use the Licensed Material has terminated under
334
- Section 6(a), it reinstates:
335
-
336
- 1. automatically as of the date the violation is cured, provided
337
- it is cured within 30 days of Your discovery of the
338
- violation; or
339
-
340
- 2. upon express reinstatement by the Licensor.
341
-
342
- For the avoidance of doubt, this Section 6(b) does not affect any
343
- right the Licensor may have to seek remedies for Your violations
344
- of this Public License.
345
-
346
- c. For the avoidance of doubt, the Licensor may also offer the
347
- Licensed Material under separate terms or conditions or stop
348
- distributing the Licensed Material at any time; however, doing so
349
- will not terminate this Public License.
350
-
351
- d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
352
- License.
353
-
354
-
355
- Section 7 -- Other Terms and Conditions.
356
-
357
- a. The Licensor shall not be bound by any additional or different
358
- terms or conditions communicated by You unless expressly agreed.
359
-
360
- b. Any arrangements, understandings, or agreements regarding the
361
- Licensed Material not stated herein are separate from and
362
- independent of the terms and conditions of this Public License.
363
-
364
-
365
- Section 8 -- Interpretation.
366
-
367
- a. For the avoidance of doubt, this Public License does not, and
368
- shall not be interpreted to, reduce, limit, restrict, or impose
369
- conditions on any use of the Licensed Material that could lawfully
370
- be made without permission under this Public License.
371
-
372
- b. To the extent possible, if any provision of this Public License is
373
- deemed unenforceable, it shall be automatically reformed to the
374
- minimum extent necessary to make it enforceable. If the provision
375
- cannot be reformed, it shall be severed from this Public License
376
- without affecting the enforceability of the remaining terms and
377
- conditions.
378
-
379
- c. No term or condition of this Public License will be waived and no
380
- failure to comply consented to unless expressly agreed to by the
381
- Licensor.
382
-
383
- d. Nothing in this Public License constitutes or may be interpreted
384
- as a limitation upon, or waiver of, any privileges and immunities
385
- that apply to the Licensor or You, including from the legal
386
- processes of any jurisdiction or authority.
387
-
388
- =======================================================================
389
-
390
- Creative Commons is not a party to its public
391
- licenses. Notwithstanding, Creative Commons may elect to apply one of
392
- its public licenses to material it publishes and in those instances
393
- will be considered the “Licensor.” The text of the Creative Commons
394
- public licenses is dedicated to the public domain under the CC0 Public
395
- Domain Dedication. Except for the limited purpose of indicating that
396
- material is shared under a Creative Commons public license or as
397
- otherwise permitted by the Creative Commons policies published at
398
- creativecommons.org/policies, Creative Commons does not authorize the
399
- use of the trademark "Creative Commons" or any other trademark or logo
400
- of Creative Commons without its prior written consent including,
401
- without limitation, in connection with any unauthorized modifications
402
- to any of its public licenses or any other arrangements,
403
- understandings, or agreements concerning use of licensed material. For
404
- the avoidance of doubt, this paragraph does not form part of the
405
- public licenses.
406
-
407
- Creative Commons may be contacted at creativecommons.org.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/README.md DELETED
@@ -1,204 +0,0 @@
1
- <div align="center">
2
-
3
- <a href="https://trendshift.io/repositories/10489" target="_blank"><img src="https://trendshift.io/api/badge/repositories/10489" alt="2noise%2FChatTTS | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
4
-
5
- # ChatTTS
6
- A generative speech model for daily dialogue.
7
-
8
- [![Licence](https://img.shields.io/badge/LICENSE-CC%20BY--NC%204.0-green.svg?style=for-the-badge)](https://github.com/2noise/ChatTTS/blob/main/LICENSE)
9
-
10
- [![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
11
- [![Open In Colab](https://img.shields.io/badge/Colab-F9AB00?style=for-the-badge&logo=googlecolab&color=525252)](https://colab.research.google.com/github/2noise/ChatTTS/blob/main/examples/ipynb/colab.ipynb)
12
-
13
- **English** | [**简体中文**](docs/cn/README.md) | [**日本語**](docs/jp/README.md) | [**Русский**](docs/ru/README.md)
14
-
15
- </div>
16
-
17
- ## Introduction
18
- ChatTTS is a text-to-speech model designed specifically for dialogue scenarios such as LLM assistant.
19
-
20
- ### Supported Languages
21
- - [x] English
22
- - [x] Chinese
23
- - [ ] Coming Soon...
24
-
25
- ### Highlights
26
- > You can refer to **[this video on Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)** for the detailed description.
27
-
28
- 1. **Conversational TTS**: ChatTTS is optimized for dialogue-based tasks, enabling natural and expressive speech synthesis. It supports multiple speakers, facilitating interactive conversations.
29
- 2. **Fine-grained Control**: The model could predict and control fine-grained prosodic features, including laughter, pauses, and interjections.
30
- 3. **Better Prosody**: ChatTTS surpasses most of open-source TTS models in terms of prosody. We provide pretrained models to support further research and development.
31
-
32
- ### Dataset & Model
33
- - The main model is trained with Chinese and English audio data of 100,000+ hours.
34
- - The open-source version on **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** is a 40,000 hours pre-trained model without SFT.
35
-
36
- ### Roadmap
37
- - [x] Open-source the 40k hour base model and spk_stats file
38
- - [ ] Open-source VQ encoder and Lora training code
39
- - [ ] Streaming audio generation without refining the text*
40
- - [ ] Open-source the 40k hour version with multi-emotion control
41
- - [ ] ChatTTS.cpp maybe? (PR or new repo are welcomed.)
42
-
43
- ### Disclaimer
44
- > [!Important]
45
- > This repo is for academic purposes only.
46
-
47
- It is intended for educational and research use, and should not be used for any commercial or legal purposes. The authors do not guarantee the accuracy, completeness, or reliability of the information. The information and data used in this repo, are for academic and research purposes only. The data obtained from publicly available sources, and the authors do not claim any ownership or copyright over the data.
48
-
49
- ChatTTS is a powerful text-to-speech system. However, it is very important to utilize this technology responsibly and ethically. To limit the use of ChatTTS, we added a small amount of high-frequency noise during the training of the 40,000-hour model, and compressed the audio quality as much as possible using MP3 format, to prevent malicious actors from potentially using it for criminal purposes. At the same time, we have internally trained a detection model and plan to open-source it in the future.
50
-
51
- ### Contact
52
- > GitHub issues/PRs are always welcomed.
53
-
54
- #### Formal Inquiries
55
- For formal inquiries about the model and roadmap, please contact us at **[email protected]**.
56
-
57
- #### Online Chat
58
- ##### 1. QQ Group (Chinese Social APP)
59
- - **Group 1**, 808364215 (Full)
60
- - **Group 2**, 230696694 (Full)
61
- - **Group 3**, 933639842
62
-
63
- ## Installation (WIP)
64
- > Will be uploaded to pypi soon according to https://github.com/2noise/ChatTTS/issues/269
65
- #### 1. Install Directly
66
- ```bash
67
- pip install git+https://github.com/2noise/ChatTTS
68
- ```
69
-
70
- #### 2. Install from conda
71
- ```bash
72
- git clone https://github.com/2noise/ChatTTS
73
- cd ChatTTS
74
- conda create -n chattts
75
- conda activate chattts
76
- pip install -r requirements.txt
77
- ```
78
-
79
- ## Get Started
80
- ### Install requirements
81
- ```bash
82
- pip install --upgrade -r requirements.txt
83
- ```
84
-
85
- ### Quick Start
86
- #### 1. Launch WebUI
87
- ```bash
88
- python examples/web/webui.py
89
- ```
90
-
91
- #### 2. Infer by Command Line
92
- > It will save audio to `./output_audio_xxx.wav`
93
-
94
- ```bash
95
- python examples/cmd/run.py "Please input your text."
96
- ```
97
-
98
- ### Basic
99
-
100
- ```python
101
- import ChatTTS
102
- from IPython.display import Audio
103
- import torchaudio
104
-
105
- chat = ChatTTS.Chat()
106
- chat.load_models(compile=False) # Set to True for better performance
107
-
108
- texts = ["PUT YOUR TEXT HERE",]
109
-
110
- wavs = chat.infer(texts, )
111
-
112
- torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
113
- ```
114
-
115
- ### Advanced
116
-
117
- ```python
118
- ###################################
119
- # Sample a speaker from Gaussian.
120
-
121
- rand_spk = chat.sample_random_speaker()
122
-
123
- params_infer_code = {
124
- 'spk_emb': rand_spk, # add sampled speaker
125
- 'temperature': .3, # using custom temperature
126
- 'top_P': 0.7, # top P decode
127
- 'top_K': 20, # top K decode
128
- }
129
-
130
- ###################################
131
- # For sentence level manual control.
132
-
133
- # use oral_(0-9), laugh_(0-2), break_(0-7)
134
- # to generate special token in text to synthesize.
135
- params_refine_text = {
136
- 'prompt': '[oral_2][laugh_0][break_6]'
137
- }
138
-
139
- wavs = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
140
-
141
- ###################################
142
- # For word level manual control.
143
- text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
144
- wavs = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
145
- torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
146
- ```
147
-
148
- <details open>
149
- <summary><h4>Example: self introduction</h4></summary>
150
-
151
- ```python
152
- inputs_en = """
153
- chat T T S is a text to speech model designed for dialogue applications.
154
- [uv_break]it supports mixed language input [uv_break]and offers multi speaker
155
- capabilities with precise control over prosodic elements [laugh]like like
156
- [uv_break]laughter[laugh], [uv_break]pauses, [uv_break]and intonation.
157
- [uv_break]it delivers natural and expressive speech,[uv_break]so please
158
- [uv_break] use the project responsibly at your own risk.[uv_break]
159
- """.replace('\n', '') # English is still experimental.
160
-
161
- params_refine_text = {
162
- 'prompt': '[oral_2][laugh_0][break_4]'
163
- }
164
- # audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
165
- audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
166
- torchaudio.save("output3.wav", torch.from_numpy(audio_array_en[0]), 24000)
167
- ```
168
- [male speaker](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
169
-
170
- [female speaker](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
171
- </details>
172
-
173
- ## FAQ
174
-
175
- #### 1. How much VRAM do I need? How about infer speed?
176
- For a 30-second audio clip, at least 4GB of GPU memory is required. For the 4090 GPU, it can generate audio corresponding to approximately 7 semantic tokens per second. The Real-Time Factor (RTF) is around 0.3.
177
-
178
- #### 2. Model stability is not good enough, with issues such as multi speakers or poor audio quality.
179
-
180
- This is a problem that typically occurs with autoregressive models (for bark and valle). It's generally difficult to avoid. One can try multiple samples to find a suitable result.
181
-
182
- #### 3. Besides laughter, can we control anything else? Can we control other emotions?
183
-
184
- In the current released model, the only token-level control units are `[laugh]`, `[uv_break]`, and `[lbreak]`. In future versions, we may open-source models with additional emotional control capabilities.
185
-
186
- ## Acknowledgements
187
- - [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) and [valle](https://arxiv.org/abs/2301.02111) demostrate a remarkable TTS result by an autoregressive-style system.
188
- - [fish-speech](https://github.com/fishaudio/fish-speech) reveals capability of GVQ as audio tokenizer for LLM modeling.
189
- - [vocos](https://github.com/gemelo-ai/vocos) which is used as a pretrained vocoder.
190
-
191
- ## Special Appreciation
192
- - [wlu-audio lab](https://audio.westlake.edu.cn/) for early algorithm experiments.
193
-
194
- ## Related Resources
195
- - [Awesome-ChatTTS](https://github.com/libukai/Awesome-ChatTTS)
196
-
197
- ## Thanks to all contributors for their efforts
198
- [![contributors](https://contrib.rocks/image?repo=2noise/ChatTTS)](https://github.com/2noise/ChatTTS/graphs/contributors)
199
-
200
- <div align="center">
201
-
202
- ![counter](https://counter.seku.su/cmoe?name=chattts&theme=mbs)
203
-
204
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/core.py CHANGED
@@ -1,9 +1,10 @@
 
1
  import os
2
  import json
3
  import logging
4
- import tempfile
5
  from functools import partial
6
- from typing import Literal, Optional
 
7
 
8
  import torch
9
  from omegaconf import OmegaConf
@@ -14,19 +15,19 @@ from .model.dvae import DVAE
14
  from .model.gpt import GPT_warpper
15
  from .utils.gpu_utils import select_device
16
  from .utils.infer_utils import count_invalid_characters, detect_language, apply_character_map, apply_half2full_map, HomophonesReplacer
17
- from .utils.io import get_latest_modified_file, del_all
18
  from .infer.api import refine_text, infer_code
19
  from .utils.download import check_all_assets, download_all_assets
20
- from .utils.log import set_utils_logger
 
21
 
22
 
23
  class Chat:
24
- def __init__(self, logger=logging.getLogger(__name__)):
25
  self.pretrain_models = {}
26
  self.normalizer = {}
27
  self.homophones_replacer = None
28
- self.logger = logger
29
- set_utils_logger(logger)
30
 
31
  def check_model(self, level = logging.INFO, use_decoder = False):
32
  not_finish = False
@@ -44,7 +45,7 @@ class Chat:
44
 
45
  if not not_finish:
46
  self.logger.log(level, f'All initialized.')
47
-
48
  return not not_finish
49
 
50
  def load_models(
@@ -60,8 +61,8 @@ class Chat:
60
  with tempfile.TemporaryDirectory() as tmp:
61
  download_all_assets(tmpdir=tmp)
62
  if not check_all_assets(update=False):
63
- self.logger.error("counld not satisfy all assets needed.")
64
- return False
65
  elif source == 'huggingface':
66
  hf_home = os.getenv('HF_HOME', os.path.expanduser("~/.cache/huggingface"))
67
  try:
@@ -77,7 +78,7 @@ class Chat:
77
  self.logger.log(logging.INFO, f'Load from local: {custom_path}')
78
  download_path = custom_path
79
 
80
- return self._load(**{k: os.path.join(download_path, v) for k, v in OmegaConf.load(os.path.join(download_path, 'config', 'path.yaml')).items()}, **kwargs)
81
 
82
  def _load(
83
  self,
@@ -90,18 +91,17 @@ class Chat:
90
  decoder_config_path: str = None,
91
  decoder_ckpt_path: str = None,
92
  tokenizer_path: str = None,
93
- device: Optional[torch.device] = None,
94
  compile: bool = True,
95
  ):
96
- if device is None:
97
  device = select_device(4096)
98
  self.logger.log(logging.INFO, f'use {device}')
99
- self.device = device
100
-
101
  if vocos_config_path:
102
  vocos = Vocos.from_hparams(vocos_config_path).to(
103
  # vocos on mps will crash, use cpu fallback
104
- "cpu" if "mps" in str(device) else device
105
  ).eval()
106
  assert vocos_ckpt_path, 'vocos_ckpt_path should not be None'
107
  vocos.load_state_dict(torch.load(vocos_ckpt_path))
@@ -118,14 +118,14 @@ class Chat:
118
 
119
  if gpt_config_path:
120
  cfg = OmegaConf.load(gpt_config_path)
121
- gpt = GPT_warpper(**cfg, device=device, logger=self.logger).eval()
122
  assert gpt_ckpt_path, 'gpt_ckpt_path should not be None'
123
  gpt.load_state_dict(torch.load(gpt_ckpt_path))
124
  if compile and 'cuda' in str(device):
125
  try:
126
  gpt.gpt.forward = torch.compile(gpt.gpt.forward, backend='inductor', dynamic=True)
127
  except RuntimeError as e:
128
- self.logger.warning(f'Compile failed,{e}. fallback to normal mode.')
129
  self.pretrain_models['gpt'] = gpt
130
  spk_stat_path = os.path.join(os.path.dirname(gpt_ckpt_path), 'spk_stat.pt')
131
  assert os.path.exists(spk_stat_path), f'Missing spk_stat.pt: {spk_stat_path}'
@@ -146,7 +146,7 @@ class Chat:
146
  self.pretrain_models['tokenizer'] = tokenizer
147
  self.logger.log(logging.INFO, 'tokenizer loaded.')
148
 
149
- return self.check_model()
150
 
151
  def _infer(
152
  self,
@@ -179,16 +179,14 @@ class Chat:
179
  self.logger.log(logging.WARNING, f'Invalid characters found! : {invalid_characters}')
180
  text[i] = apply_character_map(t)
181
  if do_homophone_replacement and self.init_homophones_replacer():
182
- text[i], replaced_words = self.homophones_replacer.replace(text[i])
183
- if replaced_words:
184
- repl_res = ', '.join([f'{_[0]}->{_[1]}' for _ in replaced_words])
185
- self.logger.log(logging.INFO, f'Homophones replace: {repl_res}')
186
 
187
  if not skip_refine_text:
188
  text_tokens = refine_text(
189
  self.pretrain_models,
190
  text,
191
- device=self.device,
192
  **params_refine_text,
193
  )['ids']
194
  text_tokens = [i[i < self.pretrain_models['tokenizer'].convert_tokens_to_ids('[break_0]')] for i in text_tokens]
@@ -199,28 +197,16 @@ class Chat:
199
 
200
  text = [params_infer_code.get('prompt', '') + i for i in text]
201
  params_infer_code.pop('prompt', '')
202
- result_gen = infer_code(
203
- self.pretrain_models,
204
- text,
205
- device=self.device,
206
- **params_infer_code,
207
- return_hidden=use_decoder,
208
- stream=stream,
209
- )
210
  if use_decoder:
211
  field = 'hiddens'
212
  docoder_name = 'decoder'
213
  else:
214
  field = 'ids'
215
  docoder_name = 'dvae'
216
- if "mps" in str(self.device):
217
- vocos_decode = lambda spec: [self.pretrain_models['vocos'].decode(
218
- i.cpu()
219
- ).cpu().numpy() for i in spec]
220
- else:
221
- vocos_decode = lambda spec: [self.pretrain_models['vocos'].decode(
222
- i
223
- ).cpu().numpy() for i in spec]
224
  if stream:
225
 
226
  length = 0
@@ -234,20 +220,13 @@ class Chat:
234
  if not len(chunk_data):
235
  continue
236
  self.logger.debug(f'new hidden {len(chunk_data)=}')
237
- mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1).to(self.device)) for i in [chunk_data]]
238
- del_all(result)
239
- del chunk_data
240
  wav = vocos_decode(mel_spec)
241
- del_all(mel_spec)
242
  self.logger.debug(f'yield wav chunk {len(wav[0])=} {len(wav[0][0])=}')
243
  yield wav
244
  return
245
- result = next(result_gen)
246
- mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1).to(self.device)) for i in result[field]]
247
- del_all(result)
248
- wav = vocos_decode(mel_spec)
249
- del_all(mel_spec)
250
- yield wav
251
 
252
  def infer(
253
  self,
 
1
+
2
  import os
3
  import json
4
  import logging
 
5
  from functools import partial
6
+ from typing import Literal
7
+ import tempfile
8
 
9
  import torch
10
  from omegaconf import OmegaConf
 
15
  from .model.gpt import GPT_warpper
16
  from .utils.gpu_utils import select_device
17
  from .utils.infer_utils import count_invalid_characters, detect_language, apply_character_map, apply_half2full_map, HomophonesReplacer
18
+ from .utils.io_utils import get_latest_modified_file
19
  from .infer.api import refine_text, infer_code
20
  from .utils.download import check_all_assets, download_all_assets
21
+
22
+ logging.basicConfig(level = logging.INFO)
23
 
24
 
25
  class Chat:
26
+ def __init__(self, ):
27
  self.pretrain_models = {}
28
  self.normalizer = {}
29
  self.homophones_replacer = None
30
+ self.logger = logging.getLogger(__name__)
 
31
 
32
  def check_model(self, level = logging.INFO, use_decoder = False):
33
  not_finish = False
 
45
 
46
  if not not_finish:
47
  self.logger.log(level, f'All initialized.')
48
+
49
  return not not_finish
50
 
51
  def load_models(
 
61
  with tempfile.TemporaryDirectory() as tmp:
62
  download_all_assets(tmpdir=tmp)
63
  if not check_all_assets(update=False):
64
+ logging.error("counld not satisfy all assets needed.")
65
+ exit(1)
66
  elif source == 'huggingface':
67
  hf_home = os.getenv('HF_HOME', os.path.expanduser("~/.cache/huggingface"))
68
  try:
 
78
  self.logger.log(logging.INFO, f'Load from local: {custom_path}')
79
  download_path = custom_path
80
 
81
+ self._load(**{k: os.path.join(download_path, v) for k, v in OmegaConf.load(os.path.join(download_path, 'config', 'path.yaml')).items()}, **kwargs)
82
 
83
  def _load(
84
  self,
 
91
  decoder_config_path: str = None,
92
  decoder_ckpt_path: str = None,
93
  tokenizer_path: str = None,
94
+ device: str = None,
95
  compile: bool = True,
96
  ):
97
+ if not device:
98
  device = select_device(4096)
99
  self.logger.log(logging.INFO, f'use {device}')
100
+
 
101
  if vocos_config_path:
102
  vocos = Vocos.from_hparams(vocos_config_path).to(
103
  # vocos on mps will crash, use cpu fallback
104
+ "cpu" if torch.backends.mps.is_available() else device
105
  ).eval()
106
  assert vocos_ckpt_path, 'vocos_ckpt_path should not be None'
107
  vocos.load_state_dict(torch.load(vocos_ckpt_path))
 
118
 
119
  if gpt_config_path:
120
  cfg = OmegaConf.load(gpt_config_path)
121
+ gpt = GPT_warpper(**cfg).to(device).eval()
122
  assert gpt_ckpt_path, 'gpt_ckpt_path should not be None'
123
  gpt.load_state_dict(torch.load(gpt_ckpt_path))
124
  if compile and 'cuda' in str(device):
125
  try:
126
  gpt.gpt.forward = torch.compile(gpt.gpt.forward, backend='inductor', dynamic=True)
127
  except RuntimeError as e:
128
+ logging.warning(f'Compile failed,{e}. fallback to normal mode.')
129
  self.pretrain_models['gpt'] = gpt
130
  spk_stat_path = os.path.join(os.path.dirname(gpt_ckpt_path), 'spk_stat.pt')
131
  assert os.path.exists(spk_stat_path), f'Missing spk_stat.pt: {spk_stat_path}'
 
146
  self.pretrain_models['tokenizer'] = tokenizer
147
  self.logger.log(logging.INFO, 'tokenizer loaded.')
148
 
149
+ self.check_model()
150
 
151
  def _infer(
152
  self,
 
179
  self.logger.log(logging.WARNING, f'Invalid characters found! : {invalid_characters}')
180
  text[i] = apply_character_map(t)
181
  if do_homophone_replacement and self.init_homophones_replacer():
182
+ text[i] = self.homophones_replacer.replace(t)
183
+ if t != text[i]:
184
+ self.logger.log(logging.INFO, f'Homophones replace: {t} -> {text[i]}')
 
185
 
186
  if not skip_refine_text:
187
  text_tokens = refine_text(
188
  self.pretrain_models,
189
  text,
 
190
  **params_refine_text,
191
  )['ids']
192
  text_tokens = [i[i < self.pretrain_models['tokenizer'].convert_tokens_to_ids('[break_0]')] for i in text_tokens]
 
197
 
198
  text = [params_infer_code.get('prompt', '') + i for i in text]
199
  params_infer_code.pop('prompt', '')
200
+ result_gen = infer_code(self.pretrain_models, text, **params_infer_code, return_hidden=use_decoder, stream=stream)
 
 
 
 
 
 
 
201
  if use_decoder:
202
  field = 'hiddens'
203
  docoder_name = 'decoder'
204
  else:
205
  field = 'ids'
206
  docoder_name = 'dvae'
207
+ vocos_decode = lambda spec: [self.pretrain_models['vocos'].decode(
208
+ i.cpu() if torch.backends.mps.is_available() else i
209
+ ).cpu().numpy() for i in spec]
 
 
 
 
 
210
  if stream:
211
 
212
  length = 0
 
220
  if not len(chunk_data):
221
  continue
222
  self.logger.debug(f'new hidden {len(chunk_data)=}')
223
+ mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1)) for i in [chunk_data]]
 
 
224
  wav = vocos_decode(mel_spec)
 
225
  self.logger.debug(f'yield wav chunk {len(wav[0])=} {len(wav[0][0])=}')
226
  yield wav
227
  return
228
+ mel_spec = [self.pretrain_models[docoder_name](i[None].permute(0,2,1)) for i in next(result_gen)[field]]
229
+ yield vocos_decode(mel_spec)
 
 
 
 
230
 
231
  def infer(
232
  self,
ChatTTS/docs/cn/README.md DELETED
@@ -1,235 +0,0 @@
1
- <div align="center">
2
-
3
- <a href="https://trendshift.io/repositories/10489" target="_blank"><img src="https://trendshift.io/api/badge/repositories/10489" alt="2noise%2FChatTTS | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
4
-
5
- # ChatTTS
6
- 一款适用于日常对话的生成式语音模型。
7
-
8
- [![Licence](https://img.shields.io/badge/LICENSE-CC%20BY--NC%204.0-green.svg?style=for-the-badge)](https://github.com/2noise/ChatTTS/blob/main/LICENSE)
9
-
10
- [![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
11
- [![Open In Colab](https://img.shields.io/badge/Colab-F9AB00?style=for-the-badge&logo=googlecolab&color=525252)](https://colab.research.google.com/github/2noise/ChatTTS/blob/main/examples/ipynb/colab.ipynb)
12
-
13
- [**English**](../../README.md) | **简体中文** | [**日本語**](../jp/README.md) | [**Русский**](../ru/README.md)
14
-
15
- </div>
16
-
17
- > [!NOTE]
18
- > 注意此版本可能不是最新版,所有内容请以英文版为准。
19
-
20
- ## 简介
21
-
22
- ChatTTS 是一款专门为对话场景(例如 LLM 助手)设计的文本转语音模型。
23
-
24
- ### 支持的语种
25
-
26
- - [x] 英语
27
- - [x] 中文
28
- - [ ] 敬请期待...
29
-
30
- ### 亮点
31
-
32
- > 你可以参考 **[Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)** 上的这个视频,了解本项目的详细情况。
33
-
34
- 1. **对话式 TTS**: ChatTTS 针对对话式任务进行了优化,能够实现自然且富有表现力的合成语音。它支持多个说话者,便于生成互动式对话。
35
- 2. **精细的控制**: 该模型可以预测和控制精细的韵律特征,包括笑声、停顿和插入语。
36
- 3. **更好的韵律**: ChatTTS 在韵律方面超越了大多数开源 TTS 模型。我们提供预训练模型以支持进一步的研究和开发。
37
-
38
- ### 数据集和模型
39
-
40
- - 主模型使用了 100,000+ 小时的中文和英文音频数据进行训练。
41
- - **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** 上的开源版本是一个在 40,000 小时数据上进行无监督微调的预训练模型。
42
-
43
- ### 路线图
44
-
45
- - [x] 开源 4 万小时基础模型和 spk_stats 文件
46
- - [ ] 开源 VQ 编码器和 Lora 训练代码
47
- - [ ] 无需细化文本即可进行流式音频生成
48
- - [ ] 开源具有多情感控制功能的 4 万小时版本
49
- - [ ] 也许会有 ChatTTS.cpp ?(欢迎 PR 或新建仓库)
50
-
51
- ### 免责声明
52
-
53
- > [!Important]
54
- > 此仓库仅供学术用途。
55
-
56
- 本项目旨在用于教育和研究目的,不适用于任何商业或法律目的。作者不保证信息的准确性、完整性和可靠性。此仓库中使用的信息和数据仅供学术和研究目的。数据来自公开来源,作者不声称对数据拥有任何所有权或版权。
57
-
58
- ChatTTS 是一款强大的文本转语音系统。但是,负责任和道德地使用这项技术非常重要。为了限制 ChatTTS 的使用,我们在 40,000 小时模型的训练过程中添加了少量高频噪声,并使用 MP3 格式尽可能压缩音频质量,以防止恶意行为者将其用于犯罪目的。同时,我们内部训练了一个检测模型,并计划在未来开源它。
59
-
60
- ### 联系方式
61
-
62
- > 欢迎随时提交 GitHub issues/PRs。
63
-
64
- #### 合作洽谈
65
-
66
- 如需就模型和路线图进行合作洽谈,请发送邮件至 **[email protected]**。
67
-
68
- #### 线上讨论
69
-
70
- ##### 1. 官方 QQ 群
71
-
72
- - **群 1**, 808364215 (已满)
73
- - **群 2**, 230696694 (已满)
74
- - **群 3**, 933639842
75
-
76
- ## 安装教程 (丰富中)
77
-
78
- > 将在近期上传至 pypi,详情请查看 https://github.com/2noise/ChatTTS/issues/269 上的讨论。
79
-
80
- #### 1. 使用源代码安装
81
-
82
- ```bash
83
- pip install git+https://github.com/2noise/ChatTTS
84
- ```
85
-
86
- #### 2. 使用 conda 安装
87
-
88
- ```bash
89
- git clone https://github.com/2noise/ChatTTS
90
- cd ChatTTS
91
- conda create -n chattts
92
- conda activate chattts
93
- pip install -r requirements.txt
94
- ```
95
-
96
- ## 使用教程
97
-
98
- ### 安装依赖
99
-
100
- ```bash
101
- pip install --upgrade -r requirements.txt
102
- ```
103
-
104
- ### 快速开始
105
-
106
- #### 1. 启动 WebUI
107
-
108
- ```bash
109
- python examples/web/webui.py
110
- ```
111
-
112
- #### 2. 使用命令行
113
-
114
- > 生成的音频将保存至 `./output_audio_xxx.wav`
115
-
116
- ```bash
117
- python examples/cmd/run.py "Please input your text."
118
- ```
119
-
120
- ### 基础用法
121
-
122
- ```python
123
- import ChatTTS
124
- from IPython.display import Audio
125
- import torchaudio
126
-
127
- chat = ChatTTS.Chat()
128
- chat.load_models(compile=False) # Set to True for better performance
129
-
130
- texts = ["PUT YOUR TEXT HERE",]
131
-
132
- wavs = chat.infer(texts, )
133
-
134
- torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
135
- ```
136
-
137
- ### 进阶用法
138
-
139
- ```python
140
- ###################################
141
- # Sample a speaker from Gaussian.
142
-
143
- rand_spk = chat.sample_random_speaker()
144
-
145
- params_infer_code = {
146
- 'spk_emb': rand_spk, # add sampled speaker
147
- 'temperature': .3, # using custom temperature
148
- 'top_P': 0.7, # top P decode
149
- 'top_K': 20, # top K decode
150
- }
151
-
152
- ###################################
153
- # For sentence level manual control.
154
-
155
- # use oral_(0-9), laugh_(0-2), break_(0-7)
156
- # to generate special token in text to synthesize.
157
- params_refine_text = {
158
- 'prompt': '[oral_2][laugh_0][break_6]'
159
- }
160
-
161
- wavs = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
162
-
163
- ###################################
164
- # For word level manual control.
165
- text = 'What is [uv_break]your favorite english food?[laugh][lbreak]'
166
- wavs = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
167
- torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
168
- ```
169
-
170
- <details open>
171
- <summary><h4>示例: 自我介绍</h4></summary>
172
-
173
- ```python
174
- inputs_en = """
175
- chat T T S is a text to speech model designed for dialogue applications.
176
- [uv_break]it supports mixed language input [uv_break]and offers multi speaker
177
- capabilities with precise control over prosodic elements [laugh]like like
178
- [uv_break]laughter[laugh], [uv_break]pauses, [uv_break]and intonation.
179
- [uv_break]it delivers natural and expressive speech,[uv_break]so please
180
- [uv_break] use the project responsibly at your own risk.[uv_break]
181
- """.replace('\n', '') # English is still experimental.
182
-
183
- params_refine_text = {
184
- 'prompt': '[oral_2][laugh_0][break_4]'
185
- }
186
- # audio_array_cn = chat.infer(inputs_cn, params_refine_text=params_refine_text)
187
- audio_array_en = chat.infer(inputs_en, params_refine_text=params_refine_text)
188
- torchaudio.save("output3.wav", torch.from_numpy(audio_array_en[0]), 24000)
189
- ```
190
-
191
- [男性音色](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
192
-
193
- [女性音色](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
194
-
195
- </details>
196
-
197
- ## 常见问题
198
-
199
- #### 1. 我需要多少 VRAM? 推理速度如何?
200
-
201
- 对于 30 秒的音频片段,至少需要 4GB 的 GPU 内存。 对于 4090 GPU,它可以每秒生成大约 7 个语义 token 对应的音频。实时因子 (RTF) 约为 0.3。
202
-
203
- #### 2. 模型稳定性不够好,存在多个说话者或音频质量差等问题。
204
-
205
- 这是一个通常发生在自回归模型(例如 bark 和 valle)中的问题,通常很难避免。可以尝试多个样本以找到合适的结果。
206
-
207
- #### 3. 除了笑声,我们还能控制其他东西吗?我们能控制其他情绪吗?
208
-
209
- 在当前发布的模型中,可用的 token 级控制单元是 `[laugh]`, `[uv_break]` 和 `[lbreak]`。未来的版本中,我们可能会开源具有更多情绪控制功能的模型。
210
-
211
- ## 致谢
212
-
213
- - [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) 和 [valle](https://arxiv.org/abs/2301.02111) 通过自回归式系统展示了非凡的 TTS 效果。
214
- - [fish-speech](https://github.com/fishaudio/fish-speech) 揭示了 GVQ 作为 LLM 建模的音频分词器的能力。
215
- - [vocos](https://github.com/gemelo-ai/vocos) vocos 被用作预训练声码器。
216
-
217
- ## 特别鸣谢
218
-
219
- - [wlu-audio lab](https://audio.westlake.edu.cn/) 对于早期算法实验的支持。
220
-
221
- ## 相关资源
222
-
223
- - [Awesome-ChatTTS](https://github.com/libukai/Awesome-ChatTTS) 一个 ChatTTS 的资源汇总列表。
224
-
225
- ## 贡献者列表
226
-
227
- [![contributors](https://contrib.rocks/image?repo=2noise/ChatTTS)](https://github.com/2noise/ChatTTS/graphs/contributors)
228
-
229
- ## 项目浏览量
230
-
231
- <div align="center">
232
-
233
- ![counter](https://counter.seku.su/cmoe?name=chattts&theme=mbs)
234
-
235
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/docs/jp/README.md DELETED
@@ -1,132 +0,0 @@
1
- # ChatTTS
2
- > [!NOTE]
3
- > 以下の内容は最新情報ではない可能性がありますのでご了承ください。全ての内容は英語版に基準することになります。
4
-
5
- [![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
6
-
7
- [**English**](../../README.md) | [**简体中文**](../cn/README.md) | **日本語** | [**Русский**](../ru/README.md)
8
-
9
- ChatTTSは、LLMアシスタントなどの対話シナリオ用に特別に設計されたテキストから音声へのモデルです。英語と中国語の両方をサポートしています。私たちのモデルは、中国語と英語で構成される100,000時間以上でトレーニングされています。**[HuggingFace](https://huggingface.co/2Noise/ChatTTS)**でオープンソース化されているバージョンは、40,000時間の事前トレーニングモデルで、SFTは行われていません。
10
-
11
- モデルやロードマップについての正式なお問い合わせは、**[email protected]**までご連絡ください。QQグループ:808364215に参加してディスカッションすることもできます。GitHubでの問題提起も歓迎します。
12
-
13
- ---
14
- ## ハイライト
15
- 1. **会話型TTS**: ChatTTSは対話ベースのタスクに最適化されており、自然で表現豊かな音声合成を実現します。複数の話者をサポートし、対話型の会話を容易にします。
16
- 2. **細かい制御**: このモデルは、笑い、一時停止、間投詞などの細かい韻律特徴を予測および制御することができます。
17
- 3. **より良い韻律**: ChatTTSは、韻律の面でほとんどのオープンソースTTSモデルを超えています。さらなる研究と開発をサポートするために、事前トレーニングされたモデルを提供しています。
18
-
19
- モデルの詳細な説明については、**[Bilibiliのビデオ](https://www.bilibili.com/video/BV1zn4y1o7iV)**を参照してください。
20
-
21
- ---
22
-
23
- ## 免責事項
24
-
25
- このリポジトリは学術目的のみのためです。教育および研究用途にのみ使用され、商業的または法的な目的には使用されません。著者は情報の正確性、完全性、または信頼性を保証しません。このリポジトリで使用される情報およびデータは、学術および研究目的のみのためのものです。データは公開されているソースから取得され、著者はデータに対する所有権または著作権を主張しません。
26
-
27
- ChatTTSは強力なテキストから音声へのシステムです。しかし、この技術を責任を持って、倫理的に利用することが非常に重要です。ChatTTSの使用を制限するために、40,000時間のモデルのトレーニング中に少量の高周波ノイズを追加し、MP3形式を使用して音質を可能な限り圧縮しました。これは、悪意のあるアクターが潜在的に犯罪目的で使用することを防ぐためです。同時に、私たちは内部的に検出モデルをトレーニングしており、将来的にオープンソース化する予定です。
28
-
29
- ---
30
- ## 使用方法
31
-
32
- <h4>基本的な使用方法</h4>
33
-
34
- ```python
35
- import ChatTTS
36
- from IPython.display import Audio
37
-
38
- chat = ChatTTS.Chat()
39
- chat.load_models(compile=False) # より良いパフォーマンスのためにTrueに設定
40
-
41
- texts = ["ここにテキストを入力してください",]
42
-
43
- wavs = chat.infer(texts, )
44
-
45
- torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
46
- ```
47
-
48
- <h4>高度な使用方法</h4>
49
-
50
- ```python
51
- ###################################
52
- # ガウス分布から話者をサンプリングします。
53
-
54
- rand_spk = chat.sample_random_speaker()
55
-
56
- params_infer_code = {
57
- 'spk_emb': rand_spk, # サンプリングされた話者を追加
58
- 'temperature': .3, # カスタム温度を使用
59
- 'top_P': 0.7, # トップPデコード
60
- 'top_K': 20, # トップKデコード
61
- }
62
-
63
- ###################################
64
- # 文レベルの手動制御のために。
65
-
66
- # 特別なトークンを生成するためにテキストにoral_(0-9)、laugh_(0-2)、break_(0-7)を使用します。
67
- params_refine_text = {
68
- 'prompt': '[oral_2][laugh_0][break_6]'
69
- }
70
-
71
- wav = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
72
-
73
- ###################################
74
- # 単語レベルの手動制御のために。
75
- text = 'あなたの好きな英語の食べ物は何ですか?[uv_break][laugh][lbreak]'
76
- wav = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
77
- torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
78
- ```
79
-
80
- <details open>
81
- <summary><h4>例:自己紹介</h4></summary>
82
-
83
- ```python
84
- inputs_jp = """
85
- ChatTTSは、対話アプリケーション用に設計されたテキストから音声へのモデルです。
86
- [uv_break]混合言語入力をサポートし[uv_break]、韻律要素[laugh]の正確な制御を提供します
87
- [uv_break]笑い[laugh]、[uv_break]一時停止、[uv_break]およびイントネーション。[uv_break]自然で表現豊かな音声を提供します
88
- [uv_break]したがって、自己責任でプロジェクトを責任を持って使用してください。[uv_break]
89
- """.replace('\n', '') # 英語はまだ実験的です。
90
-
91
- params_refine_text = {
92
- 'prompt': '[oral_2][laugh_0][break_4]'
93
- }
94
- audio_array_jp = chat.infer(inputs_jp, params_refine_text=params_refine_text)
95
- torchaudio.save("output3.wav", torch.from_numpy(audio_array_jp[0]), 24000)
96
- ```
97
- [男性話者](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
98
-
99
- [女性話者](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
100
- </details>
101
-
102
- ---
103
- ## ロードマップ
104
- - [x] 40k時間のベースモデルとspk_statsファイルをオープンソース化
105
- - [ ] VQエンコーダーとLoraトレーニングコードをオープンソース化
106
- - [ ] テキストをリファインせずにストリーミングオーディオ生成*
107
- - [ ] 複数の感情制御を備えた40k時間バージョンをオープンソース化
108
- - [ ] ChatTTS.cppもしかしたら?(PRや新しいリポジトリが歓迎されます。)
109
-
110
- ----
111
- ## FAQ
112
-
113
- ##### VRAMはどれくらい必要ですか?推論速度はどうですか?
114
- 30秒のオーディオクリップには、少なくとも4GBのGPUメモリが必要です。4090 GPUの場合、約7つの意味トークンに対応するオーディオを1秒あたり生成できます。リアルタイムファクター(RTF)は約0.3です。
115
-
116
- ##### モデルの安定性が十分でなく、複数の話者や音質が悪いという問題があります。
117
-
118
- これは、自己回帰モデル(barkおよびvalleの場合)で一般的に発生する問題です。一般的に避けるのは難しいです。複数のサンプルを試して、適切な結果を見つけることができます。
119
-
120
- ##### 笑い以外に何か制御できますか?他の感情を制御できますか?
121
-
122
- 現在リリースされているモデルでは、トークンレベルの制御ユニットは[laugh]、[uv_break]、および[lbreak]のみです。将来のバージョンでは、追加の感情制御機能を備えたモデルをオープンソース化する可能性があります。
123
-
124
- ---
125
- ## 謝辞
126
- - [bark](https://github.com/suno-ai/bark)、[XTTSv2](https://github.com/coqui-ai/TTS)、および[valle](https://arxiv.org/abs/2301.02111)は、自己回帰型システムによる顕著なTTS結果を示しました。
127
- - [fish-speech](https://github.com/fishaudio/fish-speech)は、LLMモデリングのためのオーディオトークナイザーとしてのGVQの能力を明らかにしました。
128
- - 事前トレーニングされたボコーダーとして使用される[vocos](https://github.com/gemelo-ai/vocos)。
129
-
130
- ---
131
- ## 特別感謝
132
- - 初期のアルゴリズム実験をサポートしてくれた[wlu-audio lab](https://audio.westlake.edu.cn/)。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/docs/ru/README.md DELETED
@@ -1,134 +0,0 @@
1
- # ChatTTS
2
- > [!NOTE]
3
- > Следующая информация может быть не самой последней, пожалуйста, смотрите английскую версию для актуальных данных.
4
-
5
- [![Huggingface](https://img.shields.io/badge/🤗%20-Models-yellow.svg?style=for-the-badge)](https://huggingface.co/2Noise/ChatTTS)
6
-
7
- [**English**](../../README.md) | [**简体中文**](../cn/README.md) | [**日本語**](../jp/README.md) | **Русский**
8
-
9
- ChatTTS - это модель преобразования текста в речь, специально разработанная для диалоговых сценариев, таких как помощник LLM. Она поддерживает как английский, так и китайский языки. Наша модель обучена на более чем 100 000 часах английского и китайского языков. Открытая версия на **[HuggingFace](https://huggingface.co/2Noise/ChatTTS)** - это предварительно обученная модель с 40 000 часами без SFT.
10
-
11
- Для официальных запросов о модели и плане развития, пожалуйста, свяжитесь с нами по адресу **[email protected]**. Вы можете присоединиться к нашей группе QQ: 808364215 для обсуждения. Добавление вопросов на GitHub также приветствуется.
12
-
13
- ---
14
- ## Особенности
15
- 1. **Диалоговый TTS**: ChatTTS оптимизирован для задач, основанных на диалогах, что позволяет создавать натуральную и выразительную речь. Он поддерживает несколько говорящих, облегчая интерактивные беседы.
16
- 2. **Тонкий контроль**: Модель может предсказывать и контролировать тонкие просодические особенности, включая смех, паузы и вставные слова.
17
- 3. **Лучшая просодия**: ChatTTS превосходит большинство открытых моделей TTS с точки зрения просодии. Мы предоставляем предварительно обученные модели для поддержки дальнейших исследований и разработок.
18
-
19
- Для подробного описания модели вы можете обратиться к **[видео на Bilibili](https://www.bilibili.com/video/BV1zn4y1o7iV)**
20
-
21
- ---
22
-
23
- ## Отказ от ответственности
24
-
25
- Этот репозиторий предназначен только для академических целей. Он предназначен для образовательного и исследовательского использования и не должен использоваться в коммерческих или юридических целях. Авторы не гарантируют точность, полноту или надежность информации. Информация и данные, использованные в этом репозитории, предназначены только для академических и исследовательских целей. Данные получены из общедоступных источников, и авторы не заявляют о каких-либо правах собственности или авторских правах на данные.
26
-
27
- ChatTTS - мощная система преобразования текста в речь. Однако очень важно использовать эту технологию ответственно и этично. Чтобы ограничить использование ChatTTS, мы добавили небольшое количество высокочастотного шума во время обучения модели на 40 000 часов и сжали качество аудио как можно больше с помощью формата MP3, чтобы предотвратить возможное использование злоумышленниками в преступных целях. В то же время мы внутренне обучили модель обнаружения и планируем открыть ее в будущем.
28
-
29
- ---
30
- ## Использование
31
-
32
- <h4>Базовое использование</h4>
33
-
34
- ```python
35
- import ChatTTS
36
- from IPython.display import Audio
37
-
38
- chat = ChatTTS.Chat()
39
- chat.load_models(compile=False) # Установите значение True для лучшей производительности
40
-
41
- texts = ["ВВЕДИТЕ ВАШ ТЕКСТ ЗДЕСЬ",]
42
-
43
- wavs = chat.infer(texts)
44
-
45
- torchaudio.save("output1.wav", torch.from_numpy(wavs[0]), 24000)
46
- ```
47
-
48
- <h4>Продвинутое использование</h4>
49
-
50
- ```python
51
- ###################################
52
- # Выборка говорящего из Гауссиана.
53
-
54
- rand_spk = chat.sample_random_speaker()
55
-
56
- params_infer_code = {
57
- 'spk_emb': rand_spk, # добавить выбранного говорящего
58
- 'temperature': .3, # использовать пользовательскую температуру
59
- 'top_P': 0.7, # декодирование top P
60
- 'top_K': 20, # декодирование top K
61
- }
62
-
63
- ###################################
64
- # Для контроля на уровне предложений.
65
-
66
- # используйте oral_(0-9), laugh_(0-2), break_(0-7)
67
- # для генерации специального токена в тексте для синтеза.
68
- params_refine_text = {
69
- 'prompt': '[oral_2][laugh_0][break_6]'
70
- }
71
-
72
- wav = chat.infer(texts, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
73
-
74
- ###################################
75
- # Для контроля на уровне слов.
76
- text = 'Какая ваша любимая английская еда?[uv_break]your favorite english food?[laugh][lbreak]'
77
- wav = chat.infer(text, skip_refine_text=True, params_refine_text=params_refine_text, params_infer_code=params_infer_code)
78
- torchaudio.save("output2.wav", torch.from_numpy(wavs[0]), 24000)
79
- ```
80
-
81
- <details open>
82
- <summary><h4>Пример: самопрезентация</h4></summary>
83
-
84
- ```python
85
- inputs_ru = """
86
- ChatTTS - это модель преобразования текста в речь, разработанная для диалоговых приложений.
87
- [uv_break]Она поддерживает смешанный языковой ввод [uv_break]и предлагает возможности множественных говорящих
88
- с точным контролем над просодическими элементами [laugh]как [uv_break]смех[laugh], [uv_break]паузы, [uv_break]и интонацию.
89
- [uv_break]Она обеспечивает натуральную и выразительную речь,[uv_break]поэтому, пожалуйста,
90
- [uv_break] используйте проект ответственно и на свой страх и риск.[uv_break]
91
- """.replace('\n', '') # Русский язык все еще находится в экспериментальной стадии.
92
-
93
- params_refine_text = {
94
- 'prompt': '[oral_2][laugh_0][break_4]'
95
- }
96
- audio_array_ru = chat.infer(inputs_ru, params_refine_text=params_refine_text)
97
- torchaudio.save("output3.wav", torch.from_numpy(audio_array_ru[0]), 24000)
98
- ```
99
- [мужской говорящий](https://github.com/2noise/ChatTTS/assets/130631963/e0f51251-db7f-4d39-a0e9-3e095bb65de1)
100
-
101
- [женский говорящий](https://github.com/2noise/ChatTTS/assets/130631963/f5dcdd01-1091-47c5-8241-c4f6aaaa8bbd)
102
- </details>
103
-
104
- ---
105
- ## План развития
106
- - [x] Открыть исходный код базовой модели на 40 тысяч часов и файла spk_stats
107
- - [ ] Открыть исходный код кодировщика VQ и кода обучения Lora
108
- - [ ] Потоковая генерация аудио без уточнения текста*
109
- - [ ] Открыть исходный код версии на 40 тысяч часов с управлением множественными эмоциями
110
- - [ ] ChatTTS.cpp возможно? (PR или новый репозиторий приветствуются.)
111
-
112
- ----
113
- ## Часто задаваемые вопросы
114
-
115
- ##### Сколько VRAM мне нужно? Как насчет скорости инференса?
116
- Для 30-секундного аудиоклипа требуется как минимум 4 ГБ памяти GPU. Для GPU 4090, он может генерировать аудио, соответствующее примерно 7 семантическим токенам в секунду. Фактор реального времени (RTF) составляет около 0.3.
117
-
118
- ##### Стабильность модели кажется недостаточно хорошей, возникают проблемы с множественными говорящими или плохим качеством аудио.
119
-
120
- Это проблема, которая обычно возникает с авторегрессивными моделями (для bark и valle). Это обычно трудно избежать. Можно попробовать несколько образцов, чтобы найти подходящий результат.
121
-
122
- ##### Помимо смеха, можем ли мы контролировать что-то еще? Можем ли мы контролировать другие эмоции?
123
-
124
- В текущей выпущенной модели единственными элементами управления на уровне токенов являются [laugh], [uv_break] и [lbreak]. В будущих версиях мы можем открыть модели с дополнительными возможностями контроля эмоций.
125
-
126
- ---
127
- ## Благодарности
128
- - [bark](https://github.com/suno-ai/bark), [XTTSv2](https://github.com/coqui-ai/TTS) и [valle](https://arxiv.org/abs/2301.02111) демонстрируют замечательный результат TTS с помощью системы авторегрессивного стиля.
129
- - [fish-speech](https://github.com/fishaudio/fish-speech) показывает возможности GVQ как аудио токенизатора для моделирования LLM.
130
- - [vocos](https://github.com/gemelo-ai/vocos), который используется в качестве предварительно обученного вокодера.
131
-
132
- ---
133
- ## Особая благодарность
134
- - [wlu-audio lab](https://audio.westlake.edu.cn/) за ранние эксперименты с алгоритмами.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/examples/cmd/run.py DELETED
@@ -1,58 +0,0 @@
1
- import os, sys
2
-
3
- if sys.platform == "darwin":
4
- os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
5
-
6
- now_dir = os.getcwd()
7
- sys.path.append(now_dir)
8
-
9
- from dotenv import load_dotenv
10
- load_dotenv("sha256.env")
11
-
12
- import wave
13
- import ChatTTS
14
- from IPython.display import Audio
15
-
16
- from tools.logger import get_logger
17
-
18
- logger = get_logger("Command")
19
-
20
- def save_wav_file(wav, index):
21
- wav_filename = f"output_audio_{index}.wav"
22
- # Convert numpy array to bytes and write to WAV file
23
- wav_bytes = (wav * 32768).astype('int16').tobytes()
24
- with wave.open(wav_filename, "wb") as wf:
25
- wf.setnchannels(1) # Mono channel
26
- wf.setsampwidth(2) # Sample width in bytes
27
- wf.setframerate(24000) # Sample rate in Hz
28
- wf.writeframes(wav_bytes)
29
- logger.info(f"Audio saved to {wav_filename}")
30
-
31
- def main():
32
- # Retrieve text from command line argument
33
- text_input = sys.argv[1] if len(sys.argv) > 1 else "<YOUR TEXT HERE>"
34
- logger.info("Received text input: %s", text_input)
35
-
36
- chat = ChatTTS.Chat(get_logger("ChatTTS"))
37
- logger.info("Initializing ChatTTS...")
38
- if chat.load_models():
39
- logger.info("Models loaded successfully.")
40
- else:
41
- logger.error("Models load failed.")
42
- sys.exit(1)
43
-
44
- texts = [text_input]
45
- logger.info("Text prepared for inference: %s", texts)
46
-
47
- wavs = chat.infer(texts, use_decoder=True)
48
- logger.info("Inference completed. Audio generation successful.")
49
- # Save each generated wav file to a local file
50
- for index, wav in enumerate(wavs):
51
- save_wav_file(wav, index)
52
-
53
- return Audio(wavs[0], rate=24_000, autoplay=True)
54
-
55
- if __name__ == "__main__":
56
- logger.info("Starting the TTS application...")
57
- main()
58
- logger.info("TTS application finished.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/examples/ipynb/colab.ipynb DELETED
@@ -1,407 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {
6
- "id": "xYJFXKP9xhQM"
7
- },
8
- "source": [
9
- "## Clone Repo"
10
- ]
11
- },
12
- {
13
- "cell_type": "code",
14
- "execution_count": null,
15
- "metadata": {
16
- "id": "hegwDOfffwzw"
17
- },
18
- "outputs": [],
19
- "source": [
20
- "!cd /content\n",
21
- "!rm -rf /content/ChatTTS\n",
22
- "!git clone https://github.com/2noise/ChatTTS.git\n",
23
- "!pip install -r /content/ChatTTS/requirements.txt\n",
24
- "!ldconfig /usr/lib64-nvidia"
25
- ]
26
- },
27
- {
28
- "cell_type": "markdown",
29
- "metadata": {
30
- "id": "zdzEFoknxqTH"
31
- },
32
- "source": [
33
- "## Import Libs"
34
- ]
35
- },
36
- {
37
- "cell_type": "code",
38
- "execution_count": null,
39
- "metadata": {
40
- "id": "lDSQ6Xf-bSre"
41
- },
42
- "outputs": [],
43
- "source": [
44
- "from dotenv import load_dotenv\n",
45
- "load_dotenv(\"ChatTTS/sha256.env\")\n",
46
- "\n",
47
- "import torch\n",
48
- "torch._dynamo.config.cache_size_limit = 64\n",
49
- "torch._dynamo.config.suppress_errors = True\n",
50
- "torch.set_float32_matmul_precision('high')\n",
51
- "\n",
52
- "from ChatTTS import ChatTTS\n",
53
- "from IPython.display import Audio"
54
- ]
55
- },
56
- {
57
- "cell_type": "markdown",
58
- "metadata": {
59
- "id": "vBzG5gxcbSrf"
60
- },
61
- "source": [
62
- "## Load Models"
63
- ]
64
- },
65
- {
66
- "cell_type": "code",
67
- "execution_count": null,
68
- "metadata": {
69
- "id": "e0QSkngRbSrg"
70
- },
71
- "outputs": [],
72
- "source": [
73
- "chat = ChatTTS.Chat()"
74
- ]
75
- },
76
- {
77
- "cell_type": "markdown",
78
- "metadata": {},
79
- "source": [
80
- "### Here are three choices for loading models:"
81
- ]
82
- },
83
- {
84
- "cell_type": "markdown",
85
- "metadata": {},
86
- "source": [
87
- "#### 1. Load models from Hugging Face:"
88
- ]
89
- },
90
- {
91
- "cell_type": "code",
92
- "execution_count": null,
93
- "metadata": {},
94
- "outputs": [],
95
- "source": [
96
- "# use force_redownload=True if the weights have been updated.\n",
97
- "chat.load_models(source='huggingface', force_redownload=True)"
98
- ]
99
- },
100
- {
101
- "cell_type": "markdown",
102
- "metadata": {},
103
- "source": [
104
- "#### 2. Load models from local directories 'asset' and 'config':"
105
- ]
106
- },
107
- {
108
- "cell_type": "code",
109
- "execution_count": null,
110
- "metadata": {},
111
- "outputs": [],
112
- "source": [
113
- "chat.load_models()\n",
114
- "# chat.load_models(source='local') same as above"
115
- ]
116
- },
117
- {
118
- "cell_type": "markdown",
119
- "metadata": {},
120
- "source": [
121
- "#### 3. Load models from a custom path:"
122
- ]
123
- },
124
- {
125
- "cell_type": "code",
126
- "execution_count": null,
127
- "metadata": {},
128
- "outputs": [],
129
- "source": [
130
- "# write the model path into custom_path\n",
131
- "chat.load_models(source='custom', custom_path='YOUR CUSTOM PATH')"
132
- ]
133
- },
134
- {
135
- "cell_type": "markdown",
136
- "metadata": {
137
- "id": "bAUs0rGQbSrh"
138
- },
139
- "source": [
140
- "## Inference"
141
- ]
142
- },
143
- {
144
- "cell_type": "markdown",
145
- "metadata": {
146
- "id": "NPZ2SFksbSrh"
147
- },
148
- "source": [
149
- "### Batch infer"
150
- ]
151
- },
152
- {
153
- "cell_type": "code",
154
- "execution_count": null,
155
- "metadata": {
156
- "id": "Su9FmUYAbSrh"
157
- },
158
- "outputs": [],
159
- "source": [
160
- "texts = [\"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\",]*3 \\\n",
161
- " + [\"我觉得像我们这些写程序的人,他,我觉得多多少少可能会对开源有一种情怀在吧我觉得开源是一个很好的形式。现在其实最先进的技术掌握在一些公司的手里的话,就他们并不会轻易的开放给所有的人用。\"]*3\n",
162
- "\n",
163
- "wavs = chat.infer(texts)"
164
- ]
165
- },
166
- {
167
- "cell_type": "code",
168
- "execution_count": null,
169
- "metadata": {
170
- "id": "YQRwB8lpbSri"
171
- },
172
- "outputs": [],
173
- "source": [
174
- "Audio(wavs[0], rate=24_000, autoplay=True)"
175
- ]
176
- },
177
- {
178
- "cell_type": "code",
179
- "execution_count": null,
180
- "metadata": {
181
- "id": "LuFG6m7AbSri"
182
- },
183
- "outputs": [],
184
- "source": [
185
- "Audio(wavs[3], rate=24_000, autoplay=True)"
186
- ]
187
- },
188
- {
189
- "cell_type": "markdown",
190
- "metadata": {
191
- "id": "oLhAGvkfbSrj"
192
- },
193
- "source": [
194
- "### Custom params"
195
- ]
196
- },
197
- {
198
- "cell_type": "code",
199
- "execution_count": null,
200
- "metadata": {
201
- "id": "kma0HBEBbSrj"
202
- },
203
- "outputs": [],
204
- "source": [
205
- "params_infer_code = {'prompt':'[speed_5]', 'temperature':.3}\n",
206
- "params_refine_text = {'prompt':'[oral_2][laugh_0][break_6]'}\n",
207
- "\n",
208
- "wav = chat.infer('四川美食可多了,有麻辣火锅、宫保鸡丁、麻婆豆腐、担担面、回锅肉、夫妻肺片等,每样都让人垂涎三尺。', \\\n",
209
- " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
210
- ]
211
- },
212
- {
213
- "cell_type": "code",
214
- "execution_count": null,
215
- "metadata": {
216
- "id": "Nl_mT9KpbSrj"
217
- },
218
- "outputs": [],
219
- "source": [
220
- "Audio(wav[0], rate=24_000, autoplay=True)"
221
- ]
222
- },
223
- {
224
- "cell_type": "markdown",
225
- "metadata": {
226
- "id": "JfAba-tTbSrk"
227
- },
228
- "source": [
229
- "### fix random speaker"
230
- ]
231
- },
232
- {
233
- "cell_type": "code",
234
- "execution_count": null,
235
- "metadata": {
236
- "id": "Qh7dcWrAbSrk"
237
- },
238
- "outputs": [],
239
- "source": [
240
- "rand_spk = chat.sample_random_speaker()\n",
241
- "params_infer_code = {'spk_emb' : rand_spk, }\n",
242
- "\n",
243
- "wav = chat.infer('四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。', \\\n",
244
- " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
245
- ]
246
- },
247
- {
248
- "cell_type": "code",
249
- "execution_count": null,
250
- "metadata": {
251
- "id": "0ljWDWzabSrk"
252
- },
253
- "outputs": [],
254
- "source": [
255
- "Audio(wav[0], rate=24_000, autoplay=True)"
256
- ]
257
- },
258
- {
259
- "cell_type": "markdown",
260
- "metadata": {
261
- "id": "u1q-BcUKbSrl"
262
- },
263
- "source": [
264
- "### Two stage control"
265
- ]
266
- },
267
- {
268
- "cell_type": "code",
269
- "execution_count": null,
270
- "metadata": {
271
- "id": "3hAAc0lJbSrl"
272
- },
273
- "outputs": [],
274
- "source": [
275
- "text = \"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\"\n",
276
- "refined_text = chat.infer(text, refine_text_only=True)\n",
277
- "refined_text"
278
- ]
279
- },
280
- {
281
- "cell_type": "code",
282
- "execution_count": null,
283
- "metadata": {
284
- "id": "0GVJxhd3BKQX"
285
- },
286
- "outputs": [],
287
- "source": [
288
- "wav = chat.infer(refined_text)"
289
- ]
290
- },
291
- {
292
- "cell_type": "code",
293
- "execution_count": null,
294
- "metadata": {
295
- "id": "ngyMht74BicY"
296
- },
297
- "outputs": [],
298
- "source": [
299
- "Audio(wav[0], rate=24_000, autoplay=True)"
300
- ]
301
- },
302
- {
303
- "cell_type": "code",
304
- "execution_count": null,
305
- "metadata": {
306
- "id": "R2WjuVrWbSrl"
307
- },
308
- "outputs": [],
309
- "source": [
310
- "text = 'so we found being competitive and collaborative [uv_break] was a huge way of staying [uv_break] motivated towards our goals, [uv_break] so [uv_break] one person to call [uv_break] when you fall off, [uv_break] one person who [uv_break] gets you back [uv_break] on then [uv_break] one person [uv_break] to actually do the activity with.'\n",
311
- "wav = chat.infer(text, skip_refine_text=True)"
312
- ]
313
- },
314
- {
315
- "cell_type": "code",
316
- "execution_count": null,
317
- "metadata": {
318
- "id": "71Y4pBdl-_Yd"
319
- },
320
- "outputs": [],
321
- "source": [
322
- "Audio(wav[0], rate=24_000, autoplay=True)"
323
- ]
324
- },
325
- {
326
- "cell_type": "markdown",
327
- "metadata": {
328
- "id": "GG5AMbQbbSrl"
329
- },
330
- "source": [
331
- "## LLM Call"
332
- ]
333
- },
334
- {
335
- "cell_type": "code",
336
- "execution_count": null,
337
- "metadata": {
338
- "id": "3rkfwc3UbSrl"
339
- },
340
- "outputs": [],
341
- "source": [
342
- "from ChatTTS.experimental.llm import llm_api\n",
343
- "\n",
344
- "API_KEY = ''\n",
345
- "client = llm_api(api_key=API_KEY,\n",
346
- " base_url=\"https://api.deepseek.com\",\n",
347
- " model=\"deepseek-chat\")"
348
- ]
349
- },
350
- {
351
- "cell_type": "code",
352
- "execution_count": null,
353
- "metadata": {
354
- "id": "TTkIsXozbSrm"
355
- },
356
- "outputs": [],
357
- "source": [
358
- "user_question = '四川有哪些好吃的美食呢?'\n",
359
- "text = client.call(user_question, prompt_version = 'deepseek')\n",
360
- "print(text)\n",
361
- "text = client.call(text, prompt_version = 'deepseek_TN')\n",
362
- "print(text)"
363
- ]
364
- },
365
- {
366
- "cell_type": "code",
367
- "execution_count": null,
368
- "metadata": {
369
- "id": "qNhCJG4VbSrm"
370
- },
371
- "outputs": [],
372
- "source": [
373
- "params_infer_code = {'spk_emb' : rand_spk, 'temperature':.3}\n",
374
- "\n",
375
- "wav = chat.infer(text, params_infer_code=params_infer_code)"
376
- ]
377
- }
378
- ],
379
- "metadata": {
380
- "accelerator": "GPU",
381
- "colab": {
382
- "collapsed_sections": [
383
- "bAUs0rGQbSrh"
384
- ],
385
- "gpuType": "T4",
386
- "provenance": []
387
- },
388
- "kernelspec": {
389
- "display_name": "Python 3",
390
- "name": "python3"
391
- },
392
- "language_info": {
393
- "codemirror_mode": {
394
- "name": "ipython",
395
- "version": 3
396
- },
397
- "file_extension": ".py",
398
- "mimetype": "text/x-python",
399
- "name": "python",
400
- "nbconvert_exporter": "python",
401
- "pygments_lexer": "ipython3",
402
- "version": "3.10.8"
403
- }
404
- },
405
- "nbformat": 4,
406
- "nbformat_minor": 0
407
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/examples/ipynb/example.ipynb DELETED
@@ -1,311 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "## Import packages"
8
- ]
9
- },
10
- {
11
- "cell_type": "code",
12
- "execution_count": null,
13
- "metadata": {},
14
- "outputs": [],
15
- "source": [
16
- "import os, sys\n",
17
- "\n",
18
- "if sys.platform == \"darwin\":\n",
19
- " os.environ[\"PYTORCH_ENABLE_MPS_FALLBACK\"] = \"1\"\n",
20
- "\n",
21
- "if not \"root_dir\" in globals():\n",
22
- " now_dir = os.getcwd() # skip examples/ipynb\n",
23
- " root_dir = os.path.join(now_dir, \"../../\")\n",
24
- " sys.path.append(root_dir)\n",
25
- " print(\"init root dir to\", root_dir)\n",
26
- "\n",
27
- "from dotenv import load_dotenv\n",
28
- "load_dotenv(os.path.join(root_dir, \"sha256.env\"))\n",
29
- "\n",
30
- "import torch\n",
31
- "torch._dynamo.config.cache_size_limit = 64\n",
32
- "torch._dynamo.config.suppress_errors = True\n",
33
- "torch.set_float32_matmul_precision('high')\n",
34
- "\n",
35
- "import ChatTTS\n",
36
- "from IPython.display import Audio"
37
- ]
38
- },
39
- {
40
- "cell_type": "markdown",
41
- "metadata": {},
42
- "source": [
43
- "## Load Models"
44
- ]
45
- },
46
- {
47
- "cell_type": "code",
48
- "execution_count": null,
49
- "metadata": {},
50
- "outputs": [],
51
- "source": [
52
- "os.chdir(root_dir)\n",
53
- "\n",
54
- "chat = ChatTTS.Chat()"
55
- ]
56
- },
57
- {
58
- "cell_type": "markdown",
59
- "metadata": {},
60
- "source": [
61
- "### Here are three choices for loading models:"
62
- ]
63
- },
64
- {
65
- "cell_type": "markdown",
66
- "metadata": {},
67
- "source": [
68
- "#### 1. Load models from Hugging Face:"
69
- ]
70
- },
71
- {
72
- "cell_type": "code",
73
- "execution_count": null,
74
- "metadata": {},
75
- "outputs": [],
76
- "source": [
77
- "# use force_redownload=True if the weights have been updated.\n",
78
- "chat.load_models(source='huggingface', force_redownload=True)"
79
- ]
80
- },
81
- {
82
- "cell_type": "markdown",
83
- "metadata": {},
84
- "source": [
85
- "#### 2. Load models from local directories 'asset' and 'config':"
86
- ]
87
- },
88
- {
89
- "cell_type": "code",
90
- "execution_count": null,
91
- "metadata": {},
92
- "outputs": [],
93
- "source": [
94
- "chat.load_models()\n",
95
- "# chat.load_models(source='local') same as above"
96
- ]
97
- },
98
- {
99
- "cell_type": "markdown",
100
- "metadata": {},
101
- "source": [
102
- "#### 3. Load models from a custom path:"
103
- ]
104
- },
105
- {
106
- "cell_type": "code",
107
- "execution_count": null,
108
- "metadata": {},
109
- "outputs": [],
110
- "source": [
111
- "# write the model path into custom_path\n",
112
- "chat.load_models(source='custom', custom_path='YOUR CUSTOM PATH')"
113
- ]
114
- },
115
- {
116
- "cell_type": "markdown",
117
- "metadata": {},
118
- "source": [
119
- "## Inference"
120
- ]
121
- },
122
- {
123
- "cell_type": "markdown",
124
- "metadata": {},
125
- "source": [
126
- "### Batch infer"
127
- ]
128
- },
129
- {
130
- "cell_type": "code",
131
- "execution_count": null,
132
- "metadata": {},
133
- "outputs": [],
134
- "source": [
135
- "texts = [\"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\",]*3 \\\n",
136
- " + [\"我觉得像我们这些写程序的人,他,我觉得多多少少可能会对开源有一种情怀在吧我觉得开源是一个很好的形式。现在其实最先进的技术掌握在一些公司的手里的话,就他们并不会轻易的开放给所有的人用。\"]*3 \n",
137
- "\n",
138
- "wavs = chat.infer(texts)"
139
- ]
140
- },
141
- {
142
- "cell_type": "code",
143
- "execution_count": null,
144
- "metadata": {},
145
- "outputs": [],
146
- "source": [
147
- "Audio(wavs[0], rate=24_000, autoplay=True)"
148
- ]
149
- },
150
- {
151
- "cell_type": "code",
152
- "execution_count": null,
153
- "metadata": {},
154
- "outputs": [],
155
- "source": [
156
- "Audio(wavs[3], rate=24_000, autoplay=True)"
157
- ]
158
- },
159
- {
160
- "cell_type": "markdown",
161
- "metadata": {},
162
- "source": [
163
- "### Custom params"
164
- ]
165
- },
166
- {
167
- "cell_type": "code",
168
- "execution_count": null,
169
- "metadata": {},
170
- "outputs": [],
171
- "source": [
172
- "params_infer_code = {'prompt':'[speed_5]', 'temperature':.3}\n",
173
- "params_refine_text = {'prompt':'[oral_2][laugh_0][break_6]'}\n",
174
- "\n",
175
- "wav = chat.infer('四川美食可多了,有麻辣火锅、宫保鸡丁、麻婆豆腐、担担面、回锅肉、夫妻肺片等,每样都让人垂涎三尺。', \\\n",
176
- " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
177
- ]
178
- },
179
- {
180
- "cell_type": "code",
181
- "execution_count": null,
182
- "metadata": {},
183
- "outputs": [],
184
- "source": [
185
- "Audio(wav[0], rate=24_000, autoplay=True)"
186
- ]
187
- },
188
- {
189
- "cell_type": "markdown",
190
- "metadata": {},
191
- "source": [
192
- "### Fix random speaker"
193
- ]
194
- },
195
- {
196
- "cell_type": "code",
197
- "execution_count": null,
198
- "metadata": {},
199
- "outputs": [],
200
- "source": [
201
- "rand_spk = chat.sample_random_speaker()\n",
202
- "params_infer_code = {'spk_emb' : rand_spk, }\n",
203
- "\n",
204
- "wav = chat.infer('四���美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。', \\\n",
205
- " params_refine_text=params_refine_text, params_infer_code=params_infer_code)"
206
- ]
207
- },
208
- {
209
- "cell_type": "code",
210
- "execution_count": null,
211
- "metadata": {},
212
- "outputs": [],
213
- "source": [
214
- "Audio(wav[0], rate=24_000, autoplay=True)"
215
- ]
216
- },
217
- {
218
- "cell_type": "markdown",
219
- "metadata": {},
220
- "source": [
221
- "### Two stage control"
222
- ]
223
- },
224
- {
225
- "cell_type": "code",
226
- "execution_count": null,
227
- "metadata": {},
228
- "outputs": [],
229
- "source": [
230
- "text = \"So we found being competitive and collaborative was a huge way of staying motivated towards our goals, so one person to call when you fall off, one person who gets you back on then one person to actually do the activity with.\"\n",
231
- "chat.infer(text, refine_text_only=True)"
232
- ]
233
- },
234
- {
235
- "cell_type": "code",
236
- "execution_count": null,
237
- "metadata": {},
238
- "outputs": [],
239
- "source": [
240
- "text = 'so we found being competitive and collaborative [uv_break] was a huge way of staying [uv_break] motivated towards our goals, [uv_break] so [uv_break] one person to call [uv_break] when you fall off, [uv_break] one person who [uv_break] gets you back [uv_break] on then [uv_break] one person [uv_break] to actually do the activity with.'\n",
241
- "wav = chat.infer(text, skip_refine_text=True)"
242
- ]
243
- },
244
- {
245
- "cell_type": "markdown",
246
- "metadata": {},
247
- "source": [
248
- "## LLM Call"
249
- ]
250
- },
251
- {
252
- "cell_type": "code",
253
- "execution_count": null,
254
- "metadata": {},
255
- "outputs": [],
256
- "source": [
257
- "from ChatTTS.experimental.llm import llm_api\n",
258
- "\n",
259
- "API_KEY = ''\n",
260
- "client = llm_api(api_key=API_KEY,\n",
261
- " base_url=\"https://api.deepseek.com\",\n",
262
- " model=\"deepseek-chat\")"
263
- ]
264
- },
265
- {
266
- "cell_type": "code",
267
- "execution_count": null,
268
- "metadata": {},
269
- "outputs": [],
270
- "source": [
271
- "user_question = '四川有哪些好吃的美食呢?'\n",
272
- "text = client.call(user_question, prompt_version = 'deepseek')\n",
273
- "print(text)\n",
274
- "text = client.call(text, prompt_version = 'deepseek_TN')\n",
275
- "print(text)"
276
- ]
277
- },
278
- {
279
- "cell_type": "code",
280
- "execution_count": null,
281
- "metadata": {},
282
- "outputs": [],
283
- "source": [
284
- "params_infer_code = {'spk_emb' : rand_spk, 'temperature':.3}\n",
285
- "\n",
286
- "wav = chat.infer(text, params_infer_code=params_infer_code)"
287
- ]
288
- }
289
- ],
290
- "metadata": {
291
- "kernelspec": {
292
- "display_name": "Python 3 (ipykernel)",
293
- "language": "python",
294
- "name": "python3"
295
- },
296
- "language_info": {
297
- "codemirror_mode": {
298
- "name": "ipython",
299
- "version": 3
300
- },
301
- "file_extension": ".py",
302
- "mimetype": "text/x-python",
303
- "name": "python",
304
- "nbconvert_exporter": "python",
305
- "pygments_lexer": "ipython3",
306
- "version": "3.9.6"
307
- }
308
- },
309
- "nbformat": 4,
310
- "nbformat_minor": 4
311
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/examples/web/funcs.py DELETED
@@ -1,100 +0,0 @@
1
- import random
2
-
3
- import torch
4
- import gradio as gr
5
- import numpy as np
6
-
7
- from tools.logger import get_logger
8
- logger = get_logger(" WebUI ")
9
-
10
- import ChatTTS
11
- chat = ChatTTS.Chat(get_logger("ChatTTS"))
12
-
13
- # 音色选项:用于预置合适的音色
14
- voices = {
15
- "默认": {"seed": 2},
16
- "音色1": {"seed": 1111},
17
- "音色2": {"seed": 2222},
18
- "音色3": {"seed": 3333},
19
- "音色4": {"seed": 4444},
20
- "音色5": {"seed": 5555},
21
- "音色6": {"seed": 6666},
22
- "音色7": {"seed": 7777},
23
- "音色8": {"seed": 8888},
24
- "音色9": {"seed": 9999},
25
- "音色10": {"seed": 11111},
26
- }
27
-
28
- def generate_seed():
29
- return gr.update(value=random.randint(1, 100000000))
30
-
31
- # 返回选择音色对应的seed
32
- def on_voice_change(vocie_selection):
33
- return voices.get(vocie_selection)['seed']
34
-
35
- def refine_text(text, audio_seed_input, text_seed_input, refine_text_flag):
36
- if not refine_text_flag:
37
- return text
38
-
39
- global chat
40
-
41
- torch.manual_seed(audio_seed_input)
42
- params_refine_text = {'prompt': '[oral_2][laugh_0][break_6]'}
43
-
44
- torch.manual_seed(text_seed_input)
45
-
46
- text = chat.infer(text,
47
- skip_refine_text=False,
48
- refine_text_only=True,
49
- params_refine_text=params_refine_text,
50
- )
51
- return text[0] if isinstance(text, list) else text
52
-
53
- def generate_audio(text, temperature, top_P, top_K, audio_seed_input, text_seed_input, stream):
54
- if not text: return None
55
-
56
- global chat
57
-
58
- torch.manual_seed(audio_seed_input)
59
- rand_spk = chat.sample_random_speaker()
60
- params_infer_code = {
61
- 'spk_emb': rand_spk,
62
- 'temperature': temperature,
63
- 'top_P': top_P,
64
- 'top_K': top_K,
65
- }
66
- torch.manual_seed(text_seed_input)
67
-
68
- wav = chat.infer(
69
- text,
70
- skip_refine_text=True,
71
- params_infer_code=params_infer_code,
72
- stream=stream,
73
- )
74
-
75
- if stream:
76
- for gen in wav:
77
- wavs = [np.array([[]])]
78
- wavs[0] = np.hstack([wavs[0], np.array(gen[0])])
79
- audio = wavs[0][0]
80
-
81
- # normalize
82
- am = np.abs(audio).max() * 32768
83
- if am > 32768:
84
- am = 32768 * 32768 / am
85
- np.multiply(audio, am, audio)
86
- audio = audio.astype(np.int16)
87
-
88
- yield 24000, audio
89
- return
90
-
91
- audio_data = np.array(wav[0]).flatten()
92
- # normalize
93
- am = np.abs(audio_data).max() * 32768
94
- if am > 32768:
95
- am = 32768 * 32768 / am
96
- np.multiply(audio_data, am, audio_data)
97
- audio_data = audio_data.astype(np.int16)
98
- sample_rate = 24000
99
-
100
- yield sample_rate, audio_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/examples/web/webui.py DELETED
@@ -1,115 +0,0 @@
1
- import os, sys
2
-
3
- if sys.platform == "darwin":
4
- os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
5
-
6
- now_dir = os.getcwd()
7
- sys.path.append(now_dir)
8
-
9
- import argparse
10
-
11
- import gradio as gr
12
-
13
- from dotenv import load_dotenv
14
- load_dotenv("sha256.env")
15
-
16
- from examples.web.funcs import *
17
-
18
- def main():
19
-
20
- with gr.Blocks() as demo:
21
- gr.Markdown("# ChatTTS WebUI")
22
- gr.Markdown("- **GitHub Repo**: https://github.com/2noise/ChatTTS")
23
- gr.Markdown("- **HuggingFace Repo**: https://huggingface.co/2Noise/ChatTTS")
24
-
25
- default_text = "四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。"
26
- text_input = gr.Textbox(label="Input Text", lines=4, placeholder="Please Input Text...", value=default_text)
27
-
28
- with gr.Row():
29
- refine_text_checkbox = gr.Checkbox(label="Refine text", value=True)
30
- temperature_slider = gr.Slider(minimum=0.00001, maximum=1.0, step=0.00001, value=0.3, label="Audio temperature", interactive=True)
31
- top_p_slider = gr.Slider(minimum=0.1, maximum=0.9, step=0.05, value=0.7, label="top_P", interactive=True)
32
- top_k_slider = gr.Slider(minimum=1, maximum=20, step=1, value=20, label="top_K", interactive=True)
33
-
34
- with gr.Row():
35
- voice_selection = gr.Dropdown(label="音色", choices=voices.keys(), value='默认')
36
- audio_seed_input = gr.Number(value=2, label="Audio Seed")
37
- generate_audio_seed = gr.Button("\U0001F3B2")
38
- text_seed_input = gr.Number(value=42, label="Text Seed")
39
- generate_text_seed = gr.Button("\U0001F3B2")
40
-
41
- with gr.Row():
42
- auto_play_checkbox = gr.Checkbox(label="Auto Play", value=False, scale=1)
43
- stream_mode_checkbox = gr.Checkbox(label="Stream Mode", value=False, scale=1)
44
- generate_button = gr.Button("Generate", scale=2)
45
-
46
- text_output = gr.Textbox(label="Output Text", interactive=False)
47
-
48
- # 使用Gradio的回调功能来更新数值输入框
49
- voice_selection.change(fn=on_voice_change, inputs=voice_selection, outputs=audio_seed_input)
50
-
51
- generate_audio_seed.click(generate_seed,
52
- inputs=[],
53
- outputs=audio_seed_input)
54
-
55
- generate_text_seed.click(generate_seed,
56
- inputs=[],
57
- outputs=text_seed_input)
58
-
59
- generate_button.click(fn=lambda: "", outputs=text_output)
60
- generate_button.click(refine_text,
61
- inputs=[text_input, audio_seed_input, text_seed_input, refine_text_checkbox],
62
- outputs=text_output)
63
-
64
- @gr.render(inputs=[auto_play_checkbox, stream_mode_checkbox])
65
- def make_audio(autoplay, stream):
66
- audio_output = gr.Audio(
67
- label="Output Audio",
68
- value=None,
69
- autoplay=autoplay,
70
- streaming=stream,
71
- interactive=False,
72
- show_label=True,
73
- )
74
- text_output.change(generate_audio,
75
- inputs=[text_output, temperature_slider, top_p_slider, top_k_slider, audio_seed_input, text_seed_input, stream_mode_checkbox],
76
- outputs=audio_output)
77
-
78
- gr.Examples(
79
- examples=[
80
- ["四川美食确实以辣闻名,但也有不辣的选择。比如甜水面、赖汤圆、蛋烘糕、叶儿粑等,这些小吃口味温和,甜而不腻,也很受欢迎。", 0.3, 0.7, 20, 2, 42, True],
81
- ["What is [uv_break]your favorite english food?[laugh][lbreak]", 0.5, 0.5, 10, 245, 531, True],
82
- ["chat T T S is a text to speech model designed for dialogue applications. [uv_break]it supports mixed language input [uv_break]and offers multi speaker capabilities with precise control over prosodic elements [laugh]like like [uv_break]laughter[laugh], [uv_break]pauses, [uv_break]and intonation. [uv_break]it delivers natural and expressive speech,[uv_break]so please[uv_break] use the project responsibly at your own risk.[uv_break]", 0.2, 0.6, 15, 67, 165, True],
83
- ],
84
- inputs=[text_input, temperature_slider, top_p_slider, top_k_slider, audio_seed_input, text_seed_input, refine_text_checkbox],
85
- )
86
-
87
- parser = argparse.ArgumentParser(description='ChatTTS demo Launch')
88
- parser.add_argument('--server_name', type=str, default='0.0.0.0', help='Server name')
89
- parser.add_argument('--server_port', type=int, default=8080, help='Server port')
90
- parser.add_argument('--root_path', type=str, default=None, help='Root Path')
91
- parser.add_argument('--custom_path', type=str, default=None, help='the custom model path')
92
- args = parser.parse_args()
93
-
94
- logger.info("loading ChatTTS model...")
95
-
96
- global chat
97
-
98
- if args.custom_path == None:
99
- ret = chat.load_models()
100
- else:
101
- logger.info('local model path: %s', args.custom_path)
102
- ret = chat.load_models('custom', custom_path=args.custom_path)
103
-
104
- if ret:
105
- logger.info("Models loaded successfully.")
106
- else:
107
- logger.error("Models load failed.")
108
- sys.exit(1)
109
-
110
-
111
- demo.launch(server_name=args.server_name, server_port=args.server_port, root_path=args.root_path, inbrowser=True)
112
-
113
-
114
- if __name__ == '__main__':
115
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/infer/api.py CHANGED
@@ -2,10 +2,7 @@
2
  import torch
3
  import torch.nn.functional as F
4
  from transformers.generation import TopKLogitsWarper, TopPLogitsWarper
5
-
6
  from ..utils.infer_utils import CustomRepetitionPenaltyLogitsProcessorRepeat
7
- from ..utils.io import del_all
8
- from ..model.gpt import GPT_warpper
9
 
10
  def infer_code(
11
  models,
@@ -17,42 +14,39 @@ def infer_code(
17
  repetition_penalty = 1.05,
18
  max_new_token = 2048,
19
  stream=False,
20
- device="cpu",
21
  **kwargs
22
  ):
23
-
24
- gpt: GPT_warpper = models['gpt']
25
-
26
  if not isinstance(text, list):
27
  text = [text]
28
 
29
  if not isinstance(temperature, list):
30
- temperature = [temperature] * gpt.num_vq
31
 
32
  if spk_emb is not None:
33
  text = [f'[Stts][spk_emb]{i}[Ptts]' for i in text]
34
  else:
35
  text = [f'[Stts][empty_spk]{i}[Ptts]' for i in text]
36
 
37
- text_token_tmp = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True)
38
- text_token = text_token_tmp.to(device)
39
- del text_token_tmp
40
- input_ids = text_token['input_ids'][...,None].expand(-1, -1, gpt.num_vq).to(gpt.device_gpt)
41
- text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=gpt.device_gpt)
42
-
43
- emb = gpt.get_emb(
44
- input_ids=input_ids,
45
- text_mask=text_mask,
46
- )
47
- del text_mask
48
 
 
49
  if spk_emb is not None:
50
- n = F.normalize(spk_emb.to(emb.dtype)[None].expand(len(text), -1), p=2.0, dim=1, eps=1e-12).to(gpt.device_gpt)
51
- emb[input_ids[..., 0] == models['tokenizer'].convert_tokens_to_ids('[spk_emb]')] = n
52
- del n
53
-
54
- num_code = int(gpt.emb_code[0].num_embeddings - 1)
55
-
56
  LogitsWarpers = []
57
  if top_P is not None:
58
  LogitsWarpers.append(TopPLogitsWarper(top_P, min_tokens_to_keep=3))
@@ -64,10 +58,10 @@ def infer_code(
64
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(\
65
  repetition_penalty, num_code, 16))
66
 
67
- result = gpt.generate(
68
- emb, input_ids,
69
  temperature = torch.tensor(temperature, device=device),
70
- attention_mask = text_token['attention_mask'],
71
  LogitsWarpers = LogitsWarpers,
72
  LogitsProcessors = LogitsProcessors,
73
  eos_token = num_code,
@@ -77,11 +71,6 @@ def infer_code(
77
  **kwargs
78
  )
79
 
80
- del_all(text_token)
81
- del emb, text_token, input_ids
82
- del_all(LogitsWarpers)
83
- del_all(LogitsProcessors)
84
-
85
  return result
86
 
87
 
@@ -94,12 +83,11 @@ def refine_text(
94
  repetition_penalty = 1.0,
95
  max_new_token = 384,
96
  prompt = '',
97
- device="cpu",
98
  **kwargs
99
  ):
100
-
101
- gpt: GPT_warpper = models['gpt']
102
-
103
  if not isinstance(text, list):
104
  text = [text]
105
 
@@ -109,7 +97,11 @@ def refine_text(
109
  text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
110
  text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
111
 
112
- input_ids = text_token['input_ids'][...,None].expand(-1, -1, gpt.num_vq)
 
 
 
 
113
 
114
  LogitsWarpers = []
115
  if top_P is not None:
@@ -120,17 +112,11 @@ def refine_text(
120
  LogitsProcessors = []
121
  if repetition_penalty is not None and repetition_penalty != 1:
122
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(repetition_penalty, len(models['tokenizer']), 16))
123
-
124
- emb = gpt.get_emb(
125
- input_ids=input_ids,
126
- text_mask=text_mask,
127
- )
128
- del text_mask
129
-
130
- result = gpt.generate(
131
- emb, input_ids,
132
  temperature = torch.tensor([temperature,], device=device),
133
- attention_mask = text_token['attention_mask'],
134
  LogitsWarpers = LogitsWarpers,
135
  LogitsProcessors = LogitsProcessors,
136
  eos_token = torch.tensor(models['tokenizer'].convert_tokens_to_ids('[Ebreak]'), device=device)[None],
@@ -139,10 +125,4 @@ def refine_text(
139
  stream = False,
140
  **kwargs
141
  )
142
-
143
- del_all(text_token)
144
- del emb, text_token, input_ids
145
- del_all(LogitsWarpers)
146
- del_all(LogitsProcessors)
147
-
148
  return next(result)
 
2
  import torch
3
  import torch.nn.functional as F
4
  from transformers.generation import TopKLogitsWarper, TopPLogitsWarper
 
5
  from ..utils.infer_utils import CustomRepetitionPenaltyLogitsProcessorRepeat
 
 
6
 
7
  def infer_code(
8
  models,
 
14
  repetition_penalty = 1.05,
15
  max_new_token = 2048,
16
  stream=False,
 
17
  **kwargs
18
  ):
19
+
20
+ device = next(models['gpt'].parameters()).device
21
+
22
  if not isinstance(text, list):
23
  text = [text]
24
 
25
  if not isinstance(temperature, list):
26
+ temperature = [temperature] * models['gpt'].num_vq
27
 
28
  if spk_emb is not None:
29
  text = [f'[Stts][spk_emb]{i}[Ptts]' for i in text]
30
  else:
31
  text = [f'[Stts][empty_spk]{i}[Ptts]' for i in text]
32
 
33
+ text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
34
+ input_ids = text_token['input_ids'][...,None].expand(-1, -1, models['gpt'].num_vq)
35
+ text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
36
+
37
+ inputs = {
38
+ 'input_ids': input_ids,
39
+ 'text_mask': text_mask,
40
+ 'attention_mask': text_token['attention_mask'],
41
+ }
 
 
42
 
43
+ emb = models['gpt'].get_emb(**inputs)
44
  if spk_emb is not None:
45
+ emb[inputs['input_ids'][..., 0] == models['tokenizer'].convert_tokens_to_ids('[spk_emb]')] = \
46
+ F.normalize(spk_emb.to(device).to(emb.dtype)[None].expand(len(text), -1), p=2.0, dim=1, eps=1e-12)
47
+
48
+ num_code = models['gpt'].emb_code[0].num_embeddings - 1
49
+
 
50
  LogitsWarpers = []
51
  if top_P is not None:
52
  LogitsWarpers.append(TopPLogitsWarper(top_P, min_tokens_to_keep=3))
 
58
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(\
59
  repetition_penalty, num_code, 16))
60
 
61
+ result = models['gpt'].generate(
62
+ emb, inputs['input_ids'],
63
  temperature = torch.tensor(temperature, device=device),
64
+ attention_mask = inputs['attention_mask'],
65
  LogitsWarpers = LogitsWarpers,
66
  LogitsProcessors = LogitsProcessors,
67
  eos_token = num_code,
 
71
  **kwargs
72
  )
73
 
 
 
 
 
 
74
  return result
75
 
76
 
 
83
  repetition_penalty = 1.0,
84
  max_new_token = 384,
85
  prompt = '',
 
86
  **kwargs
87
  ):
88
+
89
+ device = next(models['gpt'].parameters()).device
90
+
91
  if not isinstance(text, list):
92
  text = [text]
93
 
 
97
  text_token = models['tokenizer'](text, return_tensors='pt', add_special_tokens=False, padding=True).to(device)
98
  text_mask = torch.ones(text_token['input_ids'].shape, dtype=bool, device=device)
99
 
100
+ inputs = {
101
+ 'input_ids': text_token['input_ids'][...,None].expand(-1, -1, models['gpt'].num_vq),
102
+ 'text_mask': text_mask,
103
+ 'attention_mask': text_token['attention_mask'],
104
+ }
105
 
106
  LogitsWarpers = []
107
  if top_P is not None:
 
112
  LogitsProcessors = []
113
  if repetition_penalty is not None and repetition_penalty != 1:
114
  LogitsProcessors.append(CustomRepetitionPenaltyLogitsProcessorRepeat(repetition_penalty, len(models['tokenizer']), 16))
115
+
116
+ result = models['gpt'].generate(
117
+ models['gpt'].get_emb(**inputs), inputs['input_ids'],
 
 
 
 
 
 
118
  temperature = torch.tensor([temperature,], device=device),
119
+ attention_mask = inputs['attention_mask'],
120
  LogitsWarpers = LogitsWarpers,
121
  LogitsProcessors = LogitsProcessors,
122
  eos_token = torch.tensor(models['tokenizer'].convert_tokens_to_ids('[Ebreak]'), device=device)[None],
 
125
  stream = False,
126
  **kwargs
127
  )
 
 
 
 
 
 
128
  return next(result)
ChatTTS/model/dvae.py CHANGED
@@ -1,4 +1,5 @@
1
  import math
 
2
  from vector_quantize_pytorch import GroupedResidualFSQ
3
 
4
  import torch
@@ -65,32 +66,23 @@ class GFSQ(nn.Module):
65
  self.G = G
66
  self.R = R
67
 
68
- def _embed(self, x: torch.Tensor):
69
  if self.transpose:
70
  x = x.transpose(1,2)
71
- """
72
  x = rearrange(
73
  x, "b t (g r) -> g b t r", g = self.G, r = self.R,
74
- )
75
- """
76
- x.view(-1, self.G, self.R).permute(2, 0, 1, 3)
77
  feat = self.quantizer.get_output_from_indices(x)
78
  return feat.transpose(1,2) if self.transpose else feat
79
-
80
  def forward(self, x,):
81
  if self.transpose:
82
  x = x.transpose(1,2)
83
  feat, ind = self.quantizer(x)
84
- """
85
  ind = rearrange(
86
  ind, "g b t r ->b t (g r)",
87
- )
88
- """
89
- ind = ind.permute(1, 2, 0, 3).contiguous()
90
- ind = ind.view(ind.size(0), ind.size(1), -1)
91
- embed_onehot_tmp = F.one_hot(ind.long(), self.n_ind)
92
- embed_onehot = embed_onehot_tmp.to(x.dtype)
93
- del embed_onehot_tmp
94
  e_mean = torch.mean(embed_onehot, dim=[0,1])
95
  e_mean = e_mean / (e_mean.sum(dim=1) + self.eps).unsqueeze(1)
96
  perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + self.eps), dim=1))
 
1
  import math
2
+ from einops import rearrange
3
  from vector_quantize_pytorch import GroupedResidualFSQ
4
 
5
  import torch
 
66
  self.G = G
67
  self.R = R
68
 
69
+ def _embed(self, x):
70
  if self.transpose:
71
  x = x.transpose(1,2)
 
72
  x = rearrange(
73
  x, "b t (g r) -> g b t r", g = self.G, r = self.R,
74
+ )
 
 
75
  feat = self.quantizer.get_output_from_indices(x)
76
  return feat.transpose(1,2) if self.transpose else feat
77
+
78
  def forward(self, x,):
79
  if self.transpose:
80
  x = x.transpose(1,2)
81
  feat, ind = self.quantizer(x)
 
82
  ind = rearrange(
83
  ind, "g b t r ->b t (g r)",
84
+ )
85
+ embed_onehot = F.one_hot(ind.long(), self.n_ind).to(x.dtype)
 
 
 
 
 
86
  e_mean = torch.mean(embed_onehot, dim=[0,1])
87
  e_mean = e_mean / (e_mean.sum(dim=1) + self.eps).unsqueeze(1)
88
  perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + self.eps), dim=1))
ChatTTS/model/gpt.py CHANGED
@@ -2,10 +2,8 @@ import os
2
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
3
 
4
  import logging
5
- from typing import Union
6
-
7
-
8
  from tqdm import tqdm
 
9
  from transformers.cache_utils import Cache
10
 
11
  import torch
@@ -14,10 +12,8 @@ import torch.nn.functional as F
14
  import torch.nn.utils.parametrize as P
15
  from torch.nn.utils.parametrizations import weight_norm
16
  from transformers import LlamaModel, LlamaConfig
17
-
18
- from ..utils.io import del_all
19
-
20
-
21
  class LlamaMLP(nn.Module):
22
  def __init__(self, hidden_size, intermediate_size):
23
  super().__init__()
@@ -40,67 +36,40 @@ class GPT_warpper(nn.Module):
40
  num_audio_tokens,
41
  num_text_tokens,
42
  num_vq=4,
43
- device="cpu",
44
- logger=logging.getLogger(__name__)
45
  ):
46
  super().__init__()
47
 
48
- self.logger = logger
49
- self.device = device
50
- self.device_gpt = device if "mps" not in str(device) else "cpu"
51
- self.num_vq = num_vq
52
-
53
- self.gpt = self.build_model(gpt_config, self.device_gpt)
54
  self.model_dim = self.gpt.config.hidden_size
55
- self.emb_code = nn.ModuleList(
56
- [nn.Embedding(
57
- num_audio_tokens, self.model_dim, device=self.device_gpt,
58
- ) for _ in range(num_vq)],
59
- )
60
- self.emb_text = nn.Embedding(num_text_tokens, self.model_dim, device=self.device_gpt)
61
 
62
- self.head_text = weight_norm(
63
- nn.Linear(
64
- self.model_dim, num_text_tokens, bias=False, device=device,
65
- ),
66
- name='weight',
67
- )
68
- self.head_code = nn.ModuleList(
69
- [weight_norm(
70
- nn.Linear(
71
- self.model_dim, num_audio_tokens, bias=False, device=device,
72
- ),
73
- name='weight',
74
- ) for _ in range(self.num_vq)],
75
- )
76
 
77
- def build_model(self, config, device):
78
 
79
  configuration = LlamaConfig(**config)
80
  model = LlamaModel(configuration)
81
  del model.embed_tokens
82
 
83
- return model.to(device)
84
-
85
- def get_emb(self, input_ids, text_mask):
86
- print(f'get_emb gpt_device:{self.device_gpt}, device:{self.device},')
87
- emb_text = self.emb_text(input_ids[text_mask][:, 0].to(self.device_gpt))
88
-
89
- text_mask_inv = ~text_mask
90
- masked_input_ids = input_ids[text_mask_inv].to(self.device_gpt)
91
- del text_mask_inv
92
 
93
- emb_code = [self.emb_code[i](masked_input_ids[:, i]) for i in range(self.num_vq)]
 
 
94
  emb_code = torch.stack(emb_code, 2).sum(2)
95
-
96
  emb = torch.zeros((input_ids.shape[:-1])+(emb_text.shape[-1],), device=emb_text.device, dtype=emb_text.dtype)
97
  emb[text_mask] = emb_text
98
  emb[~text_mask] = emb_code.to(emb.dtype)
99
-
100
- del emb_text, emb_code
101
-
102
  return emb
103
-
104
  def prepare_inputs_for_generation(
105
  self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
106
  ):
@@ -188,7 +157,7 @@ class GPT_warpper(nn.Module):
188
  emb,
189
  inputs_ids,
190
  temperature,
191
- eos_token: Union[int, torch.Tensor],
192
  attention_mask = None,
193
  max_new_token = 2048,
194
  min_new_token = 0,
@@ -208,8 +177,8 @@ class GPT_warpper(nn.Module):
208
  start_idx, end_idx = inputs_ids.shape[1], torch.zeros(inputs_ids.shape[0], device=inputs_ids.device, dtype=torch.long)
209
  finish = torch.zeros(inputs_ids.shape[0], device=inputs_ids.device).bool()
210
 
211
- temperature = temperature.unsqueeze_(0).expand(inputs_ids.shape[0], -1).contiguous().view(-1, 1)
212
- # temperature = rearrange(temperature, "b n -> (b n) 1")
213
 
214
  attention_mask_cache = torch.ones((inputs_ids.shape[0], inputs_ids.shape[1]+max_new_token,), dtype=torch.bool, device=inputs_ids.device)
215
  if attention_mask is not None:
@@ -220,6 +189,7 @@ class GPT_warpper(nn.Module):
220
  past_key_values = None
221
 
222
  for i in range(max_new_token):
 
223
  model_input = self.prepare_inputs_for_generation(
224
  inputs_ids,
225
  past_key_values,
@@ -230,26 +200,17 @@ class GPT_warpper(nn.Module):
230
  if i == 0:
231
  model_input['inputs_embeds'] = emb
232
  else:
233
- inputs_ids_emb = model_input['input_ids'].to(self.device_gpt)
234
  if infer_text:
235
- model_input['inputs_embeds'] = self.emb_text(inputs_ids_emb[:,:,0])
236
  else:
237
- code_emb = [self.emb_code[i](inputs_ids_emb[:,:,i]) for i in range(self.num_vq)]
238
  model_input['inputs_embeds'] = torch.stack(code_emb, 3).sum(3)
239
- del inputs_ids_emb, model_input['input_ids']
240
-
241
- outputs = self.gpt.forward(
242
- attention_mask=model_input["attention_mask"].to(self.device_gpt),
243
- position_ids=model_input["position_ids"].to(self.device_gpt),
244
- past_key_values=model_input["past_key_values"],
245
- inputs_embeds=model_input['inputs_embeds'].to(self.device_gpt),
246
- use_cache=model_input['use_cache'],
247
- output_attentions=return_attn,
248
- cache_position=model_input['cache_position'].to(self.device_gpt),
249
- )
250
- del_all(model_input)
251
  attentions.append(outputs.attentions)
252
- hidden_states = outputs[0].to(self.device) # 🐻
253
  past_key_values = outputs.past_key_values
254
  del outputs
255
  if return_hidden:
@@ -264,14 +225,8 @@ class GPT_warpper(nn.Module):
264
  logits = logits[:, -1].float()
265
 
266
  if not infer_text:
267
- # logits = rearrange(logits, "b c n -> (b n) c")
268
- logits = logits.permute(0, 2, 1)
269
- logits = logits.reshape(-1, logits.size(2))
270
- # logits_token = rearrange(inputs_ids[:, start_idx:], "b c n -> (b n) c")
271
- inputs_ids_sliced = inputs_ids[:, start_idx:].permute(0, 2, 1)
272
- logits_token = inputs_ids_sliced.reshape(
273
- inputs_ids_sliced.size(0)*inputs_ids_sliced.size(1), -1,
274
- )
275
  else:
276
  logits_token = inputs_ids[:, start_idx:, 0]
277
 
@@ -292,11 +247,10 @@ class GPT_warpper(nn.Module):
292
 
293
  del logits
294
 
295
- idx_next = torch.multinomial(scores, num_samples=1).to(finish.device)
296
 
297
  if not infer_text:
298
- # idx_next = rearrange(idx_next, "(b n) 1 -> b n", n=self.num_vq)
299
- idx_next = idx_next.view(-1, self.num_vq)
300
  finish_or = (idx_next == eos_token).any(1)
301
  finish |= finish_or
302
  del finish_or
@@ -324,11 +278,9 @@ class GPT_warpper(nn.Module):
324
  'attentions': attentions,
325
  'hiddens':y_hiddens,
326
  }
327
-
328
  if finish.all():
329
  pbar.update(max_new_token-i-1)
330
  break
331
- pbar.update(1)
332
 
333
  inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
334
  inputs_ids = [i[:, 0] for i in inputs_ids] if infer_text else inputs_ids
 
2
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
3
 
4
  import logging
 
 
 
5
  from tqdm import tqdm
6
+ from einops import rearrange
7
  from transformers.cache_utils import Cache
8
 
9
  import torch
 
12
  import torch.nn.utils.parametrize as P
13
  from torch.nn.utils.parametrizations import weight_norm
14
  from transformers import LlamaModel, LlamaConfig
15
+
16
+
 
 
17
  class LlamaMLP(nn.Module):
18
  def __init__(self, hidden_size, intermediate_size):
19
  super().__init__()
 
36
  num_audio_tokens,
37
  num_text_tokens,
38
  num_vq=4,
 
 
39
  ):
40
  super().__init__()
41
 
42
+ self.logger = logging.getLogger(__name__)
43
+ self.gpt = self.build_model(gpt_config)
 
 
 
 
44
  self.model_dim = self.gpt.config.hidden_size
 
 
 
 
 
 
45
 
46
+ self.num_vq = num_vq
47
+ self.emb_code = nn.ModuleList([nn.Embedding(num_audio_tokens, self.model_dim) for i in range(self.num_vq)])
48
+ self.emb_text = nn.Embedding(num_text_tokens, self.model_dim)
49
+ self.head_text = weight_norm(nn.Linear(self.model_dim, num_text_tokens, bias=False), name='weight')
50
+ self.head_code = nn.ModuleList([weight_norm(nn.Linear(self.model_dim, num_audio_tokens, bias=False), name='weight') for i in range(self.num_vq)])
 
 
 
 
 
 
 
 
 
51
 
52
+ def build_model(self, config):
53
 
54
  configuration = LlamaConfig(**config)
55
  model = LlamaModel(configuration)
56
  del model.embed_tokens
57
 
58
+ return model
59
+
60
+ def get_emb(self, input_ids, text_mask, **kwargs):
 
 
 
 
 
 
61
 
62
+ emb_text = self.emb_text(input_ids[text_mask][:, 0])
63
+
64
+ emb_code = [self.emb_code[i](input_ids[~text_mask][:, i]) for i in range(self.num_vq)]
65
  emb_code = torch.stack(emb_code, 2).sum(2)
66
+
67
  emb = torch.zeros((input_ids.shape[:-1])+(emb_text.shape[-1],), device=emb_text.device, dtype=emb_text.dtype)
68
  emb[text_mask] = emb_text
69
  emb[~text_mask] = emb_code.to(emb.dtype)
70
+
 
 
71
  return emb
72
+
73
  def prepare_inputs_for_generation(
74
  self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
75
  ):
 
157
  emb,
158
  inputs_ids,
159
  temperature,
160
+ eos_token,
161
  attention_mask = None,
162
  max_new_token = 2048,
163
  min_new_token = 0,
 
177
  start_idx, end_idx = inputs_ids.shape[1], torch.zeros(inputs_ids.shape[0], device=inputs_ids.device, dtype=torch.long)
178
  finish = torch.zeros(inputs_ids.shape[0], device=inputs_ids.device).bool()
179
 
180
+ temperature = temperature[None].expand(inputs_ids.shape[0], -1)
181
+ temperature = rearrange(temperature, "b n -> (b n) 1")
182
 
183
  attention_mask_cache = torch.ones((inputs_ids.shape[0], inputs_ids.shape[1]+max_new_token,), dtype=torch.bool, device=inputs_ids.device)
184
  if attention_mask is not None:
 
189
  past_key_values = None
190
 
191
  for i in range(max_new_token):
192
+ pbar.update(1)
193
  model_input = self.prepare_inputs_for_generation(
194
  inputs_ids,
195
  past_key_values,
 
200
  if i == 0:
201
  model_input['inputs_embeds'] = emb
202
  else:
 
203
  if infer_text:
204
+ model_input['inputs_embeds'] = self.emb_text(model_input['input_ids'][:,:,0])
205
  else:
206
+ code_emb = [self.emb_code[i](model_input['input_ids'][:,:,i]) for i in range(self.num_vq)]
207
  model_input['inputs_embeds'] = torch.stack(code_emb, 3).sum(3)
208
+
209
+ model_input['input_ids'] = None
210
+ outputs = self.gpt.forward(**model_input, output_attentions=return_attn)
211
+ del model_input
 
 
 
 
 
 
 
 
212
  attentions.append(outputs.attentions)
213
+ hidden_states = outputs[0] # 🐻
214
  past_key_values = outputs.past_key_values
215
  del outputs
216
  if return_hidden:
 
225
  logits = logits[:, -1].float()
226
 
227
  if not infer_text:
228
+ logits = rearrange(logits, "b c n -> (b n) c")
229
+ logits_token = rearrange(inputs_ids[:, start_idx:], "b c n -> (b n) c")
 
 
 
 
 
 
230
  else:
231
  logits_token = inputs_ids[:, start_idx:, 0]
232
 
 
247
 
248
  del logits
249
 
250
+ idx_next = torch.multinomial(scores, num_samples=1)
251
 
252
  if not infer_text:
253
+ idx_next = rearrange(idx_next, "(b n) 1 -> b n", n=self.num_vq)
 
254
  finish_or = (idx_next == eos_token).any(1)
255
  finish |= finish_or
256
  del finish_or
 
278
  'attentions': attentions,
279
  'hiddens':y_hiddens,
280
  }
 
281
  if finish.all():
282
  pbar.update(max_new_token-i-1)
283
  break
 
284
 
285
  inputs_ids = [inputs_ids[idx, start_idx: start_idx+i] for idx, i in enumerate(end_idx.int())]
286
  inputs_ids = [i[:, 0] for i in inputs_ids] if infer_text else inputs_ids
ChatTTS/requirements.txt DELETED
@@ -1,13 +0,0 @@
1
- numpy<2.0.0
2
- omegaconf>=2.3.0
3
- torch>=2.1.0
4
- tqdm
5
- vector_quantize_pytorch
6
- transformers>=4.41.1
7
- vocos
8
- IPython
9
- gradio
10
- python-dotenv
11
- pynini==2.1.5; sys_platform == 'linux'
12
- WeTextProcessing; sys_platform == 'linux'
13
- nemo_text_processing; sys_platform == 'linux'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/setup.py DELETED
@@ -1,15 +0,0 @@
1
- from setuptools import setup, find_packages
2
- setup(name='chattts',
3
- version='0.0.1',
4
- author='2noise',
5
- url='https://github.com/2noise/ChatTTS',
6
- install_requires=['omegaconf>=2.3.0',
7
- 'torch>=2.1.0',
8
- 'tqdm',
9
- 'vector_quantize_pytorch',
10
- 'transformers>=4.41.1',
11
- 'vocos',
12
- 'IPython',
13
- ], # 定义依赖哪些模块
14
- packages=find_packages(), # 系统自动从当前目录开始找包
15
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/sha256.env DELETED
@@ -1,12 +0,0 @@
1
- sha256_asset_Decoder_pt = 9964e36e840f0e3a748c5f716fe6de6490d2135a5f5155f4a642d51860e2ec38
2
- sha256_asset_DVAE_pt = 613cb128adf89188c93ea5880ea0b798e66b1fe6186d0c535d99bcd87bfd6976
3
- sha256_asset_GPT_pt = d7d4ee6461ea097a2be23eb40d73fb94ad3b3d39cb64fbb50cb3357fd466cadb
4
- sha256_asset_spk_stat_pt = 3228d8a4cbbf349d107a1b76d2f47820865bd3c9928c4bdfe1cefd5c7071105f
5
- sha256_asset_tokenizer_pt = e911ae7c6a7c27953433f35c44227a67838fe229a1f428503bdb6cd3d1bcc69c
6
- sha256_asset_Vocos_pt = 09a670eda1c08b740013679c7a90ebb7f1a97646ea7673069a6838e6b51d6c58
7
-
8
- sha256_config_decoder_yaml = 0890ab719716b0ad8abcb9eba0a9bf52c59c2e45ddedbbbb5ed514ff87bff369
9
- sha256_config_dvae_yaml = 1b3a5aa0c6a314f766d4432ab36f84e882e29561648d837f71c04c7bea494fc6
10
- sha256_config_gpt_yaml = 0c3c7277b674094bdd00b63b18b18aa3156502101dbd03c7f802e0fcf26cff51
11
- sha256_config_path_yaml = 79829705c2d2a29b3f55e3b3f228bb81875e4e265211595fb50a73eb6434684b
12
- sha256_config_vocos_yaml = 1ca837ce790dd8b55bdd5a16c6af8f813926b9c9b48f2a4da305e7e9ff0c9b0c
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/tools/checksum/main.go DELETED
@@ -1,38 +0,0 @@
1
- package main
2
-
3
- import (
4
- "crypto/sha256"
5
- "encoding/hex"
6
- "fmt"
7
- "io"
8
- "os"
9
- )
10
-
11
- func main() {
12
- var buf [32]byte
13
- h := sha256.New()
14
- lst := make([]any, 0, 64)
15
- for _, fname := range files {
16
- f, err := os.Open(fname)
17
- if err != nil {
18
- panic(err)
19
- }
20
- _, err = io.Copy(h, f)
21
- if err != nil {
22
- panic(err)
23
- }
24
- s := hex.EncodeToString(h.Sum(buf[:0]))
25
- fmt.Println("sha256 of", fname, "=", s)
26
- lst = append(lst, s)
27
- h.Reset()
28
- f.Close()
29
- }
30
- f, err := os.Create("sha256.env")
31
- if err != nil {
32
- panic(err)
33
- }
34
- _, err = fmt.Fprintf(f, envtmpl, lst...)
35
- if err != nil {
36
- panic(err)
37
- }
38
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/tools/checksum/tmpl.go DELETED
@@ -1,30 +0,0 @@
1
- package main
2
-
3
- var files = [...]string{
4
- "asset/Decoder.pt",
5
- "asset/DVAE.pt",
6
- "asset/GPT.pt",
7
- "asset/spk_stat.pt",
8
- "asset/tokenizer.pt",
9
- "asset/Vocos.pt",
10
-
11
- "config/decoder.yaml",
12
- "config/dvae.yaml",
13
- "config/gpt.yaml",
14
- "config/path.yaml",
15
- "config/vocos.yaml",
16
- }
17
-
18
- const envtmpl = `sha256_asset_Decoder_pt = %s
19
- sha256_asset_DVAE_pt = %s
20
- sha256_asset_GPT_pt = %s
21
- sha256_asset_spk_stat_pt = %s
22
- sha256_asset_tokenizer_pt = %s
23
- sha256_asset_Vocos_pt = %s
24
-
25
- sha256_config_decoder_yaml = %s
26
- sha256_config_dvae_yaml = %s
27
- sha256_config_gpt_yaml = %s
28
- sha256_config_path_yaml = %s
29
- sha256_config_vocos_yaml = %s
30
- `
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/tools/logger/__init__.py DELETED
@@ -1 +0,0 @@
1
- from .log import get_logger
 
 
ChatTTS/tools/logger/log.py DELETED
@@ -1,53 +0,0 @@
1
- import platform
2
- import logging
3
- from datetime import datetime, timezone
4
-
5
- # from https://github.com/FloatTech/ZeroBot-Plugin/blob/c70766a989698452e60e5e48fb2f802a2444330d/console/console_windows.go#L89-L96
6
- colorCodePanic = "\x1b[1;31m"
7
- colorCodeFatal = "\x1b[1;31m"
8
- colorCodeError = "\x1b[31m"
9
- colorCodeWarn = "\x1b[33m"
10
- colorCodeInfo = "\x1b[37m"
11
- colorCodeDebug = "\x1b[32m"
12
- colorCodeTrace = "\x1b[36m"
13
- colorReset = "\x1b[0m"
14
-
15
- log_level_color_code = {
16
- logging.DEBUG: colorCodeDebug,
17
- logging.INFO: colorCodeInfo,
18
- logging.WARN: colorCodeWarn,
19
- logging.ERROR: colorCodeError,
20
- logging.FATAL: colorCodeFatal,
21
- }
22
-
23
- log_level_msg_str = {
24
- logging.DEBUG: "DEBU",
25
- logging.INFO: "INFO",
26
- logging.WARN: "WARN",
27
- logging.ERROR: "ERRO",
28
- logging.FATAL: "FATL",
29
- }
30
-
31
- class Formatter(logging.Formatter):
32
- def __init__(self, color=platform.system().lower() != "windows"):
33
- # https://stackoverflow.com/questions/2720319/python-figure-out-local-timezone
34
- self.tz = datetime.now(timezone.utc).astimezone().tzinfo
35
- self.color = color
36
-
37
- def format(self, record: logging.LogRecord):
38
- logstr = "[" + datetime.now(self.tz).strftime('%z %Y%m%d %H:%M:%S') + "] ["
39
- if self.color:
40
- logstr += log_level_color_code.get(record.levelno, colorCodeInfo)
41
- logstr += log_level_msg_str.get(record.levelno, record.levelname)
42
- if self.color:
43
- logstr += colorReset
44
- logstr += f"] {str(record.name)} | {str(record.msg)}"
45
- return logstr
46
-
47
- def get_logger(name: str, lv = logging.INFO):
48
- logger = logging.getLogger(name)
49
- syslog = logging.StreamHandler()
50
- syslog.setFormatter(Formatter())
51
- logger.setLevel(lv)
52
- logger.addHandler(syslog)
53
- return logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/utils/download.py CHANGED
@@ -3,8 +3,10 @@ from pathlib import Path
3
  import hashlib
4
  import requests
5
  from io import BytesIO
 
 
 
6
 
7
- from .log import logger
8
 
9
  def sha256(f) -> str:
10
  sha256_hash = hashlib.sha256()
 
3
  import hashlib
4
  import requests
5
  from io import BytesIO
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
 
 
10
 
11
  def sha256(f) -> str:
12
  sha256_hash = hashlib.sha256()
ChatTTS/utils/gpu_utils.py CHANGED
@@ -1,9 +1,9 @@
1
 
2
  import torch
3
-
4
- from .log import logger
5
 
6
  def select_device(min_memory=2048):
 
7
  if torch.cuda.is_available():
8
  available_gpus = []
9
  for i in range(torch.cuda.device_count()):
@@ -12,8 +12,6 @@ def select_device(min_memory=2048):
12
  available_gpus.append((i, free_memory))
13
  selected_gpu, max_free_memory = max(available_gpus, key=lambda x: x[1])
14
  device = torch.device(f'cuda:{selected_gpu}')
15
- logger.info(f'GPU found, using cuda:{selected_gpu}')
16
- print(f'GPU found, using cuda:{selected_gpu}')
17
  free_memory_mb = max_free_memory / (1024 * 1024)
18
  if free_memory_mb < min_memory:
19
  logger.warning(f'GPU {selected_gpu} has {round(free_memory_mb, 2)} MB memory left. Switching to CPU.')
 
1
 
2
  import torch
3
+ import logging
 
4
 
5
  def select_device(min_memory=2048):
6
+ logger = logging.getLogger(__name__)
7
  if torch.cuda.is_available():
8
  available_gpus = []
9
  for i in range(torch.cuda.device_count()):
 
12
  available_gpus.append((i, free_memory))
13
  selected_gpu, max_free_memory = max(available_gpus, key=lambda x: x[1])
14
  device = torch.device(f'cuda:{selected_gpu}')
 
 
15
  free_memory_mb = max_free_memory / (1024 * 1024)
16
  if free_memory_mb < min_memory:
17
  logger.warning(f'GPU {selected_gpu} has {round(free_memory_mb, 2)} MB memory left. Switching to CPU.')
ChatTTS/utils/infer_utils.py CHANGED
@@ -2,6 +2,7 @@
2
  import re
3
  import torch
4
  import torch.nn.functional as F
 
5
  import json
6
 
7
 
@@ -75,15 +76,12 @@ class HomophonesReplacer:
75
 
76
  def replace(self, text):
77
  result = []
78
- replaced_words = []
79
  for char in text:
80
  if char in self.homophones_map:
81
- repl_char = self.homophones_map[char]
82
- result.append(repl_char)
83
- replaced_words.append((char, repl_char))
84
  else:
85
  result.append(char)
86
- return ''.join(result), replaced_words
87
 
88
  def count_invalid_characters(s):
89
 
 
2
  import re
3
  import torch
4
  import torch.nn.functional as F
5
+ import os
6
  import json
7
 
8
 
 
76
 
77
  def replace(self, text):
78
  result = []
 
79
  for char in text:
80
  if char in self.homophones_map:
81
+ result.append(self.homophones_map[char])
 
 
82
  else:
83
  result.append(char)
84
+ return ''.join(result)
85
 
86
  def count_invalid_characters(s):
87
 
ChatTTS/utils/io.py DELETED
@@ -1,33 +0,0 @@
1
-
2
- import os
3
- import logging
4
- from typing import Union
5
-
6
- from .log import logger
7
-
8
- def get_latest_modified_file(directory):
9
-
10
- files = [os.path.join(directory, f) for f in os.listdir(directory)]
11
- if not files:
12
- logger.log(logging.WARNING, f'No files found in the directory: {directory}')
13
- return None
14
- latest_file = max(files, key=os.path.getmtime)
15
-
16
- return latest_file
17
-
18
- def del_all(d: Union[dict, list]):
19
- if isinstance(d, dict):
20
- lst = list(d.keys())
21
- for k in lst:
22
- x = d.pop(k)
23
- if isinstance(x, dict) or isinstance(x, list):
24
- del_all(x)
25
- del x
26
- return
27
- elif isinstance(d, list):
28
- while len(d):
29
- x = d.pop()
30
- if isinstance(x, dict) or isinstance(x, list):
31
- del_all(x)
32
- del x
33
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ChatTTS/utils/log.py DELETED
@@ -1,8 +0,0 @@
1
- import logging
2
- from pathlib import Path
3
-
4
- logger = logging.getLogger(Path(__file__).parent.name)
5
-
6
- def set_utils_logger(l: logging.Logger):
7
- global logger
8
- logger = l
 
 
 
 
 
 
 
 
 
abc CHANGED
@@ -1 +1 @@
1
- Subproject commit f809de7289f740bc8fe2bab6f65fa3c73cf448fd
 
1
+ Subproject commit e6412b1c8b51c56396c49efa008c6ff7afc7220c
setup.py CHANGED
@@ -6,6 +6,7 @@ setup(name='chattts',
6
  install_requires=['omegaconf>=2.3.0',
7
  'torch>=2.1.0',
8
  'tqdm',
 
9
  'vector_quantize_pytorch',
10
  'transformers>=4.41.1',
11
  'vocos',
 
6
  install_requires=['omegaconf>=2.3.0',
7
  'torch>=2.1.0',
8
  'tqdm',
9
+ 'einops',
10
  'vector_quantize_pytorch',
11
  'transformers>=4.41.1',
12
  'vocos',