kevinwang676 commited on
Commit
8a1292d
1 Parent(s): ecdffc4

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +160 -0
  2. Bert_VITS2_Guide.ipynb +323 -0
  3. LICENSE +674 -0
  4. README.md +16 -12
  5. README_zh.md +1 -0
  6. attentions.py +343 -0
  7. bert/chinese-roberta-wwm-ext-large/.gitattributes +9 -0
  8. bert/chinese-roberta-wwm-ext-large/README.md +64 -0
  9. bert/chinese-roberta-wwm-ext-large/added_tokens.json +1 -0
  10. bert/chinese-roberta-wwm-ext-large/config.json +28 -0
  11. bert/chinese-roberta-wwm-ext-large/special_tokens_map.json +1 -0
  12. bert/chinese-roberta-wwm-ext-large/tokenizer.json +0 -0
  13. bert/chinese-roberta-wwm-ext-large/tokenizer_config.json +1 -0
  14. bert/chinese-roberta-wwm-ext-large/vocab.txt +0 -0
  15. bert_gen.py +53 -0
  16. commons.py +161 -0
  17. configs/config.json +342 -0
  18. custom_character_voice/44100.txt +1 -0
  19. data_utils.py +332 -0
  20. filelists/esd.list +2 -0
  21. inference_webui.py +132 -0
  22. inference_webui.py.old +142 -0
  23. losses.py +61 -0
  24. mel_processing.py +112 -0
  25. models.py +707 -0
  26. modules.py +452 -0
  27. monotonic_align/__init__.py +19 -0
  28. monotonic_align/core.c +0 -0
  29. monotonic_align/core.pyx +42 -0
  30. monotonic_align/monotonic_align/monotonic_align +0 -0
  31. monotonic_align/setup.py +9 -0
  32. preprocess_text.py +69 -0
  33. requirements.txt +26 -0
  34. setup_ffmpeg.py +55 -0
  35. short_audio_transcribe.py +122 -0
  36. start.bat +2 -0
  37. text/__init__.py +28 -0
  38. text/chinese.py +193 -0
  39. text/chinese_bert.py +50 -0
  40. text/cleaner.py +27 -0
  41. text/cmudict.rep +0 -0
  42. text/cmudict_cache.pickle +3 -0
  43. text/english.py +138 -0
  44. text/english_bert_mock.py +5 -0
  45. text/japanese.py +104 -0
  46. text/opencpop-strict.txt +429 -0
  47. text/symbols.py +51 -0
  48. text/tone_sandhi.py +351 -0
  49. train_ms.py +402 -0
  50. transcribe_genshin.py +78 -0
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
Bert_VITS2_Guide.ipynb ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "authorship_tag": "ABX9TyP+PQNqeOew0Ap+hzVH7i8r",
8
+ "include_colab_link": true
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ }
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {
22
+ "id": "view-in-github",
23
+ "colab_type": "text"
24
+ },
25
+ "source": [
26
+ "<a href=\"https://colab.research.google.com/github/KevinWang676/Bert-VITS2-quick-start/blob/main/Bert_VITS2_Guide.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "markdown",
31
+ "source": [
32
+ "### 0. 如果使用AutoDL,请运行下载packages的加速代码:"
33
+ ],
34
+ "metadata": {
35
+ "id": "CGg4SV4ObQaT"
36
+ }
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "metadata": {
42
+ "id": "MgfAJzoHbK2-"
43
+ },
44
+ "outputs": [],
45
+ "source": [
46
+ "!source /etc/network_turbo\n",
47
+ "!python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "markdown",
52
+ "source": [
53
+ "### 1. 数据集重采样和标注"
54
+ ],
55
+ "metadata": {
56
+ "id": "sloMn00-bgxY"
57
+ }
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "source": [
62
+ "import subprocess\n",
63
+ "import random\n",
64
+ "import os\n",
65
+ "from pathlib import Path\n",
66
+ "import librosa\n",
67
+ "from scipy.io import wavfile\n",
68
+ "import numpy as np\n",
69
+ "import torch\n",
70
+ "import csv\n",
71
+ "import whisper\n",
72
+ "\n",
73
+ "a=\"linghua\" # 请在这里修改说话人的名字,目前只支持中文语音\n",
74
+ "\n",
75
+ "def split_long_audio(model, filepaths, save_dir=\"data_dir\", out_sr=44100):\n",
76
+ " if isinstance(filepaths, str):\n",
77
+ " filepaths = [filepaths]\n",
78
+ "\n",
79
+ " for file_idx, filepath in enumerate(filepaths):\n",
80
+ "\n",
81
+ " save_path = Path(save_dir)\n",
82
+ " save_path.mkdir(exist_ok=True, parents=True)\n",
83
+ "\n",
84
+ " print(f\"Transcribing file {file_idx}: '{filepath}' to segments...\")\n",
85
+ " result = model.transcribe(filepath, word_timestamps=True, task=\"transcribe\", beam_size=5, best_of=5)\n",
86
+ " segments = result['segments']\n",
87
+ "\n",
88
+ " wav, sr = librosa.load(filepath, sr=None, offset=0, duration=None, mono=True)\n",
89
+ " wav, _ = librosa.effects.trim(wav, top_db=20)\n",
90
+ " peak = np.abs(wav).max()\n",
91
+ " if peak > 1.0:\n",
92
+ " wav = 0.98 * wav / peak\n",
93
+ " wav2 = librosa.resample(wav, orig_sr=sr, target_sr=out_sr)\n",
94
+ " wav2 /= max(wav2.max(), -wav2.min())\n",
95
+ "\n",
96
+ " for i, seg in enumerate(segments):\n",
97
+ " start_time = seg['start']\n",
98
+ " end_time = seg['end']\n",
99
+ " wav_seg = wav2[int(start_time * out_sr):int(end_time * out_sr)]\n",
100
+ " wav_seg_name = f\"{a}_{i}.wav\" # 在上方可修改名字\n",
101
+ " out_fpath = save_path / wav_seg_name\n",
102
+ " wavfile.write(out_fpath, rate=out_sr, data=(wav_seg * np.iinfo(np.int16).max).astype(np.int16))"
103
+ ],
104
+ "metadata": {
105
+ "id": "LtLBGhGCbYYh"
106
+ },
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "source": [
113
+ "whisper_size = \"large\"\n",
114
+ "whisper_model = whisper.load_model(whisper_size)"
115
+ ],
116
+ "metadata": {
117
+ "id": "--wS7X95b--m"
118
+ },
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "source": [
125
+ "### 请将下方的**linghua.wav**修改成自己的.wav文件名,路径./custom_character_voice/**linghua**/也可以改为自己的角色名\n"
126
+ ],
127
+ "metadata": {
128
+ "id": "0wAE5HRXcCQ_"
129
+ }
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "source": [
134
+ "split_long_audio(whisper_model, \"./linghua.wav\", \"./custom_character_voice/linghua/\")"
135
+ ],
136
+ "metadata": {
137
+ "id": "3f7ljJhCcEbd"
138
+ },
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "source": [
145
+ "!python short_audio_transcribe.py --languages \"C\" --whisper_size large"
146
+ ],
147
+ "metadata": {
148
+ "id": "rBJDPe3ccVrP"
149
+ },
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "markdown",
155
+ "source": [
156
+ "#### 处理完成后,可以打开\"./filelists/short_character_anno.list\"文件进行微调"
157
+ ],
158
+ "metadata": {
159
+ "id": "4pesbcMjcikn"
160
+ }
161
+ },
162
+ {
163
+ "cell_type": "markdown",
164
+ "source": [
165
+ "### 2. 文本处理"
166
+ ],
167
+ "metadata": {
168
+ "id": "9pxo4KL-ceGI"
169
+ }
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "source": [
174
+ "!python preprocess_text.py"
175
+ ],
176
+ "metadata": {
177
+ "id": "_xfO2r_0cgCT"
178
+ },
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "markdown",
184
+ "source": [
185
+ "### 3. 运行bert_gen.py"
186
+ ],
187
+ "metadata": {
188
+ "id": "DoDs7lL6cu01"
189
+ }
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "source": [
194
+ "!python bert_gen.py"
195
+ ],
196
+ "metadata": {
197
+ "id": "jyiT28B3cxWX"
198
+ },
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "markdown",
204
+ "source": [
205
+ "### 4. 训练"
206
+ ],
207
+ "metadata": {
208
+ "id": "dHQPDFdbc04g"
209
+ }
210
+ },
211
+ {
212
+ "cell_type": "markdown",
213
+ "source": [
214
+ "#### 可以在\"./configs/config.json\"更改训练参数,包括epoch,学习率等"
215
+ ],
216
+ "metadata": {
217
+ "id": "gHNws-IUc6Sd"
218
+ }
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "source": [
223
+ "cd monotonic_align"
224
+ ],
225
+ "metadata": {
226
+ "id": "S56s0emH8BqN"
227
+ },
228
+ "execution_count": null,
229
+ "outputs": []
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "source": [
234
+ "!python setup.py build_ext --inplace"
235
+ ],
236
+ "metadata": {
237
+ "id": "6rLsyel-8KKc"
238
+ },
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "source": [
245
+ "cd .."
246
+ ],
247
+ "metadata": {
248
+ "id": "mUgA6ho2-XAN"
249
+ },
250
+ "execution_count": null,
251
+ "outputs": []
252
+ },
253
+ {
254
+ "cell_type": "markdown",
255
+ "source": [
256
+ "#### 若为首次训练,请运行:"
257
+ ],
258
+ "metadata": {
259
+ "id": "8vJ6VF__dCYW"
260
+ }
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "source": [
265
+ "!python train_ms.py -c ./configs/config.json"
266
+ ],
267
+ "metadata": {
268
+ "id": "iwHCWVijc5h6"
269
+ },
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "markdown",
275
+ "source": [
276
+ "#### 若为继续训练,请运行:"
277
+ ],
278
+ "metadata": {
279
+ "id": "skAGULw2dKXW"
280
+ }
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "source": [
285
+ "!python train_ms.py -c ./configs/config.json --cont"
286
+ ],
287
+ "metadata": {
288
+ "id": "Ru09Gmavc2t4"
289
+ },
290
+ "execution_count": null,
291
+ "outputs": []
292
+ },
293
+ {
294
+ "cell_type": "markdown",
295
+ "source": [
296
+ "### 5. 推理"
297
+ ],
298
+ "metadata": {
299
+ "id": "IinmucfadVLU"
300
+ }
301
+ },
302
+ {
303
+ "cell_type": "markdown",
304
+ "source": [
305
+ "#### 请将下方的**G_lastest.pth**修改为最新的模型文件,如**G_3400.pth**"
306
+ ],
307
+ "metadata": {
308
+ "id": "psBRLH_TdZDb"
309
+ }
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "source": [
314
+ "!python inference_webui.py --model_dir ./logs/OUTPUT_MODEL/G_latest.pth"
315
+ ],
316
+ "metadata": {
317
+ "id": "lOWVtUgMdUZa"
318
+ },
319
+ "execution_count": null,
320
+ "outputs": []
321
+ }
322
+ ]
323
+ }
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,13 +1,17 @@
1
- ---
2
- title: Bert VITS2
3
- emoji: 🏆
4
- colorFrom: blue
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 3.44.3
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Bert-VITS2-auto-preprocessing ⚡
2
+ ### [简体中文](https://github.com/KevinWang676/Bert-VITS2-quick-start/blob/main/README_zh.md)
 
 
 
 
 
 
 
 
 
3
 
4
+ This project is aimed at combining the features of [VITS-fast-fine-tuning](https://github.com/Plachtaa/VITS-fast-fine-tuning) with the original [Bert-VITS2](https://github.com/fishaudio/Bert-VITS2). Users can slice and label the uploaded audios automatically using the code we provide.
5
+
6
+ ```
7
+ git clone https://github.com/KevinWang676/Bert-VITS2-quick-start.git
8
+ cd Bert-VITS2-quick-start
9
+ pip install -r requirements.txt
10
+ ```
11
+
12
+ ## References
13
+ + [anyvoiceai/MassTTS](https://github.com/anyvoiceai/MassTTS)
14
+ + [jaywalnut310/vits](https://github.com/jaywalnut310/vits)
15
+ + [p0p4k/vits2_pytorch](https://github.com/p0p4k/vits2_pytorch)
16
+ + [svc-develop-team/so-vits-svc](https://github.com/svc-develop-team/so-vits-svc)
17
+ + [PaddlePaddle/PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech)
README_zh.md ADDED
@@ -0,0 +1 @@
 
 
1
+
attentions.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import commons
9
+ import modules
10
+ from torch.nn.utils import weight_norm, remove_weight_norm
11
+ class LayerNorm(nn.Module):
12
+ def __init__(self, channels, eps=1e-5):
13
+ super().__init__()
14
+ self.channels = channels
15
+ self.eps = eps
16
+
17
+ self.gamma = nn.Parameter(torch.ones(channels))
18
+ self.beta = nn.Parameter(torch.zeros(channels))
19
+
20
+ def forward(self, x):
21
+ x = x.transpose(1, -1)
22
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
23
+ return x.transpose(1, -1)
24
+
25
+
26
+
27
+ @torch.jit.script
28
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
29
+ n_channels_int = n_channels[0]
30
+ in_act = input_a + input_b
31
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
32
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
33
+ acts = t_act * s_act
34
+ return acts
35
+
36
+ class Encoder(nn.Module):
37
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, isflow = True, **kwargs):
38
+ super().__init__()
39
+ self.hidden_channels = hidden_channels
40
+ self.filter_channels = filter_channels
41
+ self.n_heads = n_heads
42
+ self.n_layers = n_layers
43
+ self.kernel_size = kernel_size
44
+ self.p_dropout = p_dropout
45
+ self.window_size = window_size
46
+ if isflow:
47
+ cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
48
+ self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
49
+ self.cond_layer = weight_norm(cond_layer, name='weight')
50
+ self.gin_channels = 256
51
+ self.cond_layer_idx = self.n_layers
52
+ if 'gin_channels' in kwargs:
53
+ self.gin_channels = kwargs['gin_channels']
54
+ if self.gin_channels != 0:
55
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
56
+ # vits2 says 3rd block, so idx is 2 by default
57
+ self.cond_layer_idx = kwargs['cond_layer_idx'] if 'cond_layer_idx' in kwargs else 2
58
+ print(self.gin_channels, self.cond_layer_idx)
59
+ assert self.cond_layer_idx < self.n_layers, 'cond_layer_idx should be less than n_layers'
60
+ self.drop = nn.Dropout(p_dropout)
61
+ self.attn_layers = nn.ModuleList()
62
+ self.norm_layers_1 = nn.ModuleList()
63
+ self.ffn_layers = nn.ModuleList()
64
+ self.norm_layers_2 = nn.ModuleList()
65
+ for i in range(self.n_layers):
66
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
67
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
68
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
69
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
70
+ def forward(self, x, x_mask, g=None):
71
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
72
+ x = x * x_mask
73
+ for i in range(self.n_layers):
74
+ if i == self.cond_layer_idx and g is not None:
75
+ g = self.spk_emb_linear(g.transpose(1, 2))
76
+ g = g.transpose(1, 2)
77
+ x = x + g
78
+ x = x * x_mask
79
+ y = self.attn_layers[i](x, x, attn_mask)
80
+ y = self.drop(y)
81
+ x = self.norm_layers_1[i](x + y)
82
+
83
+ y = self.ffn_layers[i](x, x_mask)
84
+ y = self.drop(y)
85
+ x = self.norm_layers_2[i](x + y)
86
+ x = x * x_mask
87
+ return x
88
+
89
+
90
+ class Decoder(nn.Module):
91
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
92
+ super().__init__()
93
+ self.hidden_channels = hidden_channels
94
+ self.filter_channels = filter_channels
95
+ self.n_heads = n_heads
96
+ self.n_layers = n_layers
97
+ self.kernel_size = kernel_size
98
+ self.p_dropout = p_dropout
99
+ self.proximal_bias = proximal_bias
100
+ self.proximal_init = proximal_init
101
+
102
+ self.drop = nn.Dropout(p_dropout)
103
+ self.self_attn_layers = nn.ModuleList()
104
+ self.norm_layers_0 = nn.ModuleList()
105
+ self.encdec_attn_layers = nn.ModuleList()
106
+ self.norm_layers_1 = nn.ModuleList()
107
+ self.ffn_layers = nn.ModuleList()
108
+ self.norm_layers_2 = nn.ModuleList()
109
+ for i in range(self.n_layers):
110
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
111
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
112
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
113
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
114
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
115
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
116
+
117
+ def forward(self, x, x_mask, h, h_mask):
118
+ """
119
+ x: decoder input
120
+ h: encoder output
121
+ """
122
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
123
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
124
+ x = x * x_mask
125
+ for i in range(self.n_layers):
126
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
127
+ y = self.drop(y)
128
+ x = self.norm_layers_0[i](x + y)
129
+
130
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
131
+ y = self.drop(y)
132
+ x = self.norm_layers_1[i](x + y)
133
+
134
+ y = self.ffn_layers[i](x, x_mask)
135
+ y = self.drop(y)
136
+ x = self.norm_layers_2[i](x + y)
137
+ x = x * x_mask
138
+ return x
139
+
140
+
141
+ class MultiHeadAttention(nn.Module):
142
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
143
+ super().__init__()
144
+ assert channels % n_heads == 0
145
+
146
+ self.channels = channels
147
+ self.out_channels = out_channels
148
+ self.n_heads = n_heads
149
+ self.p_dropout = p_dropout
150
+ self.window_size = window_size
151
+ self.heads_share = heads_share
152
+ self.block_length = block_length
153
+ self.proximal_bias = proximal_bias
154
+ self.proximal_init = proximal_init
155
+ self.attn = None
156
+
157
+ self.k_channels = channels // n_heads
158
+ self.conv_q = nn.Conv1d(channels, channels, 1)
159
+ self.conv_k = nn.Conv1d(channels, channels, 1)
160
+ self.conv_v = nn.Conv1d(channels, channels, 1)
161
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
162
+ self.drop = nn.Dropout(p_dropout)
163
+
164
+ if window_size is not None:
165
+ n_heads_rel = 1 if heads_share else n_heads
166
+ rel_stddev = self.k_channels**-0.5
167
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
168
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
169
+
170
+ nn.init.xavier_uniform_(self.conv_q.weight)
171
+ nn.init.xavier_uniform_(self.conv_k.weight)
172
+ nn.init.xavier_uniform_(self.conv_v.weight)
173
+ if proximal_init:
174
+ with torch.no_grad():
175
+ self.conv_k.weight.copy_(self.conv_q.weight)
176
+ self.conv_k.bias.copy_(self.conv_q.bias)
177
+
178
+ def forward(self, x, c, attn_mask=None):
179
+ q = self.conv_q(x)
180
+ k = self.conv_k(c)
181
+ v = self.conv_v(c)
182
+
183
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
184
+
185
+ x = self.conv_o(x)
186
+ return x
187
+
188
+ def attention(self, query, key, value, mask=None):
189
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
190
+ b, d, t_s, t_t = (*key.size(), query.size(2))
191
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
192
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
193
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
194
+
195
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
196
+ if self.window_size is not None:
197
+ assert t_s == t_t, "Relative attention is only available for self-attention."
198
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
199
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
200
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
201
+ scores = scores + scores_local
202
+ if self.proximal_bias:
203
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
204
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
205
+ if mask is not None:
206
+ scores = scores.masked_fill(mask == 0, -1e4)
207
+ if self.block_length is not None:
208
+ assert t_s == t_t, "Local attention is only available for self-attention."
209
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
210
+ scores = scores.masked_fill(block_mask == 0, -1e4)
211
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
212
+ p_attn = self.drop(p_attn)
213
+ output = torch.matmul(p_attn, value)
214
+ if self.window_size is not None:
215
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
216
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
217
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
218
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
219
+ return output, p_attn
220
+
221
+ def _matmul_with_relative_values(self, x, y):
222
+ """
223
+ x: [b, h, l, m]
224
+ y: [h or 1, m, d]
225
+ ret: [b, h, l, d]
226
+ """
227
+ ret = torch.matmul(x, y.unsqueeze(0))
228
+ return ret
229
+
230
+ def _matmul_with_relative_keys(self, x, y):
231
+ """
232
+ x: [b, h, l, d]
233
+ y: [h or 1, m, d]
234
+ ret: [b, h, l, m]
235
+ """
236
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
237
+ return ret
238
+
239
+ def _get_relative_embeddings(self, relative_embeddings, length):
240
+ max_relative_position = 2 * self.window_size + 1
241
+ # Pad first before slice to avoid using cond ops.
242
+ pad_length = max(length - (self.window_size + 1), 0)
243
+ slice_start_position = max((self.window_size + 1) - length, 0)
244
+ slice_end_position = slice_start_position + 2 * length - 1
245
+ if pad_length > 0:
246
+ padded_relative_embeddings = F.pad(
247
+ relative_embeddings,
248
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
249
+ else:
250
+ padded_relative_embeddings = relative_embeddings
251
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
252
+ return used_relative_embeddings
253
+
254
+ def _relative_position_to_absolute_position(self, x):
255
+ """
256
+ x: [b, h, l, 2*l-1]
257
+ ret: [b, h, l, l]
258
+ """
259
+ batch, heads, length, _ = x.size()
260
+ # Concat columns of pad to shift from relative to absolute indexing.
261
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
262
+
263
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
264
+ x_flat = x.view([batch, heads, length * 2 * length])
265
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
266
+
267
+ # Reshape and slice out the padded elements.
268
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
269
+ return x_final
270
+
271
+ def _absolute_position_to_relative_position(self, x):
272
+ """
273
+ x: [b, h, l, l]
274
+ ret: [b, h, l, 2*l-1]
275
+ """
276
+ batch, heads, length, _ = x.size()
277
+ # padd along column
278
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
279
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
280
+ # add 0's in the beginning that will skew the elements after reshape
281
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
282
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
283
+ return x_final
284
+
285
+ def _attention_bias_proximal(self, length):
286
+ """Bias for self-attention to encourage attention to close positions.
287
+ Args:
288
+ length: an integer scalar.
289
+ Returns:
290
+ a Tensor with shape [1, 1, length, length]
291
+ """
292
+ r = torch.arange(length, dtype=torch.float32)
293
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
294
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
295
+
296
+
297
+ class FFN(nn.Module):
298
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
299
+ super().__init__()
300
+ self.in_channels = in_channels
301
+ self.out_channels = out_channels
302
+ self.filter_channels = filter_channels
303
+ self.kernel_size = kernel_size
304
+ self.p_dropout = p_dropout
305
+ self.activation = activation
306
+ self.causal = causal
307
+
308
+ if causal:
309
+ self.padding = self._causal_padding
310
+ else:
311
+ self.padding = self._same_padding
312
+
313
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
314
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
315
+ self.drop = nn.Dropout(p_dropout)
316
+
317
+ def forward(self, x, x_mask):
318
+ x = self.conv_1(self.padding(x * x_mask))
319
+ if self.activation == "gelu":
320
+ x = x * torch.sigmoid(1.702 * x)
321
+ else:
322
+ x = torch.relu(x)
323
+ x = self.drop(x)
324
+ x = self.conv_2(self.padding(x * x_mask))
325
+ return x * x_mask
326
+
327
+ def _causal_padding(self, x):
328
+ if self.kernel_size == 1:
329
+ return x
330
+ pad_l = self.kernel_size - 1
331
+ pad_r = 0
332
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
333
+ x = F.pad(x, commons.convert_pad_shape(padding))
334
+ return x
335
+
336
+ def _same_padding(self, x):
337
+ if self.kernel_size == 1:
338
+ return x
339
+ pad_l = (self.kernel_size - 1) // 2
340
+ pad_r = self.kernel_size // 2
341
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
342
+ x = F.pad(x, commons.convert_pad_shape(padding))
343
+ return x
bert/chinese-roberta-wwm-ext-large/.gitattributes ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
2
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.h5 filter=lfs diff=lfs merge=lfs -text
5
+ *.tflite filter=lfs diff=lfs merge=lfs -text
6
+ *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.ot filter=lfs diff=lfs merge=lfs -text
8
+ *.onnx filter=lfs diff=lfs merge=lfs -text
9
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
bert/chinese-roberta-wwm-ext-large/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ tags:
5
+ - bert
6
+ license: "apache-2.0"
7
+ ---
8
+
9
+ How to download the files:
10
+ ```
11
+ curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash
12
+ sudo apt-get install git-lfs
13
+ git clone https://huggingface.co/hfl/chinese-roberta-wwm-ext-large
14
+ ```
15
+
16
+ # Please use 'Bert' related functions to load this model!
17
+
18
+ ## Chinese BERT with Whole Word Masking
19
+ For further accelerating Chinese natural language processing, we provide **Chinese pre-trained BERT with Whole Word Masking**.
20
+
21
+ **[Pre-Training with Whole Word Masking for Chinese BERT](https://arxiv.org/abs/1906.08101)**
22
+ Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang, Shijin Wang, Guoping Hu
23
+
24
+ This repository is developed based on:https://github.com/google-research/bert
25
+
26
+ You may also interested in,
27
+ - Chinese BERT series: https://github.com/ymcui/Chinese-BERT-wwm
28
+ - Chinese MacBERT: https://github.com/ymcui/MacBERT
29
+ - Chinese ELECTRA: https://github.com/ymcui/Chinese-ELECTRA
30
+ - Chinese XLNet: https://github.com/ymcui/Chinese-XLNet
31
+ - Knowledge Distillation Toolkit - TextBrewer: https://github.com/airaria/TextBrewer
32
+
33
+ More resources by HFL: https://github.com/ymcui/HFL-Anthology
34
+
35
+ ## Citation
36
+ If you find the technical report or resource is useful, please cite the following technical report in your paper.
37
+ - Primary: https://arxiv.org/abs/2004.13922
38
+ ```
39
+ @inproceedings{cui-etal-2020-revisiting,
40
+ title = "Revisiting Pre-Trained Models for {C}hinese Natural Language Processing",
41
+ author = "Cui, Yiming and
42
+ Che, Wanxiang and
43
+ Liu, Ting and
44
+ Qin, Bing and
45
+ Wang, Shijin and
46
+ Hu, Guoping",
47
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings",
48
+ month = nov,
49
+ year = "2020",
50
+ address = "Online",
51
+ publisher = "Association for Computational Linguistics",
52
+ url = "https://www.aclweb.org/anthology/2020.findings-emnlp.58",
53
+ pages = "657--668",
54
+ }
55
+ ```
56
+ - Secondary: https://arxiv.org/abs/1906.08101
57
+ ```
58
+ @article{chinese-bert-wwm,
59
+ title={Pre-Training with Whole Word Masking for Chinese BERT},
60
+ author={Cui, Yiming and Che, Wanxiang and Liu, Ting and Qin, Bing and Yang, Ziqing and Wang, Shijin and Hu, Guoping},
61
+ journal={arXiv preprint arXiv:1906.08101},
62
+ year={2019}
63
+ }
64
+ ```
bert/chinese-roberta-wwm-ext-large/added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
bert/chinese-roberta-wwm-ext-large/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "bos_token_id": 0,
7
+ "directionality": "bidi",
8
+ "eos_token_id": 2,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-12,
15
+ "max_position_embeddings": 512,
16
+ "model_type": "bert",
17
+ "num_attention_heads": 16,
18
+ "num_hidden_layers": 24,
19
+ "output_past": true,
20
+ "pad_token_id": 0,
21
+ "pooler_fc_size": 768,
22
+ "pooler_num_attention_heads": 12,
23
+ "pooler_num_fc_layers": 3,
24
+ "pooler_size_per_head": 128,
25
+ "pooler_type": "first_token_transform",
26
+ "type_vocab_size": 2,
27
+ "vocab_size": 21128
28
+ }
bert/chinese-roberta-wwm-ext-large/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
bert/chinese-roberta-wwm-ext-large/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
bert/chinese-roberta-wwm-ext-large/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"init_inputs": []}
bert/chinese-roberta-wwm-ext-large/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert_gen.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.utils.data import DataLoader
3
+ from multiprocessing import Pool
4
+ import commons
5
+ import utils
6
+ from data_utils import TextAudioSpeakerLoader, TextAudioSpeakerCollate
7
+ from tqdm import tqdm
8
+ import warnings
9
+
10
+ from text import cleaned_text_to_sequence, get_bert
11
+
12
+ config_path = 'configs/config.json'
13
+ hps = utils.get_hparams_from_file(config_path)
14
+
15
+ def process_line(line):
16
+ _id, spk, language_str, text, phones, tone, word2ph = line.strip().split("|")
17
+ phone = phones.split(" ")
18
+ tone = [int(i) for i in tone.split(" ")]
19
+ word2ph = [int(i) for i in word2ph.split(" ")]
20
+ w2pho = [i for i in word2ph]
21
+ word2ph = [i for i in word2ph]
22
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
23
+
24
+ if hps.data.add_blank:
25
+ phone = commons.intersperse(phone, 0)
26
+ tone = commons.intersperse(tone, 0)
27
+ language = commons.intersperse(language, 0)
28
+ for i in range(len(word2ph)):
29
+ word2ph[i] = word2ph[i] * 2
30
+ word2ph[0] += 1
31
+ wav_path = f'{_id}'
32
+
33
+ bert_path = wav_path.replace(".wav", ".bert.pt")
34
+ try:
35
+ bert = torch.load(bert_path)
36
+ assert bert.shape[-1] == len(phone)
37
+ except:
38
+ bert = get_bert(text, word2ph, language_str)
39
+ assert bert.shape[-1] == len(phone)
40
+ torch.save(bert, bert_path)
41
+
42
+
43
+ if __name__ == '__main__':
44
+ lines = []
45
+ with open(hps.data.training_files, encoding='utf-8' ) as f:
46
+ lines.extend(f.readlines())
47
+
48
+ # with open(hps.data.validation_files, encoding='utf-8' ) as f:
49
+ # lines.extend(f.readlines())
50
+
51
+ with Pool(processes=2) as pool: #A100 40GB suitable config,if coom,please decrease the processess number.
52
+ for _ in tqdm(pool.imap_unordered(process_line, lines)):
53
+ pass
commons.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+
8
+ def init_weights(m, mean=0.0, std=0.01):
9
+ classname = m.__class__.__name__
10
+ if classname.find("Conv") != -1:
11
+ m.weight.data.normal_(mean, std)
12
+
13
+
14
+ def get_padding(kernel_size, dilation=1):
15
+ return int((kernel_size*dilation - dilation)/2)
16
+
17
+
18
+ def convert_pad_shape(pad_shape):
19
+ l = pad_shape[::-1]
20
+ pad_shape = [item for sublist in l for item in sublist]
21
+ return pad_shape
22
+
23
+
24
+ def intersperse(lst, item):
25
+ result = [item] * (len(lst) * 2 + 1)
26
+ result[1::2] = lst
27
+ return result
28
+
29
+
30
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
31
+ """KL(P||Q)"""
32
+ kl = (logs_q - logs_p) - 0.5
33
+ kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
34
+ return kl
35
+
36
+
37
+ def rand_gumbel(shape):
38
+ """Sample from the Gumbel distribution, protect from overflows."""
39
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
40
+ return -torch.log(-torch.log(uniform_samples))
41
+
42
+
43
+ def rand_gumbel_like(x):
44
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
45
+ return g
46
+
47
+
48
+ def slice_segments(x, ids_str, segment_size=4):
49
+ ret = torch.zeros_like(x[:, :, :segment_size])
50
+ for i in range(x.size(0)):
51
+ idx_str = ids_str[i]
52
+ idx_end = idx_str + segment_size
53
+ ret[i] = x[i, :, idx_str:idx_end]
54
+ return ret
55
+
56
+
57
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
58
+ b, d, t = x.size()
59
+ if x_lengths is None:
60
+ x_lengths = t
61
+ ids_str_max = x_lengths - segment_size + 1
62
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
63
+ ret = slice_segments(x, ids_str, segment_size)
64
+ return ret, ids_str
65
+
66
+
67
+ def get_timing_signal_1d(
68
+ length, channels, min_timescale=1.0, max_timescale=1.0e4):
69
+ position = torch.arange(length, dtype=torch.float)
70
+ num_timescales = channels // 2
71
+ log_timescale_increment = (
72
+ math.log(float(max_timescale) / float(min_timescale)) /
73
+ (num_timescales - 1))
74
+ inv_timescales = min_timescale * torch.exp(
75
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
76
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
77
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
78
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
79
+ signal = signal.view(1, channels, length)
80
+ return signal
81
+
82
+
83
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
84
+ b, channels, length = x.size()
85
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
86
+ return x + signal.to(dtype=x.dtype, device=x.device)
87
+
88
+
89
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
90
+ b, channels, length = x.size()
91
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
92
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
93
+
94
+
95
+ def subsequent_mask(length):
96
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
97
+ return mask
98
+
99
+
100
+ @torch.jit.script
101
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
102
+ n_channels_int = n_channels[0]
103
+ in_act = input_a + input_b
104
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
105
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
106
+ acts = t_act * s_act
107
+ return acts
108
+
109
+
110
+ def convert_pad_shape(pad_shape):
111
+ l = pad_shape[::-1]
112
+ pad_shape = [item for sublist in l for item in sublist]
113
+ return pad_shape
114
+
115
+
116
+ def shift_1d(x):
117
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
118
+ return x
119
+
120
+
121
+ def sequence_mask(length, max_length=None):
122
+ if max_length is None:
123
+ max_length = length.max()
124
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
125
+ return x.unsqueeze(0) < length.unsqueeze(1)
126
+
127
+
128
+ def generate_path(duration, mask):
129
+ """
130
+ duration: [b, 1, t_x]
131
+ mask: [b, 1, t_y, t_x]
132
+ """
133
+ device = duration.device
134
+
135
+ b, _, t_y, t_x = mask.shape
136
+ cum_duration = torch.cumsum(duration, -1)
137
+
138
+ cum_duration_flat = cum_duration.view(b * t_x)
139
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
140
+ path = path.view(b, t_x, t_y)
141
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
142
+ path = path.unsqueeze(1).transpose(2,3) * mask
143
+ return path
144
+
145
+
146
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
147
+ if isinstance(parameters, torch.Tensor):
148
+ parameters = [parameters]
149
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
150
+ norm_type = float(norm_type)
151
+ if clip_value is not None:
152
+ clip_value = float(clip_value)
153
+
154
+ total_norm = 0
155
+ for p in parameters:
156
+ param_norm = p.grad.data.norm(norm_type)
157
+ total_norm += param_norm.item() ** norm_type
158
+ if clip_value is not None:
159
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
160
+ total_norm = total_norm ** (1. / norm_type)
161
+ return total_norm
configs/config.json ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 10,
4
+ "eval_interval": 100,
5
+ "seed": 52,
6
+ "epochs": 1000,
7
+ "learning_rate": 0.00015,
8
+ "betas": [
9
+ 0.8,
10
+ 0.99
11
+ ],
12
+ "eps": 1e-09,
13
+ "batch_size": 12,
14
+ "fp16_run": false,
15
+ "lr_decay": 0.999875,
16
+ "segment_size": 16384,
17
+ "init_lr_ratio": 1,
18
+ "warmup_epochs": 0,
19
+ "c_mel": 45,
20
+ "c_kl": 1.0
21
+ },
22
+ "data": {
23
+ "use_mel_posterior_encoder": false,
24
+ "training_files": "filelists/train.list",
25
+ "validation_files": "filelists/val.list",
26
+ "max_wav_value": 32768.0,
27
+ "sampling_rate": 44100,
28
+ "filter_length": 2048,
29
+ "hop_length": 512,
30
+ "win_length": 2048,
31
+ "n_mel_channels": 128,
32
+ "mel_fmin": 0.0,
33
+ "mel_fmax": null,
34
+ "add_blank": true,
35
+ "n_speakers": 256,
36
+ "cleaned_text": true,
37
+ "spk2id": {
38
+ "丹恒": 0,
39
+ "克拉拉": 1,
40
+ "穹": 2,
41
+ "「信使」": 3,
42
+ "史瓦罗": 4,
43
+ "彦卿": 5,
44
+ "晴霓": 6,
45
+ "杰帕德": 7,
46
+ "素裳": 8,
47
+ "绿芙蓉": 9,
48
+ "罗刹": 10,
49
+ "艾丝妲": 11,
50
+ "黑塔": 12,
51
+ "丹枢": 13,
52
+ "希露瓦": 14,
53
+ "白露": 15,
54
+ "费斯曼": 16,
55
+ "停云": 17,
56
+ "可可利亚": 18,
57
+ "景元": 19,
58
+ "螺丝咕姆": 20,
59
+ "青镞": 21,
60
+ "公输师傅": 22,
61
+ "卡芙卡": 23,
62
+ "大毫": 24,
63
+ "驭空": 25,
64
+ "半夏": 26,
65
+ "奥列格": 27,
66
+ "娜塔莎": 28,
67
+ "桑博": 29,
68
+ "瓦尔特": 30,
69
+ "阿兰": 31,
70
+ "伦纳德": 32,
71
+ "佩拉": 33,
72
+ "卡波特": 34,
73
+ "帕姆": 35,
74
+ "帕斯卡": 36,
75
+ "青雀": 37,
76
+ "三月七": 38,
77
+ "刃": 39,
78
+ "姬子": 40,
79
+ "布洛妮娅": 41,
80
+ "希儿": 42,
81
+ "星": 43,
82
+ "符玄": 44,
83
+ "虎克": 45,
84
+ "银狼": 46,
85
+ "镜流": 47,
86
+ "「博士」": 48,
87
+ "「大肉丸」": 49,
88
+ "九条裟罗": 50,
89
+ "佐西摩斯": 51,
90
+ "刻晴": 52,
91
+ "博易": 53,
92
+ "卡维": 54,
93
+ "可莉": 55,
94
+ "嘉玛": 56,
95
+ "埃舍尔": 57,
96
+ "塔杰·拉德卡尼": 58,
97
+ "大慈树王": 59,
98
+ "宵宫": 60,
99
+ "康纳": 61,
100
+ "影": 62,
101
+ "枫原万叶": 63,
102
+ "欧菲妮": 64,
103
+ "玛乔丽": 65,
104
+ "珊瑚": 66,
105
+ "田铁嘴": 67,
106
+ "砂糖": 68,
107
+ "神里绫华": 69,
108
+ "罗莎莉亚": 70,
109
+ "荒泷一斗": 71,
110
+ "莎拉": 72,
111
+ "迪希雅": 73,
112
+ "钟离": 74,
113
+ "阿圆": 75,
114
+ "阿娜耶": 76,
115
+ "阿拉夫": 77,
116
+ "雷泽": 78,
117
+ "香菱": 79,
118
+ "龙二": 80,
119
+ "「公子」": 81,
120
+ "「白老先生」": 82,
121
+ "优菈": 83,
122
+ "凯瑟琳": 84,
123
+ "哲平": 85,
124
+ "夏洛蒂": 86,
125
+ "安柏": 87,
126
+ "巴达维": 88,
127
+ "式大将": 89,
128
+ "斯坦利": 90,
129
+ "毗伽尔": 91,
130
+ "海妮耶": 92,
131
+ "爱德琳": 93,
132
+ "纳西妲": 94,
133
+ "老孟": 95,
134
+ "芙宁娜": 96,
135
+ "阿守": 97,
136
+ "阿祇": 98,
137
+ "丹吉尔": 99,
138
+ "丽莎": 100,
139
+ "五郎": 101,
140
+ "元太": 102,
141
+ "克列门特": 103,
142
+ "克罗索": 104,
143
+ "北斗": 105,
144
+ "埃勒曼": 106,
145
+ "天目十五": 107,
146
+ "奥兹": 108,
147
+ "恶龙": 109,
148
+ "早柚": 110,
149
+ "杜拉夫": 111,
150
+ "松浦": 112,
151
+ "柊千里": 113,
152
+ "甘雨": 114,
153
+ "石头": 115,
154
+ "纯水精灵?": 116,
155
+ "羽生田千鹤": 117,
156
+ "莱依拉": 118,
157
+ "菲谢尔": 119,
158
+ "言笑": 120,
159
+ "诺艾尔": 121,
160
+ "赛诺": 122,
161
+ "辛焱": 123,
162
+ "迪娜泽黛": 124,
163
+ "那维莱特": 125,
164
+ "八重神子": 126,
165
+ "凯亚": 127,
166
+ "吴船长": 128,
167
+ "埃德": 129,
168
+ "天叔": 130,
169
+ "女士": 131,
170
+ "恕筠": 132,
171
+ "提纳里": 133,
172
+ "派蒙": 134,
173
+ "流浪者": 135,
174
+ "深渊使徒": 136,
175
+ "玛格丽特": 137,
176
+ "珐露珊": 138,
177
+ "琴": 139,
178
+ "瑶瑶": 140,
179
+ "留云借风真君": 141,
180
+ "绮良良": 142,
181
+ "舒伯特": 143,
182
+ "荧": 144,
183
+ "莫娜": 145,
184
+ "行秋": 146,
185
+ "迈勒斯": 147,
186
+ "阿佩普": 148,
187
+ "鹿野奈奈": 149,
188
+ "七七": 150,
189
+ "伊迪娅": 151,
190
+ "博来": 152,
191
+ "坎蒂丝": 153,
192
+ "埃尔欣根": 154,
193
+ "埃泽": 155,
194
+ "塞琉斯": 156,
195
+ "夜兰": 157,
196
+ "常九爷": 158,
197
+ "悦": 159,
198
+ "戴因斯雷布": 160,
199
+ "笼钓瓶一心": 161,
200
+ "纳比尔": 162,
201
+ "胡桃": 163,
202
+ "艾尔海森": 164,
203
+ "艾莉丝": 165,
204
+ "菲米尼": 166,
205
+ "蒂玛乌斯": 167,
206
+ "迪奥娜": 168,
207
+ "阿晃": 169,
208
+ "阿洛瓦": 170,
209
+ "陆行岩本真蕈·元素生命": 171,
210
+ "雷电将军": 172,
211
+ "魈": 173,
212
+ "鹿野院平藏": 174,
213
+ "「女士」": 175,
214
+ "「散兵」": 176,
215
+ "凝光": 177,
216
+ "妮露": 178,
217
+ "娜维娅": 179,
218
+ "宛烟": 180,
219
+ "慧心": 181,
220
+ "托克": 182,
221
+ "托马": 183,
222
+ "掇星攫辰天君": 184,
223
+ "旁白": 185,
224
+ "浮游水蕈兽·元素生命": 186,
225
+ "烟绯": 187,
226
+ "玛塞勒": 188,
227
+ "百闻": 189,
228
+ "知易": 190,
229
+ "米卡": 191,
230
+ "西拉杰": 192,
231
+ "迪卢克": 193,
232
+ "重云": 194,
233
+ "阿扎尔": 195,
234
+ "霍夫曼": 196,
235
+ "上杉": 197,
236
+ "久利须": 198,
237
+ "嘉良": 199,
238
+ "回声海螺": 200,
239
+ "多莉": 201,
240
+ "安西": 202,
241
+ "德沃沙克": 203,
242
+ "拉赫曼": 204,
243
+ "林尼": 205,
244
+ "查尔斯": 206,
245
+ "深渊法师": 207,
246
+ "温迪": 208,
247
+ "爱贝尔": 209,
248
+ "珊瑚宫心海": 210,
249
+ "班尼特": 211,
250
+ "琳妮特": 212,
251
+ "申鹤": 213,
252
+ "神里绫人": 214,
253
+ "艾伯特": 215,
254
+ "萍姥姥": 216,
255
+ "萨赫哈蒂": 217,
256
+ "萨齐因": 218,
257
+ "阿尔卡米": 219,
258
+ "阿贝多": 220,
259
+ "anzai": 221,
260
+ "久岐忍": 222,
261
+ "九条镰治": 223,
262
+ "云堇": 224,
263
+ "伊利亚斯": 225,
264
+ "埃洛伊": 226,
265
+ "塞塔蕾": 227,
266
+ "拉齐": 228,
267
+ "昆钧": 229,
268
+ "柯莱": 230,
269
+ "沙扎曼": 231,
270
+ "海芭夏": 232,
271
+ "白术": 233,
272
+ "空": 234,
273
+ "艾文": 235,
274
+ "芭芭拉": 236,
275
+ "莫塞伊思": 237,
276
+ "莺儿": 238,
277
+ "达达利亚": 239,
278
+ "迈蒙": 240,
279
+ "长生": 241,
280
+ "阿巴图伊": 242,
281
+ "陆景和": 243,
282
+ "莫弈": 244,
283
+ "夏彦": 245,
284
+ "左然": 246,
285
+ "标贝": 247
286
+ }
287
+ },
288
+ "model": {
289
+ "use_spk_conditioned_encoder": true,
290
+ "use_noise_scaled_mas": true,
291
+ "use_mel_posterior_encoder": false,
292
+ "use_duration_discriminator": true,
293
+ "inter_channels": 192,
294
+ "hidden_channels": 192,
295
+ "filter_channels": 768,
296
+ "n_heads": 2,
297
+ "n_layers": 6,
298
+ "kernel_size": 3,
299
+ "p_dropout": 0.1,
300
+ "resblock": "1",
301
+ "resblock_kernel_sizes": [
302
+ 3,
303
+ 7,
304
+ 11
305
+ ],
306
+ "resblock_dilation_sizes": [
307
+ [
308
+ 1,
309
+ 3,
310
+ 5
311
+ ],
312
+ [
313
+ 1,
314
+ 3,
315
+ 5
316
+ ],
317
+ [
318
+ 1,
319
+ 3,
320
+ 5
321
+ ]
322
+ ],
323
+ "upsample_rates": [
324
+ 8,
325
+ 8,
326
+ 2,
327
+ 2,
328
+ 2
329
+ ],
330
+ "upsample_initial_channel": 512,
331
+ "upsample_kernel_sizes": [
332
+ 16,
333
+ 16,
334
+ 8,
335
+ 2,
336
+ 2
337
+ ],
338
+ "n_layers_q": 3,
339
+ "use_spectral_norm": false,
340
+ "gin_channels": 256
341
+ }
342
+ }
custom_character_voice/44100.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
data_utils.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+ import torchaudio
8
+ import commons
9
+ from mel_processing import spectrogram_torch, mel_spectrogram_torch, spec_to_mel_torch
10
+ from utils import load_wav_to_torch, load_filepaths_and_text
11
+ from text import cleaned_text_to_sequence, get_bert
12
+
13
+ """Multi speaker version"""
14
+
15
+
16
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
17
+ """
18
+ 1) loads audio, speaker_id, text pairs
19
+ 2) normalizes text and converts them to sequences of integers
20
+ 3) computes spectrograms from audio files.
21
+ """
22
+
23
+ def __init__(self, audiopaths_sid_text, hparams):
24
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
25
+ self.max_wav_value = hparams.max_wav_value
26
+ self.sampling_rate = hparams.sampling_rate
27
+ self.filter_length = hparams.filter_length
28
+ self.hop_length = hparams.hop_length
29
+ self.win_length = hparams.win_length
30
+ self.sampling_rate = hparams.sampling_rate
31
+ self.spk_map = hparams.spk2id
32
+ self.hparams = hparams
33
+
34
+ self.use_mel_spec_posterior = getattr(hparams, "use_mel_posterior_encoder", False)
35
+ if self.use_mel_spec_posterior:
36
+ self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
37
+
38
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
39
+
40
+ self.add_blank = hparams.add_blank
41
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
42
+ self.max_text_len = getattr(hparams, "max_text_len", 300)
43
+
44
+ random.seed(1234)
45
+ random.shuffle(self.audiopaths_sid_text)
46
+ self._filter()
47
+
48
+ def _filter(self):
49
+ """
50
+ Filter text & store spec lengths
51
+ """
52
+ # Store spectrogram lengths for Bucketing
53
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
54
+ # spec_length = wav_length // hop_length
55
+
56
+ audiopaths_sid_text_new = []
57
+ lengths = []
58
+ skipped = 0
59
+ for _id, spk, language, text, phones, tone, word2ph in self.audiopaths_sid_text:
60
+ audiopath = f'{_id}'
61
+ if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
62
+ phones = phones.split(" ")
63
+ tone = [int(i) for i in tone.split(" ")]
64
+ word2ph = [int(i) for i in word2ph.split(" ")]
65
+ audiopaths_sid_text_new.append([audiopath, spk, language, text, phones, tone, word2ph])
66
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
67
+ else:
68
+ skipped += 1
69
+ print("skipped: ", skipped, ", total: ", len(self.audiopaths_sid_text))
70
+ self.audiopaths_sid_text = audiopaths_sid_text_new
71
+ self.lengths = lengths
72
+
73
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
74
+ # separate filename, speaker_id and text
75
+ audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
76
+
77
+ bert, phones, tone, language = self.get_text(text, word2ph, phones, tone, language, audiopath)
78
+
79
+ spec, wav = self.get_audio(audiopath)
80
+ sid = torch.LongTensor([int(self.spk_map[sid])])
81
+ return (phones, spec, wav, sid, tone, language, bert)
82
+
83
+ def get_audio(self, filename):
84
+ audio_norm, sampling_rate = torchaudio.load(filename, frame_offset=0, num_frames=-1, normalize=True, channels_first=True)
85
+ '''
86
+ audio, sampling_rate = load_wav_to_torch(filename)
87
+ if sampling_rate != self.sampling_rate:
88
+ raise ValueError("{} {} SR doesn't match target {} SR".format(
89
+ sampling_rate, self.sampling_rate))
90
+ audio_norm = audio / self.max_wav_value
91
+ audio_norm = audio_norm.unsqueeze(0)
92
+ '''
93
+ spec_filename = filename.replace(".wav", ".spec.pt")
94
+ if self.use_mel_spec_posterior:
95
+ spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
96
+ if os.path.exists(spec_filename):
97
+ spec = torch.load(spec_filename)
98
+ else:
99
+ if self.use_mel_spec_posterior:
100
+ # if os.path.exists(filename.replace(".wav", ".spec.pt")):
101
+ # # spec, n_fft, num_mels, sampling_rate, fmin, fmax
102
+ # spec = spec_to_mel_torch(
103
+ # torch.load(filename.replace(".wav", ".spec.pt")),
104
+ # self.filter_length, self.n_mel_channels, self.sampling_rate,
105
+ # self.hparams.mel_fmin, self.hparams.mel_fmax)
106
+ spec = mel_spectrogram_torch(audio_norm, self.filter_length,
107
+ self.n_mel_channels, self.sampling_rate, self.hop_length,
108
+ self.win_length, self.hparams.mel_fmin, self.hparams.mel_fmax, center=False)
109
+ else:
110
+ spec = spectrogram_torch(audio_norm, self.filter_length,
111
+ self.sampling_rate, self.hop_length, self.win_length,
112
+ center=False)
113
+ spec = torch.squeeze(spec, 0)
114
+ torch.save(spec, spec_filename)
115
+ return spec, audio_norm
116
+
117
+ def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
118
+ # print(text, word2ph,phone, tone, language_str)
119
+ pold = phone
120
+ w2pho = [i for i in word2ph]
121
+ word2ph = [i for i in word2ph]
122
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
123
+ pold2 = phone
124
+
125
+ if self.add_blank:
126
+ p1 = len(phone)
127
+ phone = commons.intersperse(phone, 0)
128
+ p2 = len(phone)
129
+ t1 = len(tone)
130
+ tone = commons.intersperse(tone, 0)
131
+ t2 = len(tone)
132
+ language = commons.intersperse(language, 0)
133
+ for i in range(len(word2ph)):
134
+ word2ph[i] = word2ph[i] * 2
135
+ word2ph[0] += 1
136
+ bert_path = wav_path.replace(".wav", ".bert.pt")
137
+ try:
138
+ bert = torch.load(bert_path)
139
+ assert bert.shape[-1] == len(phone)
140
+ except:
141
+ bert = get_bert(text, word2ph, language_str)
142
+ torch.save(bert, bert_path)
143
+ #print(bert.shape[-1], bert_path, text, pold)
144
+ assert bert.shape[-1] == len(phone)
145
+
146
+ assert bert.shape[-1] == len(phone), (
147
+ bert.shape, len(phone), sum(word2ph), p1, p2, t1, t2, pold, pold2, word2ph, text, w2pho)
148
+ phone = torch.LongTensor(phone)
149
+ tone = torch.LongTensor(tone)
150
+ language = torch.LongTensor(language)
151
+ return bert, phone, tone, language
152
+
153
+ def get_sid(self, sid):
154
+ sid = torch.LongTensor([int(sid)])
155
+ return sid
156
+
157
+ def __getitem__(self, index):
158
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
159
+
160
+ def __len__(self):
161
+ return len(self.audiopaths_sid_text)
162
+
163
+
164
+ class TextAudioSpeakerCollate():
165
+ """ Zero-pads model inputs and targets
166
+ """
167
+
168
+ def __init__(self, return_ids=False):
169
+ self.return_ids = return_ids
170
+
171
+ def __call__(self, batch):
172
+ """Collate's training batch from normalized text, audio and speaker identities
173
+ PARAMS
174
+ ------
175
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
176
+ """
177
+ # Right zero-pad all one-hot text sequences to max input length
178
+ _, ids_sorted_decreasing = torch.sort(
179
+ torch.LongTensor([x[1].size(1) for x in batch]),
180
+ dim=0, descending=True)
181
+
182
+ max_text_len = max([len(x[0]) for x in batch])
183
+ max_spec_len = max([x[1].size(1) for x in batch])
184
+ max_wav_len = max([x[2].size(1) for x in batch])
185
+
186
+ text_lengths = torch.LongTensor(len(batch))
187
+ spec_lengths = torch.LongTensor(len(batch))
188
+ wav_lengths = torch.LongTensor(len(batch))
189
+ sid = torch.LongTensor(len(batch))
190
+
191
+ text_padded = torch.LongTensor(len(batch), max_text_len)
192
+ tone_padded = torch.LongTensor(len(batch), max_text_len)
193
+ language_padded = torch.LongTensor(len(batch), max_text_len)
194
+ bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
195
+
196
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
197
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
198
+ text_padded.zero_()
199
+ tone_padded.zero_()
200
+ language_padded.zero_()
201
+ spec_padded.zero_()
202
+ wav_padded.zero_()
203
+ bert_padded.zero_()
204
+ for i in range(len(ids_sorted_decreasing)):
205
+ row = batch[ids_sorted_decreasing[i]]
206
+
207
+ text = row[0]
208
+ text_padded[i, :text.size(0)] = text
209
+ text_lengths[i] = text.size(0)
210
+
211
+ spec = row[1]
212
+ spec_padded[i, :, :spec.size(1)] = spec
213
+ spec_lengths[i] = spec.size(1)
214
+
215
+ wav = row[2]
216
+ wav_padded[i, :, :wav.size(1)] = wav
217
+ wav_lengths[i] = wav.size(1)
218
+
219
+ sid[i] = row[3]
220
+
221
+ tone = row[4]
222
+ tone_padded[i, :tone.size(0)] = tone
223
+
224
+ language = row[5]
225
+ language_padded[i, :language.size(0)] = language
226
+
227
+ bert = row[6]
228
+ bert_padded[i, :, :bert.size(1)] = bert
229
+
230
+ return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, tone_padded, language_padded, bert_padded
231
+
232
+
233
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
234
+ """
235
+ Maintain similar input lengths in a batch.
236
+ Length groups are specified by boundaries.
237
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
238
+
239
+ It removes samples which are not included in the boundaries.
240
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
241
+ """
242
+
243
+ def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):
244
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
245
+ self.lengths = dataset.lengths
246
+ self.batch_size = batch_size
247
+ self.boundaries = boundaries
248
+
249
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
250
+ self.total_size = sum(self.num_samples_per_bucket)
251
+ self.num_samples = self.total_size // self.num_replicas
252
+
253
+ def _create_buckets(self):
254
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
255
+ for i in range(len(self.lengths)):
256
+ length = self.lengths[i]
257
+ idx_bucket = self._bisect(length)
258
+ if idx_bucket != -1:
259
+ buckets[idx_bucket].append(i)
260
+
261
+ for i in range(len(buckets) - 1, 0, -1):
262
+ if len(buckets[i]) == 0:
263
+ buckets.pop(i)
264
+ self.boundaries.pop(i + 1)
265
+
266
+ num_samples_per_bucket = []
267
+ for i in range(len(buckets)):
268
+ len_bucket = len(buckets[i])
269
+ total_batch_size = self.num_replicas * self.batch_size
270
+ rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size
271
+ num_samples_per_bucket.append(len_bucket + rem)
272
+ return buckets, num_samples_per_bucket
273
+
274
+ def __iter__(self):
275
+ # deterministically shuffle based on epoch
276
+ g = torch.Generator()
277
+ g.manual_seed(self.epoch)
278
+
279
+ indices = []
280
+ if self.shuffle:
281
+ for bucket in self.buckets:
282
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
283
+ else:
284
+ for bucket in self.buckets:
285
+ indices.append(list(range(len(bucket))))
286
+
287
+ batches = []
288
+ for i in range(len(self.buckets)):
289
+ bucket = self.buckets[i]
290
+ len_bucket = len(bucket)
291
+ if (len_bucket == 0):
292
+ continue
293
+ ids_bucket = indices[i]
294
+ num_samples_bucket = self.num_samples_per_bucket[i]
295
+
296
+ # add extra samples to make it evenly divisible
297
+ rem = num_samples_bucket - len_bucket
298
+ ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
299
+
300
+ # subsample
301
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
302
+
303
+ # batching
304
+ for j in range(len(ids_bucket) // self.batch_size):
305
+ batch = [bucket[idx] for idx in ids_bucket[j * self.batch_size:(j + 1) * self.batch_size]]
306
+ batches.append(batch)
307
+
308
+ if self.shuffle:
309
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
310
+ batches = [batches[i] for i in batch_ids]
311
+ self.batches = batches
312
+
313
+ assert len(self.batches) * self.batch_size == self.num_samples
314
+ return iter(self.batches)
315
+
316
+ def _bisect(self, x, lo=0, hi=None):
317
+ if hi is None:
318
+ hi = len(self.boundaries) - 1
319
+
320
+ if hi > lo:
321
+ mid = (hi + lo) // 2
322
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
323
+ return mid
324
+ elif x <= self.boundaries[mid]:
325
+ return self._bisect(x, lo, mid)
326
+ else:
327
+ return self._bisect(x, mid + 1, hi)
328
+ else:
329
+ return -1
330
+
331
+ def __len__(self):
332
+ return self.num_samples // self.batch_size
filelists/esd.list ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Example:
2
+ {wav_path}|{speaker_name}|{language}|{text}
inference_webui.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, os
2
+
3
+ if sys.platform == "darwin":
4
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
5
+
6
+ import logging
7
+
8
+ logging.getLogger("numba").setLevel(logging.WARNING)
9
+ logging.getLogger("markdown_it").setLevel(logging.WARNING)
10
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
11
+ logging.getLogger("matplotlib").setLevel(logging.WARNING)
12
+
13
+ logging.basicConfig(level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s")
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ import torch
18
+ import argparse
19
+ import commons
20
+ import utils
21
+ from models import SynthesizerTrn
22
+ from text.symbols import symbols
23
+ from text import cleaned_text_to_sequence, get_bert
24
+ from text.cleaner import clean_text
25
+ import gradio as gr
26
+ import webbrowser
27
+
28
+
29
+ net_g = None
30
+
31
+
32
+ def get_text(text, language_str, hps):
33
+ norm_text, phone, tone, word2ph = clean_text(text, language_str)
34
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
35
+
36
+ if hps.data.add_blank:
37
+ phone = commons.intersperse(phone, 0)
38
+ tone = commons.intersperse(tone, 0)
39
+ language = commons.intersperse(language, 0)
40
+ for i in range(len(word2ph)):
41
+ word2ph[i] = word2ph[i] * 2
42
+ word2ph[0] += 1
43
+ bert = get_bert(norm_text, word2ph, language_str)
44
+ del word2ph
45
+
46
+ assert bert.shape[-1] == len(phone)
47
+
48
+ phone = torch.LongTensor(phone)
49
+ tone = torch.LongTensor(tone)
50
+ language = torch.LongTensor(language)
51
+
52
+ return bert, phone, tone, language
53
+
54
+ def infer(text, sdp_ratio, noise_scale, noise_scale_w, length_scale, sid):
55
+ global net_g
56
+ bert, phones, tones, lang_ids = get_text(text, "ZH", hps)
57
+ with torch.no_grad():
58
+ x_tst=phones.to(device).unsqueeze(0)
59
+ tones=tones.to(device).unsqueeze(0)
60
+ lang_ids=lang_ids.to(device).unsqueeze(0)
61
+ bert = bert.to(device).unsqueeze(0)
62
+ x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
63
+ del phones
64
+ speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
65
+ audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids, bert, sdp_ratio=sdp_ratio
66
+ , noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
67
+ del x_tst, tones, lang_ids, bert, x_tst_lengths, speakers
68
+ return audio
69
+
70
+ def tts_fn(text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale):
71
+ with torch.no_grad():
72
+ audio = infer(text, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker)
73
+ return "Success", (hps.data.sampling_rate, audio)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_argument("--model_dir", default="./logs/OUTPUT_MODEL/G_100.pth", help="path of your model")
79
+ parser.add_argument("--config_dir", default="./configs/config.json", help="path of your config file")
80
+ parser.add_argument("--share", default=False, help="make link public")
81
+ parser.add_argument("-d", "--debug", action="store_true", help="enable DEBUG-LEVEL log")
82
+
83
+ args = parser.parse_args()
84
+ if args.debug:
85
+ logger.info("Enable DEBUG-LEVEL log")
86
+ logging.basicConfig(level=logging.DEBUG)
87
+ hps = utils.get_hparams_from_file(args.config_dir)
88
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
89
+ '''
90
+ device = (
91
+ "cuda:0"
92
+ if torch.cuda.is_available()
93
+ else (
94
+ "mps"
95
+ if sys.platform == "darwin" and torch.backends.mps.is_available()
96
+ else "cpu"
97
+ )
98
+ )
99
+ '''
100
+ net_g = SynthesizerTrn(
101
+ len(symbols),
102
+ hps.data.filter_length // 2 + 1,
103
+ hps.train.segment_size // hps.data.hop_length,
104
+ n_speakers=hps.data.n_speakers,
105
+ **hps.model).to(device)
106
+ _ = net_g.eval()
107
+
108
+ _ = utils.load_checkpoint(args.model_dir, net_g, None, skip_optimizer=True)
109
+
110
+ speaker_ids = hps.data.spk2id
111
+ speakers = list(speaker_ids.keys())
112
+ with gr.Blocks() as app:
113
+ with gr.Row():
114
+ with gr.Column():
115
+ text = gr.TextArea(label="Text", placeholder="Input Text Here",
116
+ value="那是流萤吗,是明灭迷离,天真绮丽的憧憬。那是尘埃吧,是虚无纷飞,终将落地的谎言。")
117
+ speaker = gr.Dropdown(choices=speakers, value=speakers[0], label='Speaker')
118
+ sdp_ratio = gr.Slider(minimum=0, maximum=1, value=0.2, step=0.1, label='语调变化')
119
+ noise_scale = gr.Slider(minimum=0.1, maximum=1.5, value=0.6, step=0.1, label='感情变化')
120
+ noise_scale_w = gr.Slider(minimum=0.1, maximum=1.4, value=0.8, step=0.1, label='音节发音长度变化')
121
+ length_scale = gr.Slider(minimum=0.1, maximum=2, value=1, step=0.1, label='语速')
122
+ btn = gr.Button("开启AI语音之旅吧!", variant="primary")
123
+ with gr.Column():
124
+ text_output = gr.Textbox(label="Message")
125
+ audio_output = gr.Audio(label="Output Audio")
126
+
127
+ btn.click(tts_fn,
128
+ inputs=[text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale],
129
+ outputs=[text_output, audio_output])
130
+
131
+ webbrowser.open("http://127.0.0.1:6006")
132
+ app.launch(server_port=6006, show_error=True)
inference_webui.py.old ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ from torch import no_grad, LongTensor
5
+ import argparse
6
+ import commons
7
+ from mel_processing import spectrogram_torch
8
+ import utils
9
+ from models import SynthesizerTrn
10
+ import gradio as gr
11
+ import librosa
12
+ import webbrowser
13
+ import time
14
+ import commons
15
+ import utils
16
+ from models import SynthesizerTrn
17
+ from text.symbols import symbols
18
+ from text import cleaned_text_to_sequence,_symbol_to_id, get_bert
19
+ from text.cleaner import clean_text
20
+ from scipy.io import wavfile
21
+
22
+
23
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
24
+ import logging
25
+ logging.getLogger("PIL").setLevel(logging.WARNING)
26
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
27
+ logging.getLogger("markdown_it").setLevel(logging.WARNING)
28
+ logging.getLogger("httpx").setLevel(logging.WARNING)
29
+ logging.getLogger("asyncio").setLevel(logging.WARNING)
30
+
31
+ language_marks = {
32
+ "简体中文": "[ZH]",
33
+ }
34
+ lang = ['简体中文']
35
+ def get_text(text, language_str, hps):
36
+ norm_text, phone, tone, word2ph = clean_text(text, language_str)
37
+ print([f"{p}{t}" for p, t in zip(phone, tone)])
38
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
39
+
40
+ if hps.data.add_blank:
41
+ phone = commons.intersperse(phone, 0)
42
+ tone = commons.intersperse(tone, 0)
43
+ language = commons.intersperse(language, 0)
44
+ for i in range(len(word2ph)):
45
+ word2ph[i] = word2ph[i] * 2
46
+ word2ph[0] += 1
47
+ bert = get_bert(norm_text, word2ph, language_str)
48
+
49
+ assert bert.shape[-1] == len(phone)
50
+
51
+ phone = torch.LongTensor(phone)
52
+ tone = torch.LongTensor(tone)
53
+ language = torch.LongTensor(language)
54
+
55
+ return bert, phone, tone, language
56
+ '''
57
+ def create_tts_fn(model, hps, speaker_ids):
58
+ def tts_fn(text, speaker, language, speed):
59
+ if language is not None:
60
+ text = language_marks[language] + text + language_marks[language]
61
+ speaker_id = speaker_ids[speaker]
62
+ stn_tst = get_text(text, hps, False)
63
+ with no_grad():
64
+ x_tst = stn_tst.unsqueeze(0).to(device)
65
+ x_tst_lengths = LongTensor([stn_tst.size(0)]).to(device)
66
+ sid = LongTensor([speaker_id]).to(device)
67
+ audio = model.infer(x_tst, x_tst_lengths, sid=sid, noise_scale=.667, noise_scale_w=0.8,
68
+ length_scale=1.0 / speed)[0][0, 0].data.cpu().float().numpy()
69
+ del stn_tst, x_tst, x_tst_lengths, sid
70
+ return "Success", (hps.data.sampling_rate, audio)
71
+
72
+ return tts_fn
73
+ '''
74
+ dev='cuda'
75
+ def infer(text, sdp_ratio, noise_scale, noise_scale_w,length_scale,sid):
76
+ bert, phones, tones, lang_ids = get_text(text,"ZH", hps,)
77
+ print(sid)
78
+ with torch.no_grad():
79
+ x_tst=phones.to(dev).unsqueeze(0)
80
+ tones=tones.to(dev).unsqueeze(0)
81
+ lang_ids=lang_ids.to(dev).unsqueeze(0)
82
+ bert = bert.to(dev).unsqueeze(0)
83
+ x_tst_lengths = torch.LongTensor([phones.size(0)]).to(dev)
84
+ del phones
85
+ speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(dev)
86
+ audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids,bert, sdp_ratio=sdp_ratio
87
+ , noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
88
+ del x_tst, tones, lang_ids, bert, x_tst_lengths, speakers
89
+ return "Success",(hps.data.sampling_rate, audio)
90
+
91
+ if __name__ == "__main__":
92
+ parser = argparse.ArgumentParser()
93
+ parser.add_argument("--model_dir", default="./G_latest.pth", help="directory to your fine-tuned model")
94
+ parser.add_argument("--config_dir", default="./configs\config.json", help="directory to your model config file")
95
+ parser.add_argument("--share", default=False, help="make link public (used in colab)")
96
+
97
+ args = parser.parse_args()
98
+ hps = utils.get_hparams_from_file(args.config_dir)
99
+
100
+
101
+ net_g = SynthesizerTrn(
102
+ len(symbols),
103
+ hps.data.filter_length // 2 + 1,
104
+ hps.train.segment_size // hps.data.hop_length,
105
+ n_speakers=hps.data.n_speakers,
106
+ **hps.model).to(dev)
107
+ _ = net_g.eval()
108
+
109
+ _ = utils.load_checkpoint(args.model_dir, net_g, None,skip_optimizer=True)
110
+
111
+ speaker_ids = hps.data.spk2id
112
+ speakers = list(hps.data.spk2id.keys())
113
+ #inf = infer(net_g, hps, speaker_ids)
114
+ app = gr.Blocks()
115
+ with app:
116
+ with gr.Tab("Text-to-Speech"):
117
+ with gr.Row():
118
+ with gr.Column():
119
+ textbox = gr.TextArea(label="Text",
120
+ placeholder="Type your sentence here",
121
+ value="生活就像海洋,只有意志坚强的人,才能到达彼岸。", elem_id=f"tts-input")
122
+ # select character
123
+ char_dropdown = gr.Dropdown(choices=speakers, value=speakers[0], label='character')
124
+ language_dropdown = gr.Dropdown(choices=lang, value=lang[0], label='language')
125
+ sdp_ratio = gr.Slider(minimum=0.1, maximum=0.9, value=0.2, step=0.1,
126
+ label='SDP/DP混合比-语调方差')
127
+ noise_scale = gr.Slider(minimum=0.1, maximum=1.5, value=0.5, step=0.1,
128
+ label='noise/感情变化')
129
+ noise_scale_w = gr.Slider(minimum=0.1, maximum=1.4, value=0.9, step=0.1,
130
+ label='noisew/音节发音长度变化')
131
+ length_scale = gr.Slider(minimum=0.1, maximum=2, value=1.0, step=0.1,
132
+ label='length/语速')
133
+ with gr.Column():
134
+ text_output = gr.Textbox(label="Message")
135
+ audio_output = gr.Audio(label="Output Audio", elem_id="tts-audio")
136
+ btn = gr.Button("Generate!")
137
+ btn.click(infer,
138
+ inputs=[textbox,sdp_ratio,noise_scale,noise_scale_w,length_scale,char_dropdown],
139
+ outputs=[text_output, audio_output])
140
+ webbrowser.open("http://127.0.0.1:7860")
141
+ app.launch(share=args.share)
142
+
losses.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import commons
5
+
6
+
7
+ def feature_loss(fmap_r, fmap_g):
8
+ loss = 0
9
+ for dr, dg in zip(fmap_r, fmap_g):
10
+ for rl, gl in zip(dr, dg):
11
+ rl = rl.float().detach()
12
+ gl = gl.float()
13
+ loss += torch.mean(torch.abs(rl - gl))
14
+
15
+ return loss * 2
16
+
17
+
18
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
19
+ loss = 0
20
+ r_losses = []
21
+ g_losses = []
22
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
23
+ dr = dr.float()
24
+ dg = dg.float()
25
+ r_loss = torch.mean((1-dr)**2)
26
+ g_loss = torch.mean(dg**2)
27
+ loss += (r_loss + g_loss)
28
+ r_losses.append(r_loss.item())
29
+ g_losses.append(g_loss.item())
30
+
31
+ return loss, r_losses, g_losses
32
+
33
+
34
+ def generator_loss(disc_outputs):
35
+ loss = 0
36
+ gen_losses = []
37
+ for dg in disc_outputs:
38
+ dg = dg.float()
39
+ l = torch.mean((1-dg)**2)
40
+ gen_losses.append(l)
41
+ loss += l
42
+
43
+ return loss, gen_losses
44
+
45
+
46
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
47
+ """
48
+ z_p, logs_q: [b, h, t_t]
49
+ m_p, logs_p: [b, h, t_t]
50
+ """
51
+ z_p = z_p.float()
52
+ logs_q = logs_q.float()
53
+ m_p = m_p.float()
54
+ logs_p = logs_p.float()
55
+ z_mask = z_mask.float()
56
+
57
+ kl = logs_p - logs_q - 0.5
58
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
59
+ kl = torch.sum(kl * z_mask)
60
+ l = kl / torch.sum(z_mask)
61
+ return l
mel_processing.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.data
8
+ import numpy as np
9
+ import librosa
10
+ import librosa.util as librosa_util
11
+ from librosa.util import normalize, pad_center, tiny
12
+ from scipy.signal import get_window
13
+ from scipy.io.wavfile import read
14
+ from librosa.filters import mel as librosa_mel_fn
15
+
16
+ MAX_WAV_VALUE = 32768.0
17
+
18
+
19
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
20
+ """
21
+ PARAMS
22
+ ------
23
+ C: compression factor
24
+ """
25
+ return torch.log(torch.clamp(x, min=clip_val) * C)
26
+
27
+
28
+ def dynamic_range_decompression_torch(x, C=1):
29
+ """
30
+ PARAMS
31
+ ------
32
+ C: compression factor used to compress
33
+ """
34
+ return torch.exp(x) / C
35
+
36
+
37
+ def spectral_normalize_torch(magnitudes):
38
+ output = dynamic_range_compression_torch(magnitudes)
39
+ return output
40
+
41
+
42
+ def spectral_de_normalize_torch(magnitudes):
43
+ output = dynamic_range_decompression_torch(magnitudes)
44
+ return output
45
+
46
+
47
+ mel_basis = {}
48
+ hann_window = {}
49
+
50
+
51
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
52
+ if torch.min(y) < -1.:
53
+ print('min value is ', torch.min(y))
54
+ if torch.max(y) > 1.:
55
+ print('max value is ', torch.max(y))
56
+
57
+ global hann_window
58
+ dtype_device = str(y.dtype) + '_' + str(y.device)
59
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
60
+ if wnsize_dtype_device not in hann_window:
61
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
62
+
63
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
64
+ y = y.squeeze(1)
65
+
66
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
67
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
68
+
69
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
70
+ return spec
71
+
72
+
73
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
74
+ global mel_basis
75
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
76
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
77
+ if fmax_dtype_device not in mel_basis:
78
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
79
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
80
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
81
+ spec = spectral_normalize_torch(spec)
82
+ return spec
83
+
84
+
85
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
86
+ if torch.min(y) < -1.:
87
+ print('min value is ', torch.min(y))
88
+ if torch.max(y) > 1.:
89
+ print('max value is ', torch.max(y))
90
+
91
+ global mel_basis, hann_window
92
+ dtype_device = str(y.dtype) + '_' + str(y.device)
93
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
94
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
95
+ if fmax_dtype_device not in mel_basis:
96
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
97
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
98
+ if wnsize_dtype_device not in hann_window:
99
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
100
+
101
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
102
+ y = y.squeeze(1)
103
+
104
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
105
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
106
+
107
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
108
+
109
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
110
+ spec = spectral_normalize_torch(spec)
111
+
112
+ return spec
models.py ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ import commons
8
+ import modules
9
+ import attentions
10
+ import monotonic_align
11
+
12
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
13
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
14
+
15
+ from commons import init_weights, get_padding
16
+ from text import symbols, num_tones, num_languages
17
+ class DurationDiscriminator(nn.Module): #vits2
18
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
19
+ super().__init__()
20
+
21
+ self.in_channels = in_channels
22
+ self.filter_channels = filter_channels
23
+ self.kernel_size = kernel_size
24
+ self.p_dropout = p_dropout
25
+ self.gin_channels = gin_channels
26
+
27
+ self.drop = nn.Dropout(p_dropout)
28
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2)
29
+ self.norm_1 = modules.LayerNorm(filter_channels)
30
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
31
+ self.norm_2 = modules.LayerNorm(filter_channels)
32
+ self.dur_proj = nn.Conv1d(1, filter_channels, 1)
33
+
34
+ self.pre_out_conv_1 = nn.Conv1d(2*filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
35
+ self.pre_out_norm_1 = modules.LayerNorm(filter_channels)
36
+ self.pre_out_conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2)
37
+ self.pre_out_norm_2 = modules.LayerNorm(filter_channels)
38
+
39
+ if gin_channels != 0:
40
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
41
+
42
+ self.output_layer = nn.Sequential(
43
+ nn.Linear(filter_channels, 1),
44
+ nn.Sigmoid()
45
+ )
46
+
47
+ def forward_probability(self, x, x_mask, dur, g=None):
48
+ dur = self.dur_proj(dur)
49
+ x = torch.cat([x, dur], dim=1)
50
+ x = self.pre_out_conv_1(x * x_mask)
51
+ x = torch.relu(x)
52
+ x = self.pre_out_norm_1(x)
53
+ x = self.drop(x)
54
+ x = self.pre_out_conv_2(x * x_mask)
55
+ x = torch.relu(x)
56
+ x = self.pre_out_norm_2(x)
57
+ x = self.drop(x)
58
+ x = x * x_mask
59
+ x = x.transpose(1, 2)
60
+ output_prob = self.output_layer(x)
61
+ return output_prob
62
+
63
+ def forward(self, x, x_mask, dur_r, dur_hat, g=None):
64
+ x = torch.detach(x)
65
+ if g is not None:
66
+ g = torch.detach(g)
67
+ x = x + self.cond(g)
68
+ x = self.conv_1(x * x_mask)
69
+ x = torch.relu(x)
70
+ x = self.norm_1(x)
71
+ x = self.drop(x)
72
+ x = self.conv_2(x * x_mask)
73
+ x = torch.relu(x)
74
+ x = self.norm_2(x)
75
+ x = self.drop(x)
76
+
77
+ output_probs = []
78
+ for dur in [dur_r, dur_hat]:
79
+ output_prob = self.forward_probability(x, x_mask, dur, g)
80
+ output_probs.append(output_prob)
81
+
82
+ return output_probs
83
+
84
+ class TransformerCouplingBlock(nn.Module):
85
+ def __init__(self,
86
+ channels,
87
+ hidden_channels,
88
+ filter_channels,
89
+ n_heads,
90
+ n_layers,
91
+ kernel_size,
92
+ p_dropout,
93
+ n_flows=4,
94
+ gin_channels=0,
95
+ share_parameter=False
96
+ ):
97
+
98
+ super().__init__()
99
+ self.channels = channels
100
+ self.hidden_channels = hidden_channels
101
+ self.kernel_size = kernel_size
102
+ self.n_layers = n_layers
103
+ self.n_flows = n_flows
104
+ self.gin_channels = gin_channels
105
+
106
+ self.flows = nn.ModuleList()
107
+
108
+ self.wn = attentions.FFT(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = self.gin_channels) if share_parameter else None
109
+
110
+ for i in range(n_flows):
111
+ self.flows.append(
112
+ modules.TransformerCouplingLayer(channels, hidden_channels, kernel_size, n_layers, n_heads, p_dropout, filter_channels, mean_only=True, wn_sharing_parameter=self.wn, gin_channels = self.gin_channels))
113
+ self.flows.append(modules.Flip())
114
+
115
+ def forward(self, x, x_mask, g=None, reverse=False):
116
+ if not reverse:
117
+ for flow in self.flows:
118
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
119
+ else:
120
+ for flow in reversed(self.flows):
121
+ x = flow(x, x_mask, g=g, reverse=reverse)
122
+ return x
123
+
124
+ class StochasticDurationPredictor(nn.Module):
125
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
126
+ super().__init__()
127
+ filter_channels = in_channels # it needs to be removed from future version.
128
+ self.in_channels = in_channels
129
+ self.filter_channels = filter_channels
130
+ self.kernel_size = kernel_size
131
+ self.p_dropout = p_dropout
132
+ self.n_flows = n_flows
133
+ self.gin_channels = gin_channels
134
+
135
+ self.log_flow = modules.Log()
136
+ self.flows = nn.ModuleList()
137
+ self.flows.append(modules.ElementwiseAffine(2))
138
+ for i in range(n_flows):
139
+ self.flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
140
+ self.flows.append(modules.Flip())
141
+
142
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
143
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
144
+ self.post_convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
145
+ self.post_flows = nn.ModuleList()
146
+ self.post_flows.append(modules.ElementwiseAffine(2))
147
+ for i in range(4):
148
+ self.post_flows.append(modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
149
+ self.post_flows.append(modules.Flip())
150
+
151
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
152
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
153
+ self.convs = modules.DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
154
+ if gin_channels != 0:
155
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
156
+
157
+ def forward(self, x, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
158
+ x = torch.detach(x)
159
+ x = self.pre(x)
160
+ if g is not None:
161
+ g = torch.detach(g)
162
+ x = x + self.cond(g)
163
+ x = self.convs(x, x_mask)
164
+ x = self.proj(x) * x_mask
165
+
166
+ if not reverse:
167
+ flows = self.flows
168
+ assert w is not None
169
+
170
+ logdet_tot_q = 0
171
+ h_w = self.post_pre(w)
172
+ h_w = self.post_convs(h_w, x_mask)
173
+ h_w = self.post_proj(h_w) * x_mask
174
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(device=x.device, dtype=x.dtype) * x_mask
175
+ z_q = e_q
176
+ for flow in self.post_flows:
177
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
178
+ logdet_tot_q += logdet_q
179
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
180
+ u = torch.sigmoid(z_u) * x_mask
181
+ z0 = (w - u) * x_mask
182
+ logdet_tot_q += torch.sum((F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
183
+ logq = torch.sum(-0.5 * (math.log(2 * math.pi) + (e_q ** 2)) * x_mask, [1, 2]) - logdet_tot_q
184
+
185
+ logdet_tot = 0
186
+ z0, logdet = self.log_flow(z0, x_mask)
187
+ logdet_tot += logdet
188
+ z = torch.cat([z0, z1], 1)
189
+ for flow in flows:
190
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
191
+ logdet_tot = logdet_tot + logdet
192
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) + (z ** 2)) * x_mask, [1, 2]) - logdet_tot
193
+ return nll + logq # [b]
194
+ else:
195
+ flows = list(reversed(self.flows))
196
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
197
+ z = torch.randn(x.size(0), 2, x.size(2)).to(device=x.device, dtype=x.dtype) * noise_scale
198
+ for flow in flows:
199
+ z = flow(z, x_mask, g=x, reverse=reverse)
200
+ z0, z1 = torch.split(z, [1, 1], 1)
201
+ logw = z0
202
+ return logw
203
+
204
+
205
+ class DurationPredictor(nn.Module):
206
+ def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
207
+ super().__init__()
208
+
209
+ self.in_channels = in_channels
210
+ self.filter_channels = filter_channels
211
+ self.kernel_size = kernel_size
212
+ self.p_dropout = p_dropout
213
+ self.gin_channels = gin_channels
214
+
215
+ self.drop = nn.Dropout(p_dropout)
216
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
217
+ self.norm_1 = modules.LayerNorm(filter_channels)
218
+ self.conv_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
219
+ self.norm_2 = modules.LayerNorm(filter_channels)
220
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
221
+
222
+ if gin_channels != 0:
223
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
224
+
225
+ def forward(self, x, x_mask, g=None):
226
+ x = torch.detach(x)
227
+ if g is not None:
228
+ g = torch.detach(g)
229
+ x = x + self.cond(g)
230
+ x = self.conv_1(x * x_mask)
231
+ x = torch.relu(x)
232
+ x = self.norm_1(x)
233
+ x = self.drop(x)
234
+ x = self.conv_2(x * x_mask)
235
+ x = torch.relu(x)
236
+ x = self.norm_2(x)
237
+ x = self.drop(x)
238
+ x = self.proj(x * x_mask)
239
+ return x * x_mask
240
+
241
+
242
+ class TextEncoder(nn.Module):
243
+ def __init__(self,
244
+ n_vocab,
245
+ out_channels,
246
+ hidden_channels,
247
+ filter_channels,
248
+ n_heads,
249
+ n_layers,
250
+ kernel_size,
251
+ p_dropout,
252
+ gin_channels=0):
253
+ super().__init__()
254
+ self.n_vocab = n_vocab
255
+ self.out_channels = out_channels
256
+ self.hidden_channels = hidden_channels
257
+ self.filter_channels = filter_channels
258
+ self.n_heads = n_heads
259
+ self.n_layers = n_layers
260
+ self.kernel_size = kernel_size
261
+ self.p_dropout = p_dropout
262
+ self.gin_channels = gin_channels
263
+ self.emb = nn.Embedding(len(symbols), hidden_channels)
264
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
265
+ self.tone_emb = nn.Embedding(num_tones, hidden_channels)
266
+ nn.init.normal_(self.tone_emb.weight, 0.0, hidden_channels ** -0.5)
267
+ self.language_emb = nn.Embedding(num_languages, hidden_channels)
268
+ nn.init.normal_(self.language_emb.weight, 0.0, hidden_channels ** -0.5)
269
+ self.bert_proj = nn.Conv1d(1024, hidden_channels, 1)
270
+
271
+ self.encoder = attentions.Encoder(
272
+ hidden_channels,
273
+ filter_channels,
274
+ n_heads,
275
+ n_layers,
276
+ kernel_size,
277
+ p_dropout,
278
+ gin_channels=self.gin_channels)
279
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
280
+
281
+ def forward(self, x, x_lengths, tone, language, bert, g=None):
282
+ x = (self.emb(x)+ self.tone_emb(tone)+ self.language_emb(language)+self.bert_proj(bert).transpose(1,2)) * math.sqrt(self.hidden_channels) # [b, t, h]
283
+ x = torch.transpose(x, 1, -1) # [b, h, t]
284
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
285
+
286
+ x = self.encoder(x * x_mask, x_mask, g=g)
287
+ stats = self.proj(x) * x_mask
288
+
289
+ m, logs = torch.split(stats, self.out_channels, dim=1)
290
+ return x, m, logs, x_mask
291
+
292
+
293
+ class ResidualCouplingBlock(nn.Module):
294
+ def __init__(self,
295
+ channels,
296
+ hidden_channels,
297
+ kernel_size,
298
+ dilation_rate,
299
+ n_layers,
300
+ n_flows=4,
301
+ gin_channels=0):
302
+ super().__init__()
303
+ self.channels = channels
304
+ self.hidden_channels = hidden_channels
305
+ self.kernel_size = kernel_size
306
+ self.dilation_rate = dilation_rate
307
+ self.n_layers = n_layers
308
+ self.n_flows = n_flows
309
+ self.gin_channels = gin_channels
310
+
311
+ self.flows = nn.ModuleList()
312
+ for i in range(n_flows):
313
+ self.flows.append(
314
+ modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
315
+ gin_channels=gin_channels, mean_only=True))
316
+ self.flows.append(modules.Flip())
317
+
318
+ def forward(self, x, x_mask, g=None, reverse=False):
319
+ if not reverse:
320
+ for flow in self.flows:
321
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
322
+ else:
323
+ for flow in reversed(self.flows):
324
+ x = flow(x, x_mask, g=g, reverse=reverse)
325
+ return x
326
+
327
+
328
+ class PosteriorEncoder(nn.Module):
329
+ def __init__(self,
330
+ in_channels,
331
+ out_channels,
332
+ hidden_channels,
333
+ kernel_size,
334
+ dilation_rate,
335
+ n_layers,
336
+ gin_channels=0):
337
+ super().__init__()
338
+ self.in_channels = in_channels
339
+ self.out_channels = out_channels
340
+ self.hidden_channels = hidden_channels
341
+ self.kernel_size = kernel_size
342
+ self.dilation_rate = dilation_rate
343
+ self.n_layers = n_layers
344
+ self.gin_channels = gin_channels
345
+
346
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
347
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
348
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
349
+
350
+ def forward(self, x, x_lengths, g=None):
351
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
352
+ x = self.pre(x) * x_mask
353
+ x = self.enc(x, x_mask, g=g)
354
+ stats = self.proj(x) * x_mask
355
+ m, logs = torch.split(stats, self.out_channels, dim=1)
356
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
357
+ return z, m, logs, x_mask
358
+
359
+
360
+ class Generator(torch.nn.Module):
361
+ def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
362
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
363
+ super(Generator, self).__init__()
364
+ self.num_kernels = len(resblock_kernel_sizes)
365
+ self.num_upsamples = len(upsample_rates)
366
+ self.conv_pre = Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
367
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
368
+
369
+ self.ups = nn.ModuleList()
370
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
371
+ self.ups.append(weight_norm(
372
+ ConvTranspose1d(upsample_initial_channel // (2 ** i), upsample_initial_channel // (2 ** (i + 1)),
373
+ k, u, padding=(k - u) // 2)))
374
+
375
+ self.resblocks = nn.ModuleList()
376
+ for i in range(len(self.ups)):
377
+ ch = upsample_initial_channel // (2 ** (i + 1))
378
+ for j, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
379
+ self.resblocks.append(resblock(ch, k, d))
380
+
381
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
382
+ self.ups.apply(init_weights)
383
+
384
+ if gin_channels != 0:
385
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
386
+
387
+ def forward(self, x, g=None):
388
+ x = self.conv_pre(x)
389
+ if g is not None:
390
+ x = x + self.cond(g)
391
+
392
+ for i in range(self.num_upsamples):
393
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
394
+ x = self.ups[i](x)
395
+ xs = None
396
+ for j in range(self.num_kernels):
397
+ if xs is None:
398
+ xs = self.resblocks[i * self.num_kernels + j](x)
399
+ else:
400
+ xs += self.resblocks[i * self.num_kernels + j](x)
401
+ x = xs / self.num_kernels
402
+ x = F.leaky_relu(x)
403
+ x = self.conv_post(x)
404
+ x = torch.tanh(x)
405
+
406
+ return x
407
+
408
+ def remove_weight_norm(self):
409
+ print('Removing weight norm...')
410
+ for l in self.ups:
411
+ remove_weight_norm(l)
412
+ for l in self.resblocks:
413
+ l.remove_weight_norm()
414
+
415
+
416
+ class DiscriminatorP(torch.nn.Module):
417
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
418
+ super(DiscriminatorP, self).__init__()
419
+ self.period = period
420
+ self.use_spectral_norm = use_spectral_norm
421
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
422
+ self.convs = nn.ModuleList([
423
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
424
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
425
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
426
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
427
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
428
+ ])
429
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
430
+
431
+ def forward(self, x):
432
+ fmap = []
433
+
434
+ # 1d to 2d
435
+ b, c, t = x.shape
436
+ if t % self.period != 0: # pad first
437
+ n_pad = self.period - (t % self.period)
438
+ x = F.pad(x, (0, n_pad), "reflect")
439
+ t = t + n_pad
440
+ x = x.view(b, c, t // self.period, self.period)
441
+
442
+ for l in self.convs:
443
+ x = l(x)
444
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
445
+ fmap.append(x)
446
+ x = self.conv_post(x)
447
+ fmap.append(x)
448
+ x = torch.flatten(x, 1, -1)
449
+
450
+ return x, fmap
451
+
452
+
453
+ class DiscriminatorS(torch.nn.Module):
454
+ def __init__(self, use_spectral_norm=False):
455
+ super(DiscriminatorS, self).__init__()
456
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
457
+ self.convs = nn.ModuleList([
458
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
459
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
460
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
461
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
462
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
463
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
464
+ ])
465
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
466
+
467
+ def forward(self, x):
468
+ fmap = []
469
+
470
+ for l in self.convs:
471
+ x = l(x)
472
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
473
+ fmap.append(x)
474
+ x = self.conv_post(x)
475
+ fmap.append(x)
476
+ x = torch.flatten(x, 1, -1)
477
+
478
+ return x, fmap
479
+
480
+
481
+ class MultiPeriodDiscriminator(torch.nn.Module):
482
+ def __init__(self, use_spectral_norm=False):
483
+ super(MultiPeriodDiscriminator, self).__init__()
484
+ periods = [2, 3, 5, 7, 11]
485
+
486
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
487
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
488
+ self.discriminators = nn.ModuleList(discs)
489
+
490
+ def forward(self, y, y_hat):
491
+ y_d_rs = []
492
+ y_d_gs = []
493
+ fmap_rs = []
494
+ fmap_gs = []
495
+ for i, d in enumerate(self.discriminators):
496
+ y_d_r, fmap_r = d(y)
497
+ y_d_g, fmap_g = d(y_hat)
498
+ y_d_rs.append(y_d_r)
499
+ y_d_gs.append(y_d_g)
500
+ fmap_rs.append(fmap_r)
501
+ fmap_gs.append(fmap_g)
502
+
503
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
504
+
505
+ class ReferenceEncoder(nn.Module):
506
+ '''
507
+ inputs --- [N, Ty/r, n_mels*r] mels
508
+ outputs --- [N, ref_enc_gru_size]
509
+ '''
510
+
511
+ def __init__(self, spec_channels, gin_channels=0):
512
+
513
+ super().__init__()
514
+ self.spec_channels = spec_channels
515
+ ref_enc_filters = [32, 32, 64, 64, 128, 128]
516
+ K = len(ref_enc_filters)
517
+ filters = [1] + ref_enc_filters
518
+ convs = [weight_norm(nn.Conv2d(in_channels=filters[i],
519
+ out_channels=filters[i + 1],
520
+ kernel_size=(3, 3),
521
+ stride=(2, 2),
522
+ padding=(1, 1))) for i in range(K)]
523
+ self.convs = nn.ModuleList(convs)
524
+ # self.wns = nn.ModuleList([weight_norm(num_features=ref_enc_filters[i]) for i in range(K)])
525
+
526
+ out_channels = self.calculate_channels(spec_channels, 3, 2, 1, K)
527
+ self.gru = nn.GRU(input_size=ref_enc_filters[-1] * out_channels,
528
+ hidden_size=256 // 2,
529
+ batch_first=True)
530
+ self.proj = nn.Linear(128, gin_channels)
531
+
532
+ def forward(self, inputs, mask=None):
533
+ N = inputs.size(0)
534
+ out = inputs.view(N, 1, -1, self.spec_channels) # [N, 1, Ty, n_freqs]
535
+ for conv in self.convs:
536
+ out = conv(out)
537
+ # out = wn(out)
538
+ out = F.relu(out) # [N, 128, Ty//2^K, n_mels//2^K]
539
+
540
+ out = out.transpose(1, 2) # [N, Ty//2^K, 128, n_mels//2^K]
541
+ T = out.size(1)
542
+ N = out.size(0)
543
+ out = out.contiguous().view(N, T, -1) # [N, Ty//2^K, 128*n_mels//2^K]
544
+
545
+ self.gru.flatten_parameters()
546
+ memory, out = self.gru(out) # out --- [1, N, 128]
547
+
548
+ return self.proj(out.squeeze(0))
549
+
550
+ def calculate_channels(self, L, kernel_size, stride, pad, n_convs):
551
+ for i in range(n_convs):
552
+ L = (L - kernel_size + 2 * pad) // stride + 1
553
+ return L
554
+
555
+
556
+ class SynthesizerTrn(nn.Module):
557
+ """
558
+ Synthesizer for Training
559
+ """
560
+
561
+ def __init__(self,
562
+ n_vocab,
563
+ spec_channels,
564
+ segment_size,
565
+ inter_channels,
566
+ hidden_channels,
567
+ filter_channels,
568
+ n_heads,
569
+ n_layers,
570
+ kernel_size,
571
+ p_dropout,
572
+ resblock,
573
+ resblock_kernel_sizes,
574
+ resblock_dilation_sizes,
575
+ upsample_rates,
576
+ upsample_initial_channel,
577
+ upsample_kernel_sizes,
578
+ n_speakers=256,
579
+ gin_channels=256,
580
+ use_sdp=True,
581
+ n_flow_layer = 4,
582
+ n_layers_trans_flow = 3,
583
+ flow_share_parameter = False,
584
+ use_transformer_flow = True,
585
+ **kwargs):
586
+
587
+ super().__init__()
588
+ self.n_vocab = n_vocab
589
+ self.spec_channels = spec_channels
590
+ self.inter_channels = inter_channels
591
+ self.hidden_channels = hidden_channels
592
+ self.filter_channels = filter_channels
593
+ self.n_heads = n_heads
594
+ self.n_layers = n_layers
595
+ self.kernel_size = kernel_size
596
+ self.p_dropout = p_dropout
597
+ self.resblock = resblock
598
+ self.resblock_kernel_sizes = resblock_kernel_sizes
599
+ self.resblock_dilation_sizes = resblock_dilation_sizes
600
+ self.upsample_rates = upsample_rates
601
+ self.upsample_initial_channel = upsample_initial_channel
602
+ self.upsample_kernel_sizes = upsample_kernel_sizes
603
+ self.segment_size = segment_size
604
+ self.n_speakers = n_speakers
605
+ self.gin_channels = gin_channels
606
+ self.n_layers_trans_flow = n_layers_trans_flow
607
+ self.use_spk_conditioned_encoder = kwargs.get("use_spk_conditioned_encoder", True)
608
+ self.use_sdp = use_sdp
609
+ self.use_noise_scaled_mas = kwargs.get("use_noise_scaled_mas", False)
610
+ self.mas_noise_scale_initial = kwargs.get("mas_noise_scale_initial", 0.01)
611
+ self.noise_scale_delta = kwargs.get("noise_scale_delta", 2e-6)
612
+ self.current_mas_noise_scale = self.mas_noise_scale_initial
613
+ if self.use_spk_conditioned_encoder and gin_channels > 0:
614
+ self.enc_gin_channels = gin_channels
615
+ self.enc_p = TextEncoder(n_vocab,
616
+ inter_channels,
617
+ hidden_channels,
618
+ filter_channels,
619
+ n_heads,
620
+ n_layers,
621
+ kernel_size,
622
+ p_dropout,
623
+ gin_channels=self.enc_gin_channels)
624
+ self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates,
625
+ upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
626
+ self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16,
627
+ gin_channels=gin_channels)
628
+ if use_transformer_flow:
629
+ self.flow = TransformerCouplingBlock(inter_channels, hidden_channels, filter_channels, n_heads, n_layers_trans_flow, 5, p_dropout, n_flow_layer, gin_channels=gin_channels,share_parameter= flow_share_parameter)
630
+ else:
631
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, n_flow_layer, gin_channels=gin_channels)
632
+ self.sdp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels)
633
+ self.dp = DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
634
+
635
+ if n_speakers >= 1:
636
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
637
+ else:
638
+ self.ref_enc = ReferenceEncoder(spec_channels, gin_channels)
639
+
640
+ def forward(self, x, x_lengths, y, y_lengths, sid, tone, language, bert):
641
+ if self.n_speakers > 0:
642
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
643
+ else:
644
+ g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1)
645
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g)
646
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
647
+ z_p = self.flow(z, y_mask, g=g)
648
+
649
+ with torch.no_grad():
650
+ # negative cross-entropy
651
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
652
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1], keepdim=True) # [b, 1, t_s]
653
+ neg_cent2 = torch.matmul(-0.5 * (z_p ** 2).transpose(1, 2),
654
+ s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
655
+ neg_cent3 = torch.matmul(z_p.transpose(1, 2), (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
656
+ neg_cent4 = torch.sum(-0.5 * (m_p ** 2) * s_p_sq_r, [1], keepdim=True) # [b, 1, t_s]
657
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
658
+ if self.use_noise_scaled_mas:
659
+ epsilon = torch.std(neg_cent) * torch.randn_like(neg_cent) * self.current_mas_noise_scale
660
+ neg_cent = neg_cent + epsilon
661
+
662
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
663
+ attn = monotonic_align.maximum_path(neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
664
+
665
+ w = attn.sum(2)
666
+
667
+ l_length_sdp = self.sdp(x, x_mask, w, g=g)
668
+ l_length_sdp = l_length_sdp / torch.sum(x_mask)
669
+
670
+ logw_ = torch.log(w + 1e-6) * x_mask
671
+ logw = self.dp(x, x_mask, g=g)
672
+ l_length_dp = torch.sum((logw - logw_) ** 2, [1, 2]) / torch.sum(x_mask) # for averaging
673
+
674
+ l_length = l_length_dp + l_length_sdp
675
+
676
+ # expand prior
677
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2)
678
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1, 2)
679
+
680
+ z_slice, ids_slice = commons.rand_slice_segments(z, y_lengths, self.segment_size)
681
+ o = self.dec(z_slice, g=g)
682
+ return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (x, logw, logw_)
683
+
684
+ def infer(self, x, x_lengths, sid, tone, language, bert, noise_scale=.667, length_scale=1, noise_scale_w=0.8, max_len=None, sdp_ratio=0,y=None):
685
+ #x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert)
686
+ # g = self.gst(y)
687
+ if self.n_speakers > 0:
688
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
689
+ else:
690
+ g = self.ref_enc(y.transpose(1,2)).unsqueeze(-1)
691
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths, tone, language, bert,g=g)
692
+ logw = self.sdp(x, x_mask, g=g, reverse=True, noise_scale=noise_scale_w) * (sdp_ratio) + self.dp(x, x_mask, g=g) * (1 - sdp_ratio)
693
+ w = torch.exp(logw) * x_mask * length_scale
694
+ w_ceil = torch.ceil(w)
695
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
696
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None), 1).to(x_mask.dtype)
697
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
698
+ attn = commons.generate_path(w_ceil, attn_mask)
699
+
700
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
701
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(1, 2)).transpose(1,
702
+ 2) # [b, t', t], [b, t, d] -> [b, d, t']
703
+
704
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
705
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
706
+ o = self.dec((z * y_mask)[:, :, :max_len], g=g)
707
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
modules.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import scipy
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
+ from torch.nn.utils import weight_norm, remove_weight_norm
11
+
12
+ import commons
13
+ from commons import init_weights, get_padding
14
+ from transforms import piecewise_rational_quadratic_transform
15
+ from attentions import Encoder
16
+
17
+ LRELU_SLOPE = 0.1
18
+
19
+ class LayerNorm(nn.Module):
20
+ def __init__(self, channels, eps=1e-5):
21
+ super().__init__()
22
+ self.channels = channels
23
+ self.eps = eps
24
+
25
+ self.gamma = nn.Parameter(torch.ones(channels))
26
+ self.beta = nn.Parameter(torch.zeros(channels))
27
+
28
+ def forward(self, x):
29
+ x = x.transpose(1, -1)
30
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
31
+ return x.transpose(1, -1)
32
+
33
+ class ConvReluNorm(nn.Module):
34
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
35
+ super().__init__()
36
+ self.in_channels = in_channels
37
+ self.hidden_channels = hidden_channels
38
+ self.out_channels = out_channels
39
+ self.kernel_size = kernel_size
40
+ self.n_layers = n_layers
41
+ self.p_dropout = p_dropout
42
+ assert n_layers > 1, "Number of layers should be larger than 0."
43
+
44
+ self.conv_layers = nn.ModuleList()
45
+ self.norm_layers = nn.ModuleList()
46
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
47
+ self.norm_layers.append(LayerNorm(hidden_channels))
48
+ self.relu_drop = nn.Sequential(
49
+ nn.ReLU(),
50
+ nn.Dropout(p_dropout))
51
+ for _ in range(n_layers-1):
52
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
53
+ self.norm_layers.append(LayerNorm(hidden_channels))
54
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
55
+ self.proj.weight.data.zero_()
56
+ self.proj.bias.data.zero_()
57
+
58
+ def forward(self, x, x_mask):
59
+ x_org = x
60
+ for i in range(self.n_layers):
61
+ x = self.conv_layers[i](x * x_mask)
62
+ x = self.norm_layers[i](x)
63
+ x = self.relu_drop(x)
64
+ x = x_org + self.proj(x)
65
+ return x * x_mask
66
+
67
+
68
+ class DDSConv(nn.Module):
69
+ """
70
+ Dialted and Depth-Separable Convolution
71
+ """
72
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
73
+ super().__init__()
74
+ self.channels = channels
75
+ self.kernel_size = kernel_size
76
+ self.n_layers = n_layers
77
+ self.p_dropout = p_dropout
78
+
79
+ self.drop = nn.Dropout(p_dropout)
80
+ self.convs_sep = nn.ModuleList()
81
+ self.convs_1x1 = nn.ModuleList()
82
+ self.norms_1 = nn.ModuleList()
83
+ self.norms_2 = nn.ModuleList()
84
+ for i in range(n_layers):
85
+ dilation = kernel_size ** i
86
+ padding = (kernel_size * dilation - dilation) // 2
87
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
88
+ groups=channels, dilation=dilation, padding=padding
89
+ ))
90
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
91
+ self.norms_1.append(LayerNorm(channels))
92
+ self.norms_2.append(LayerNorm(channels))
93
+
94
+ def forward(self, x, x_mask, g=None):
95
+ if g is not None:
96
+ x = x + g
97
+ for i in range(self.n_layers):
98
+ y = self.convs_sep[i](x * x_mask)
99
+ y = self.norms_1[i](y)
100
+ y = F.gelu(y)
101
+ y = self.convs_1x1[i](y)
102
+ y = self.norms_2[i](y)
103
+ y = F.gelu(y)
104
+ y = self.drop(y)
105
+ x = x + y
106
+ return x * x_mask
107
+
108
+
109
+ class WN(torch.nn.Module):
110
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
111
+ super(WN, self).__init__()
112
+ assert(kernel_size % 2 == 1)
113
+ self.hidden_channels =hidden_channels
114
+ self.kernel_size = kernel_size,
115
+ self.dilation_rate = dilation_rate
116
+ self.n_layers = n_layers
117
+ self.gin_channels = gin_channels
118
+ self.p_dropout = p_dropout
119
+
120
+ self.in_layers = torch.nn.ModuleList()
121
+ self.res_skip_layers = torch.nn.ModuleList()
122
+ self.drop = nn.Dropout(p_dropout)
123
+
124
+ if gin_channels != 0:
125
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
126
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
127
+
128
+ for i in range(n_layers):
129
+ dilation = dilation_rate ** i
130
+ padding = int((kernel_size * dilation - dilation) / 2)
131
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
132
+ dilation=dilation, padding=padding)
133
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
134
+ self.in_layers.append(in_layer)
135
+
136
+ # last one is not necessary
137
+ if i < n_layers - 1:
138
+ res_skip_channels = 2 * hidden_channels
139
+ else:
140
+ res_skip_channels = hidden_channels
141
+
142
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
143
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
144
+ self.res_skip_layers.append(res_skip_layer)
145
+
146
+ def forward(self, x, x_mask, g=None, **kwargs):
147
+ output = torch.zeros_like(x)
148
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
149
+
150
+ if g is not None:
151
+ g = self.cond_layer(g)
152
+
153
+ for i in range(self.n_layers):
154
+ x_in = self.in_layers[i](x)
155
+ if g is not None:
156
+ cond_offset = i * 2 * self.hidden_channels
157
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
158
+ else:
159
+ g_l = torch.zeros_like(x_in)
160
+
161
+ acts = commons.fused_add_tanh_sigmoid_multiply(
162
+ x_in,
163
+ g_l,
164
+ n_channels_tensor)
165
+ acts = self.drop(acts)
166
+
167
+ res_skip_acts = self.res_skip_layers[i](acts)
168
+ if i < self.n_layers - 1:
169
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
170
+ x = (x + res_acts) * x_mask
171
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
172
+ else:
173
+ output = output + res_skip_acts
174
+ return output * x_mask
175
+
176
+ def remove_weight_norm(self):
177
+ if self.gin_channels != 0:
178
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
179
+ for l in self.in_layers:
180
+ torch.nn.utils.remove_weight_norm(l)
181
+ for l in self.res_skip_layers:
182
+ torch.nn.utils.remove_weight_norm(l)
183
+
184
+
185
+ class ResBlock1(torch.nn.Module):
186
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
187
+ super(ResBlock1, self).__init__()
188
+ self.convs1 = nn.ModuleList([
189
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
190
+ padding=get_padding(kernel_size, dilation[0]))),
191
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
192
+ padding=get_padding(kernel_size, dilation[1]))),
193
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
194
+ padding=get_padding(kernel_size, dilation[2])))
195
+ ])
196
+ self.convs1.apply(init_weights)
197
+
198
+ self.convs2 = nn.ModuleList([
199
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
200
+ padding=get_padding(kernel_size, 1))),
201
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
202
+ padding=get_padding(kernel_size, 1))),
203
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
204
+ padding=get_padding(kernel_size, 1)))
205
+ ])
206
+ self.convs2.apply(init_weights)
207
+
208
+ def forward(self, x, x_mask=None):
209
+ for c1, c2 in zip(self.convs1, self.convs2):
210
+ xt = F.leaky_relu(x, LRELU_SLOPE)
211
+ if x_mask is not None:
212
+ xt = xt * x_mask
213
+ xt = c1(xt)
214
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
215
+ if x_mask is not None:
216
+ xt = xt * x_mask
217
+ xt = c2(xt)
218
+ x = xt + x
219
+ if x_mask is not None:
220
+ x = x * x_mask
221
+ return x
222
+
223
+ def remove_weight_norm(self):
224
+ for l in self.convs1:
225
+ remove_weight_norm(l)
226
+ for l in self.convs2:
227
+ remove_weight_norm(l)
228
+
229
+
230
+ class ResBlock2(torch.nn.Module):
231
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
232
+ super(ResBlock2, self).__init__()
233
+ self.convs = nn.ModuleList([
234
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
235
+ padding=get_padding(kernel_size, dilation[0]))),
236
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
237
+ padding=get_padding(kernel_size, dilation[1])))
238
+ ])
239
+ self.convs.apply(init_weights)
240
+
241
+ def forward(self, x, x_mask=None):
242
+ for c in self.convs:
243
+ xt = F.leaky_relu(x, LRELU_SLOPE)
244
+ if x_mask is not None:
245
+ xt = xt * x_mask
246
+ xt = c(xt)
247
+ x = xt + x
248
+ if x_mask is not None:
249
+ x = x * x_mask
250
+ return x
251
+
252
+ def remove_weight_norm(self):
253
+ for l in self.convs:
254
+ remove_weight_norm(l)
255
+
256
+
257
+ class Log(nn.Module):
258
+ def forward(self, x, x_mask, reverse=False, **kwargs):
259
+ if not reverse:
260
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
261
+ logdet = torch.sum(-y, [1, 2])
262
+ return y, logdet
263
+ else:
264
+ x = torch.exp(x) * x_mask
265
+ return x
266
+
267
+
268
+ class Flip(nn.Module):
269
+ def forward(self, x, *args, reverse=False, **kwargs):
270
+ x = torch.flip(x, [1])
271
+ if not reverse:
272
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
273
+ return x, logdet
274
+ else:
275
+ return x
276
+
277
+
278
+ class ElementwiseAffine(nn.Module):
279
+ def __init__(self, channels):
280
+ super().__init__()
281
+ self.channels = channels
282
+ self.m = nn.Parameter(torch.zeros(channels,1))
283
+ self.logs = nn.Parameter(torch.zeros(channels,1))
284
+
285
+ def forward(self, x, x_mask, reverse=False, **kwargs):
286
+ if not reverse:
287
+ y = self.m + torch.exp(self.logs) * x
288
+ y = y * x_mask
289
+ logdet = torch.sum(self.logs * x_mask, [1,2])
290
+ return y, logdet
291
+ else:
292
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
293
+ return x
294
+
295
+
296
+ class ResidualCouplingLayer(nn.Module):
297
+ def __init__(self,
298
+ channels,
299
+ hidden_channels,
300
+ kernel_size,
301
+ dilation_rate,
302
+ n_layers,
303
+ p_dropout=0,
304
+ gin_channels=0,
305
+ mean_only=False):
306
+ assert channels % 2 == 0, "channels should be divisible by 2"
307
+ super().__init__()
308
+ self.channels = channels
309
+ self.hidden_channels = hidden_channels
310
+ self.kernel_size = kernel_size
311
+ self.dilation_rate = dilation_rate
312
+ self.n_layers = n_layers
313
+ self.half_channels = channels // 2
314
+ self.mean_only = mean_only
315
+
316
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
317
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
318
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
319
+ self.post.weight.data.zero_()
320
+ self.post.bias.data.zero_()
321
+
322
+ def forward(self, x, x_mask, g=None, reverse=False):
323
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
324
+ h = self.pre(x0) * x_mask
325
+ h = self.enc(h, x_mask, g=g)
326
+ stats = self.post(h) * x_mask
327
+ if not self.mean_only:
328
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
329
+ else:
330
+ m = stats
331
+ logs = torch.zeros_like(m)
332
+
333
+ if not reverse:
334
+ x1 = m + x1 * torch.exp(logs) * x_mask
335
+ x = torch.cat([x0, x1], 1)
336
+ logdet = torch.sum(logs, [1,2])
337
+ return x, logdet
338
+ else:
339
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
340
+ x = torch.cat([x0, x1], 1)
341
+ return x
342
+
343
+
344
+ class ConvFlow(nn.Module):
345
+ def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
346
+ super().__init__()
347
+ self.in_channels = in_channels
348
+ self.filter_channels = filter_channels
349
+ self.kernel_size = kernel_size
350
+ self.n_layers = n_layers
351
+ self.num_bins = num_bins
352
+ self.tail_bound = tail_bound
353
+ self.half_channels = in_channels // 2
354
+
355
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
356
+ self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
357
+ self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
358
+ self.proj.weight.data.zero_()
359
+ self.proj.bias.data.zero_()
360
+
361
+ def forward(self, x, x_mask, g=None, reverse=False):
362
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
363
+ h = self.pre(x0)
364
+ h = self.convs(h, x_mask, g=g)
365
+ h = self.proj(h) * x_mask
366
+
367
+ b, c, t = x0.shape
368
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
369
+
370
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
371
+ unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
372
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
373
+
374
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
375
+ unnormalized_widths,
376
+ unnormalized_heights,
377
+ unnormalized_derivatives,
378
+ inverse=reverse,
379
+ tails='linear',
380
+ tail_bound=self.tail_bound
381
+ )
382
+
383
+ x = torch.cat([x0, x1], 1) * x_mask
384
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
385
+ if not reverse:
386
+ return x, logdet
387
+ else:
388
+ return x
389
+ class TransformerCouplingLayer(nn.Module):
390
+ def __init__(self,
391
+ channels,
392
+ hidden_channels,
393
+ kernel_size,
394
+ n_layers,
395
+ n_heads,
396
+ p_dropout=0,
397
+ filter_channels=0,
398
+ mean_only=False,
399
+ wn_sharing_parameter=None,
400
+ gin_channels = 0
401
+ ):
402
+ assert channels % 2 == 0, "channels should be divisible by 2"
403
+ super().__init__()
404
+ self.channels = channels
405
+ self.hidden_channels = hidden_channels
406
+ self.kernel_size = kernel_size
407
+ self.n_layers = n_layers
408
+ self.half_channels = channels // 2
409
+ self.mean_only = mean_only
410
+
411
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
412
+ self.enc = Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter
413
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
414
+ self.post.weight.data.zero_()
415
+ self.post.bias.data.zero_()
416
+
417
+ def forward(self, x, x_mask, g=None, reverse=False):
418
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
419
+ h = self.pre(x0) * x_mask
420
+ h = self.enc(h, x_mask, g=g)
421
+ stats = self.post(h) * x_mask
422
+ if not self.mean_only:
423
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
424
+ else:
425
+ m = stats
426
+ logs = torch.zeros_like(m)
427
+
428
+ if not reverse:
429
+ x1 = m + x1 * torch.exp(logs) * x_mask
430
+ x = torch.cat([x0, x1], 1)
431
+ logdet = torch.sum(logs, [1,2])
432
+ return x, logdet
433
+ else:
434
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
435
+ x = torch.cat([x0, x1], 1)
436
+ return x
437
+
438
+ x1, logabsdet = piecewise_rational_quadratic_transform(x1,
439
+ unnormalized_widths,
440
+ unnormalized_heights,
441
+ unnormalized_derivatives,
442
+ inverse=reverse,
443
+ tails='linear',
444
+ tail_bound=self.tail_bound
445
+ )
446
+
447
+ x = torch.cat([x0, x1], 1) * x_mask
448
+ logdet = torch.sum(logabsdet * x_mask, [1,2])
449
+ if not reverse:
450
+ return x, logdet
451
+ else:
452
+ return x
monotonic_align/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from .monotonic_align.core import maximum_path_c
4
+
5
+
6
+ def maximum_path(neg_cent, mask):
7
+ """ Cython optimized version.
8
+ neg_cent: [b, t_t, t_s]
9
+ mask: [b, t_t, t_s]
10
+ """
11
+ device = neg_cent.device
12
+ dtype = neg_cent.dtype
13
+ neg_cent = neg_cent.data.cpu().numpy().astype(np.float32)
14
+ path = np.zeros(neg_cent.shape, dtype=np.int32)
15
+
16
+ t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(np.int32)
17
+ t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(np.int32)
18
+ maximum_path_c(path, neg_cent, t_t_max, t_s_max)
19
+ return torch.from_numpy(path).to(device=device, dtype=dtype)
monotonic_align/core.c ADDED
The diff for this file is too large to render. See raw diff
 
monotonic_align/core.pyx ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport cython
2
+ from cython.parallel import prange
3
+
4
+
5
+ @cython.boundscheck(False)
6
+ @cython.wraparound(False)
7
+ cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil:
8
+ cdef int x
9
+ cdef int y
10
+ cdef float v_prev
11
+ cdef float v_cur
12
+ cdef float tmp
13
+ cdef int index = t_x - 1
14
+
15
+ for y in range(t_y):
16
+ for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
17
+ if x == y:
18
+ v_cur = max_neg_val
19
+ else:
20
+ v_cur = value[y-1, x]
21
+ if x == 0:
22
+ if y == 0:
23
+ v_prev = 0.
24
+ else:
25
+ v_prev = max_neg_val
26
+ else:
27
+ v_prev = value[y-1, x-1]
28
+ value[y, x] += max(v_prev, v_cur)
29
+
30
+ for y in range(t_y - 1, -1, -1):
31
+ path[y, index] = 1
32
+ if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]):
33
+ index = index - 1
34
+
35
+
36
+ @cython.boundscheck(False)
37
+ @cython.wraparound(False)
38
+ cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil:
39
+ cdef int b = paths.shape[0]
40
+ cdef int i
41
+ for i in prange(b, nogil=True):
42
+ maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i])
monotonic_align/monotonic_align/monotonic_align ADDED
File without changes
monotonic_align/setup.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from distutils.core import setup
2
+ from Cython.Build import cythonize
3
+ import numpy
4
+
5
+ setup(
6
+ name = 'monotonic_align',
7
+ ext_modules = cythonize("core.pyx"),
8
+ include_dirs=[numpy.get_include()]
9
+ )
preprocess_text.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from random import shuffle
3
+
4
+ import tqdm
5
+ from text.cleaner import clean_text
6
+ from collections import defaultdict
7
+ import shutil
8
+ stage = [1,2,3]
9
+
10
+ transcription_path = 'filelists/short_character_anno.list'
11
+ train_path = 'filelists/train.list'
12
+ val_path = 'filelists/val.list'
13
+ config_path = "configs/config.json"
14
+ val_per_spk = 4
15
+ max_val_total = 8
16
+
17
+ if 1 in stage:
18
+ with open( transcription_path+'.cleaned', 'w', encoding='utf-8') as f:
19
+ for line in tqdm.tqdm(open(transcription_path, encoding='utf-8').readlines()):
20
+ try:
21
+ utt, spk, language, text = line.strip().split('|')
22
+ #language = "ZH"
23
+ norm_text, phones, tones, word2ph = clean_text(text, language)
24
+ f.write('{}|{}|{}|{}|{}|{}|{}\n'.format(utt, spk, language, norm_text, ' '.join(phones),
25
+ " ".join([str(i) for i in tones]),
26
+ " ".join([str(i) for i in word2ph])))
27
+ except:
28
+ print("err!", utt)
29
+
30
+ if 2 in stage:
31
+ spk_utt_map = defaultdict(list)
32
+ spk_id_map = {}
33
+ current_sid = 0
34
+
35
+ with open( transcription_path+'.cleaned', encoding='utf-8') as f:
36
+ for line in f.readlines():
37
+ utt, spk, language, text, phones, tones, word2ph = line.strip().split('|')
38
+ spk_utt_map[spk].append(line)
39
+ if spk not in spk_id_map.keys():
40
+ spk_id_map[spk] = current_sid
41
+ current_sid += 1
42
+ train_list = []
43
+ val_list = []
44
+ for spk, utts in spk_utt_map.items():
45
+ shuffle(utts)
46
+ val_list+=utts[:val_per_spk]
47
+ train_list+=utts[val_per_spk:]
48
+ if len(val_list) > max_val_total:
49
+ train_list+=val_list[max_val_total:]
50
+ val_list = val_list[:max_val_total]
51
+
52
+ with open( train_path,"w", encoding='utf-8') as f:
53
+ for line in train_list:
54
+ f.write(line)
55
+
56
+ file_path = transcription_path+'.cleaned'
57
+ shutil.copy(file_path,'./filelists/train.list')
58
+
59
+ with open(val_path, "w", encoding='utf-8') as f:
60
+ for line in val_list:
61
+ f.write(line)
62
+
63
+ if 3 in stage:
64
+ assert 2 in stage
65
+ config = json.load(open(config_path))
66
+ config['data']["n_speakers"] = current_sid #
67
+ config["data"]['spk2id'] = spk_id_map
68
+ with open(config_path, 'w', encoding='utf-8') as f:
69
+ json.dump(config, f, indent=2, ensure_ascii=False)
requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ librosa==0.9.1
2
+ matplotlib
3
+ numpy
4
+ numba
5
+ phonemizer
6
+ scipy
7
+ tensorboard
8
+ torch
9
+ torchaudio
10
+ torchvision
11
+ Unidecode
12
+ amfm_decompy
13
+ jieba
14
+ transformers
15
+ pypinyin
16
+ cn2an
17
+ gradio
18
+ av
19
+ mecab-python3
20
+ loguru
21
+ unidic-lite
22
+ cmudict
23
+ fugashi
24
+ num2words
25
+ Cython==0.29.21
26
+ openai-whisper
setup_ffmpeg.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import re
4
+ from pathlib import Path
5
+ import winreg
6
+
7
+ def check_ffmpeg_path():
8
+ path_list = os.environ['Path'].split(';')
9
+ ffmpeg_found = False
10
+
11
+ for path in path_list:
12
+ if 'ffmpeg' in path.lower() and 'bin' in path.lower():
13
+ ffmpeg_found = True
14
+ print("FFmpeg already installed.")
15
+ break
16
+
17
+ return ffmpeg_found
18
+
19
+ def add_ffmpeg_path_to_user_variable():
20
+ ffmpeg_bin_path = Path('.\\ffmpeg\\bin')
21
+ if ffmpeg_bin_path.is_dir():
22
+ abs_path = str(ffmpeg_bin_path.resolve())
23
+
24
+ try:
25
+ key = winreg.OpenKey(
26
+ winreg.HKEY_CURRENT_USER,
27
+ r"Environment",
28
+ 0,
29
+ winreg.KEY_READ | winreg.KEY_WRITE
30
+ )
31
+
32
+ try:
33
+ current_path, _ = winreg.QueryValueEx(key, "Path")
34
+ if abs_path not in current_path:
35
+ new_path = f"{current_path};{abs_path}"
36
+ winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
37
+ print(f"Added FFmpeg path to user variable 'Path': {abs_path}")
38
+ else:
39
+ print("FFmpeg path already exists in the user variable 'Path'.")
40
+ finally:
41
+ winreg.CloseKey(key)
42
+ except WindowsError:
43
+ print("Error: Unable to modify user variable 'Path'.")
44
+ sys.exit(1)
45
+
46
+ else:
47
+ print("Error: ffmpeg\\bin folder not found in the current path.")
48
+ sys.exit(1)
49
+
50
+ def main():
51
+ if not check_ffmpeg_path():
52
+ add_ffmpeg_path_to_user_variable()
53
+
54
+ if __name__ == "__main__":
55
+ main()
short_audio_transcribe.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import whisper
2
+ import os
3
+ import json
4
+ import torchaudio
5
+ import argparse
6
+ import torch
7
+
8
+ lang2token = {
9
+ 'zh': "[ZH]",
10
+ 'ja': "[JA]",
11
+ "en": "[EN]",
12
+ }
13
+ def transcribe_one(audio_path):
14
+ # load audio and pad/trim it to fit 30 seconds
15
+ audio = whisper.load_audio(audio_path)
16
+ audio = whisper.pad_or_trim(audio)
17
+
18
+ # make log-Mel spectrogram and move to the same device as the model
19
+ mel = whisper.log_mel_spectrogram(audio).to(model.device)
20
+
21
+ # detect the spoken language
22
+ _, probs = model.detect_language(mel)
23
+ print(f"Detected language: {max(probs, key=probs.get)}")
24
+ lang = max(probs, key=probs.get)
25
+ # decode the audio
26
+ options = whisper.DecodingOptions(beam_size=5)
27
+ result = whisper.decode(model, mel, options)
28
+
29
+ # print the recognized text
30
+ print(result.text)
31
+ return lang, result.text
32
+ if __name__ == "__main__":
33
+ parser = argparse.ArgumentParser()
34
+ parser.add_argument("--languages", default="CJE")
35
+ parser.add_argument("--whisper_size", default="medium")
36
+ args = parser.parse_args()
37
+ if args.languages == "CJE":
38
+ lang2token = {
39
+ 'zh': "[ZH]",
40
+ 'ja': "[JA]",
41
+ "en": "[EN]",
42
+ }
43
+ elif args.languages == "CJ":
44
+ lang2token = {
45
+ 'zh': "[ZH]",
46
+ 'ja': "[JA]",
47
+ }
48
+ elif args.languages == "C":
49
+ lang2token = {
50
+ 'zh': "[ZH]",
51
+ }
52
+ assert (torch.cuda.is_available()), "Please enable GPU in order to run Whisper!"
53
+ model = whisper.load_model(args.whisper_size)
54
+ parent_dir = "./custom_character_voice/"
55
+ speaker_names = list(os.walk(parent_dir))[0][1]
56
+ speaker_annos = []
57
+ total_files = sum([len(files) for r, d, files in os.walk(parent_dir)])
58
+ # resample audios
59
+ # 2023/4/21: Get the target sampling rate
60
+ with open("./configs/config.json", 'r', encoding='utf-8') as f:
61
+ hps = json.load(f)
62
+ target_sr = hps['data']['sampling_rate']
63
+ processed_files = 0
64
+ for speaker in speaker_names:
65
+ for i, wavfile in enumerate(list(os.walk(parent_dir + speaker))[0][2]):
66
+ # try to load file as audio
67
+ if wavfile.startswith("processed_"):
68
+ continue
69
+ try:
70
+ wav, sr = torchaudio.load(parent_dir + speaker + "/" + wavfile, frame_offset=0, num_frames=-1, normalize=True,
71
+ channels_first=True)
72
+ wav = wav.mean(dim=0).unsqueeze(0)
73
+ if sr != target_sr:
74
+ wav = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sr)(wav)
75
+ if wav.shape[1] / sr > 20:
76
+ print(f"{wavfile} too long, ignoring\n")
77
+ save_path = parent_dir + speaker + "/" + f"processed_{i}.wav"
78
+ torchaudio.save(save_path, wav, target_sr, channels_first=True)
79
+ # transcribe text
80
+ lang, text = transcribe_one(save_path)
81
+ if lang not in list(lang2token.keys()):
82
+ print(f"{lang} not supported, ignoring\n")
83
+ continue
84
+ text = "ZH|" + text + "\n"#
85
+ #text = lang2token[lang] + text + lang2token[lang] + "\n"
86
+ speaker_annos.append(save_path + "|" + speaker + "|" + text)
87
+
88
+ processed_files += 1
89
+ print(f"Processed: {processed_files}/{total_files}")
90
+ except:
91
+ continue
92
+
93
+ # # clean annotation
94
+ # import argparse
95
+ # import text
96
+ # from utils import load_filepaths_and_text
97
+ # for i, line in enumerate(speaker_annos):
98
+ # path, sid, txt = line.split("|")
99
+ # cleaned_text = text._clean_text(txt, ["cjke_cleaners2"])
100
+ # cleaned_text += "\n" if not cleaned_text.endswith("\n") else ""
101
+ # speaker_annos[i] = path + "|" + sid + "|" + cleaned_text
102
+ # write into annotation
103
+ if len(speaker_annos) == 0:
104
+ print("Warning: no short audios found, this IS expected if you have only uploaded long audios, videos or video links.")
105
+ print("this IS NOT expected if you have uploaded a zip file of short audios. Please check your file structure or make sure your audio language is supported.")
106
+ with open("./filelists/short_character_anno.list", 'w', encoding='utf-8') as f:
107
+ for line in speaker_annos:
108
+ f.write(line)
109
+
110
+ # import json
111
+ # # generate new config
112
+ # with open("./configs/finetune_speaker.json", 'r', encoding='utf-8') as f:
113
+ # hps = json.load(f)
114
+ # # modify n_speakers
115
+ # hps['data']["n_speakers"] = 1000 + len(speaker2id)
116
+ # # add speaker names
117
+ # for speaker in speaker_names:
118
+ # hps['speakers'][speaker] = speaker2id[speaker]
119
+ # # save modified config
120
+ # with open("./configs/modified_finetune_speaker.json", 'w', encoding='utf-8') as f:
121
+ # json.dump(hps, f, indent=2)
122
+ # print("finished")
start.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ set PYTHON=venv\python.exe
2
+ start cmd /k "set PYTHON=%PYTHON%"
text/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from text.symbols import *
2
+
3
+
4
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
5
+
6
+ def cleaned_text_to_sequence(cleaned_text, tones, language):
7
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
8
+ Args:
9
+ text: string to convert to a sequence
10
+ Returns:
11
+ List of integers corresponding to the symbols in the text
12
+ '''
13
+ phones = [_symbol_to_id[symbol] for symbol in cleaned_text]
14
+ tone_start = language_tone_start_map[language]
15
+ tones = [i + tone_start for i in tones]
16
+ lang_id = language_id_map[language]
17
+ lang_ids = [lang_id for i in phones]
18
+ return phones, tones, lang_ids
19
+
20
+ def get_bert(norm_text, word2ph, language):
21
+ from .chinese_bert import get_bert_feature as zh_bert
22
+ from .english_bert_mock import get_bert_feature as en_bert
23
+ lang_bert_func_map = {
24
+ 'ZH': zh_bert,
25
+ 'EN': en_bert
26
+ }
27
+ bert = lang_bert_func_map[language](norm_text, word2ph)
28
+ return bert
text/chinese.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+
4
+ import cn2an
5
+ from pypinyin import lazy_pinyin, Style
6
+
7
+ from text import symbols
8
+ from text.symbols import punctuation
9
+ from text.tone_sandhi import ToneSandhi
10
+
11
+ current_file_path = os.path.dirname(__file__)
12
+ pinyin_to_symbol_map = {line.split("\t")[0]: line.strip().split("\t")[1] for line in
13
+ open(os.path.join(current_file_path, 'opencpop-strict.txt')).readlines()}
14
+
15
+ import jieba.posseg as psg
16
+
17
+
18
+ rep_map = {
19
+ ':': ',',
20
+ ';': ',',
21
+ ',': ',',
22
+ '。': '.',
23
+ '!': '!',
24
+ '?': '?',
25
+ '\n': '.',
26
+ "·": ",",
27
+ '、': ",",
28
+ '...': '…',
29
+ '$': '.',
30
+ '“': "'",
31
+ '”': "'",
32
+ '‘': "'",
33
+ '’': "'",
34
+ '(': "'",
35
+ ')': "'",
36
+ '(': "'",
37
+ ')': "'",
38
+ '《': "'",
39
+ '》': "'",
40
+ '【': "'",
41
+ '】': "'",
42
+ '[': "'",
43
+ ']': "'",
44
+ '—': "-",
45
+ '~': "-",
46
+ '~': "-",
47
+ '「': "'",
48
+ '」': "'",
49
+
50
+ }
51
+
52
+ tone_modifier = ToneSandhi()
53
+
54
+ def replace_punctuation(text):
55
+ text = text.replace("嗯", "恩").replace("呣","母")
56
+ pattern = re.compile('|'.join(re.escape(p) for p in rep_map.keys()))
57
+
58
+ replaced_text = pattern.sub(lambda x: rep_map[x.group()], text)
59
+
60
+ replaced_text = re.sub(r'[^\u4e00-\u9fa5'+"".join(punctuation)+r']+', '', replaced_text)
61
+
62
+ return replaced_text
63
+
64
+ def g2p(text):
65
+ pattern = r'(?<=[{0}])\s*'.format(''.join(punctuation))
66
+ sentences = [i for i in re.split(pattern, text) if i.strip()!='']
67
+ phones, tones, word2ph = _g2p(sentences)
68
+ assert sum(word2ph) == len(phones)
69
+ assert len(word2ph) == len(text) #Sometimes it will crash,you can add a try-catch.
70
+ phones = ['_'] + phones + ["_"]
71
+ tones = [0] + tones + [0]
72
+ word2ph = [1] + word2ph + [1]
73
+ return phones, tones, word2ph
74
+
75
+
76
+ def _get_initials_finals(word):
77
+ initials = []
78
+ finals = []
79
+ orig_initials = lazy_pinyin(
80
+ word, neutral_tone_with_five=True, style=Style.INITIALS)
81
+ orig_finals = lazy_pinyin(
82
+ word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
83
+ for c, v in zip(orig_initials, orig_finals):
84
+ initials.append(c)
85
+ finals.append(v)
86
+ return initials, finals
87
+
88
+
89
+ def _g2p(segments):
90
+ phones_list = []
91
+ tones_list = []
92
+ word2ph = []
93
+ for seg in segments:
94
+ pinyins = []
95
+ # Replace all English words in the sentence
96
+ seg = re.sub('[a-zA-Z]+', '', seg)
97
+ seg_cut = psg.lcut(seg)
98
+ initials = []
99
+ finals = []
100
+ seg_cut = tone_modifier.pre_merge_for_modify(seg_cut)
101
+ for word, pos in seg_cut:
102
+ if pos == 'eng':
103
+ continue
104
+ sub_initials, sub_finals = _get_initials_finals(word)
105
+ sub_finals = tone_modifier.modified_tone(word, pos,
106
+ sub_finals)
107
+ initials.append(sub_initials)
108
+ finals.append(sub_finals)
109
+
110
+ # assert len(sub_initials) == len(sub_finals) == len(word)
111
+ initials = sum(initials, [])
112
+ finals = sum(finals, [])
113
+ #
114
+ for c, v in zip(initials, finals):
115
+ raw_pinyin = c+v
116
+ # NOTE: post process for pypinyin outputs
117
+ # we discriminate i, ii and iii
118
+ if c == v:
119
+ assert c in punctuation
120
+ phone = [c]
121
+ tone = '0'
122
+ word2ph.append(1)
123
+ else:
124
+ v_without_tone = v[:-1]
125
+ tone = v[-1]
126
+
127
+ pinyin = c+v_without_tone
128
+ assert tone in '12345'
129
+
130
+ if c:
131
+ # 多音节
132
+ v_rep_map = {
133
+ "uei": 'ui',
134
+ 'iou': 'iu',
135
+ 'uen': 'un',
136
+ }
137
+ if v_without_tone in v_rep_map.keys():
138
+ pinyin = c+v_rep_map[v_without_tone]
139
+ else:
140
+ # 单音节
141
+ pinyin_rep_map = {
142
+ 'ing': 'ying',
143
+ 'i': 'yi',
144
+ 'in': 'yin',
145
+ 'u': 'wu',
146
+ }
147
+ if pinyin in pinyin_rep_map.keys():
148
+ pinyin = pinyin_rep_map[pinyin]
149
+ else:
150
+ single_rep_map = {
151
+ 'v': 'yu',
152
+ 'e': 'e',
153
+ 'i': 'y',
154
+ 'u': 'w',
155
+ }
156
+ if pinyin[0] in single_rep_map.keys():
157
+ pinyin = single_rep_map[pinyin[0]]+pinyin[1:]
158
+
159
+ assert pinyin in pinyin_to_symbol_map.keys(), (pinyin, seg, raw_pinyin)
160
+ phone = pinyin_to_symbol_map[pinyin].split(' ')
161
+ word2ph.append(len(phone))
162
+
163
+ phones_list += phone
164
+ tones_list += [int(tone)] * len(phone)
165
+ return phones_list, tones_list, word2ph
166
+
167
+
168
+
169
+ def text_normalize(text):
170
+ numbers = re.findall(r'\d+(?:\.?\d+)?', text)
171
+ for number in numbers:
172
+ text = text.replace(number, cn2an.an2cn(number), 1)
173
+ text = replace_punctuation(text)
174
+ return text
175
+
176
+ def get_bert_feature(text, word2ph):
177
+ from text import chinese_bert
178
+ return chinese_bert.get_bert_feature(text, word2ph)
179
+
180
+ if __name__ == '__main__':
181
+ from text.chinese_bert import get_bert_feature
182
+ text = "啊!但是《原神》是由,米哈\游自主, [研发]的一款全.新开放世界.冒险游戏"
183
+ text = text_normalize(text)
184
+ print(text)
185
+ phones, tones, word2ph = g2p(text)
186
+ bert = get_bert_feature(text, word2ph)
187
+
188
+ print(phones, tones, word2ph, bert.shape)
189
+
190
+
191
+ # # 示例用法
192
+ # text = "这是一个示例文本:,你好!这是一个测试...."
193
+ # print(g2p_paddle(text)) # 输出: 这是一个示例文本你好这是一个测试
text/chinese_bert.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
3
+
4
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
5
+
6
+ tokenizer = AutoTokenizer.from_pretrained("./bert/chinese-roberta-wwm-ext-large")
7
+ model = AutoModelForMaskedLM.from_pretrained("./bert/chinese-roberta-wwm-ext-large").to(device)
8
+
9
+ def get_bert_feature(text, word2ph):
10
+ with torch.no_grad():
11
+ inputs = tokenizer(text, return_tensors='pt')
12
+ for i in inputs:
13
+ inputs[i] = inputs[i].to(device)
14
+ res = model(**inputs, output_hidden_states=True)
15
+ res = torch.cat(res['hidden_states'][-3:-2], -1)[0].cpu()
16
+
17
+ assert len(word2ph) == len(text)+2
18
+ word2phone = word2ph
19
+ phone_level_feature = []
20
+ for i in range(len(word2phone)):
21
+ repeat_feature = res[i].repeat(word2phone[i], 1)
22
+ phone_level_feature.append(repeat_feature)
23
+
24
+ phone_level_feature = torch.cat(phone_level_feature, dim=0)
25
+
26
+
27
+ return phone_level_feature.T
28
+
29
+ if __name__ == '__main__':
30
+ # feature = get_bert_feature('你好,我是说的道理。')
31
+ import torch
32
+
33
+ word_level_feature = torch.rand(38, 1024) # 12个词,每个词1024维特征
34
+ word2phone = [1, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1]
35
+
36
+ # 计算总帧数
37
+ total_frames = sum(word2phone)
38
+ print(word_level_feature.shape)
39
+ print(word2phone)
40
+ phone_level_feature = []
41
+ for i in range(len(word2phone)):
42
+ print(word_level_feature[i].shape)
43
+
44
+ # 对每个词重复word2phone[i]次
45
+ repeat_feature = word_level_feature[i].repeat(word2phone[i], 1)
46
+ phone_level_feature.append(repeat_feature)
47
+
48
+ phone_level_feature = torch.cat(phone_level_feature, dim=0)
49
+ print(phone_level_feature.shape) # torch.Size([36, 1024])
50
+
text/cleaner.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from text import chinese, cleaned_text_to_sequence
2
+
3
+
4
+ language_module_map = {
5
+ 'ZH': chinese
6
+ }
7
+
8
+
9
+ def clean_text(text, language):
10
+ language_module = language_module_map[language]
11
+ norm_text = language_module.text_normalize(text)
12
+ phones, tones, word2ph = language_module.g2p(norm_text)
13
+ return norm_text, phones, tones, word2ph
14
+
15
+ def clean_text_bert(text, language):
16
+ language_module = language_module_map[language]
17
+ norm_text = language_module.text_normalize(text)
18
+ phones, tones, word2ph = language_module.g2p(norm_text)
19
+ bert = language_module.get_bert_feature(norm_text, word2ph)
20
+ return phones, tones, bert
21
+
22
+ def text_to_sequence(text, language):
23
+ norm_text, phones, tones, word2ph = clean_text(text, language)
24
+ return cleaned_text_to_sequence(phones, tones, language)
25
+
26
+ if __name__ == '__main__':
27
+ pass
text/cmudict.rep ADDED
The diff for this file is too large to render. See raw diff
 
text/cmudict_cache.pickle ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9b21b20325471934ba92f2e4a5976989e7d920caa32e7a286eacb027d197949
3
+ size 6212655
text/english.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import os
3
+ import re
4
+ from g2p_en import G2p
5
+ from string import punctuation
6
+
7
+ from text import symbols
8
+
9
+ current_file_path = os.path.dirname(__file__)
10
+ CMU_DICT_PATH = os.path.join(current_file_path, 'cmudict.rep')
11
+ CACHE_PATH = os.path.join(current_file_path, 'cmudict_cache.pickle')
12
+ _g2p = G2p()
13
+
14
+ arpa = {'AH0', 'S', 'AH1', 'EY2', 'AE2', 'EH0', 'OW2', 'UH0', 'NG', 'B', 'G', 'AY0', 'M', 'AA0', 'F', 'AO0', 'ER2', 'UH1', 'IY1', 'AH2', 'DH', 'IY0', 'EY1', 'IH0', 'K', 'N', 'W', 'IY2', 'T', 'AA1', 'ER1', 'EH2', 'OY0', 'UH2', 'UW1', 'Z', 'AW2', 'AW1', 'V', 'UW2', 'AA2', 'ER', 'AW0', 'UW0', 'R', 'OW1', 'EH1', 'ZH', 'AE0', 'IH2', 'IH', 'Y', 'JH', 'P', 'AY1', 'EY0', 'OY2', 'TH', 'HH', 'D', 'ER0', 'CH', 'AO1', 'AE1', 'AO2', 'OY1', 'AY2', 'IH1', 'OW0', 'L', 'SH'}
15
+
16
+
17
+ def post_replace_ph(ph):
18
+ rep_map = {
19
+ ':': ',',
20
+ ';': ',',
21
+ ',': ',',
22
+ '。': '.',
23
+ '!': '!',
24
+ '?': '?',
25
+ '\n': '.',
26
+ "·": ",",
27
+ '、': ",",
28
+ '...': '…',
29
+ 'v': "V"
30
+ }
31
+ if ph in rep_map.keys():
32
+ ph = rep_map[ph]
33
+ if ph in symbols:
34
+ return ph
35
+ if ph not in symbols:
36
+ ph = 'UNK'
37
+ return ph
38
+
39
+ def read_dict():
40
+ g2p_dict = {}
41
+ start_line = 49
42
+ with open(CMU_DICT_PATH) as f:
43
+ line = f.readline()
44
+ line_index = 1
45
+ while line:
46
+ if line_index >= start_line:
47
+ line = line.strip()
48
+ word_split = line.split(' ')
49
+ word = word_split[0]
50
+
51
+ syllable_split = word_split[1].split(' - ')
52
+ g2p_dict[word] = []
53
+ for syllable in syllable_split:
54
+ phone_split = syllable.split(' ')
55
+ g2p_dict[word].append(phone_split)
56
+
57
+ line_index = line_index + 1
58
+ line = f.readline()
59
+
60
+ return g2p_dict
61
+
62
+
63
+ def cache_dict(g2p_dict, file_path):
64
+ with open(file_path, 'wb') as pickle_file:
65
+ pickle.dump(g2p_dict, pickle_file)
66
+
67
+
68
+ def get_dict():
69
+ if os.path.exists(CACHE_PATH):
70
+ with open(CACHE_PATH, 'rb') as pickle_file:
71
+ g2p_dict = pickle.load(pickle_file)
72
+ else:
73
+ g2p_dict = read_dict()
74
+ cache_dict(g2p_dict, CACHE_PATH)
75
+
76
+ return g2p_dict
77
+
78
+ eng_dict = get_dict()
79
+
80
+ def refine_ph(phn):
81
+ tone = 0
82
+ if re.search(r'\d$', phn):
83
+ tone = int(phn[-1]) + 1
84
+ phn = phn[:-1]
85
+ return phn.lower(), tone
86
+
87
+ def refine_syllables(syllables):
88
+ tones = []
89
+ phonemes = []
90
+ for phn_list in syllables:
91
+ for i in range(len(phn_list)):
92
+ phn = phn_list[i]
93
+ phn, tone = refine_ph(phn)
94
+ phonemes.append(phn)
95
+ tones.append(tone)
96
+ return phonemes, tones
97
+
98
+
99
+ def text_normalize(text):
100
+ # todo: eng text normalize
101
+ return text
102
+
103
+ def g2p(text):
104
+
105
+ phones = []
106
+ tones = []
107
+ words = re.split(r"([,;.\-\?\!\s+])", text)
108
+ for w in words:
109
+ if w.upper() in eng_dict:
110
+ phns, tns = refine_syllables(eng_dict[w.upper()])
111
+ phones += phns
112
+ tones += tns
113
+ else:
114
+ phone_list = list(filter(lambda p: p != " ", _g2p(w)))
115
+ for ph in phone_list:
116
+ if ph in arpa:
117
+ ph, tn = refine_ph(ph)
118
+ phones.append(ph)
119
+ tones.append(tn)
120
+ else:
121
+ phones.append(ph)
122
+ tones.append(0)
123
+ # todo: implement word2ph
124
+ word2ph = [1 for i in phones]
125
+
126
+ phones = [post_replace_ph(i) for i in phones]
127
+ return phones, tones, word2ph
128
+
129
+ if __name__ == "__main__":
130
+ # print(get_dict())
131
+ # print(eng_word_to_phoneme("hello"))
132
+ print(g2p("In this paper, we propose 1 DSPGAN, a GAN-based universal vocoder."))
133
+ # all_phones = set()
134
+ # for k, syllables in eng_dict.items():
135
+ # for group in syllables:
136
+ # for ph in group:
137
+ # all_phones.add(ph)
138
+ # print(all_phones)
text/english_bert_mock.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def get_bert_feature(norm_text, word2ph):
5
+ return torch.zeros(1024, sum(word2ph))
text/japanese.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/CjangCjengh/vits/blob/main/text/japanese.py
2
+ import re
3
+ import sys
4
+
5
+ import pyopenjtalk
6
+
7
+ from text import symbols
8
+
9
+ # Regular expression matching Japanese without punctuation marks:
10
+ _japanese_characters = re.compile(
11
+ r'[A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]')
12
+
13
+ # Regular expression matching non-Japanese characters or punctuation marks:
14
+ _japanese_marks = re.compile(
15
+ r'[^A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]')
16
+
17
+ # List of (symbol, Japanese) pairs for marks:
18
+ _symbols_to_japanese = [(re.compile('%s' % x[0]), x[1]) for x in [
19
+ ('%', 'パーセント')
20
+ ]]
21
+
22
+
23
+ # List of (consonant, sokuon) pairs:
24
+ _real_sokuon = [(re.compile('%s' % x[0]), x[1]) for x in [
25
+ (r'Q([↑↓]*[kg])', r'k#\1'),
26
+ (r'Q([↑↓]*[tdjʧ])', r't#\1'),
27
+ (r'Q([↑↓]*[sʃ])', r's\1'),
28
+ (r'Q([↑↓]*[pb])', r'p#\1')
29
+ ]]
30
+
31
+ # List of (consonant, hatsuon) pairs:
32
+ _real_hatsuon = [(re.compile('%s' % x[0]), x[1]) for x in [
33
+ (r'N([↑↓]*[pbm])', r'm\1'),
34
+ (r'N([↑↓]*[ʧʥj])', r'n^\1'),
35
+ (r'N([↑↓]*[tdn])', r'n\1'),
36
+ (r'N([↑↓]*[kg])', r'ŋ\1')
37
+ ]]
38
+
39
+
40
+
41
+ def post_replace_ph(ph):
42
+ rep_map = {
43
+ ':': ',',
44
+ ';': ',',
45
+ ',': ',',
46
+ '。': '.',
47
+ '!': '!',
48
+ '?': '?',
49
+ '\n': '.',
50
+ "·": ",",
51
+ '、': ",",
52
+ '...': '…',
53
+ 'v': "V"
54
+ }
55
+ if ph in rep_map.keys():
56
+ ph = rep_map[ph]
57
+ if ph in symbols:
58
+ return ph
59
+ if ph not in symbols:
60
+ ph = 'UNK'
61
+ return ph
62
+
63
+ def symbols_to_japanese(text):
64
+ for regex, replacement in _symbols_to_japanese:
65
+ text = re.sub(regex, replacement, text)
66
+ return text
67
+
68
+
69
+ def preprocess_jap(text):
70
+ '''Reference https://r9y9.github.io/ttslearn/latest/notebooks/ch10_Recipe-Tacotron.html'''
71
+ text = symbols_to_japanese(text)
72
+ sentences = re.split(_japanese_marks, text)
73
+ marks = re.findall(_japanese_marks, text)
74
+ text = []
75
+ for i, sentence in enumerate(sentences):
76
+ if re.match(_japanese_characters, sentence):
77
+ p = pyopenjtalk.g2p(sentence)
78
+ text += p.split(" ")
79
+
80
+ if i < len(marks):
81
+ text += [marks[i].replace(' ', '')]
82
+ return text
83
+
84
+ def text_normalize(text):
85
+ # todo: jap text normalize
86
+ return text
87
+
88
+ def g2p(norm_text):
89
+ phones = preprocess_jap(norm_text)
90
+ phones = [post_replace_ph(i) for i in phones]
91
+ # todo: implement tones and word2ph
92
+ tones = [0 for i in phones]
93
+ word2ph = [1 for i in phones]
94
+ return phones, tones, word2ph
95
+
96
+
97
+ if __name__ == '__main__':
98
+ for line in open("../../../Downloads/transcript_utf8.txt").readlines():
99
+ text = line.split(":")[1]
100
+ phones, tones, word2ph = g2p(text)
101
+ for p in phones:
102
+ if p == "z":
103
+ print(text, phones)
104
+ sys.exit(0)
text/opencpop-strict.txt ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ a AA a
2
+ ai AA ai
3
+ an AA an
4
+ ang AA ang
5
+ ao AA ao
6
+ ba b a
7
+ bai b ai
8
+ ban b an
9
+ bang b ang
10
+ bao b ao
11
+ bei b ei
12
+ ben b en
13
+ beng b eng
14
+ bi b i
15
+ bian b ian
16
+ biao b iao
17
+ bie b ie
18
+ bin b in
19
+ bing b ing
20
+ bo b o
21
+ bu b u
22
+ ca c a
23
+ cai c ai
24
+ can c an
25
+ cang c ang
26
+ cao c ao
27
+ ce c e
28
+ cei c ei
29
+ cen c en
30
+ ceng c eng
31
+ cha ch a
32
+ chai ch ai
33
+ chan ch an
34
+ chang ch ang
35
+ chao ch ao
36
+ che ch e
37
+ chen ch en
38
+ cheng ch eng
39
+ chi ch ir
40
+ chong ch ong
41
+ chou ch ou
42
+ chu ch u
43
+ chua ch ua
44
+ chuai ch uai
45
+ chuan ch uan
46
+ chuang ch uang
47
+ chui ch ui
48
+ chun ch un
49
+ chuo ch uo
50
+ ci c i0
51
+ cong c ong
52
+ cou c ou
53
+ cu c u
54
+ cuan c uan
55
+ cui c ui
56
+ cun c un
57
+ cuo c uo
58
+ da d a
59
+ dai d ai
60
+ dan d an
61
+ dang d ang
62
+ dao d ao
63
+ de d e
64
+ dei d ei
65
+ den d en
66
+ deng d eng
67
+ di d i
68
+ dia d ia
69
+ dian d ian
70
+ diao d iao
71
+ die d ie
72
+ ding d ing
73
+ diu d iu
74
+ dong d ong
75
+ dou d ou
76
+ du d u
77
+ duan d uan
78
+ dui d ui
79
+ dun d un
80
+ duo d uo
81
+ e EE e
82
+ ei EE ei
83
+ en EE en
84
+ eng EE eng
85
+ er EE er
86
+ fa f a
87
+ fan f an
88
+ fang f ang
89
+ fei f ei
90
+ fen f en
91
+ feng f eng
92
+ fo f o
93
+ fou f ou
94
+ fu f u
95
+ ga g a
96
+ gai g ai
97
+ gan g an
98
+ gang g ang
99
+ gao g ao
100
+ ge g e
101
+ gei g ei
102
+ gen g en
103
+ geng g eng
104
+ gong g ong
105
+ gou g ou
106
+ gu g u
107
+ gua g ua
108
+ guai g uai
109
+ guan g uan
110
+ guang g uang
111
+ gui g ui
112
+ gun g un
113
+ guo g uo
114
+ ha h a
115
+ hai h ai
116
+ han h an
117
+ hang h ang
118
+ hao h ao
119
+ he h e
120
+ hei h ei
121
+ hen h en
122
+ heng h eng
123
+ hong h ong
124
+ hou h ou
125
+ hu h u
126
+ hua h ua
127
+ huai h uai
128
+ huan h uan
129
+ huang h uang
130
+ hui h ui
131
+ hun h un
132
+ huo h uo
133
+ ji j i
134
+ jia j ia
135
+ jian j ian
136
+ jiang j iang
137
+ jiao j iao
138
+ jie j ie
139
+ jin j in
140
+ jing j ing
141
+ jiong j iong
142
+ jiu j iu
143
+ ju j v
144
+ jv j v
145
+ juan j van
146
+ jvan j van
147
+ jue j ve
148
+ jve j ve
149
+ jun j vn
150
+ jvn j vn
151
+ ka k a
152
+ kai k ai
153
+ kan k an
154
+ kang k ang
155
+ kao k ao
156
+ ke k e
157
+ kei k ei
158
+ ken k en
159
+ keng k eng
160
+ kong k ong
161
+ kou k ou
162
+ ku k u
163
+ kua k ua
164
+ kuai k uai
165
+ kuan k uan
166
+ kuang k uang
167
+ kui k ui
168
+ kun k un
169
+ kuo k uo
170
+ la l a
171
+ lai l ai
172
+ lan l an
173
+ lang l ang
174
+ lao l ao
175
+ le l e
176
+ lei l ei
177
+ leng l eng
178
+ li l i
179
+ lia l ia
180
+ lian l ian
181
+ liang l iang
182
+ liao l iao
183
+ lie l ie
184
+ lin l in
185
+ ling l ing
186
+ liu l iu
187
+ lo l o
188
+ long l ong
189
+ lou l ou
190
+ lu l u
191
+ luan l uan
192
+ lun l un
193
+ luo l uo
194
+ lv l v
195
+ lve l ve
196
+ ma m a
197
+ mai m ai
198
+ man m an
199
+ mang m ang
200
+ mao m ao
201
+ me m e
202
+ mei m ei
203
+ men m en
204
+ meng m eng
205
+ mi m i
206
+ mian m ian
207
+ miao m iao
208
+ mie m ie
209
+ min m in
210
+ ming m ing
211
+ miu m iu
212
+ mo m o
213
+ mou m ou
214
+ mu m u
215
+ na n a
216
+ nai n ai
217
+ nan n an
218
+ nang n ang
219
+ nao n ao
220
+ ne n e
221
+ nei n ei
222
+ nen n en
223
+ neng n eng
224
+ ni n i
225
+ nian n ian
226
+ niang n iang
227
+ niao n iao
228
+ nie n ie
229
+ nin n in
230
+ ning n ing
231
+ niu n iu
232
+ nong n ong
233
+ nou n ou
234
+ nu n u
235
+ nuan n uan
236
+ nun n un
237
+ nuo n uo
238
+ nv n v
239
+ nve n ve
240
+ o OO o
241
+ ou OO ou
242
+ pa p a
243
+ pai p ai
244
+ pan p an
245
+ pang p ang
246
+ pao p ao
247
+ pei p ei
248
+ pen p en
249
+ peng p eng
250
+ pi p i
251
+ pian p ian
252
+ piao p iao
253
+ pie p ie
254
+ pin p in
255
+ ping p ing
256
+ po p o
257
+ pou p ou
258
+ pu p u
259
+ qi q i
260
+ qia q ia
261
+ qian q ian
262
+ qiang q iang
263
+ qiao q iao
264
+ qie q ie
265
+ qin q in
266
+ qing q ing
267
+ qiong q iong
268
+ qiu q iu
269
+ qu q v
270
+ qv q v
271
+ quan q van
272
+ qvan q van
273
+ que q ve
274
+ qve q ve
275
+ qun q vn
276
+ qvn q vn
277
+ ran r an
278
+ rang r ang
279
+ rao r ao
280
+ re r e
281
+ ren r en
282
+ reng r eng
283
+ ri r ir
284
+ rong r ong
285
+ rou r ou
286
+ ru r u
287
+ rua r ua
288
+ ruan r uan
289
+ rui r ui
290
+ run r un
291
+ ruo r uo
292
+ sa s a
293
+ sai s ai
294
+ san s an
295
+ sang s ang
296
+ sao s ao
297
+ se s e
298
+ sen s en
299
+ seng s eng
300
+ sha sh a
301
+ shai sh ai
302
+ shan sh an
303
+ shang sh ang
304
+ shao sh ao
305
+ she sh e
306
+ shei sh ei
307
+ shen sh en
308
+ sheng sh eng
309
+ shi sh ir
310
+ shou sh ou
311
+ shu sh u
312
+ shua sh ua
313
+ shuai sh uai
314
+ shuan sh uan
315
+ shuang sh uang
316
+ shui sh ui
317
+ shun sh un
318
+ shuo sh uo
319
+ si s i0
320
+ song s ong
321
+ sou s ou
322
+ su s u
323
+ suan s uan
324
+ sui s ui
325
+ sun s un
326
+ suo s uo
327
+ ta t a
328
+ tai t ai
329
+ tan t an
330
+ tang t ang
331
+ tao t ao
332
+ te t e
333
+ tei t ei
334
+ teng t eng
335
+ ti t i
336
+ tian t ian
337
+ tiao t iao
338
+ tie t ie
339
+ ting t ing
340
+ tong t ong
341
+ tou t ou
342
+ tu t u
343
+ tuan t uan
344
+ tui t ui
345
+ tun t un
346
+ tuo t uo
347
+ wa w a
348
+ wai w ai
349
+ wan w an
350
+ wang w ang
351
+ wei w ei
352
+ wen w en
353
+ weng w eng
354
+ wo w o
355
+ wu w u
356
+ xi x i
357
+ xia x ia
358
+ xian x ian
359
+ xiang x iang
360
+ xiao x iao
361
+ xie x ie
362
+ xin x in
363
+ xing x ing
364
+ xiong x iong
365
+ xiu x iu
366
+ xu x v
367
+ xv x v
368
+ xuan x van
369
+ xvan x van
370
+ xue x ve
371
+ xve x ve
372
+ xun x vn
373
+ xvn x vn
374
+ ya y a
375
+ yan y En
376
+ yang y ang
377
+ yao y ao
378
+ ye y E
379
+ yi y i
380
+ yin y in
381
+ ying y ing
382
+ yo y o
383
+ yong y ong
384
+ you y ou
385
+ yu y v
386
+ yv y v
387
+ yuan y van
388
+ yvan y van
389
+ yue y ve
390
+ yve y ve
391
+ yun y vn
392
+ yvn y vn
393
+ za z a
394
+ zai z ai
395
+ zan z an
396
+ zang z ang
397
+ zao z ao
398
+ ze z e
399
+ zei z ei
400
+ zen z en
401
+ zeng z eng
402
+ zha zh a
403
+ zhai zh ai
404
+ zhan zh an
405
+ zhang zh ang
406
+ zhao zh ao
407
+ zhe zh e
408
+ zhei zh ei
409
+ zhen zh en
410
+ zheng zh eng
411
+ zhi zh ir
412
+ zhong zh ong
413
+ zhou zh ou
414
+ zhu zh u
415
+ zhua zh ua
416
+ zhuai zh uai
417
+ zhuan zh uan
418
+ zhuang zh uang
419
+ zhui zh ui
420
+ zhun zh un
421
+ zhuo zh uo
422
+ zi z i0
423
+ zong z ong
424
+ zou z ou
425
+ zu z u
426
+ zuan z uan
427
+ zui z ui
428
+ zun z un
429
+ zuo z uo
text/symbols.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ punctuation = ['!', '?', '…', ",", ".", "'", '-']
2
+ pu_symbols = punctuation + ["SP", "UNK"]
3
+ pad = '_'
4
+
5
+ # chinese
6
+ zh_symbols = ['E', 'En', 'a', 'ai', 'an', 'ang', 'ao', 'b', 'c', 'ch', 'd', 'e', 'ei', 'en', 'eng', 'er', 'f', 'g', 'h',
7
+ 'i', 'i0', 'ia', 'ian', 'iang', 'iao', 'ie', 'in', 'ing', 'iong', 'ir', 'iu', 'j', 'k', 'l', 'm', 'n', 'o',
8
+ 'ong',
9
+ 'ou', 'p', 'q', 'r', 's', 'sh', 't', 'u', 'ua', 'uai', 'uan', 'uang', 'ui', 'un', 'uo', 'v', 'van', 've', 'vn',
10
+ 'w', 'x', 'y', 'z', 'zh',
11
+ "AA", "EE", "OO"]
12
+ num_zh_tones = 6
13
+
14
+ # japanese
15
+ ja_symbols = ['I', 'N', 'U', 'a', 'b', 'by', 'ch', 'cl', 'd', 'dy', 'e', 'f', 'g', 'gy', 'h', 'hy', 'i', 'j', 'k', 'ky',
16
+ 'm', 'my', 'n', 'ny', 'o', 'p', 'py', 'r', 'ry', 's', 'sh', 't', 'ts', 'u', 'V', 'w', 'y', 'z']
17
+ num_ja_tones = 1
18
+
19
+ # English
20
+ en_symbols = ['aa', 'ae', 'ah', 'ao', 'aw', 'ay', 'b', 'ch', 'd', 'dh', 'eh', 'er', 'ey', 'f', 'g', 'hh', 'ih', 'iy',
21
+ 'jh', 'k', 'l', 'm', 'n', 'ng', 'ow', 'oy', 'p', 'r', 's',
22
+ 'sh', 't', 'th', 'uh', 'uw', 'V', 'w', 'y', 'z', 'zh']
23
+ num_en_tones = 4
24
+
25
+ # combine all symbols
26
+ normal_symbols = sorted(set(zh_symbols + ja_symbols + en_symbols))
27
+ symbols = [pad] + normal_symbols + pu_symbols
28
+ sil_phonemes_ids = [symbols.index(i) for i in pu_symbols]
29
+
30
+ # combine all tones
31
+ num_tones = num_zh_tones + num_ja_tones + num_en_tones
32
+
33
+ # language maps
34
+ language_id_map = {
35
+ 'ZH': 0,
36
+ "JA": 1,
37
+ "EN": 2
38
+ }
39
+ num_languages = len(language_id_map.keys())
40
+
41
+ language_tone_start_map = {
42
+ 'ZH': 0,
43
+ "JA": num_zh_tones,
44
+ "EN": num_zh_tones + num_ja_tones
45
+ }
46
+
47
+ if __name__ == '__main__':
48
+ a = set(zh_symbols)
49
+ b = set(en_symbols)
50
+ print(sorted(a&b))
51
+
text/tone_sandhi.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import List
15
+ from typing import Tuple
16
+
17
+ import jieba
18
+ from pypinyin import lazy_pinyin
19
+ from pypinyin import Style
20
+
21
+
22
+ class ToneSandhi():
23
+ def __init__(self):
24
+ self.must_neural_tone_words = {
25
+ '麻烦', '麻利', '鸳鸯', '高粱', '骨头', '骆驼', '马虎', '首饰', '馒头', '馄饨', '风筝',
26
+ '难为', '队伍', '阔气', '闺女', '门道', '锄头', '铺盖', '铃铛', '铁匠', '钥匙', '里脊',
27
+ '里头', '部分', '那么', '道士', '造化', '迷糊', '连累', '这么', '这个', '运气', '过去',
28
+ '软和', '转悠', '踏实', '跳蚤', '跟头', '趔趄', '财主', '豆腐', '讲究', '记性', '记号',
29
+ '认识', '规矩', '见识', '裁缝', '补丁', '衣裳', '衣服', '衙门', '街坊', '行李', '行当',
30
+ '蛤蟆', '蘑菇', '薄荷', '葫芦', '葡萄', '萝卜', '荸荠', '苗条', '苗头', '苍蝇', '芝麻',
31
+ '舒服', '舒坦', '舌头', '自在', '膏药', '脾气', '脑袋', '脊梁', '能耐', '胳膊', '胭脂',
32
+ '胡萝', '胡琴', '胡同', '聪明', '耽误', '耽搁', '耷拉', '耳朵', '老爷', '老实', '老婆',
33
+ '老头', '老太', '翻腾', '罗嗦', '罐头', '编辑', '结实', '红火', '累赘', '糨糊', '糊涂',
34
+ '精神', '粮食', '簸箕', '篱笆', '算计', '算盘', '答应', '笤帚', '笑语', '笑话', '窟窿',
35
+ '窝囊', '窗户', '稳当', '稀罕', '称呼', '秧歌', '秀气', '秀才', '福气', '祖宗', '砚台',
36
+ '码头', '石榴', '石头', '石匠', '知识', '眼睛', '眯缝', '眨巴', '眉毛', '相声', '盘算',
37
+ '白净', '痢疾', '痛快', '疟疾', '疙瘩', '疏忽', '畜生', '生意', '甘蔗', '琵琶', '琢磨',
38
+ '琉璃', '玻璃', '玫瑰', '玄乎', '狐狸', '状元', '特务', '牲口', '牙碜', '牌楼', '爽快',
39
+ '爱人', '热闹', '烧饼', '烟筒', '烂糊', '点心', '炊帚', '灯笼', '火候', '漂亮', '滑溜',
40
+ '溜达', '温和', '清楚', '消息', '浪头', '活泼', '比方', '正经', '欺负', '模糊', '槟榔',
41
+ '棺材', '棒槌', '棉花', '核桃', '栅栏', '柴火', '架势', '枕头', '枇杷', '机灵', '本事',
42
+ '木头', '木匠', '朋友', '月饼', '月亮', '暖和', '明白', '时候', '新鲜', '故事', '收拾',
43
+ '收成', '提防', '挖苦', '挑剔', '指甲', '指头', '拾掇', '拳头', '拨弄', '招牌', '招呼',
44
+ '抬举', '护士', '折腾', '扫帚', '打量', '打算', '打点', '打扮', '打听', '打发', '扎实',
45
+ '扁担', '戒指', '懒得', '意识', '意思', '情形', '悟性', '怪物', '思量', '怎么', '念头',
46
+ '念叨', '快活', '忙活', '志气', '心思', '得罪', '张罗', '弟兄', '开通', '应酬', '庄稼',
47
+ '干事', '帮手', '帐篷', '希罕', '师父', '师傅', '巴结', '巴掌', '差事', '工夫', '岁数',
48
+ '屁股', '尾巴', '少爷', '小气', '小伙', '将就', '对头', '对付', '寡妇', '家伙', '客气',
49
+ '实在', '官司', '学问', '学生', '字号', '嫁妆', '媳妇', '媒人', '婆家', '娘家', '委屈',
50
+ '姑娘', '姐夫', '妯娌', '妥当', '妖精', '奴才', '女婿', '头发', '太阳', '大爷', '大方',
51
+ '大意', '大夫', '多少', '多么', '外甥', '壮实', '地道', '地方', '在乎', '困难', '嘴巴',
52
+ '嘱咐', '嘟囔', '嘀咕', '喜欢', '喇嘛', '喇叭', '商量', '唾沫', '哑巴', '哈欠', '哆嗦',
53
+ '咳嗽', '和尚', '告诉', '告示', '含糊', '吓唬', '后头', '名字', '名堂', '合同', '吆喝',
54
+ '叫唤', '口袋', '厚道', '厉害', '千斤', '包袱', '包涵', '匀称', '勤快', '动静', '动弹',
55
+ '功夫', '力气', '前头', '刺猬', '刺激', '别扭', '利落', '利索', '利害', '分析', '出息',
56
+ '凑合', '凉快', '冷战', '冤枉', '冒失', '养活', '关系', '先生', '兄弟', '便宜', '使唤',
57
+ '佩服', '作坊', '体面', '位置', '似的', '伙计', '休息', '什么', '人家', '亲戚', '亲家',
58
+ '交情', '云彩', '事情', '买卖', '主意', '丫头', '丧气', '两口', '东西', '东家', '世故',
59
+ '不由', '不在', '下水', '下巴', '上头', '上司', '丈夫', '丈人', '一辈', '那个', '菩萨',
60
+ '父亲', '母亲', '咕噜', '邋遢', '费用', '冤家', '甜头', '介绍', '荒唐', '大人', '泥鳅',
61
+ '幸福', '熟悉', '计划', '扑腾', '蜡烛', '姥爷', '照顾', '喉咙', '吉他', '弄堂', '蚂蚱',
62
+ '凤凰', '拖沓', '寒碜', '糟蹋', '倒腾', '报复', '逻辑', '盘缠', '喽啰', '牢骚', '咖喱',
63
+ '扫把', '惦记'
64
+ }
65
+ self.must_not_neural_tone_words = {
66
+ "男子", "女子", "分子", "原子", "量子", "莲子", "石子", "瓜子", "电子", "人人", "虎虎"
67
+ }
68
+ self.punc = ":,;。?!“”‘’':,;.?!"
69
+
70
+ # the meaning of jieba pos tag: https://blog.csdn.net/weixin_44174352/article/details/113731041
71
+ # e.g.
72
+ # word: "家里"
73
+ # pos: "s"
74
+ # finals: ['ia1', 'i3']
75
+ def _neural_sandhi(self, word: str, pos: str,
76
+ finals: List[str]) -> List[str]:
77
+
78
+ # reduplication words for n. and v. e.g. 奶奶, 试试, 旺旺
79
+ for j, item in enumerate(word):
80
+ if j - 1 >= 0 and item == word[j - 1] and pos[0] in {
81
+ "n", "v", "a"
82
+ } and word not in self.must_not_neural_tone_words:
83
+ finals[j] = finals[j][:-1] + "5"
84
+ ge_idx = word.find("个")
85
+ if len(word) >= 1 and word[-1] in "吧呢啊呐噻嘛吖嗨呐哦哒额滴哩哟喽啰耶喔诶":
86
+ finals[-1] = finals[-1][:-1] + "5"
87
+ elif len(word) >= 1 and word[-1] in "的地得":
88
+ finals[-1] = finals[-1][:-1] + "5"
89
+ # e.g. 走了, 看着, 去过
90
+ # elif len(word) == 1 and word in "了着过" and pos in {"ul", "uz", "ug"}:
91
+ # finals[-1] = finals[-1][:-1] + "5"
92
+ elif len(word) > 1 and word[-1] in "们子" and pos in {
93
+ "r", "n"
94
+ } and word not in self.must_not_neural_tone_words:
95
+ finals[-1] = finals[-1][:-1] + "5"
96
+ # e.g. 桌上, 地下, 家里
97
+ elif len(word) > 1 and word[-1] in "上下里" and pos in {"s", "l", "f"}:
98
+ finals[-1] = finals[-1][:-1] + "5"
99
+ # e.g. 上来, 下去
100
+ elif len(word) > 1 and word[-1] in "来去" and word[-2] in "上下进出回过起开":
101
+ finals[-1] = finals[-1][:-1] + "5"
102
+ # 个做量词
103
+ elif (ge_idx >= 1 and
104
+ (word[ge_idx - 1].isnumeric() or
105
+ word[ge_idx - 1] in "几有两半多各整每做是")) or word == '个':
106
+ finals[ge_idx] = finals[ge_idx][:-1] + "5"
107
+ else:
108
+ if word in self.must_neural_tone_words or word[
109
+ -2:] in self.must_neural_tone_words:
110
+ finals[-1] = finals[-1][:-1] + "5"
111
+
112
+ word_list = self._split_word(word)
113
+ finals_list = [finals[:len(word_list[0])], finals[len(word_list[0]):]]
114
+ for i, word in enumerate(word_list):
115
+ # conventional neural in Chinese
116
+ if word in self.must_neural_tone_words or word[
117
+ -2:] in self.must_neural_tone_words:
118
+ finals_list[i][-1] = finals_list[i][-1][:-1] + "5"
119
+ finals = sum(finals_list, [])
120
+ return finals
121
+
122
+ def _bu_sandhi(self, word: str, finals: List[str]) -> List[str]:
123
+ # e.g. 看不懂
124
+ if len(word) == 3 and word[1] == "不":
125
+ finals[1] = finals[1][:-1] + "5"
126
+ else:
127
+ for i, char in enumerate(word):
128
+ # "不" before tone4 should be bu2, e.g. 不怕
129
+ if char == "不" and i + 1 < len(word) and finals[i +
130
+ 1][-1] == "4":
131
+ finals[i] = finals[i][:-1] + "2"
132
+ return finals
133
+
134
+ def _yi_sandhi(self, word: str, finals: List[str]) -> List[str]:
135
+ # "一" in number sequences, e.g. 一零零, 二一零
136
+ if word.find("一") != -1 and all(
137
+ [item.isnumeric() for item in word if item != "一"]):
138
+ return finals
139
+ # "一" between reduplication words shold be yi5, e.g. 看一看
140
+ elif len(word) == 3 and word[1] == "一" and word[0] == word[-1]:
141
+ finals[1] = finals[1][:-1] + "5"
142
+ # when "一" is ordinal word, it should be yi1
143
+ elif word.startswith("第一"):
144
+ finals[1] = finals[1][:-1] + "1"
145
+ else:
146
+ for i, char in enumerate(word):
147
+ if char == "一" and i + 1 < len(word):
148
+ # "一" before tone4 should be yi2, e.g. 一段
149
+ if finals[i + 1][-1] == "4":
150
+ finals[i] = finals[i][:-1] + "2"
151
+ # "一" before non-tone4 should be yi4, e.g. 一天
152
+ else:
153
+ # "一" 后面如果是标点,还读一声
154
+ if word[i + 1] not in self.punc:
155
+ finals[i] = finals[i][:-1] + "4"
156
+ return finals
157
+
158
+ def _split_word(self, word: str) -> List[str]:
159
+ word_list = jieba.cut_for_search(word)
160
+ word_list = sorted(word_list, key=lambda i: len(i), reverse=False)
161
+ first_subword = word_list[0]
162
+ first_begin_idx = word.find(first_subword)
163
+ if first_begin_idx == 0:
164
+ second_subword = word[len(first_subword):]
165
+ new_word_list = [first_subword, second_subword]
166
+ else:
167
+ second_subword = word[:-len(first_subword)]
168
+ new_word_list = [second_subword, first_subword]
169
+ return new_word_list
170
+
171
+ def _three_sandhi(self, word: str, finals: List[str]) -> List[str]:
172
+ if len(word) == 2 and self._all_tone_three(finals):
173
+ finals[0] = finals[0][:-1] + "2"
174
+ elif len(word) == 3:
175
+ word_list = self._split_word(word)
176
+ if self._all_tone_three(finals):
177
+ # disyllabic + monosyllabic, e.g. 蒙古/包
178
+ if len(word_list[0]) == 2:
179
+ finals[0] = finals[0][:-1] + "2"
180
+ finals[1] = finals[1][:-1] + "2"
181
+ # monosyllabic + disyllabic, e.g. 纸/老虎
182
+ elif len(word_list[0]) == 1:
183
+ finals[1] = finals[1][:-1] + "2"
184
+ else:
185
+ finals_list = [
186
+ finals[:len(word_list[0])], finals[len(word_list[0]):]
187
+ ]
188
+ if len(finals_list) == 2:
189
+ for i, sub in enumerate(finals_list):
190
+ # e.g. 所有/人
191
+ if self._all_tone_three(sub) and len(sub) == 2:
192
+ finals_list[i][0] = finals_list[i][0][:-1] + "2"
193
+ # e.g. 好/喜欢
194
+ elif i == 1 and not self._all_tone_three(sub) and finals_list[i][0][-1] == "3" and \
195
+ finals_list[0][-1][-1] == "3":
196
+
197
+ finals_list[0][-1] = finals_list[0][-1][:-1] + "2"
198
+ finals = sum(finals_list, [])
199
+ # split idiom into two words who's length is 2
200
+ elif len(word) == 4:
201
+ finals_list = [finals[:2], finals[2:]]
202
+ finals = []
203
+ for sub in finals_list:
204
+ if self._all_tone_three(sub):
205
+ sub[0] = sub[0][:-1] + "2"
206
+ finals += sub
207
+
208
+ return finals
209
+
210
+ def _all_tone_three(self, finals: List[str]) -> bool:
211
+ return all(x[-1] == "3" for x in finals)
212
+
213
+ # merge "不" and the word behind it
214
+ # if don't merge, "不" sometimes appears alone according to jieba, which may occur sandhi error
215
+ def _merge_bu(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
216
+ new_seg = []
217
+ last_word = ""
218
+ for word, pos in seg:
219
+ if last_word == "不":
220
+ word = last_word + word
221
+ if word != "不":
222
+ new_seg.append((word, pos))
223
+ last_word = word[:]
224
+ if last_word == "不":
225
+ new_seg.append((last_word, 'd'))
226
+ last_word = ""
227
+ return new_seg
228
+
229
+ # function 1: merge "一" and reduplication words in it's left and right, e.g. "听","一","听" ->"听一听"
230
+ # function 2: merge single "一" and the word behind it
231
+ # if don't merge, "一" sometimes appears alone according to jieba, which may occur sandhi error
232
+ # e.g.
233
+ # input seg: [('听', 'v'), ('一', 'm'), ('听', 'v')]
234
+ # output seg: [['听一听', 'v']]
235
+ def _merge_yi(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
236
+ new_seg = []
237
+ # function 1
238
+ for i, (word, pos) in enumerate(seg):
239
+ if i - 1 >= 0 and word == "一" and i + 1 < len(seg) and seg[i - 1][
240
+ 0] == seg[i + 1][0] and seg[i - 1][1] == "v":
241
+ new_seg[i - 1][0] = new_seg[i - 1][0] + "一" + new_seg[i - 1][0]
242
+ else:
243
+ if i - 2 >= 0 and seg[i - 1][0] == "一" and seg[i - 2][
244
+ 0] == word and pos == "v":
245
+ continue
246
+ else:
247
+ new_seg.append([word, pos])
248
+ seg = new_seg
249
+ new_seg = []
250
+ # function 2
251
+ for i, (word, pos) in enumerate(seg):
252
+ if new_seg and new_seg[-1][0] == "一":
253
+ new_seg[-1][0] = new_seg[-1][0] + word
254
+ else:
255
+ new_seg.append([word, pos])
256
+ return new_seg
257
+
258
+ # the first and the second words are all_tone_three
259
+ def _merge_continuous_three_tones(
260
+ self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
261
+ new_seg = []
262
+ sub_finals_list = [
263
+ lazy_pinyin(
264
+ word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
265
+ for (word, pos) in seg
266
+ ]
267
+ assert len(sub_finals_list) == len(seg)
268
+ merge_last = [False] * len(seg)
269
+ for i, (word, pos) in enumerate(seg):
270
+ if i - 1 >= 0 and self._all_tone_three(
271
+ sub_finals_list[i - 1]) and self._all_tone_three(
272
+ sub_finals_list[i]) and not merge_last[i - 1]:
273
+ # if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi
274
+ if not self._is_reduplication(seg[i - 1][0]) and len(
275
+ seg[i - 1][0]) + len(seg[i][0]) <= 3:
276
+ new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
277
+ merge_last[i] = True
278
+ else:
279
+ new_seg.append([word, pos])
280
+ else:
281
+ new_seg.append([word, pos])
282
+
283
+ return new_seg
284
+
285
+ def _is_reduplication(self, word: str) -> bool:
286
+ return len(word) == 2 and word[0] == word[1]
287
+
288
+ # the last char of first word and the first char of second word is tone_three
289
+ def _merge_continuous_three_tones_2(
290
+ self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
291
+ new_seg = []
292
+ sub_finals_list = [
293
+ lazy_pinyin(
294
+ word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
295
+ for (word, pos) in seg
296
+ ]
297
+ assert len(sub_finals_list) == len(seg)
298
+ merge_last = [False] * len(seg)
299
+ for i, (word, pos) in enumerate(seg):
300
+ if i - 1 >= 0 and sub_finals_list[i - 1][-1][-1] == "3" and sub_finals_list[i][0][-1] == "3" and not \
301
+ merge_last[i - 1]:
302
+ # if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi
303
+ if not self._is_reduplication(seg[i - 1][0]) and len(
304
+ seg[i - 1][0]) + len(seg[i][0]) <= 3:
305
+ new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
306
+ merge_last[i] = True
307
+ else:
308
+ new_seg.append([word, pos])
309
+ else:
310
+ new_seg.append([word, pos])
311
+ return new_seg
312
+
313
+ def _merge_er(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
314
+ new_seg = []
315
+ for i, (word, pos) in enumerate(seg):
316
+ if i - 1 >= 0 and word == "儿" and seg[i-1][0] != "#":
317
+ new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
318
+ else:
319
+ new_seg.append([word, pos])
320
+ return new_seg
321
+
322
+ def _merge_reduplication(
323
+ self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
324
+ new_seg = []
325
+ for i, (word, pos) in enumerate(seg):
326
+ if new_seg and word == new_seg[-1][0]:
327
+ new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
328
+ else:
329
+ new_seg.append([word, pos])
330
+ return new_seg
331
+
332
+ def pre_merge_for_modify(
333
+ self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
334
+ seg = self._merge_bu(seg)
335
+ try:
336
+ seg = self._merge_yi(seg)
337
+ except:
338
+ print("_merge_yi failed")
339
+ seg = self._merge_reduplication(seg)
340
+ seg = self._merge_continuous_three_tones(seg)
341
+ seg = self._merge_continuous_three_tones_2(seg)
342
+ seg = self._merge_er(seg)
343
+ return seg
344
+
345
+ def modified_tone(self, word: str, pos: str,
346
+ finals: List[str]) -> List[str]:
347
+ finals = self._bu_sandhi(word, finals)
348
+ finals = self._yi_sandhi(word, finals)
349
+ finals = self._neural_sandhi(word, pos, finals)
350
+ finals = self._three_sandhi(word, finals)
351
+ return finals
train_ms.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+ import itertools
5
+ import math
6
+ import torch
7
+ import shutil
8
+ from torch import nn, optim
9
+ from torch.nn import functional as F
10
+ from torch.utils.data import DataLoader
11
+ from torch.utils.tensorboard import SummaryWriter
12
+ import torch.multiprocessing as mp
13
+ import torch.distributed as dist
14
+ from torch.nn.parallel import DistributedDataParallel as DDP
15
+ from torch.cuda.amp import autocast, GradScaler
16
+ from tqdm import tqdm
17
+ import logging
18
+ logging.getLogger('numba').setLevel(logging.WARNING)
19
+ import commons
20
+ import utils
21
+ from data_utils import (
22
+ TextAudioSpeakerLoader,
23
+ TextAudioSpeakerCollate,
24
+ DistributedBucketSampler
25
+ )
26
+ from models import (
27
+ SynthesizerTrn,
28
+ MultiPeriodDiscriminator,
29
+ DurationDiscriminator,
30
+ )
31
+ from losses import (
32
+ generator_loss,
33
+ discriminator_loss,
34
+ feature_loss,
35
+ kl_loss
36
+ )
37
+ from mel_processing import mel_spectrogram_torch, spec_to_mel_torch
38
+ from text.symbols import symbols
39
+
40
+ torch.backends.cudnn.benchmark = True
41
+ torch.backends.cuda.matmul.allow_tf32 = True
42
+ torch.backends.cudnn.allow_tf32 = True
43
+ torch.set_float32_matmul_precision('medium')
44
+ global_step = 0
45
+
46
+
47
+ def main():
48
+ """Assume Single Node Multi GPUs Training Only"""
49
+ assert torch.cuda.is_available(), "CPU training is not allowed."
50
+
51
+ n_gpus = torch.cuda.device_count()
52
+ os.environ['MASTER_ADDR'] = 'localhost'
53
+ os.environ['MASTER_PORT'] = '65280'
54
+
55
+ hps = utils.get_hparams()
56
+ if not hps.cont:
57
+ shutil.copy('./pretrained_models/D_0.pth','./logs/OUTPUT_MODEL/D_0.pth')
58
+ shutil.copy('./pretrained_models/G_0.pth','./logs/OUTPUT_MODEL/G_0.pth')
59
+ shutil.copy('./pretrained_models/DUR_0.pth','./logs/OUTPUT_MODEL/DUR_0.pth')
60
+ mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
61
+
62
+
63
+ def run(rank, n_gpus, hps):
64
+ global global_step
65
+ if rank == 0:
66
+ logger = utils.get_logger(hps.model_dir)
67
+ logger.info(hps)
68
+ utils.check_git_hash(hps.model_dir)
69
+ writer = SummaryWriter(log_dir=hps.model_dir)
70
+ writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
71
+
72
+ dist.init_process_group(backend= 'gloo' if os.name == 'nt' else 'nccl', init_method='env://', world_size=n_gpus, rank=rank)
73
+ torch.manual_seed(hps.train.seed)
74
+ torch.cuda.set_device(rank)
75
+
76
+ train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data)
77
+ train_sampler = DistributedBucketSampler(
78
+ train_dataset,
79
+ hps.train.batch_size,
80
+ [32, 300, 400, 500, 600, 700, 800, 900, 1000],
81
+ num_replicas=n_gpus,
82
+ rank=rank,
83
+ shuffle=True)
84
+ collate_fn = TextAudioSpeakerCollate()
85
+ train_loader = DataLoader(train_dataset, num_workers=2, shuffle=False, pin_memory=True,
86
+ collate_fn=collate_fn, batch_sampler=train_sampler)
87
+ if rank == 0:
88
+ eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data)
89
+ eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False,
90
+ batch_size=1, pin_memory=True,
91
+ drop_last=False, collate_fn=collate_fn)
92
+ if "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas == True:
93
+ print("Using noise scaled MAS for VITS2")
94
+ use_noise_scaled_mas = True
95
+ mas_noise_scale_initial = 0.01
96
+ noise_scale_delta = 2e-6
97
+ else:
98
+ print("Using normal MAS for VITS1")
99
+ use_noise_scaled_mas = False
100
+ mas_noise_scale_initial = 0.0
101
+ noise_scale_delta = 0.0
102
+ if "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator == True:
103
+ print("Using duration discriminator for VITS2")
104
+ use_duration_discriminator = True
105
+ net_dur_disc = DurationDiscriminator(
106
+ hps.model.hidden_channels,
107
+ hps.model.hidden_channels,
108
+ 3,
109
+ 0.1,
110
+ gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0,
111
+ ).cuda(rank)
112
+ if "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder == True:
113
+ if hps.data.n_speakers == 0:
114
+ raise ValueError("n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model")
115
+ use_spk_conditioned_encoder = True
116
+ else:
117
+ print("Using normal encoder for VITS1")
118
+ use_spk_conditioned_encoder = False
119
+
120
+ net_g = SynthesizerTrn(
121
+ len(symbols),
122
+ hps.data.filter_length // 2 + 1,
123
+ hps.train.segment_size // hps.data.hop_length,
124
+ n_speakers=hps.data.n_speakers,
125
+ mas_noise_scale_initial = mas_noise_scale_initial,
126
+ noise_scale_delta = noise_scale_delta,
127
+ **hps.model).cuda(rank)
128
+
129
+ freeze_enc = getattr(hps.model, "freeze_enc", False)
130
+ if freeze_enc:
131
+ print("freeze encoder !!!")
132
+ for param in net_g.enc_p.parameters():
133
+ param.requires_grad = False
134
+
135
+ net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank)
136
+ optim_g = torch.optim.AdamW(
137
+ filter(lambda p: p.requires_grad, net_g.parameters()),
138
+ hps.train.learning_rate,
139
+ betas=hps.train.betas,
140
+ eps=hps.train.eps)
141
+ optim_d = torch.optim.AdamW(
142
+ net_d.parameters(),
143
+ hps.train.learning_rate,
144
+ betas=hps.train.betas,
145
+ eps=hps.train.eps)
146
+ if net_dur_disc is not None:
147
+ optim_dur_disc = torch.optim.AdamW(
148
+ net_dur_disc.parameters(),
149
+ hps.train.learning_rate,
150
+ betas=hps.train.betas,
151
+ eps=hps.train.eps)
152
+ else:
153
+ optim_dur_disc = None
154
+ net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True)
155
+ net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True)
156
+ if net_dur_disc is not None:
157
+ net_dur_disc = DDP(net_dur_disc, device_ids=[rank], find_unused_parameters=True)
158
+
159
+ pretrain_dir = None
160
+ if pretrain_dir is None:
161
+ try:
162
+ if net_dur_disc is not None:
163
+ _, optim_dur_disc, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=not hps.cont)
164
+ _, optim_g, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g,
165
+ optim_g, skip_optimizer=not hps.cont)
166
+ _, optim_d, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d,
167
+ optim_d, skip_optimizer=not hps.cont)
168
+
169
+ epoch_str = max(epoch_str, 1)
170
+ global_step = (epoch_str - 1) * len(train_loader)
171
+ except Exception as e:
172
+ print(e)
173
+ epoch_str = 1
174
+ global_step = 0
175
+ else:
176
+ _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "G_*.pth"), net_g,
177
+ optim_g, True)
178
+ _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "D_*.pth"), net_d,
179
+ optim_d, True)
180
+
181
+
182
+
183
+ scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
184
+ scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
185
+ if net_dur_disc is not None:
186
+ scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)
187
+ else:
188
+ scheduler_dur_disc = None
189
+ scaler = GradScaler(enabled=hps.train.fp16_run)
190
+
191
+ for epoch in range(epoch_str, hps.train.epochs + 1):
192
+ if rank == 0:
193
+ train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval])
194
+ else:
195
+ train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None)
196
+ scheduler_g.step()
197
+ scheduler_d.step()
198
+ if net_dur_disc is not None:
199
+ scheduler_dur_disc.step()
200
+
201
+
202
+ def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):
203
+ net_g, net_d, net_dur_disc = nets
204
+ optim_g, optim_d, optim_dur_disc = optims
205
+ scheduler_g, scheduler_d, scheduler_dur_disc = schedulers
206
+ train_loader, eval_loader = loaders
207
+ if writers is not None:
208
+ writer, writer_eval = writers
209
+
210
+ train_loader.batch_sampler.set_epoch(epoch)
211
+ global global_step
212
+
213
+ net_g.train()
214
+ net_d.train()
215
+ if net_dur_disc is not None:
216
+ net_dur_disc.train()
217
+ for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)):
218
+ if net_g.module.use_noise_scaled_mas:
219
+ current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step
220
+ net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0)
221
+ x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)
222
+ spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True)
223
+ y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)
224
+ speakers = speakers.cuda(rank, non_blocking=True)
225
+ tone = tone.cuda(rank, non_blocking=True)
226
+ language = language.cuda(rank, non_blocking=True)
227
+ bert = bert.cuda(rank, non_blocking=True)
228
+
229
+ with autocast(enabled=hps.train.fp16_run):
230
+ y_hat, l_length, attn, ids_slice, x_mask, z_mask, \
231
+ (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert)
232
+ mel = spec_to_mel_torch(
233
+ spec,
234
+ hps.data.filter_length,
235
+ hps.data.n_mel_channels,
236
+ hps.data.sampling_rate,
237
+ hps.data.mel_fmin,
238
+ hps.data.mel_fmax)
239
+ y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)
240
+ y_hat_mel = mel_spectrogram_torch(
241
+ y_hat.squeeze(1),
242
+ hps.data.filter_length,
243
+ hps.data.n_mel_channels,
244
+ hps.data.sampling_rate,
245
+ hps.data.hop_length,
246
+ hps.data.win_length,
247
+ hps.data.mel_fmin,
248
+ hps.data.mel_fmax
249
+ )
250
+
251
+ y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice
252
+
253
+ # Discriminator
254
+ y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
255
+ with autocast(enabled=False):
256
+ loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g)
257
+ loss_disc_all = loss_disc
258
+ if net_dur_disc is not None:
259
+ y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach())
260
+ with autocast(enabled=False):
261
+ # TODO: I think need to mean using the mask, but for now, just mean all
262
+ loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g)
263
+ loss_dur_disc_all = loss_dur_disc
264
+ optim_dur_disc.zero_grad()
265
+ scaler.scale(loss_dur_disc_all).backward()
266
+ scaler.unscale_(optim_dur_disc)
267
+ grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None)
268
+ scaler.step(optim_dur_disc)
269
+
270
+ optim_d.zero_grad()
271
+ scaler.scale(loss_disc_all).backward()
272
+ scaler.unscale_(optim_d)
273
+ grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
274
+ scaler.step(optim_d)
275
+
276
+ with autocast(enabled=hps.train.fp16_run):
277
+ # Generator
278
+ y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
279
+ if net_dur_disc is not None:
280
+ y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_)
281
+ with autocast(enabled=False):
282
+ loss_dur = torch.sum(l_length.float())
283
+ loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
284
+ loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
285
+
286
+ loss_fm = feature_loss(fmap_r, fmap_g)
287
+ loss_gen, losses_gen = generator_loss(y_d_hat_g)
288
+ loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl
289
+ if net_dur_disc is not None:
290
+ loss_dur_gen, losses_dur_gen = generator_loss(y_dur_hat_g)
291
+ loss_gen_all += loss_dur_gen
292
+ optim_g.zero_grad()
293
+ scaler.scale(loss_gen_all).backward()
294
+ scaler.unscale_(optim_g)
295
+ grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
296
+ scaler.step(optim_g)
297
+ scaler.update()
298
+
299
+ if rank == 0:
300
+ if global_step % hps.train.log_interval == 0:
301
+ lr = optim_g.param_groups[0]['lr']
302
+ losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl]
303
+ logger.info('Train Epoch: {} [{:.0f}%]'.format(
304
+ epoch,
305
+ 100. * batch_idx / len(train_loader)))
306
+ logger.info([x.item() for x in losses] + [global_step, lr])
307
+
308
+ scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr,
309
+ "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g}
310
+ scalar_dict.update(
311
+ {"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/dur": loss_dur, "loss/g/kl": loss_kl})
312
+ scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
313
+ scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
314
+ scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
315
+
316
+ image_dict = {
317
+ "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),
318
+ "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()),
319
+ "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),
320
+ "all/attn": utils.plot_alignment_to_numpy(attn[0, 0].data.cpu().numpy())
321
+ }
322
+ utils.summarize(
323
+ writer=writer,
324
+ global_step=global_step,
325
+ images=image_dict,
326
+ scalars=scalar_dict)
327
+
328
+ if global_step % hps.train.eval_interval == 0:
329
+ evaluate(hps, net_g, eval_loader, writer_eval)
330
+ utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch,
331
+ os.path.join(hps.model_dir, "G_{}.pth".format(global_step)))
332
+ utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch,
333
+ os.path.join(hps.model_dir, "D_{}.pth".format(global_step)))
334
+ if net_dur_disc is not None:
335
+ utils.save_checkpoint(net_dur_disc, optim_dur_disc, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "DUR_{}.pth".format(global_step)))
336
+ keep_ckpts = getattr(hps.train, 'keep_ckpts', 5)
337
+ if keep_ckpts > 0:
338
+ utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True)
339
+
340
+
341
+ global_step += 1
342
+
343
+ if rank == 0:
344
+ logger.info('====> Epoch: {}'.format(epoch))
345
+
346
+
347
+
348
+ def evaluate(hps, generator, eval_loader, writer_eval):
349
+ generator.eval()
350
+ image_dict = {}
351
+ audio_dict = {}
352
+ print("Evaluating ...")
353
+ with torch.no_grad():
354
+ for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in enumerate(eval_loader):
355
+ x, x_lengths = x.cuda(), x_lengths.cuda()
356
+ spec, spec_lengths = spec.cuda(), spec_lengths.cuda()
357
+ y, y_lengths = y.cuda(), y_lengths.cuda()
358
+ speakers = speakers.cuda()
359
+ bert = bert.cuda()
360
+ tone = tone.cuda()
361
+ language = language.cuda()
362
+ for use_sdp in [True, False]:
363
+ y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, tone, language, bert, y=spec, max_len=1000, sdp_ratio=0.0 if not use_sdp else 1.0)
364
+ y_hat_lengths = mask.sum([1, 2]).long() * hps.data.hop_length
365
+
366
+ mel = spec_to_mel_torch(
367
+ spec,
368
+ hps.data.filter_length,
369
+ hps.data.n_mel_channels,
370
+ hps.data.sampling_rate,
371
+ hps.data.mel_fmin,
372
+ hps.data.mel_fmax)
373
+ y_hat_mel = mel_spectrogram_torch(
374
+ y_hat.squeeze(1).float(),
375
+ hps.data.filter_length,
376
+ hps.data.n_mel_channels,
377
+ hps.data.sampling_rate,
378
+ hps.data.hop_length,
379
+ hps.data.win_length,
380
+ hps.data.mel_fmin,
381
+ hps.data.mel_fmax
382
+ )
383
+ image_dict.update({
384
+ f"gen/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy())
385
+ })
386
+ audio_dict.update({
387
+ f"gen/audio_{batch_idx}_{use_sdp}": y_hat[0, :, :y_hat_lengths[0]]
388
+ })
389
+ image_dict.update({f"gt/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())})
390
+ audio_dict.update({f"gt/audio_{batch_idx}": y[0, :, :y_lengths[0]]})
391
+
392
+ utils.summarize(
393
+ writer=writer_eval,
394
+ global_step=global_step,
395
+ images=image_dict,
396
+ audios=audio_dict,
397
+ audio_sampling_rate=hps.data.sampling_rate
398
+ )
399
+ generator.train()
400
+
401
+ if __name__ == "__main__":
402
+ main()
transcribe_genshin.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=gbk
2
+ import os
3
+ import argparse
4
+ import librosa
5
+ import numpy as np
6
+ from multiprocessing import Pool, cpu_count
7
+
8
+ import soundfile
9
+ from scipy.io import wavfile
10
+ from tqdm import tqdm
11
+
12
+ global speaker_annos
13
+ speaker_annos = []
14
+
15
+ def process(item):
16
+ spkdir, wav_name, args = item
17
+ speaker = spkdir.replace("\\", "/").split("/")[-1]
18
+ wav_path = os.path.join(args.in_dir, speaker, wav_name)
19
+ if os.path.exists(wav_path) and '.wav' in wav_path:
20
+ os.makedirs(os.path.join(args.out_dir, speaker), exist_ok=True)
21
+ wav, sr = librosa.load(wav_path, sr=args.sr)
22
+ soundfile.write(
23
+ os.path.join(args.out_dir, speaker, wav_name),
24
+ wav,
25
+ sr
26
+ )
27
+
28
+ def process_text(item):
29
+ spkdir, wav_name, args = item
30
+ speaker = spkdir.replace("\\", "/").split("/")[-1]
31
+ wav_path = os.path.join(args.in_dir, speaker, wav_name)
32
+ global speaker_annos
33
+ tr_name = wav_name.replace('.wav', '')
34
+ with open(args.out_dir+'/'+speaker+'/'+tr_name+'.lab', "r", encoding="utf-8") as file:
35
+ text = file.read()
36
+ text = text.replace("{NICKNAME}",'������')
37
+ text = text.replace("{M#��}{F#��}",'��')
38
+ text = text.replace("{M#��}{F#��}",'��')
39
+ substring = "{M#����}{F#���}"
40
+ if substring in text:
41
+ if tr_name.endswith("a"):
42
+ text = text.replace("{M#����}{F#���}",'����')
43
+ if tr_name.endswith("b"):
44
+ text = text.replace("{M#����}{F#���}",'���')
45
+ text = text.replace("#",'')
46
+ text = "ZH|" + text + "\n" #
47
+ speaker_annos.append(args.out_dir+'/'+speaker+'/'+wav_name+ "|" + speaker + "|" + text)
48
+
49
+
50
+
51
+ if __name__ == "__main__":
52
+ parent_dir = "./genshin_dataset/"
53
+ speaker_names = list(os.walk(parent_dir))[0][1]
54
+ parser = argparse.ArgumentParser()
55
+ parser.add_argument("--sr", type=int, default=44100, help="sampling rate")
56
+ parser.add_argument("--in_dir", type=str, default="./genshin_dataset", help="path to source dir")
57
+ parser.add_argument("--out_dir", type=str, default="./genshin_dataset", help="path to target dir")
58
+ args = parser.parse_args()
59
+ # processs = 8
60
+ processs = cpu_count()-2 if cpu_count() >4 else 1
61
+ pool = Pool(processes=processs)
62
+
63
+ for speaker in os.listdir(args.in_dir):
64
+ spk_dir = os.path.join(args.in_dir, speaker)
65
+ if os.path.isdir(spk_dir):
66
+ print(spk_dir)
67
+ for _ in tqdm(pool.imap_unordered(process, [(spk_dir, i, args) for i in os.listdir(spk_dir) if i.endswith("wav")])):
68
+ pass
69
+ for i in os.listdir(spk_dir):
70
+ if i.endswith("wav"):
71
+ pro=(spk_dir, i, args)
72
+ process_text(pro)
73
+ if len(speaker_annos) == 0:
74
+ print("transcribe error!!!")
75
+ with open("./filelists/short_character_anno.list", 'w', encoding='utf-8') as f:
76
+ for line in speaker_annos:
77
+ f.write(line)
78
+ print("transcript file finished.")