Spaces:
Sleeping
Sleeping
Ailyth
commited on
Commit
•
9a85c9a
0
Parent(s):
push_231002011740
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +45 -0
- .gitignore +160 -0
- Bert_VITS2_Guide.ipynb +323 -0
- LICENSE +674 -0
- MODELS/DLM.pth +3 -0
- MODELS/G_2900.pth +3 -0
- MODELS/adorabledarling.pth +3 -0
- MODELS/rabbit4900.pth +3 -0
- MODELS/silverhandG_4400.pth +3 -0
- README.md +13 -0
- README_zh.md +1 -0
- app.py +161 -0
- attentions.py +343 -0
- bert/chinese-roberta-wwm-ext-large/added_tokens.json +1 -0
- bert/chinese-roberta-wwm-ext-large/config.json +28 -0
- bert/chinese-roberta-wwm-ext-large/flax_model.msgpack +3 -0
- bert/chinese-roberta-wwm-ext-large/pytorch_model.bin +3 -0
- bert/chinese-roberta-wwm-ext-large/special_tokens_map.json +1 -0
- bert/chinese-roberta-wwm-ext-large/tf_model.h5 +3 -0
- bert/chinese-roberta-wwm-ext-large/tokenizer.json +0 -0
- bert/chinese-roberta-wwm-ext-large/tokenizer_config.json +1 -0
- bert/chinese-roberta-wwm-ext-large/vocab.txt +0 -0
- bert_gen.py +53 -0
- commons.py +161 -0
- configs/config.json +95 -0
- data_utils.py +332 -0
- losses.py +61 -0
- mel_processing.py +112 -0
- models.py +707 -0
- modules.py +452 -0
- monotonic_align/__init__.py +20 -0
- monotonic_align/core.c +0 -0
- monotonic_align/core.py +36 -0
- monotonic_align/core.pyx +42 -0
- monotonic_align/monotonic_align/monotonic_align +0 -0
- monotonic_align/setup.py +9 -0
- preprocess_text.py +69 -0
- requirements.txt +26 -0
- setup_ffmpeg.py +55 -0
- short_audio_transcribe.py +122 -0
- start.bat +2 -0
- text/__init__.py +28 -0
- text/chinese.py +193 -0
- text/chinese_bert.py +50 -0
- text/cleaner.py +27 -0
- text/cmudict.rep +0 -0
- text/cmudict_cache.pickle +3 -0
- text/english.py +138 -0
- text/english_bert_mock.py +5 -0
- text/japanese.py +104 -0
.gitattributes
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
core.o filter=lfs diff=lfs merge=lfs -text
|
37 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
38 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
39 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
40 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
41 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
42 |
+
*.tar.gz filter=lfs diff=lfs merge=lfs -text
|
43 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
44 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
45 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
.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>.
|
MODELS/DLM.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3f4187dbad0c4b817dfdb8e2db8b9bb35ed98280e2d5580215d346e416bbf82e
|
3 |
+
size 629528157
|
MODELS/G_2900.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:04509249431a35303227a2476a68348089fc3552667bc225aa056b13895505d1
|
3 |
+
size 629528157
|
MODELS/adorabledarling.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:434ffd70ae4e3688bbfac4a5618363991f24e1205223ccbddcc2218a1d79d313
|
3 |
+
size 629528157
|
MODELS/rabbit4900.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:087be2e67ea98eff8937cf97a752be6386e803e6e7c4e2bbfdf684f30cf677ad
|
3 |
+
size 629528157
|
MODELS/silverhandG_4400.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5fc0f7d1dfb6e03007830def07f7683f7d91bf2b73e6a54a007d91b354e22cb5
|
3 |
+
size 629528157
|
README.md
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: 声音生成测试
|
3 |
+
emoji: ✨
|
4 |
+
colorFrom: red
|
5 |
+
colorTo: indigo
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.36.1
|
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
|
README_zh.md
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
app.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import soundfile as sf
|
28 |
+
from datetime import datetime
|
29 |
+
import pytz
|
30 |
+
|
31 |
+
|
32 |
+
net_g = None
|
33 |
+
models = {
|
34 |
+
"AdorableDarling": "./MODELS/adorabledarling.pth",
|
35 |
+
"Silverleg": "./MODELS/silverhandG_4400.pth",
|
36 |
+
"MoonLucidAloof": "./lMODELS/G_2900.pth",
|
37 |
+
"Rrabbitt": "./MODELS/rabbit4900.pth",
|
38 |
+
"Mainlade": "./MODELS/DLM.pth",
|
39 |
+
}
|
40 |
+
|
41 |
+
def get_text(text, language_str, hps):
|
42 |
+
norm_text, phone, tone, word2ph = clean_text(text, language_str)
|
43 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
44 |
+
|
45 |
+
if hps.data.add_blank:
|
46 |
+
phone = commons.intersperse(phone, 0)
|
47 |
+
tone = commons.intersperse(tone, 0)
|
48 |
+
language = commons.intersperse(language, 0)
|
49 |
+
for i in range(len(word2ph)):
|
50 |
+
word2ph[i] = word2ph[i] * 2
|
51 |
+
word2ph[0] += 1
|
52 |
+
bert = get_bert(norm_text, word2ph, language_str)
|
53 |
+
del word2ph
|
54 |
+
|
55 |
+
assert bert.shape[-1] == len(phone)
|
56 |
+
|
57 |
+
phone = torch.LongTensor(phone)
|
58 |
+
tone = torch.LongTensor(tone)
|
59 |
+
language = torch.LongTensor(language)
|
60 |
+
|
61 |
+
return bert, phone, tone, language
|
62 |
+
|
63 |
+
def infer(text, sdp_ratio, noise_scale, noise_scale_w, length_scale, sid, model_dir):
|
64 |
+
global net_g
|
65 |
+
bert, phones, tones, lang_ids = get_text(text, "ZH", hps)
|
66 |
+
with torch.no_grad():
|
67 |
+
x_tst=phones.to(device).unsqueeze(0)
|
68 |
+
tones=tones.to(device).unsqueeze(0)
|
69 |
+
lang_ids=lang_ids.to(device).unsqueeze(0)
|
70 |
+
bert = bert.to(device).unsqueeze(0)
|
71 |
+
x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
|
72 |
+
del phones
|
73 |
+
speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
|
74 |
+
audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids, bert, sdp_ratio=sdp_ratio
|
75 |
+
, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy()
|
76 |
+
del x_tst, tones, lang_ids, bert, x_tst_lengths, speakers
|
77 |
+
sf.write("tmp.wav", audio, 44100)
|
78 |
+
return audio
|
79 |
+
|
80 |
+
def convert_wav_to_mp3(wav_file):
|
81 |
+
tz = pytz.timezone('Asia/Shanghai')
|
82 |
+
now = datetime.now(tz).strftime('%m%d%H%M%S')
|
83 |
+
os.makedirs('out', exist_ok=True)
|
84 |
+
output_path_mp3 = os.path.join('out', f"{now}.mp3")
|
85 |
+
|
86 |
+
renamed_input_path = os.path.join('in', f"in.wav")
|
87 |
+
os.makedirs('in', exist_ok=True)
|
88 |
+
os.rename(wav_file.name, renamed_input_path)
|
89 |
+
command = ["ffmpeg", "-i", renamed_input_path, "-acodec", "libmp3lame", "-y", output_path_mp3]
|
90 |
+
os.system(" ".join(command))
|
91 |
+
return output_path_mp3
|
92 |
+
|
93 |
+
def tts_generator(text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale, model):
|
94 |
+
global net_g
|
95 |
+
model_path = models[model]
|
96 |
+
net_g, _, _, _ = utils.load_checkpoint(model_path, net_g, None, skip_optimizer=True)
|
97 |
+
with torch.no_grad():
|
98 |
+
audio = infer(text, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker,model_dir=model)
|
99 |
+
with open('tmp.wav', 'rb') as wav_file:
|
100 |
+
mp3 = convert_wav_to_mp3(wav_file)
|
101 |
+
return "生成语音成功", (hps.data.sampling_rate, audio), mp3
|
102 |
+
|
103 |
+
if __name__ == "__main__":
|
104 |
+
parser = argparse.ArgumentParser()
|
105 |
+
parser.add_argument("--model_dir", default="", help="path of your model")
|
106 |
+
parser.add_argument("--config_dir", default="./configs/config.json", help="path of your config file")
|
107 |
+
parser.add_argument("--share", default=False, help="make link public")
|
108 |
+
parser.add_argument("-d", "--debug", action="store_true", help="enable DEBUG-LEVEL log")
|
109 |
+
|
110 |
+
args = parser.parse_args()
|
111 |
+
if args.debug:
|
112 |
+
logger.info("Enable DEBUG-LEVEL log")
|
113 |
+
logging.basicConfig(level=logging.DEBUG)
|
114 |
+
hps = utils.get_hparams_from_file(args.config_dir)
|
115 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
116 |
+
|
117 |
+
net_g = SynthesizerTrn(
|
118 |
+
len(symbols),
|
119 |
+
hps.data.filter_length // 2 + 1,
|
120 |
+
hps.train.segment_size // hps.data.hop_length,
|
121 |
+
n_speakers=hps.data.n_speakers,
|
122 |
+
**hps.model).to(device)
|
123 |
+
_ = net_g.eval()
|
124 |
+
|
125 |
+
|
126 |
+
speaker_ids = hps.data.spk2id
|
127 |
+
speakers = list(speaker_ids.keys())
|
128 |
+
|
129 |
+
with gr.Blocks() as app:
|
130 |
+
with gr.Row():
|
131 |
+
with gr.Column():
|
132 |
+
|
133 |
+
|
134 |
+
gr.Markdown(value="""
|
135 |
+
测试用
|
136 |
+
""")
|
137 |
+
text = gr.TextArea(label="Text", placeholder="Input Text Here",
|
138 |
+
value="在不在?能不能借给我三百块钱买可乐",info="使用huggingface的免费CPU进行推理,因此速度不快,一次性不要输入超过500汉字")
|
139 |
+
|
140 |
+
model = gr.Radio(choices=list(models.keys()), value=list(models.keys())[0], label='音声模型')
|
141 |
+
#model = gr.Dropdown(choices=models,value=models[0], label='音声模型')
|
142 |
+
speaker = gr.Radio(choices=speakers, value=speakers[0], label='Speaker')
|
143 |
+
gr.Markdown("生成参数,效果玄学")
|
144 |
+
sdp_ratio = gr.Slider(minimum=0, maximum=1, value=0.2, step=0.01, label='语调变化')
|
145 |
+
noise_scale = gr.Slider(minimum=0.1, maximum=1.5, value=0.5, step=0.01, label='感情变化')
|
146 |
+
noise_scale_w = gr.Slider(minimum=0.1, maximum=1.4, value=0.9, step=0.01, label='音节长度')
|
147 |
+
length_scale = gr.Slider(minimum=0.1, maximum=2, value=1, step=0.01, label='生成语音总长度')
|
148 |
+
btn = gr.Button("生成", variant="primary")
|
149 |
+
with gr.Column():
|
150 |
+
text_output = gr.Textbox(label="Message")
|
151 |
+
audio_output = gr.Audio(label="输出音频")
|
152 |
+
MP3_output = gr.File(label="WAV2MP3")
|
153 |
+
gr.Markdown(value="""
|
154 |
+
|
155 |
+
""")
|
156 |
+
btn.click(tts_generator,
|
157 |
+
inputs=[text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale, model],
|
158 |
+
outputs=[text_output, audio_output,MP3_output])
|
159 |
+
|
160 |
+
|
161 |
+
app.launch(show_error=True)
|
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/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/flax_model.msgpack
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a46a510fe646213c728b80c9d0d5691d05235523d67f9ac3c3ce4e67deabf926
|
3 |
+
size 1302196529
|
bert/chinese-roberta-wwm-ext-large/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4ac62d49144d770c5ca9a5d1d3039c4995665a080febe63198189857c6bd11cd
|
3 |
+
size 1306484351
|
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/tf_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:72d18616fb285b720cb869c25aa9f4d7371033dfd5d8ba82aca448fdd28132bf
|
3 |
+
size 1302594480
|
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,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"train": {
|
3 |
+
"log_interval": 10,
|
4 |
+
"eval_interval": 500,
|
5 |
+
"seed": 52,
|
6 |
+
"epochs": 2000,
|
7 |
+
"learning_rate": 0.00015,
|
8 |
+
"betas": [
|
9 |
+
0.8,
|
10 |
+
0.99
|
11 |
+
],
|
12 |
+
"eps": 1e-09,
|
13 |
+
"batch_size": 14,
|
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": 1,
|
36 |
+
"cleaned_text": true,
|
37 |
+
"spk2id": {
|
38 |
+
"default": 0
|
39 |
+
}
|
40 |
+
},
|
41 |
+
"model": {
|
42 |
+
"use_spk_conditioned_encoder": true,
|
43 |
+
"use_noise_scaled_mas": true,
|
44 |
+
"use_mel_posterior_encoder": false,
|
45 |
+
"use_duration_discriminator": true,
|
46 |
+
"inter_channels": 192,
|
47 |
+
"hidden_channels": 192,
|
48 |
+
"filter_channels": 768,
|
49 |
+
"n_heads": 2,
|
50 |
+
"n_layers": 6,
|
51 |
+
"kernel_size": 3,
|
52 |
+
"p_dropout": 0.1,
|
53 |
+
"resblock": "1",
|
54 |
+
"resblock_kernel_sizes": [
|
55 |
+
3,
|
56 |
+
7,
|
57 |
+
11
|
58 |
+
],
|
59 |
+
"resblock_dilation_sizes": [
|
60 |
+
[
|
61 |
+
1,
|
62 |
+
3,
|
63 |
+
5
|
64 |
+
],
|
65 |
+
[
|
66 |
+
1,
|
67 |
+
3,
|
68 |
+
5
|
69 |
+
],
|
70 |
+
[
|
71 |
+
1,
|
72 |
+
3,
|
73 |
+
5
|
74 |
+
]
|
75 |
+
],
|
76 |
+
"upsample_rates": [
|
77 |
+
8,
|
78 |
+
8,
|
79 |
+
2,
|
80 |
+
2,
|
81 |
+
2
|
82 |
+
],
|
83 |
+
"upsample_initial_channel": 512,
|
84 |
+
"upsample_kernel_sizes": [
|
85 |
+
16,
|
86 |
+
16,
|
87 |
+
8,
|
88 |
+
2,
|
89 |
+
2
|
90 |
+
],
|
91 |
+
"n_layers_q": 3,
|
92 |
+
"use_spectral_norm": false,
|
93 |
+
"gin_channels": 256
|
94 |
+
}
|
95 |
+
}
|
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
|
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,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy import zeros, int32, float32
|
2 |
+
from torch import from_numpy
|
3 |
+
|
4 |
+
from .core import maximum_path_jit
|
5 |
+
|
6 |
+
|
7 |
+
def maximum_path(neg_cent, mask):
|
8 |
+
""" numba optimized version.
|
9 |
+
neg_cent: [b, t_t, t_s]
|
10 |
+
mask: [b, t_t, t_s]
|
11 |
+
"""
|
12 |
+
device = neg_cent.device
|
13 |
+
dtype = neg_cent.dtype
|
14 |
+
neg_cent = neg_cent.data.cpu().numpy().astype(float32)
|
15 |
+
path = zeros(neg_cent.shape, dtype=int32)
|
16 |
+
|
17 |
+
t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(int32)
|
18 |
+
t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(int32)
|
19 |
+
maximum_path_jit(path, neg_cent, t_t_max, t_s_max)
|
20 |
+
return 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.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numba
|
2 |
+
|
3 |
+
|
4 |
+
@numba.jit(numba.void(numba.int32[:, :, ::1], numba.float32[:, :, ::1], numba.int32[::1], numba.int32[::1]),
|
5 |
+
nopython=True, nogil=True)
|
6 |
+
def maximum_path_jit(paths, values, t_ys, t_xs):
|
7 |
+
b = paths.shape[0]
|
8 |
+
max_neg_val = -1e9
|
9 |
+
for i in range(int(b)):
|
10 |
+
path = paths[i]
|
11 |
+
value = values[i]
|
12 |
+
t_y = t_ys[i]
|
13 |
+
t_x = t_xs[i]
|
14 |
+
|
15 |
+
v_prev = v_cur = 0.0
|
16 |
+
index = t_x - 1
|
17 |
+
|
18 |
+
for y in range(t_y):
|
19 |
+
for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
|
20 |
+
if x == y:
|
21 |
+
v_cur = max_neg_val
|
22 |
+
else:
|
23 |
+
v_cur = value[y - 1, x]
|
24 |
+
if x == 0:
|
25 |
+
if y == 0:
|
26 |
+
v_prev = 0.
|
27 |
+
else:
|
28 |
+
v_prev = max_neg_val
|
29 |
+
else:
|
30 |
+
v_prev = value[y - 1, x - 1]
|
31 |
+
value[y, x] += max(v_prev, v_cur)
|
32 |
+
|
33 |
+
for y in range(t_y - 1, -1, -1):
|
34 |
+
path[y, index] = 1
|
35 |
+
if index != 0 and (index == y or value[y - 1, index] < value[y - 1, index - 1]):
|
36 |
+
index = index - 1
|
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)
|