MarcusSu1216 commited on
Commit
e3c945a
·
1 Parent(s): f848dbd

Upload 23 files

Browse files
Files changed (23) hide show
  1. .gitignore +153 -0
  2. LICENSE +21 -0
  3. README.md +241 -12
  4. README_zh_CN.md +241 -0
  5. app.py +446 -0
  6. data_utils.py +155 -0
  7. flask_api.py +60 -0
  8. flask_api_full_song.py +55 -0
  9. inference_main.py +137 -0
  10. models.py +420 -0
  11. onnx_export.py +54 -0
  12. preprocess_flist_config.py +75 -0
  13. preprocess_hubert_f0.py +101 -0
  14. requirements.txt +21 -0
  15. requirements_win.txt +24 -0
  16. resample.py +48 -0
  17. setup.py +143 -0
  18. train.py +315 -0
  19. utils.py +533 -0
  20. wav_upload.py +23 -0
  21. webUI.py +172 -0
  22. 启动tensorboard.bat +9 -0
  23. 启动webui.bat +8 -0
.gitignore ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Created by https://www.toptal.com/developers/gitignore/api/python
3
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python
4
+
5
+ ### Python ###
6
+ # Byte-compiled / optimized / DLL files
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+
11
+ # C extensions
12
+ *.so
13
+
14
+ # Distribution / packaging
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ pip-wheel-metadata/
29
+ share/python-wheels/
30
+ *.egg-info/
31
+ .installed.cfg
32
+ *.egg
33
+ MANIFEST
34
+
35
+ # PyInstaller
36
+ # Usually these files are written by a python script from a template
37
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
38
+ *.manifest
39
+ *.spec
40
+
41
+ # Installer logs
42
+ pip-log.txt
43
+ pip-delete-this-directory.txt
44
+
45
+ # Unit test / coverage reports
46
+ htmlcov/
47
+ .tox/
48
+ .nox/
49
+ .coverage
50
+ .coverage.*
51
+ .cache
52
+ nosetests.xml
53
+ coverage.xml
54
+ *.cover
55
+ *.py,cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+ pytestdebug.log
59
+
60
+ # Translations
61
+ *.mo
62
+ *.pot
63
+
64
+ # Django stuff:
65
+ *.log
66
+ local_settings.py
67
+ db.sqlite3
68
+ db.sqlite3-journal
69
+
70
+ # Flask stuff:
71
+ instance/
72
+ .webassets-cache
73
+
74
+ # Scrapy stuff:
75
+ .scrapy
76
+
77
+ # Sphinx documentation
78
+ docs/_build/
79
+ doc/_build/
80
+
81
+ # PyBuilder
82
+ target/
83
+
84
+ # Jupyter Notebook
85
+ .ipynb_checkpoints
86
+
87
+ # IPython
88
+ profile_default/
89
+ ipython_config.py
90
+
91
+ # pyenv
92
+ .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
102
+ __pypackages__/
103
+
104
+ # Celery stuff
105
+ celerybeat-schedule
106
+ celerybeat.pid
107
+
108
+ # SageMath parsed files
109
+ *.sage.py
110
+
111
+ # Environments
112
+ .env
113
+ .venv
114
+ env/
115
+ venv/
116
+ ENV/
117
+ env.bak/
118
+ venv.bak/
119
+
120
+ # Spyder project settings
121
+ .spyderproject
122
+ .spyproject
123
+
124
+ # Rope project settings
125
+ .ropeproject
126
+
127
+ # mkdocs documentation
128
+ /site
129
+
130
+ # mypy
131
+ .mypy_cache/
132
+ .dmypy.json
133
+ dmypy.json
134
+
135
+ # Pyre type checker
136
+ .pyre/
137
+
138
+ # pytype static type analyzer
139
+ .pytype/
140
+
141
+ # End of https://www.toptal.com/developers/gitignore/api/python
142
+
143
+ dataset
144
+ dataset_raw
145
+ raw
146
+ results
147
+ inference/chunks_temp.json
148
+ logs
149
+ hubert/checkpoint_best_legacy_500.pt
150
+ configs/config.json
151
+ filelists/test.txt
152
+ filelists/train.txt
153
+ filelists/val.txt
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Jingyi Li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,12 +1,241 @@
1
- ---
2
- title: XingTong
3
- emoji: 📉
4
- colorFrom: pink
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 3.28.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SoftVC VITS Singing Voice Conversion
2
+
3
+ [**English**](./README.md) | [**中文简体**](./README_zh_CN.md)
4
+
5
+ #### ✨ A fork with a greatly improved interface: [34j/so-vits-svc-fork](https://github.com/34j/so-vits-svc-fork)
6
+
7
+ #### ✨ A client supports real-time conversion: [w-okada/voice-changer](https://github.com/w-okada/voice-changer)
8
+
9
+ ## 📏 Terms of Use
10
+
11
+ # Warning: Please solve the authorization problem of the dataset on your own. You shall be solely responsible for any problems caused by the use of non-authorized datasets for training and all consequences thereof.The repository and its maintainer, svc develop team, have nothing to do with the consequences!
12
+
13
+ 1. This project is established for academic exchange purposes only and is intended for communication and learning purposes. It is not intended for production environments.
14
+ 2. Any videos based on sovits that are published on video platforms must clearly indicate in the description that they are used for voice changing and specify the input source of the voice or audio, for example, using videos or audios published by others and separating the vocals as input source for conversion, which must provide clear original video or music links. If your own voice or other synthesized voices from other commercial vocal synthesis software are used as the input source for conversion, you must also explain it in the description.
15
+ 3. You shall be solely responsible for any infringement problems caused by the input source. When using other commercial vocal synthesis software as input source, please ensure that you comply with the terms of use of the software. Note that many vocal synthesis engines clearly state in their terms of use that they cannot be used for input source conversion.
16
+ 4. Continuing to use this project is deemed as agreeing to the relevant provisions stated in this repository README. This repository README has the obligation to persuade, and is not responsible for any subsequent problems that may arise.
17
+ 5. If you distribute this repository's code or publish any results produced by this project publicly (including but not limited to video sharing platforms), please indicate the original author and code source (this repository).
18
+ 6. If you use this project for any other plan, please contact and inform the author of this repository in advance. Thank you very much.
19
+
20
+ ## 🆕 Update!
21
+
22
+ > Updated the 4.0-v2 model, the entire process is the same as 4.0. Compared to 4.0, there is some improvement in certain scenarios, but there are also some cases where it has regressed. Please refer to the [4.0-v2 branch](https://github.com/svc-develop-team/so-vits-svc/tree/4.0-v2) for more information.
23
+
24
+ ## 📝 Model Introduction
25
+
26
+ The singing voice conversion model uses SoftVC content encoder to extract source audio speech features, then the vectors are directly fed into VITS instead of converting to a text based intermediate; thus the pitch and intonations are conserved. Additionally, the vocoder is changed to [NSF HiFiGAN](https://github.com/openvpi/DiffSinger/tree/refactor/modules/nsf_hifigan) to solve the problem of sound interruption.
27
+
28
+ ### 🆕 4.0 Version Update Content
29
+
30
+ - Feature input is changed to [Content Vec](https://github.com/auspicious3000/contentvec)
31
+ - The sampling rate is unified to use 44100Hz
32
+ - Due to the change of hop size and other parameters, as well as the streamlining of some model structures, the required GPU memory for inference is **significantly reduced**. The 44kHz GPU memory usage of version 4.0 is even smaller than the 32kHz usage of version 3.0.
33
+ - Some code structures have been adjusted
34
+ - The dataset creation and training process are consistent with version 3.0, but the model is completely non-universal, and the data set needs to be fully pre-processed again.
35
+ - Added an option 1: automatic pitch prediction for vc mode, which means that you don't need to manually enter the pitch key when converting speech, and the pitch of male and female voices can be automatically converted. However, this mode will cause pitch shift when converting songs.
36
+ - Added option 2: reduce timbre leakage through k-means clustering scheme, making the timbre more similar to the target timbre.
37
+
38
+ ## 💬 About Python Version
39
+
40
+ After conducting tests, we believe that the project runs stably on Python version 3.8.9.
41
+
42
+ ## 📥 Pre-trained Model Files
43
+
44
+ #### **Required**
45
+
46
+ - ContentVec: [checkpoint_best_legacy_500.pt](https://ibm.box.com/s/z1wgl1stco8ffooyatzdwsqn2psd9lrr)
47
+ - Place it under the `hubert` directory
48
+
49
+ ```shell
50
+ # contentvec
51
+ wget -P hubert/ http://obs.cstcloud.cn/share/obs/sankagenkeshi/checkpoint_best_legacy_500.pt
52
+ # Alternatively, you can manually download and place it in the hubert directory
53
+ ```
54
+
55
+ #### **Optional(Strongly recommend)**
56
+
57
+ - Pre-trained model files: `G_0.pth` `D_0.pth`
58
+ - Place them under the `logs/44k` directory
59
+
60
+ Get them from svc-develop-team(TBD) or anywhere else.
61
+
62
+ Although the pretrained model generally does not cause any copyright problems, please pay attention to it. For example, ask the author in advance, or the author has indicated the feasible use in the description clearly.
63
+
64
+ ## 📊 Dataset Preparation
65
+
66
+ Simply place the dataset in the `dataset_raw` directory with the following file structure.
67
+
68
+ ```
69
+ dataset_raw
70
+ ├───speaker0
71
+ │ ├───xxx1-xxx1.wav
72
+ │ ├───...
73
+ │ └───Lxx-0xx8.wav
74
+ └───speaker1
75
+ ├───xx2-0xxx2.wav
76
+ ├───...
77
+ └───xxx7-xxx007.wav
78
+ ```
79
+
80
+ You can customize the speaker name.
81
+
82
+ ```
83
+ dataset_raw
84
+ └───suijiSUI
85
+ ├───1.wav
86
+ ├───...
87
+ └───25788785-20221210-200143-856_01_(Vocals)_0_0.wav
88
+ ```
89
+
90
+ ## 🛠️ Preprocessing
91
+
92
+ 1. Resample to 44100Hz and mono
93
+
94
+ ```shell
95
+ python resample.py
96
+ ```
97
+
98
+ 2. Automatically split the dataset into training and validation sets, and generate configuration files
99
+
100
+ ```shell
101
+ python preprocess_flist_config.py
102
+ ```
103
+
104
+ 3. Generate hubert and f0
105
+
106
+ ```shell
107
+ python preprocess_hubert_f0.py
108
+ ```
109
+
110
+ After completing the above steps, the dataset directory will contain the preprocessed data, and the dataset_raw folder can be deleted.
111
+
112
+ #### You can modify some parameters in the generated config.json
113
+
114
+ * `keep_ckpts`: Keep the last `keep_ckpts` models during training. Set to `0` will keep them all. Default is `3`.
115
+
116
+ * `all_in_mem`: Load all dataset to RAM. It can be enabled when the disk IO of some platforms is too low and the system memory is **much larger** than your dataset.
117
+
118
+ ## 🏋️‍♀️ Training
119
+
120
+ ```shell
121
+ python train.py -c configs/config.json -m 44k
122
+ ```
123
+
124
+ ## 🤖 Inference
125
+
126
+ Use [inference_main.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/inference_main.py)
127
+
128
+ ```shell
129
+ # Example
130
+ python inference_main.py -m "logs/44k/G_30400.pth" -c "configs/config.json" -n "君の知らない物語-src.wav" -t 0 -s "nen"
131
+ ```
132
+
133
+ Required parameters:
134
+ - `-m` | `--model_path`: path to the model.
135
+ - `-c` | `--config_path`: path to the configuration file.
136
+ - `-n` | `--clean_names`: a list of wav file names located in the raw folder.
137
+ - `-t` | `--trans`: pitch adjustment, supports positive and negative (semitone) values.
138
+ - `-s` | `--spk_list`: target speaker name for synthesis.
139
+ - `-cl` | `--clip`: voice forced slicing, set to 0 to turn off(default), duration in seconds.
140
+
141
+ Optional parameters: see the next section
142
+ - `-lg` | `--linear_gradient`: The cross fade length of two audio slices in seconds. If there is a discontinuous voice after forced slicing, you can adjust this value. Otherwise, it is recommended to use the default value of 0.
143
+ - `-fmp` | `--f0_mean_pooling`: Apply mean filter (pooling) to f0,which may improve some hoarse sounds. Enabling this option will reduce inference speed.
144
+ - `-a` | `--auto_predict_f0`: automatic pitch prediction for voice conversion, do not enable this when converting songs as it can cause serious pitch issues.
145
+ - `-cm` | `--cluster_model_path`: path to the clustering model, fill in any value if clustering is not trained.
146
+ - `-cr` | `--cluster_infer_ratio`: proportion of the clustering solution, range 0-1, fill in 0 if the clustering model is not trained.
147
+
148
+ ## 🤔 Optional Settings
149
+
150
+ If the results from the previous section are satisfactory, or if you didn't understand what is being discussed in the following section, you can skip it, and it won't affect the model usage. (These optional settings have a relatively small impact, and they may have some effect on certain specific data, but in most cases, the difference may not be noticeable.)
151
+
152
+ ### Automatic f0 prediction
153
+
154
+ During the 4.0 model training, an f0 predictor is also trained, which can be used for automatic pitch prediction during voice conversion. However, if the effect is not good, manual pitch prediction can be used instead. But please do not enable this feature when converting singing voice as it may cause serious pitch shifting!
155
+ - Set `auto_predict_f0` to true in inference_main.
156
+
157
+ ### Cluster-based timbre leakage control
158
+
159
+ Introduction: The clustering scheme can reduce timbre leakage and make the trained model sound more like the target's timbre (although this effect is not very obvious), but using clustering alone will lower the model's clarity (the model may sound unclear). Therefore, this model adopts a fusion method to linearly control the proportion of clustering and non-clustering schemes. In other words, you can manually adjust the ratio between "sounding like the target's timbre" and "being clear and articulate" to find a suitable trade-off point.
160
+
161
+ The existing steps before clustering do not need to be changed. All you need to do is to train an additional clustering model, which has a relatively low training cost.
162
+
163
+ - Training process:
164
+ - Train on a machine with a good CPU performance. According to my experience, it takes about 4 minutes to train each speaker on a Tencent Cloud 6-core CPU.
165
+ - Execute "python cluster/train_cluster.py". The output of the model will be saved in "logs/44k/kmeans_10000.pt".
166
+ - Inference process:
167
+ - Specify "cluster_model_path" in inference_main.
168
+ - Specify "cluster_infer_ratio" in inference_main, where 0 means not using clustering at all, 1 means only using clustering, and usually 0.5 is sufficient.
169
+
170
+ ### F0 mean filtering
171
+
172
+ Introduction: The mean filtering of F0 can effectively reduce the hoarse sound caused by the predicted fluctuation of pitch (the hoarse sound caused by reverb or harmony can not be eliminated temporarily). This function has been greatly improved on some songs. If the song appears dumb after reasoning, it can be considered to open.
173
+ - Set f0_mean_pooling to true in inference_main
174
+
175
+ ### [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1kv-3y2DmZo0uya8pEr1xk7cSB-4e_Pct?usp=sharing) [sovits4_for_colab.ipynb](https://colab.research.google.com/drive/1kv-3y2DmZo0uya8pEr1xk7cSB-4e_Pct?usp=sharing)
176
+
177
+ #### [23/03/16] No longer need to download hubert manually
178
+
179
+ ## 📤 Exporting to Onnx
180
+
181
+ Use [onnx_export.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/onnx_export.py)
182
+
183
+ - Create a folder named `checkpoints` and open it
184
+ - Create a folder in the `checkpoints` folder as your project folder, naming it after your project, for example `aziplayer`
185
+ - Rename your model as `model.pth`, the configuration file as `config.json`, and place them in the `aziplayer` folder you just created
186
+ - Modify `"NyaruTaffy"` in `path = "NyaruTaffy"` in [onnx_export.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/onnx_export.py) to your project name, `path = "aziplayer"`
187
+ - Run [onnx_export.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/onnx_export.py)
188
+ - Wait for it to finish running. A `model.onnx` will be generated in your project folder, which is the exported model.
189
+
190
+ ### UI support for Onnx models
191
+
192
+ - [MoeSS](https://github.com/NaruseMioShirakana/MoeSS)
193
+
194
+ Note: For Hubert Onnx models, please use the models provided by MoeSS. Currently, they cannot be exported on their own (Hubert in fairseq has many unsupported operators and things involving constants that can cause errors or result in problems with the input/output shape and results when exported.) [Hubert4.0](https://huggingface.co/NaruseMioShirakana/MoeSS-SUBModel)
195
+
196
+ ## ☀️ Previous contributors
197
+
198
+ For some reason the author deleted the original repository. Because of the negligence of the organization members, the contributor list was cleared because all files were directly reuploaded to this repository at the beginning of the reconstruction of this repository. Now add a previous contributor list to README.md.
199
+
200
+ *Some members have not listed according to their personal wishes.*
201
+
202
+ <table>
203
+ <tr>
204
+ <td align="center"><a href="https://github.com/MistEO"><img src="https://avatars.githubusercontent.com/u/18511905?v=4" width="100px;" alt=""/><br /><sub><b>MistEO</b></sub></a><br /></td>
205
+ <td align="center"><a href="https://github.com/XiaoMiku01"><img src="https://avatars.githubusercontent.com/u/54094119?v=4" width="100px;" alt=""/><br /><sub><b>XiaoMiku01</b></sub></a><br /></td>
206
+ <td align="center"><a href="https://github.com/ForsakenRei"><img src="https://avatars.githubusercontent.com/u/23041178?v=4" width="100px;" alt=""/><br /><sub><b>しぐれ</b></sub></a><br /></td>
207
+ <td align="center"><a href="https://github.com/TomoGaSukunai"><img src="https://avatars.githubusercontent.com/u/25863522?v=4" width="100px;" alt=""/><br /><sub><b>TomoGaSukunai</b></sub></a><br /></td>
208
+ <td align="center"><a href="https://github.com/Plachtaa"><img src="https://avatars.githubusercontent.com/u/112609742?v=4" width="100px;" alt=""/><br /><sub><b>Plachtaa</b></sub></a><br /></td>
209
+ <td align="center"><a href="https://github.com/zdxiaoda"><img src="https://avatars.githubusercontent.com/u/45501959?v=4" width="100px;" alt=""/><br /><sub><b>zd小达</b></sub></a><br /></td>
210
+ <td align="center"><a href="https://github.com/Archivoice"><img src="https://avatars.githubusercontent.com/u/107520869?v=4" width="100px;" alt=""/><br /><sub><b>凍聲響世</b></sub></a><br /></td>
211
+ </tr>
212
+ </table>
213
+
214
+ ## 📚 Some legal provisions for reference
215
+
216
+ #### Any country, region, organization, or individual using this project must comply with the following laws.
217
+
218
+ #### 《民法典》
219
+
220
+ ##### 第一千零一十九条
221
+
222
+ 任何组织或者个人不得以丑化、污损,或者利用信息技术手段伪造等方式侵害他人的肖像权。未经肖像权人同意,不得制作、使用、公开肖像权人的肖像,但是法律另有规定的除外。未经肖像权人同意,肖像作品权利人不得以发表、复制、发行、出租、展览等方式使用或者公开肖像权人的肖像。对自然人声音的保护,参照适用肖像权保护的有关规定。
223
+
224
+ ##### 第一千零二十四条
225
+
226
+ 【名誉权】民事主体享有名誉权。任何组织或者个人不得以侮辱、诽���等方式侵害他人的名誉权。
227
+
228
+ ##### 第一千零二十七条
229
+
230
+ 【作品侵害名誉权】行为人发表的文学、艺术作品以真人真事或者特定人为描述对象,含有侮辱、诽谤内容,侵害他人名誉权的,受害人有权依法请求该行为人承担民事责任。行为人发表的文学、艺术作品不以特定人为描述对象,仅其中的情节与该特定人的情况相似的,不承担民事责任。
231
+
232
+ #### 《[中华人民共和国宪法](http://www.gov.cn/guoqing/2018-03/22/content_5276318.htm)》
233
+
234
+ #### 《[中华人民共和国刑法](http://gongbao.court.gov.cn/Details/f8e30d0689b23f57bfc782d21035c3.html?sw=%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E5%88%91%E6%B3%95)》
235
+
236
+ #### 《[中华人民共和国民法典](http://gongbao.court.gov.cn/Details/51eb6750b8361f79be8f90d09bc202.html)》
237
+
238
+ ## 💪 Thanks to all contributors for their efforts
239
+ <a href="https://github.com/svc-develop-team/so-vits-svc/graphs/contributors" target="_blank">
240
+ <img src="https://contrib.rocks/image?repo=svc-develop-team/so-vits-svc" />
241
+ </a>
README_zh_CN.md ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SoftVC VITS Singing Voice Conversion
2
+
3
+ [**English**](./README.md) | [**中文简体**](./README_zh_CN.md)
4
+
5
+ #### ✨ 改善了交互的一个分支推荐:[34j/so-vits-svc-fork](https://github.com/34j/so-vits-svc-fork)
6
+
7
+ #### ✨ 支持实时转换的一个客户端:[w-okada/voice-changer](https://github.com/w-okada/voice-changer)
8
+
9
+ ## 📏 使用规约
10
+
11
+ # Warning:请自行解决数据集授权问题,禁止使用非授权数据集进行训练!任何由于使用非授权数据集进行训练造成的问题,需自行承担全部责任和后果!与仓库、仓库维护者、svc develop team 无关!
12
+
13
+ 1. 本项目是基于学术交流目的建立,仅供交流与学习使用,并非为生产环境准备。
14
+ 2. 任何发布到视频平台的基于 sovits 制作的视频,都必须要在简介明确指明用于变声器转换的输入源歌声、音频,例如:使用他人发布的视频 / 音频,通过分离的人声作为输入源进行转换的,必须要给出明确的原视频、音乐链接;若使用是自己的人声,或是使用其他歌声合成引擎合成的声音作为输入源进行转换的,也必须在简介加以说明。
15
+ 3. 由输入源造成的侵权问题需自行承担全部责任和一切后果。使用其他商用歌声合成软件作为输入源时,请确保遵守该软件的使用条例,注意,许多歌声合成引擎使用条例中明确指明不可用于输入源进行转换!
16
+ 4. 继续使用视为已同意本仓库 README 所述相关条例,本仓库 README 已进行劝导义务,不对后续可能存在问题负责。
17
+ 5. 如将本仓库代码二次分发,或将由此项目产出的任何结果公开发表 (包括但不限于视频网站投稿),请注明原作者及代码来源 (此仓库)。
18
+ 6. 如果将此项目用于任何其他企划,请提前联系并告知本仓库作者,十分感谢。
19
+
20
+ ## 🆕 Update!
21
+
22
+ > 更新了4.0-v2模型,全部流程同4.0,相比4.0在部分场景下有一定提升,但也有些情况有退步,具体可移步[4.0-v2分支](https://github.com/svc-develop-team/so-vits-svc/tree/4.0-v2)
23
+
24
+ ## 📝 模型简介
25
+
26
+ 歌声音色转换模型,通过SoftVC内容编码器提取源音频语音特征,与F0同时输入VITS替换原本的文本输入达到歌声转换的效果。同时,更换声码器为 [NSF HiFiGAN](https://github.com/openvpi/DiffSinger/tree/refactor/modules/nsf_hifigan) 解决断音问题
27
+
28
+ ### 🆕 4.0 版本更新内容
29
+
30
+ + 特征输入更换为 [Content Vec](https://github.com/auspicious3000/contentvec)
31
+ + 采样率统一使用44100hz
32
+ + 由于更改了hop size等参数以及精简了部分模型结构,推理所需显存占用**大幅降低**,4.0版本44khz显存占用甚至小于3.0版本的32khz
33
+ + 调整了部分代码结构
34
+ + 数据集制作、训练过程和3.0保持一致,但模型完全不通用,数据集也需要全部重新预处理
35
+ + 增加了可选项 1:vc模式自动预测音高f0,即转换语音时不需要手动输入变调key,男女声的调能自动转换,但仅限语音转换,该模式转换歌声会跑调
36
+ + 增加了可选项 2:通过kmeans聚类方案减小音色泄漏,即使得音色更加像目标音色
37
+
38
+ ## 💬 关于 Python 版本问题
39
+
40
+ 我们在进行测试后,认为 Python 3.8.9 版本能够稳定地运行该项目
41
+
42
+ ## 📥 预先下载的模型文件
43
+
44
+ #### **必须项**
45
+
46
+ + contentvec :[checkpoint_best_legacy_500.pt](https://ibm.box.com/s/z1wgl1stco8ffooyatzdwsqn2psd9lrr)
47
+ + 放在`hubert`目录下
48
+
49
+ ```shell
50
+ # contentvec
51
+ http://obs.cstcloud.cn/share/obs/sankagenkeshi/checkpoint_best_legacy_500.pt
52
+ # 也可手动下载放在hubert目录
53
+ ```
54
+
55
+ #### **可选项(强烈建议使用)**
56
+
57
+ + 预训练底模文件: `G_0.pth` `D_0.pth`
58
+ + 放在`logs/44k`目录下
59
+
60
+ 从svc-develop-team(待定)或任何其他地方获取
61
+
62
+ 虽然底模一般不会引起什么版权问题,但还是请注意一下,比如事先询问作者,又或者作者在模型描述中明确写明了可行的用途
63
+
64
+ ## 📊 数据集准备
65
+
66
+ 仅需要以以下文件结构将数据集放入dataset_raw目录即可
67
+
68
+ ```
69
+ dataset_raw
70
+ ├───speaker0
71
+ │ ├───xxx1-xxx1.wav
72
+ │ ├───...
73
+ │ └───Lxx-0xx8.wav
74
+ └───speaker1
75
+ ├───xx2-0xxx2.wav
76
+ ├───...
77
+ └───xxx7-xxx007.wav
78
+ ```
79
+
80
+ 可以自定义说话人名称
81
+
82
+ ```
83
+ dataset_raw
84
+ └───suijiSUI
85
+ ├───1.wav
86
+ ├───...
87
+ └───25788785-20221210-200143-856_01_(Vocals)_0_0.wav
88
+ ```
89
+
90
+ ## 🛠️ 数据预处理
91
+
92
+ 1. 重采样至44100Hz单声道
93
+
94
+ ```shell
95
+ python resample.py
96
+ ```
97
+
98
+ 2. 自动划分训练集、验证集,以及自动生成配置文件
99
+
100
+ ```shell
101
+ python preprocess_flist_config.py
102
+ ```
103
+
104
+ 3. 生成hubert与f0
105
+
106
+ ```shell
107
+ python preprocess_hubert_f0.py
108
+ ```
109
+
110
+ 执行完以上步骤后 dataset 目录便是预处理完成的数据,可以删除 dataset_raw 文件夹了
111
+
112
+ #### 此时可以在生成的config.json修改部分参数
113
+
114
+ * `keep_ckpts`:训���时保留最后几个模型,`0`为保留所有,默认只保留最后`3`个
115
+
116
+ * `all_in_mem`:加载所有数据集到内存中,某些平台的硬盘IO过于低下、同时内存容量 **远大于** 数据集体积时可以启用
117
+
118
+ ## 🏋️‍♀️ 训练
119
+
120
+ ```shell
121
+ python train.py -c configs/config.json -m 44k
122
+ ```
123
+
124
+ ## 🤖 推理
125
+
126
+ 使用 [inference_main.py](inference_main.py)
127
+
128
+ ```shell
129
+ # 例
130
+ python inference_main.py -m "logs/44k/G_30400.pth" -c "configs/config.json" -n "君の知らない物語-src.wav" -t 0 -s "nen"
131
+ ```
132
+
133
+ 必填项部分
134
+ + `-m` | `--model_path`:模型路径
135
+ + `-c` | `--config_path`:配置文件路径
136
+ + `-n` | `--clean_names`:wav 文件名列表,放在 raw 文件夹下
137
+ + `-t` | `--trans`:音高调整,支持正负(半音)
138
+ + `-s` | `--spk_list`:合成目标说话人名称
139
+ + `-cl` | `--clip`:音频强制切片,默认0为自动切片,单位为秒/s
140
+
141
+ 可选项部分:部分具体见下一节
142
+ + `-lg` | `--linear_gradient`:两段音频切片的交叉淡入长度,如果强制切片后出现人声不连贯可调整该数值,如果连贯建议采用默认值0,单位为秒
143
+ + `-fmp` | `--f0_mean_pooling`:是否对F0使用均值滤波器(池化),对部分哑音有改善。注意,启动该选项会导致推理速度下降,默认关闭
144
+ + `-a` | `--auto_predict_f0`:语音转换自动预测音高,转换歌声时不要打开这个会严重跑调
145
+ + `-cm` | `--cluster_model_path`:聚类模型路径,如果没有训练聚类则随便填
146
+ + `-cr` | `--cluster_infer_ratio`:聚类方案占比,范围0-1,若没有训练聚类模型则默认0即可
147
+
148
+ ## 🤔 可选项
149
+
150
+ 如果前面的效果已经满意,或者没看明白下面在讲啥,那后面的内容都可以忽略,不影响模型使用(这些可选项影响比较小,可能在某些特定数据上有点效果,但大部分情况似乎都感知不太明显)
151
+
152
+ ### 自动f0预测
153
+
154
+ 4.0模型训练过程会训练一个f0预测器,对于语音转换可以开启自动音高预测,如果效果不好也可以使用手动的,但转换歌声时请不要启用此功能!!!会严重跑调!!
155
+ + 在inference_main中设置auto_predict_f0为true即可
156
+
157
+ ### 聚类音色泄漏控制
158
+
159
+ 介绍:聚类方案可以减小音色泄漏,使得模型训练出来更像目标的音色(但其实不是特别明显),但是单纯的聚类方案会降低模型的咬字(会口齿不清)(这个很明显),本模型采用了融合的方式,可以线性控制聚类方案与非聚类方案的占比,也就是可以手动在"像目标音色" 和 "咬字清晰" 之间调整比例,找到合适的折中点。
160
+
161
+ 使用聚类前面的已有步骤不用进行任何的变动,只需要额外训练一个聚类模型,虽然效果比较有限,但训练成本也比较低
162
+
163
+ + 训练过程:
164
+ + 使用cpu性能较好的机器训练,据我的经验在腾讯云6核cpu训练每个speaker需要约4分钟即可完成训练
165
+ + 执行python cluster/train_cluster.py ,模型的输出会在 logs/44k/kmeans_10000.pt
166
+ + 推理过程:
167
+ + inference_main中指定cluster_model_path
168
+ + inference_main中指定cluster_infer_ratio,0为完全不使用聚类,1为只使用聚类,通常设置0.5即可
169
+
170
+ ### F0均值滤波
171
+
172
+ 介绍:对F0进行均值滤波,可以有效的减少因音高推测波动造成的哑音(由于混响或和声等造成的哑音暂时不能消除)。该功能在部分歌曲上提升巨大,如果歌曲推理后出现哑音可以考虑开启。
173
+ + 在inference_main中设置f0_mean_pooling为true即可
174
+
175
+ ### [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1kv-3y2DmZo0uya8pEr1xk7cSB-4e_Pct?usp=sharing) [sovits4_for_colab.ipynb](https://colab.research.google.com/drive/1kv-3y2DmZo0uya8pEr1xk7cSB-4e_Pct?usp=sharing)
176
+
177
+ #### [23/03/16] 不再需要手动下载hubert
178
+
179
+ ## 📤 Onnx导出
180
+
181
+ 使用 [onnx_export.py](onnx_export.py)
182
+ + 新建文件夹:`checkpoints` 并打开
183
+ + 在`checkpoints`文件夹中新建一个文件夹作为项目文件夹,文件夹名为你的项目名称,比如`aziplayer`
184
+ + 将你的模型更名为`model.pth`,配置文件更名为`config.json`,并放置到刚才创建的`aziplayer`文件夹下
185
+ + 将 [onnx_export.py](onnx_export.py) 中`path = "NyaruTaffy"` 的 `"NyaruTaffy"` 修改为你的项目名称,`path = "aziplayer"`
186
+ + 运行 [onnx_export.py](onnx_export.py)
187
+ + 等待执行完毕,在你的项目文件夹下会生成一个`model.onnx`,即为导出的模型
188
+
189
+ ### Onnx模型支持的UI
190
+
191
+ + [MoeSS](https://github.com/NaruseMioShirakana/MoeSS)
192
+ + 我去除了所有的训练用函数和一切复杂的转置,一行都没有保留,因为我认为只有去除了这些东西,才知道你用的是Onnx
193
+ + 注意:Hubert Onnx模型请使用MoeSS提供的模型,目前无法自行导出(fairseq中Hubert有不少onnx不支持的算子和涉及到常量的东西,在导出时会报错或者导出的模型输入输出shape和结果都有问题��
194
+ [Hubert4.0](https://huggingface.co/NaruseMioShirakana/MoeSS-SUBModel)
195
+
196
+ ## ☀️ 旧贡献者
197
+
198
+ 因为某些原因原作者进行了删库处理,本仓库重建之初由于组织成员疏忽直接重新上传了所有文件导致以前的contributors全部木大,现在在README里重新添加一个旧贡献者列表
199
+
200
+ *某些成员已根据其个人意愿不将其列出*
201
+
202
+ <table>
203
+ <tr>
204
+ <td align="center"><a href="https://github.com/MistEO"><img src="https://avatars.githubusercontent.com/u/18511905?v=4" width="100px;" alt=""/><br /><sub><b>MistEO</b></sub></a><br /></td>
205
+ <td align="center"><a href="https://github.com/XiaoMiku01"><img src="https://avatars.githubusercontent.com/u/54094119?v=4" width="100px;" alt=""/><br /><sub><b>XiaoMiku01</b></sub></a><br /></td>
206
+ <td align="center"><a href="https://github.com/ForsakenRei"><img src="https://avatars.githubusercontent.com/u/23041178?v=4" width="100px;" alt=""/><br /><sub><b>しぐれ</b></sub></a><br /></td>
207
+ <td align="center"><a href="https://github.com/TomoGaSukunai"><img src="https://avatars.githubusercontent.com/u/25863522?v=4" width="100px;" alt=""/><br /><sub><b>TomoGaSukunai</b></sub></a><br /></td>
208
+ <td align="center"><a href="https://github.com/Plachtaa"><img src="https://avatars.githubusercontent.com/u/112609742?v=4" width="100px;" alt=""/><br /><sub><b>Plachtaa</b></sub></a><br /></td>
209
+ <td align="center"><a href="https://github.com/zdxiaoda"><img src="https://avatars.githubusercontent.com/u/45501959?v=4" width="100px;" alt=""/><br /><sub><b>zd小达</b></sub></a><br /></td>
210
+ <td align="center"><a href="https://github.com/Archivoice"><img src="https://avatars.githubusercontent.com/u/107520869?v=4" width="100px;" alt=""/><br /><sub><b>凍聲響世</b></sub></a><br /></td>
211
+ </tr>
212
+ </table>
213
+
214
+ ## 📚 一些法律条例参考
215
+
216
+ #### 任何国家,地区,组织和个人使用此项目必须遵守以下法律
217
+
218
+ #### 《民法典》
219
+
220
+ ##### 第一千零一十九条
221
+
222
+ 任何组织或者个人不得以丑化、污损,或者利用信息技术手段伪造等方式侵害他人的肖像权。未经肖像权人同意,不得制作、使用、公开肖像权人的肖像,但是法律另有规定的除外。未经肖像权人同意,肖像作品权利人不得以发表、复制、发行、出租、展览等方式使用或者公开肖像权人的肖像。对自然人声音的保护,参照适用肖像权保护的有关规定。
223
+
224
+ ##### 第一千零二十四条
225
+
226
+ 【名誉权】民事主体享有名誉权。任何组织或者个人不得以侮辱、诽谤等方式侵害他人的名誉权。
227
+
228
+ ##### 第一千零二十七条
229
+
230
+ 【作品侵害名誉权】行为人发表的文学、艺术作品以真人真事或者特定人为描述对象,含有侮辱、诽谤内容,侵害他人名誉权的,受害人有权依法请求该行为人承担民事责任。行为人发表的文学、艺术作品不以特定人为描述对象,仅其中的情节与该特定人的情况相似的,不承担民事责任。
231
+
232
+ #### 《[中华人民共和国宪法](http://www.gov.cn/guoqing/2018-03/22/content_5276318.htm)》
233
+
234
+ #### 《[中华人民共和国刑法](http://gongbao.court.gov.cn/Details/f8e30d0689b23f57bfc782d21035c3.html?sw=中华人民共和国刑法)》
235
+
236
+ #### 《[中华人民共和国民法典](http://gongbao.court.gov.cn/Details/51eb6750b8361f79be8f90d09bc202.html)》
237
+
238
+ ## 💪 感谢所有的贡献者
239
+ <a href="https://github.com/svc-develop-team/so-vits-svc/graphs/contributors" target="_blank">
240
+ <img src="https://contrib.rocks/image?repo=svc-develop-team/so-vits-svc" />
241
+ </a>
app.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import re
4
+ import torch
5
+ #import argparse
6
+ import gradio as gr
7
+ import gradio.processing_utils as gr_pu
8
+ import librosa
9
+ import numpy as np
10
+ import soundfile as sf
11
+ from inference.infer_tool import Svc
12
+ import logging
13
+ import json
14
+ import matplotlib.pyplot as plt
15
+ import parselmouth
16
+ import time
17
+ import subprocess
18
+ import shutil
19
+ import asyncio
20
+ import datetime
21
+
22
+ from scipy.io import wavfile
23
+
24
+ #parser = argparse.ArgumentParser()
25
+ #parser.add_argument("--user", type=str, help='set gradio user', default=None)
26
+ #parser.add_argument("--password", type=str, help='set gradio password', default=None)
27
+ #cmd_opts = parser.parse_args()
28
+
29
+ logging.getLogger('numba').setLevel(logging.WARNING)
30
+ logging.getLogger('markdown_it').setLevel(logging.WARNING)
31
+ logging.getLogger('urllib3').setLevel(logging.WARNING)
32
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
33
+
34
+ raw_path = "./dataset_raw"
35
+ models_backup_path = './models_backup'
36
+ #now_dir = os.getcwd()
37
+
38
+ def load_model_func(ckpt_name,cluster_name,config_name,enhance):
39
+ global model, cluster_model_path
40
+
41
+ config_path = "configs/" + config_name
42
+
43
+ with open(config_path, 'r') as f:
44
+ config = json.load(f)
45
+ spk_dict = config["spk"]
46
+ spk_name = config.get('spk', None)
47
+ if spk_name:
48
+ spk_choice = next(iter(spk_name))
49
+ else:
50
+ spk_choice = "未检测到音色"
51
+
52
+ ckpt_path = "logs/44k/" + ckpt_name
53
+ cluster_path = "logs/44k/" + cluster_name
54
+ if cluster_name == "no_clu":
55
+ model = Svc(ckpt_path,config_path,nsf_hifigan_enhance=enhance)
56
+ else:
57
+ model = Svc(ckpt_path,config_path,cluster_model_path=cluster_path,nsf_hifigan_enhance=enhance)
58
+
59
+ spk_list = list(spk_dict.keys())
60
+ output_msg = "模型加载成功"
61
+ return output_msg, gr.Dropdown.update(choices=spk_list, value=spk_choice)
62
+
63
+ def load_options():
64
+ file_list = os.listdir("logs/44k")
65
+ ckpt_list = []
66
+ cluster_list = []
67
+ for ck in file_list:
68
+ if os.path.splitext(ck)[-1] == ".pth" and ck[0] != "k" and ck[:2] != "D_":
69
+ ckpt_list.append(ck)
70
+ if ck[0] == "k":
71
+ cluster_list.append(ck)
72
+ if not cluster_list:
73
+ cluster_list = ["你没有聚类模型"]
74
+ return choice_ckpt.update(choices = ckpt_list), config_choice.update(choices = os.listdir("configs")), cluster_choice.update(choices = cluster_list)
75
+
76
+ def vc_fn(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling,enhancer_adaptive_key):
77
+ global model
78
+ try:
79
+ if input_audio is None:
80
+ return "You need to upload an audio", None
81
+ if model is None:
82
+ return "You need to upload an model", None
83
+ sampling_rate, audio = input_audio
84
+ # print(audio.shape,sampling_rate)
85
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
86
+ if len(audio.shape) > 1:
87
+ audio = librosa.to_mono(audio.transpose(1, 0))
88
+ temp_path = "temp.wav"
89
+ sf.write(temp_path, audio, sampling_rate, format="wav")
90
+ _audio = model.slice_inference(temp_path, sid, vc_transform, slice_db, cluster_ratio, auto_f0, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling,enhancer_adaptive_key)
91
+ model.clear_empty()
92
+ os.remove(temp_path)
93
+ #构建保存文件的路径,并保存到results文件夹内
94
+ timestamp = str(int(time.time()))
95
+ output_file = os.path.join("results", sid + "_" + timestamp + ".wav")
96
+ sf.write(output_file, _audio, model.target_sample, format="wav")
97
+ return "Success", (model.target_sample, _audio)
98
+ except Exception as e:
99
+ return "异常信息:"+str(e)+"\n请排障后重试",None
100
+
101
+ def load_raw_dirs():
102
+ #检查文件名
103
+ allowed_pattern = re.compile(r'^[a-zA-Z0-9_@#$%^&()_+\-=\s]*$')
104
+ for root, dirs, files in os.walk(raw_path):
105
+ if root != raw_path: # 只处理子文件夹内的文件
106
+ for file in files:
107
+ file_name, _ = os.path.splitext(file)
108
+ if not allowed_pattern.match(file_name):
109
+ return "数据集文件名只能包含数字、字母、下划线"
110
+ #检查有没有小可爱不用wav文件当数据集
111
+ for root, dirs, files in os.walk(raw_path):
112
+ if root != raw_path: # 只处理子文件夹内的文件
113
+ for file in files:
114
+ if not file.endswith('.wav'):
115
+ return "数据集中包含非wav格式文件,请检查后再试"
116
+ spk_dirs = []
117
+ with os.scandir(raw_path) as entries:
118
+ for entry in entries:
119
+ if entry.is_dir():
120
+ spk_dirs.append(entry.name)
121
+ if len(spk_dirs) != 0:
122
+ return raw_dirs_list.update(value=spk_dirs)
123
+ else:
124
+ return raw_dirs_list.update(value="未找到数据集,请检查dataset_raw文件夹")
125
+ '''Old function
126
+ def dataset_preprocess():
127
+ preprocess_commands = [
128
+ r".\workenv\python.exe resample.py",
129
+ r".\workenv\python.exe preprocess_flist_config.py",
130
+ r".\workenv\python.exe preprocess_hubert_f0.py"
131
+ ]
132
+ output = ""
133
+ for command in preprocess_commands:
134
+ try:
135
+ result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, text=True)
136
+ except subprocess.CalledProcessError as e:
137
+ result = e.output
138
+ output += f"Command: {command}\nResult:\n{result}\n{'-' * 50}\n"
139
+ #cmd = r".\venv\Scripts\activate&&python resample.py&&python preprocess_flist_config.py&&python preprocess_hubert_f0.py"
140
+ #print(cmd)
141
+ #p = Popen(cmd, shell=True, cwd=now_dir)
142
+ #p.wait()
143
+ config_path = "configs/config.json"
144
+ with open(config_path, 'r') as f:
145
+ config = json.load(f)
146
+ spk_dict = config["spk"]
147
+ spk_name = config.get('spk', None)
148
+ return output, speakers.update(value=spk_name)
149
+ '''
150
+ def dataset_preprocess():
151
+ preprocess_commands = [
152
+ r".\workenv\python.exe resample.py",
153
+ r".\workenv\python.exe preprocess_flist_config.py",
154
+ r".\workenv\python.exe preprocess_hubert_f0.py"
155
+ ]
156
+ accumulated_output = ""
157
+
158
+ for command in preprocess_commands:
159
+ try:
160
+ result = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, text=True)
161
+
162
+ accumulated_output += f"Command: {command}\n"
163
+ yield accumulated_output, None
164
+
165
+ for line in result.stdout:
166
+ accumulated_output += line
167
+ yield accumulated_output, None
168
+
169
+ result.communicate()
170
+
171
+ except subprocess.CalledProcessError as e:
172
+ result = e.output
173
+ accumulated_output += f"Error: {result}\n"
174
+ yield accumulated_output, None
175
+
176
+ accumulated_output += '-' * 50 + '\n'
177
+ yield accumulated_output, None
178
+
179
+ config_path = "configs/config.json"
180
+ with open(config_path, 'r') as f:
181
+ config = json.load(f)
182
+ spk_dict = config["spk"]
183
+ spk_name = config.get('spk', None)
184
+
185
+ yield accumulated_output, gr.Textbox.update(value=spk_name)
186
+
187
+ def clear_output():
188
+ return gr.Textbox.update(value="Cleared!>_<")
189
+
190
+ def config_fn(log_interval, eval_interval, keep_ckpts, batch_size, lr, fp16_run, all_in_mem):
191
+ config_origin = ".\\configs\\config.json"
192
+ with open(config_origin, 'r') as config_file:
193
+ config_data = json.load(config_file)
194
+ config_data['train']['log_interval'] = int(log_interval)
195
+ config_data['train']['eval_interval'] = int(eval_interval)
196
+ config_data['train']['keep_ckpts'] = int(keep_ckpts)
197
+ config_data['train']['batch_size'] = int(batch_size)
198
+ config_data['train']['learning_rate'] = float(lr)
199
+ config_data['train']['fp16_run'] = fp16_run
200
+ config_data['train']['all_in_mem'] = all_in_mem
201
+ with open(config_origin, 'w') as config_file:
202
+ json.dump(config_data, config_file, indent=4)
203
+ return "配置文件写入完成"
204
+
205
+ #def next_backup_folder_number(backup_path):
206
+ # numbers = [int(folder) for folder in os.listdir(backup_path) if folder.isdigit()]
207
+ # return max(numbers) + 1 if numbers else 1
208
+
209
+ def training(gpu_selection):
210
+ if not os.listdir(r"dataset\44k"):
211
+ return "数据集不存在,请检查dataset文件夹"
212
+ dataset_path = "dataset/44k"
213
+ no_npy_pt_files = True
214
+ for root, dirs, files in os.walk(dataset_path):
215
+ for file in files:
216
+ if file.endswith('.npy') or file.endswith('.pt'):
217
+ no_npy_pt_files = False
218
+ break
219
+ if no_npy_pt_files:
220
+ return "数据集中未检测到f0和hubert文件,可能是预训练未完成"
221
+ #备份logs/44k文件
222
+ logs_44k = "logs/44k"
223
+ pre_trained_model = "pre_trained_model"
224
+ models_backup = "models_backup"
225
+ timestamp = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')
226
+ #new_backup_folder_number = next_backup_folder_number(models_backup)
227
+ new_backup_folder = os.path.join(models_backup, str(timestamp))
228
+ os.makedirs(new_backup_folder, exist_ok=True)
229
+ for file in os.listdir(logs_44k):
230
+ shutil.move(os.path.join(logs_44k, file), os.path.join(new_backup_folder, file))
231
+ d_0_path = os.path.join(pre_trained_model, "D_0.pth")
232
+ g_0_path = os.path.join(pre_trained_model, "G_0.pth")
233
+ if os.path.isfile(d_0_path) and os.path.isfile(g_0_path):
234
+ print("D_0.pth and G_0.pth exist in pre_trained_model")
235
+ else:
236
+ print("D_0.pth and/or G_0.pth are missing in pre_trained_model")
237
+ shutil.copy(d_0_path, os.path.join(logs_44k, "D_0.pth"))
238
+ shutil.copy(g_0_path, os.path.join(logs_44k, "G_0.pth"))
239
+ cmd = r"set CUDA_VISIBLE_DEVICES=%s && .\workenv\python.exe train.py -c configs/config.json -m 44k" % (gpu_selection)
240
+ subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", cmd])
241
+ return "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
242
+
243
+ def continue_training(gpu_selection):
244
+ if not os.listdir(r"dataset\44k"):
245
+ return "数据集不存在,请检查dataset��件夹"
246
+ dataset_path = "dataset/44k"
247
+ no_npy_pt_files = True
248
+ for root, dirs, files in os.walk(dataset_path):
249
+ for file in files:
250
+ if file.endswith('.npy') or file.endswith('.pt'):
251
+ no_npy_pt_files = False
252
+ break
253
+ if no_npy_pt_files:
254
+ return "数据集中未检测到f0和hubert文件,可能是预训练未完成"
255
+ cmd = r"set CUDA_VISIBLE_DEVICES=%s && .\workenv\python.exe train.py -c configs/config.json -m 44k" % (gpu_selection)
256
+ subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", cmd])
257
+ return "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
258
+
259
+ def continue_selected_training(work_dir):
260
+ print(work_dir)
261
+ if work_dir is None:
262
+ return "你没有选择工作进度"
263
+ if not os.path.exists(os.path.join(models_backup_path, work_dir)):
264
+ return "该工作文件夹不存在",
265
+ logs_44k_path = r'logs\44k'
266
+ logs_44k_files = os.listdir(logs_44k_path)
267
+ d0_path = os.path.join(logs_44k_path, "D_0.pth")
268
+ g0_path = os.path.join(logs_44k_path, "G_0.pth")
269
+ if len(logs_44k_files) == 2 and os.path.isfile(d0_path) and os.path.isfile(g0_path):
270
+ os.remove(d0_path)
271
+ os.remove(g0_path)
272
+ else:
273
+ if logs_44k_files:
274
+ timestamp = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')
275
+ new_backup_folder = os.path.join(models_backup_path, timestamp)
276
+ os.makedirs(new_backup_folder)
277
+
278
+ for file in logs_44k_files:
279
+ shutil.copy(os.path.join(logs_44k_path, file), new_backup_folder)
280
+ work_dir_path = os.path.join(models_backup_path, work_dir)
281
+ work_dir_files = os.listdir(work_dir_path)
282
+ for file in work_dir_files:
283
+ shutil.copy(os.path.join(work_dir_path, file), logs_44k_path)
284
+
285
+ return "已经在新的终端窗口开始训练,请监看终端窗口的训练日志。在终端中按Ctrl+C可暂停训练。"
286
+
287
+ def previous_selection_refresh():
288
+ work_saved_list = []
289
+ for entry in os.listdir("models_backup"):
290
+ entry_path = os.path.join(models_backup_path, entry)
291
+ if os.path.isdir(entry_path):
292
+ work_saved_list.append(entry)
293
+ return gr.Dropdown.update(choices=work_saved_list)
294
+
295
+
296
+ def kmeans_training():
297
+ if not os.listdir(r"dataset\44k"):
298
+ return "数据集不存在,请检查dataset文件夹"
299
+ subprocess.Popen(["cmd", "/c", "start", "cmd", "/k", r".\workenv\python.exe cluster\train_cluster.py"])
300
+ return "已经在新的终端窗口开始训练,训练聚类模型不会输出日志,检查任务管理器中python进程有在占用CPU就是正在训练,训练一般需要5-10分钟左右"
301
+
302
+ # read ckpt list
303
+ file_list = os.listdir("logs/44k")
304
+ ckpt_list = []
305
+ cluster_list = []
306
+ for ck in file_list:
307
+ if os.path.splitext(ck)[-1] == ".pth" and ck[0] != "k" and ck[:2] != "D_":
308
+ ckpt_list.append(ck)
309
+ if ck[0] == "k":
310
+ cluster_list.append(ck)
311
+ if not cluster_list:
312
+ cluster_list = ["你没有聚类模型"]
313
+
314
+ #read GPU info
315
+ ngpu=torch.cuda.device_count()
316
+ gpu_infos=[]
317
+ if(torch.cuda.is_available()==False or ngpu==0):if_gpu_ok=False
318
+ else:
319
+ if_gpu_ok = False
320
+ for i in range(ngpu):
321
+ gpu_name=torch.cuda.get_device_name(i)
322
+ if("16"in gpu_name or "MX"in gpu_name):continue
323
+ if("10"in gpu_name or "20"in gpu_name or "30"in gpu_name or "40"in gpu_name or "A50"in gpu_name.upper() or "70"in gpu_name or "80"in gpu_name or "90"in gpu_name or "M4"in gpu_name or "T4"in gpu_name or "TITAN"in gpu_name.upper()):#A10#A100#V100#A40#P40#M40#K80
324
+ if_gpu_ok=True#至少有一张能用的N卡
325
+ gpu_infos.append("%s\t%s"%(i,gpu_name))
326
+ gpu_info="\n".join(gpu_infos)if if_gpu_ok==True and len(gpu_infos)>0 else "很遗憾您这没有能用的显卡来支持您训练"
327
+ gpus="-".join([i[0]for i in gpu_infos])
328
+
329
+ #get previous saved training work
330
+ work_saved_list = []
331
+ for entry in os.listdir("models_backup"):
332
+ entry_path = os.path.join(models_backup_path, entry)
333
+ if os.path.isdir(entry_path):
334
+ work_saved_list.append(entry)
335
+
336
+ app = gr.Blocks()
337
+ with app:
338
+ gr.Markdown(value="""
339
+ ###sovits4.0 webui 推理&训练
340
+
341
+ 修改自原项目及bilibili@麦哲云
342
+
343
+ 仅供个人娱乐和非商业用途,禁止用于血腥、暴力、性相关、政治相关内容
344
+
345
+ 作者:bilibili@羽毛布団
346
+
347
+ """)
348
+ with gr.Tabs():
349
+ with gr.TabItem("推理"):
350
+ choice_ckpt = gr.Dropdown(label="模型选择", choices=ckpt_list, value="no_model")
351
+ config_choice = gr.Dropdown(label="配置文件", choices=os.listdir("configs"), value="no_config")
352
+ cluster_choice = gr.Dropdown(label="选择聚类模型", choices=cluster_list, value="no_clu")
353
+ enhance = gr.Checkbox(label="是否使用NSF_HIFIGAN增强,该选项对部分训练集少的模型有一定的音质增强效果,但是对训练好的模型有反面效果,默认关闭", value=False)
354
+ refresh = gr.Button("刷新选项")
355
+ loadckpt = gr.Button("加载模型", variant="primary")
356
+
357
+ sid = gr.Dropdown(label="音色", value="speaker0")
358
+ model_message = gr.Textbox(label="Output Message")
359
+
360
+ refresh.click(load_options,[],[choice_ckpt,config_choice,cluster_choice])
361
+ loadckpt.click(load_model_func,[choice_ckpt,cluster_choice,config_choice,enhance],[model_message, sid])
362
+
363
+ gr.Markdown(value="""
364
+ 请稍等片刻,模型加载大约需要10秒。后续操作不需要重新加载模型
365
+ """)
366
+
367
+ vc_input3 = gr.Audio(label="上传音频")
368
+ vc_transform = gr.Number(label="变调(整数,可以正负,半音数量,升高八度就是12)", value=0)
369
+ cluster_ratio = gr.Number(label="聚类模型混合比例,0-1之间,默认为0不启用聚类,能提升音色相似度,但会导致咬字下降(如果使用建议0.5左右)", value=0)
370
+ auto_f0 = gr.Checkbox(label="自动f0预测,配合聚类模型f0预测效果更好,会导致变调功能失效(仅限转换语音,歌声不要勾选此项会究极跑调)", value=False)
371
+ F0_mean_pooling = gr.Checkbox(label="F0均值滤波(池化),开启后可能有效改善哑音(对因和声混响造成的哑音无效)。", value=False)
372
+ enhancer_adaptive_key = gr.Number(label="使NSF-HIFIGAN增强器适应更高的音域(单位为半音数)|默认为0", value=0,interactive=True)
373
+ slice_db = gr.Number(label="切片阈值", value=-40)
374
+ noise_scale = gr.Number(label="noise_scale 建议不要动,会影响音质,玄学参数", value=0.4)
375
+ cl_num = gr.Number(label="音频自动切片,0为不切片,单位为秒/s", value=0)
376
+ pad_seconds = gr.Number(label="推理音频pad秒数,由于未知原因开头结尾会有异响,pad一小段静音段后就不会出现", value=0.5)
377
+ lg_num = gr.Number(label="两端音频切片的交叉淡入长度,如果自动切片后出现人声不连贯可调整该数值,如果连贯建议采用默认值0,注意,该设置会影响推理速度,单位为秒/s", value=0)
378
+ lgr_num = gr.Number(label="自动音频切片后,需要舍弃每段切片的头尾。该参数设置交叉长度保留的比例,范围0-1,左开右闭", value=0.75,interactive=True)
379
+
380
+ vc_submit = gr.Button("转换", variant="primary")
381
+ vc_output1 = gr.Textbox(label="Output Message")
382
+ vc_output2 = gr.Audio(label="Output Audio")
383
+
384
+ vc_submit.click(vc_fn, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling,enhancer_adaptive_key], [vc_output1, vc_output2])
385
+
386
+ with gr.TabItem("训练"):
387
+ gr.Markdown(value="""请将数据集文件夹放置在dataset_raw文件夹下,确认放置正确后点击下方获取数据集名称""")
388
+ raw_dirs_list=gr.Textbox(label="Raw dataset directory(s):")
389
+ get_raw_dirs=gr.Button("识别数据集", variant="primary")
390
+ gr.Markdown(value="""确认数据集正确识别后请点击数据预处理(大数据集可能会花上很长时间预处理,没报错等着就行)""")
391
+ #with gr.Row():
392
+ raw_preprocess=gr.Button("数据预处理", variant="primary")
393
+ preprocess_output=gr.Textbox(label="预处理输出信息,完成后请检查一下是否有报错信息,如无则可以进行下一步", max_lines=999)
394
+ clear_preprocess_output=gr.Button("清空输出信息")
395
+ with gr.Group():
396
+ gr.Markdown(value="""填写训练设置和超参数""")
397
+ with gr.Row():
398
+ gr.Textbox(label="当前使用显卡信息", value=gpu_info)
399
+ gpu_selection=gr.Textbox(label="多卡用户请指定希望训练使用的显卡ID(0,1,2...)", value=gpus, interactive=True)
400
+ with gr.Row():
401
+ log_interval=gr.Textbox(label="每隔多少步(steps)生成一次评估日志", value="200")
402
+ eval_interval=gr.Textbox(label="每隔多少步(steps)验证并保存一次模型", value="800")
403
+ keep_ckpts=gr.Textbox(label="仅保留最新的X个模型,超出该数字的旧模型会被删除。设置为0则永不删除", value="10")
404
+ with gr.Row():
405
+ batch_size=gr.Textbox(label="批量大小,每步取多少条数据进行训练,大batch可以加快训练但显著增加显存占用。6G显存建议设定为4", value="12")
406
+ lr=gr.Textbox(label="学习率,尽量与batch size成正比(6:0.0001),无法整除的话四舍五入一下也行", value="0.0002")
407
+ fp16_run=gr.Checkbox(label="是否使用半精度训练,半精度训练可能降低显存占用和训练时间,但对模型质量的影响尚未查证", value=False)
408
+ all_in_mem=gr.Checkbox(label="是否加载所有数据集到内存中,硬盘IO过于低下、同时内存容量远大于数据集体积时可以启用", value=False)
409
+ with gr.Row():
410
+ gr.Markdown("请检查右侧的说话人列表是否和你要训练的目标说话人一致,确认无误后点击写入配置文件,然后就可以开始训练了")
411
+ speakers=gr.Textbox(label="说话人列表")
412
+ write_config=gr.Button("写入配置文件", variant="primary")
413
+
414
+ write_config_output=gr.Textbox(label="写入配置文件输出信息")
415
+
416
+ gr.Markdown(value="""**点击从头开始训练**将会自动将已有的训练进度保存到models_backup文件夹,并自动装载预训练模型。
417
+ **继续上一次的训练进度**将从上一个保存模型的进度继续训练。继续训练进度无需重新预处理和写入配置文件。
418
+ """)
419
+ with gr.Row():
420
+ with gr.Column():
421
+ start_training=gr.Button("从头开始训练", variant="primary")
422
+ training_output=gr.Textbox(label="训练输出信息")
423
+ with gr.Column():
424
+ continue_training_btn=gr.Button("继续上一次的训练进度", variant="primary")
425
+ continue_training_output=gr.Textbox(label="训练输出信息")
426
+ with gr.Column():
427
+ kmeans_button=gr.Button("训练聚类模型", variant="primary")
428
+ kmeans_output=gr.Textbox(label="训练输出信息")
429
+ #previous_selection_training_btn=gr.Button("继续训练已保存的工作", variant="primary")
430
+ #with gr.Row():
431
+ # select_previous_work=gr.Dropdown(label="选择已保存的工作进度", choices=work_saved_list)
432
+ # previous_selection_refresh_btn=gr.Button("刷新列表", variant="primary")
433
+ #previous_selection_output=gr.Textbox(label="训练输出信息")
434
+
435
+
436
+ get_raw_dirs.click(load_raw_dirs,[],[raw_dirs_list])
437
+ raw_preprocess.click(dataset_preprocess,[],[preprocess_output, speakers])
438
+ clear_preprocess_output.click(clear_output,[],[preprocess_output])
439
+ write_config.click(config_fn,[log_interval, eval_interval, keep_ckpts, batch_size, lr, fp16_run, all_in_mem],[write_config_output])
440
+ start_training.click(training,[gpu_selection],[training_output])
441
+ continue_training_btn.click(continue_training,[gpu_selection],[continue_training_output])
442
+ #previous_selection_training_btn.click(continue_selected_training,[select_previous_work],[previous_selection_output])
443
+ #previous_selection_refresh_btn.click(previous_selection_refresh,[],[select_previous_work])
444
+ kmeans_button.click(kmeans_training,[],[kmeans_output])
445
+
446
+ app.queue(concurrency_count=1022, max_size=2044).launch(server_name="127.0.0.1",inbrowser=True,quiet=True)
data_utils.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+
8
+ import modules.commons as commons
9
+ import utils
10
+ from modules.mel_processing import spectrogram_torch, spec_to_mel_torch
11
+ from utils import load_wav_to_torch, load_filepaths_and_text
12
+
13
+ # import h5py
14
+
15
+
16
+ """Multi speaker version"""
17
+
18
+
19
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
20
+ """
21
+ 1) loads audio, speaker_id, text pairs
22
+ 2) normalizes text and converts them to sequences of integers
23
+ 3) computes spectrograms from audio files.
24
+ """
25
+
26
+ def __init__(self, audiopaths, hparams, all_in_mem: bool = False):
27
+ self.audiopaths = load_filepaths_and_text(audiopaths)
28
+ self.max_wav_value = hparams.data.max_wav_value
29
+ self.sampling_rate = hparams.data.sampling_rate
30
+ self.filter_length = hparams.data.filter_length
31
+ self.hop_length = hparams.data.hop_length
32
+ self.win_length = hparams.data.win_length
33
+ self.sampling_rate = hparams.data.sampling_rate
34
+ self.use_sr = hparams.train.use_sr
35
+ self.spec_len = hparams.train.max_speclen
36
+ self.spk_map = hparams.spk
37
+
38
+ random.seed(1234)
39
+ random.shuffle(self.audiopaths)
40
+
41
+ self.all_in_mem = all_in_mem
42
+ if self.all_in_mem:
43
+ self.cache = [self.get_audio(p[0]) for p in self.audiopaths]
44
+
45
+ def get_audio(self, filename):
46
+ filename = filename.replace("\\", "/")
47
+ audio, sampling_rate = load_wav_to_torch(filename)
48
+ if sampling_rate != self.sampling_rate:
49
+ raise ValueError("{} SR doesn't match target {} SR".format(
50
+ sampling_rate, self.sampling_rate))
51
+ audio_norm = audio / self.max_wav_value
52
+ audio_norm = audio_norm.unsqueeze(0)
53
+ spec_filename = filename.replace(".wav", ".spec.pt")
54
+
55
+ # Ideally, all data generated after Mar 25 should have .spec.pt
56
+ if os.path.exists(spec_filename):
57
+ spec = torch.load(spec_filename)
58
+ else:
59
+ spec = spectrogram_torch(audio_norm, self.filter_length,
60
+ self.sampling_rate, self.hop_length, self.win_length,
61
+ center=False)
62
+ spec = torch.squeeze(spec, 0)
63
+ torch.save(spec, spec_filename)
64
+
65
+ spk = filename.split("/")[-2]
66
+ spk = torch.LongTensor([self.spk_map[spk]])
67
+
68
+ f0 = np.load(filename + ".f0.npy")
69
+ f0, uv = utils.interpolate_f0(f0)
70
+ f0 = torch.FloatTensor(f0)
71
+ uv = torch.FloatTensor(uv)
72
+
73
+ c = torch.load(filename+ ".soft.pt")
74
+ c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[0])
75
+
76
+
77
+ lmin = min(c.size(-1), spec.size(-1))
78
+ assert abs(c.size(-1) - spec.size(-1)) < 3, (c.size(-1), spec.size(-1), f0.shape, filename)
79
+ assert abs(audio_norm.shape[1]-lmin * self.hop_length) < 3 * self.hop_length
80
+ spec, c, f0, uv = spec[:, :lmin], c[:, :lmin], f0[:lmin], uv[:lmin]
81
+ audio_norm = audio_norm[:, :lmin * self.hop_length]
82
+
83
+ return c, f0, spec, audio_norm, spk, uv
84
+
85
+ def random_slice(self, c, f0, spec, audio_norm, spk, uv):
86
+ # if spec.shape[1] < 30:
87
+ # print("skip too short audio:", filename)
88
+ # return None
89
+ if spec.shape[1] > 800:
90
+ start = random.randint(0, spec.shape[1]-800)
91
+ end = start + 790
92
+ spec, c, f0, uv = spec[:, start:end], c[:, start:end], f0[start:end], uv[start:end]
93
+ audio_norm = audio_norm[:, start * self.hop_length : end * self.hop_length]
94
+
95
+ return c, f0, spec, audio_norm, spk, uv
96
+
97
+ def __getitem__(self, index):
98
+ if self.all_in_mem:
99
+ return self.random_slice(*self.cache[index])
100
+ else:
101
+ return self.random_slice(*self.get_audio(self.audiopaths[index][0]))
102
+
103
+ def __len__(self):
104
+ return len(self.audiopaths)
105
+
106
+
107
+ class TextAudioCollate:
108
+
109
+ def __call__(self, batch):
110
+ batch = [b for b in batch if b is not None]
111
+
112
+ input_lengths, ids_sorted_decreasing = torch.sort(
113
+ torch.LongTensor([x[0].shape[1] for x in batch]),
114
+ dim=0, descending=True)
115
+
116
+ max_c_len = max([x[0].size(1) for x in batch])
117
+ max_wav_len = max([x[3].size(1) for x in batch])
118
+
119
+ lengths = torch.LongTensor(len(batch))
120
+
121
+ c_padded = torch.FloatTensor(len(batch), batch[0][0].shape[0], max_c_len)
122
+ f0_padded = torch.FloatTensor(len(batch), max_c_len)
123
+ spec_padded = torch.FloatTensor(len(batch), batch[0][2].shape[0], max_c_len)
124
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
125
+ spkids = torch.LongTensor(len(batch), 1)
126
+ uv_padded = torch.FloatTensor(len(batch), max_c_len)
127
+
128
+ c_padded.zero_()
129
+ spec_padded.zero_()
130
+ f0_padded.zero_()
131
+ wav_padded.zero_()
132
+ uv_padded.zero_()
133
+
134
+ for i in range(len(ids_sorted_decreasing)):
135
+ row = batch[ids_sorted_decreasing[i]]
136
+
137
+ c = row[0]
138
+ c_padded[i, :, :c.size(1)] = c
139
+ lengths[i] = c.size(1)
140
+
141
+ f0 = row[1]
142
+ f0_padded[i, :f0.size(0)] = f0
143
+
144
+ spec = row[2]
145
+ spec_padded[i, :, :spec.size(1)] = spec
146
+
147
+ wav = row[3]
148
+ wav_padded[i, :, :wav.size(1)] = wav
149
+
150
+ spkids[i, 0] = row[4]
151
+
152
+ uv = row[5]
153
+ uv_padded[i, :uv.size(0)] = uv
154
+
155
+ return c_padded, f0_padded, spec_padded, wav_padded, spkids, lengths, uv_padded
flask_api.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import logging
3
+
4
+ import soundfile
5
+ import torch
6
+ import torchaudio
7
+ from flask import Flask, request, send_file
8
+ from flask_cors import CORS
9
+
10
+ from inference.infer_tool import Svc, RealTimeVC
11
+
12
+ app = Flask(__name__)
13
+
14
+ CORS(app)
15
+
16
+ logging.getLogger('numba').setLevel(logging.WARNING)
17
+
18
+
19
+ @app.route("/voiceChangeModel", methods=["POST"])
20
+ def voice_change_model():
21
+ request_form = request.form
22
+ wave_file = request.files.get("sample", None)
23
+ # 变调信息
24
+ f_pitch_change = float(request_form.get("fPitchChange", 0))
25
+ # DAW所需的采样率
26
+ daw_sample = int(float(request_form.get("sampleRate", 0)))
27
+ speaker_id = int(float(request_form.get("sSpeakId", 0)))
28
+ # http获得wav文件并转换
29
+ input_wav_path = io.BytesIO(wave_file.read())
30
+
31
+ # 模型推理
32
+ if raw_infer:
33
+ # out_audio, out_sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path)
34
+ out_audio, out_sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path, cluster_infer_ratio=0,
35
+ auto_predict_f0=False, noice_scale=0.4, f0_filter=False)
36
+ tar_audio = torchaudio.functional.resample(out_audio, svc_model.target_sample, daw_sample)
37
+ else:
38
+ out_audio = svc.process(svc_model, speaker_id, f_pitch_change, input_wav_path, cluster_infer_ratio=0,
39
+ auto_predict_f0=False, noice_scale=0.4, f0_filter=False)
40
+ tar_audio = torchaudio.functional.resample(torch.from_numpy(out_audio), svc_model.target_sample, daw_sample)
41
+ # 返回音频
42
+ out_wav_path = io.BytesIO()
43
+ soundfile.write(out_wav_path, tar_audio.cpu().numpy(), daw_sample, format="wav")
44
+ out_wav_path.seek(0)
45
+ return send_file(out_wav_path, download_name="temp.wav", as_attachment=True)
46
+
47
+
48
+ if __name__ == '__main__':
49
+ # 启用则为直接切片合成,False为交叉淡化方式
50
+ # vst插件调整0.3-0.5s切片时间可以降低延迟,直接切片方法会有连接处爆音、交叉淡化会有轻微重叠声音
51
+ # 自行选择能接受的方法,或将vst最大切片时间调整为1s,此处设为Ture,延迟大音质稳定一些
52
+ raw_infer = True
53
+ # 每个模型和config是唯一对应的
54
+ model_name = "logs/32k/G_174000-Copy1.pth"
55
+ config_name = "configs/config.json"
56
+ cluster_model_path = "logs/44k/kmeans_10000.pt"
57
+ svc_model = Svc(model_name, config_name, cluster_model_path=cluster_model_path)
58
+ svc = RealTimeVC()
59
+ # 此处与vst插件对应,不建议更改
60
+ app.run(port=6842, host="0.0.0.0", debug=False, threaded=False)
flask_api_full_song.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import numpy as np
3
+ import soundfile
4
+ from flask import Flask, request, send_file
5
+
6
+ from inference import infer_tool
7
+ from inference import slicer
8
+
9
+ app = Flask(__name__)
10
+
11
+
12
+ @app.route("/wav2wav", methods=["POST"])
13
+ def wav2wav():
14
+ request_form = request.form
15
+ audio_path = request_form.get("audio_path", None) # wav文件地址
16
+ tran = int(float(request_form.get("tran", 0))) # 音调
17
+ spk = request_form.get("spk", 0) # 说话人(id或者name都可以,具体看你的config)
18
+ wav_format = request_form.get("wav_format", 'wav') # 范围文件格式
19
+ infer_tool.format_wav(audio_path)
20
+ chunks = slicer.cut(audio_path, db_thresh=-40)
21
+ audio_data, audio_sr = slicer.chunks2audio(audio_path, chunks)
22
+
23
+ audio = []
24
+ for (slice_tag, data) in audio_data:
25
+ print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======')
26
+
27
+ length = int(np.ceil(len(data) / audio_sr * svc_model.target_sample))
28
+ if slice_tag:
29
+ print('jump empty segment')
30
+ _audio = np.zeros(length)
31
+ else:
32
+ # padd
33
+ pad_len = int(audio_sr * 0.5)
34
+ data = np.concatenate([np.zeros([pad_len]), data, np.zeros([pad_len])])
35
+ raw_path = io.BytesIO()
36
+ soundfile.write(raw_path, data, audio_sr, format="wav")
37
+ raw_path.seek(0)
38
+ out_audio, out_sr = svc_model.infer(spk, tran, raw_path)
39
+ svc_model.clear_empty()
40
+ _audio = out_audio.cpu().numpy()
41
+ pad_len = int(svc_model.target_sample * 0.5)
42
+ _audio = _audio[pad_len:-pad_len]
43
+
44
+ audio.extend(list(infer_tool.pad_array(_audio, length)))
45
+ out_wav_path = io.BytesIO()
46
+ soundfile.write(out_wav_path, audio, svc_model.target_sample, format=wav_format)
47
+ out_wav_path.seek(0)
48
+ return send_file(out_wav_path, download_name=f"temp.{wav_format}", as_attachment=True)
49
+
50
+
51
+ if __name__ == '__main__':
52
+ model_name = "logs/44k/G_60000.pth" # 模型地址
53
+ config_name = "configs/config.json" # config地址
54
+ svc_model = infer_tool.Svc(model_name, config_name)
55
+ app.run(port=1145, host="0.0.0.0", debug=False, threaded=False)
inference_main.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import logging
3
+ import time
4
+ from pathlib import Path
5
+
6
+ import librosa
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import soundfile
10
+
11
+ from inference import infer_tool
12
+ from inference import slicer
13
+ from inference.infer_tool import Svc
14
+
15
+ logging.getLogger('numba').setLevel(logging.WARNING)
16
+ chunks_dict = infer_tool.read_temp("inference/chunks_temp.json")
17
+
18
+
19
+
20
+ def main():
21
+ import argparse
22
+
23
+ parser = argparse.ArgumentParser(description='sovits4 inference')
24
+
25
+ # 一定要设置的部分
26
+ parser.add_argument('-m', '--model_path', type=str, default="logs/44k/G_0.pth", help='模型路径')
27
+ parser.add_argument('-c', '--config_path', type=str, default="configs/config.json", help='配置文件路径')
28
+ parser.add_argument('-cl', '--clip', type=float, default=0, help='音频强制切片,默认0为自动切片,单位为秒/s')
29
+ parser.add_argument('-n', '--clean_names', type=str, nargs='+', default=["君の知らない物語-src.wav"], help='wav文件名列表,放在raw文件夹下')
30
+ parser.add_argument('-t', '--trans', type=int, nargs='+', default=[0], help='音高调整,支持正负(半音)')
31
+ parser.add_argument('-s', '--spk_list', type=str, nargs='+', default=['nen'], help='合成目标说话人名称')
32
+
33
+ # 可选项部分
34
+ parser.add_argument('-a', '--auto_predict_f0', action='store_true', default=False,help='语音转换自动预测音高,转换歌声时不要打开这个会严重跑调')
35
+ parser.add_argument('-cm', '--cluster_model_path', type=str, default="logs/44k/kmeans_10000.pt", help='聚类模型路径,如果没有训练聚类则随便填')
36
+ parser.add_argument('-cr', '--cluster_infer_ratio', type=float, default=0, help='聚类方案占比,范围0-1,若没有训练聚类模型则默认0即可')
37
+ parser.add_argument('-lg', '--linear_gradient', type=float, default=0, help='两段音频切片的交叉淡入长度,如果强制切片后出现人声不连贯可调整该数值,如果连贯建议采用默认值0,单位为秒')
38
+ parser.add_argument('-fmp', '--f0_mean_pooling', type=bool, default=False, help='是否对F0使用均值滤波器(池化),对部分哑音有改善。注意,启动该选项会导致推理速度下降,默认关闭')
39
+ parser.add_argument('-eh', '--enhance', type=bool, default=False, help='是否使用NSF_HIFIGAN增强器,该选项对部分训练集少的模型有一定的音质增强效果,但是对训练好的模型有反面效果,默认关闭')
40
+
41
+ # 不用动的部分
42
+ parser.add_argument('-sd', '--slice_db', type=int, default=-40, help='默认-40,嘈杂的音频可以-30,干声保留呼吸可以-50')
43
+ parser.add_argument('-d', '--device', type=str, default=None, help='推理设备,None则为自动选择cpu和gpu')
44
+ parser.add_argument('-ns', '--noice_scale', type=float, default=0.4, help='噪音级别,会影响咬字和音质,较为玄学')
45
+ parser.add_argument('-p', '--pad_seconds', type=float, default=0.5, help='推理音频pad秒数,由于未知原因开头结尾会有异响,pad一小段静音段后就不会出现')
46
+ parser.add_argument('-wf', '--wav_format', type=str, default='flac', help='音频输出格式')
47
+ parser.add_argument('-lgr', '--linear_gradient_retain', type=float, default=0.75, help='自动音频切片后,需要舍弃每段切片的头尾。该参数设置交叉长度保留的比例,范围0-1,左开右闭')
48
+ parser.add_argument('-eak', '--enhancer_adaptive_key', type=int, default=0, help='使增强器适应更高的音域(单位为半音数)|默认为0')
49
+
50
+ args = parser.parse_args()
51
+
52
+ clean_names = args.clean_names
53
+ trans = args.trans
54
+ spk_list = args.spk_list
55
+ slice_db = args.slice_db
56
+ wav_format = args.wav_format
57
+ auto_predict_f0 = args.auto_predict_f0
58
+ cluster_infer_ratio = args.cluster_infer_ratio
59
+ noice_scale = args.noice_scale
60
+ pad_seconds = args.pad_seconds
61
+ clip = args.clip
62
+ lg = args.linear_gradient
63
+ lgr = args.linear_gradient_retain
64
+ F0_mean_pooling = args.f0_mean_pooling
65
+ enhance = args.enhance
66
+ enhancer_adaptive_key = args.enhancer_adaptive_key
67
+
68
+ svc_model = Svc(args.model_path, args.config_path, args.device, args.cluster_model_path,enhance)
69
+ infer_tool.mkdir(["raw", "results"])
70
+
71
+ infer_tool.fill_a_to_b(trans, clean_names)
72
+ for clean_name, tran in zip(clean_names, trans):
73
+ raw_audio_path = f"raw/{clean_name}"
74
+ if "." not in raw_audio_path:
75
+ raw_audio_path += ".wav"
76
+ infer_tool.format_wav(raw_audio_path)
77
+ wav_path = Path(raw_audio_path).with_suffix('.wav')
78
+ chunks = slicer.cut(wav_path, db_thresh=slice_db)
79
+ audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks)
80
+ per_size = int(clip*audio_sr)
81
+ lg_size = int(lg*audio_sr)
82
+ lg_size_r = int(lg_size*lgr)
83
+ lg_size_c_l = (lg_size-lg_size_r)//2
84
+ lg_size_c_r = lg_size-lg_size_r-lg_size_c_l
85
+ lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0
86
+
87
+ for spk in spk_list:
88
+ audio = []
89
+ for (slice_tag, data) in audio_data:
90
+ print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======')
91
+
92
+ length = int(np.ceil(len(data) / audio_sr * svc_model.target_sample))
93
+ if slice_tag:
94
+ print('jump empty segment')
95
+ _audio = np.zeros(length)
96
+ audio.extend(list(infer_tool.pad_array(_audio, length)))
97
+ continue
98
+ if per_size != 0:
99
+ datas = infer_tool.split_list_by_n(data, per_size,lg_size)
100
+ else:
101
+ datas = [data]
102
+ for k,dat in enumerate(datas):
103
+ per_length = int(np.ceil(len(dat) / audio_sr * svc_model.target_sample)) if clip!=0 else length
104
+ if clip!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======')
105
+ # padd
106
+ pad_len = int(audio_sr * pad_seconds)
107
+ dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
108
+ raw_path = io.BytesIO()
109
+ soundfile.write(raw_path, dat, audio_sr, format="wav")
110
+ raw_path.seek(0)
111
+ out_audio, out_sr = svc_model.infer(spk, tran, raw_path,
112
+ cluster_infer_ratio=cluster_infer_ratio,
113
+ auto_predict_f0=auto_predict_f0,
114
+ noice_scale=noice_scale,
115
+ F0_mean_pooling = F0_mean_pooling,
116
+ enhancer_adaptive_key = enhancer_adaptive_key
117
+ )
118
+ _audio = out_audio.cpu().numpy()
119
+ pad_len = int(svc_model.target_sample * pad_seconds)
120
+ _audio = _audio[pad_len:-pad_len]
121
+ _audio = infer_tool.pad_array(_audio, per_length)
122
+ if lg_size!=0 and k!=0:
123
+ lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr != 1 else audio[-lg_size:]
124
+ lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr != 1 else _audio[0:lg_size]
125
+ lg_pre = lg1*(1-lg)+lg2*lg
126
+ audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr != 1 else audio[0:-lg_size]
127
+ audio.extend(lg_pre)
128
+ _audio = _audio[lg_size_c_l+lg_size_r:] if lgr != 1 else _audio[lg_size:]
129
+ audio.extend(list(_audio))
130
+ key = "auto" if auto_predict_f0 else f"{tran}key"
131
+ cluster_name = "" if cluster_infer_ratio == 0 else f"_{cluster_infer_ratio}"
132
+ res_path = f'./results/{clean_name}_{key}_{spk}{cluster_name}.{wav_format}'
133
+ soundfile.write(res_path, audio, svc_model.target_sample, format=wav_format)
134
+ svc_model.clear_empty()
135
+
136
+ if __name__ == '__main__':
137
+ main()
models.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 modules.attentions as attentions
8
+ import modules.commons as commons
9
+ import modules.modules as modules
10
+
11
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
12
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
13
+
14
+ import utils
15
+ from modules.commons import init_weights, get_padding
16
+ from vdecoder.hifigan.models import Generator
17
+ from utils import f0_to_coarse
18
+
19
+ class ResidualCouplingBlock(nn.Module):
20
+ def __init__(self,
21
+ channels,
22
+ hidden_channels,
23
+ kernel_size,
24
+ dilation_rate,
25
+ n_layers,
26
+ n_flows=4,
27
+ gin_channels=0):
28
+ super().__init__()
29
+ self.channels = channels
30
+ self.hidden_channels = hidden_channels
31
+ self.kernel_size = kernel_size
32
+ self.dilation_rate = dilation_rate
33
+ self.n_layers = n_layers
34
+ self.n_flows = n_flows
35
+ self.gin_channels = gin_channels
36
+
37
+ self.flows = nn.ModuleList()
38
+ for i in range(n_flows):
39
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
40
+ self.flows.append(modules.Flip())
41
+
42
+ def forward(self, x, x_mask, g=None, reverse=False):
43
+ if not reverse:
44
+ for flow in self.flows:
45
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
46
+ else:
47
+ for flow in reversed(self.flows):
48
+ x = flow(x, x_mask, g=g, reverse=reverse)
49
+ return x
50
+
51
+
52
+ class Encoder(nn.Module):
53
+ def __init__(self,
54
+ in_channels,
55
+ out_channels,
56
+ hidden_channels,
57
+ kernel_size,
58
+ dilation_rate,
59
+ n_layers,
60
+ gin_channels=0):
61
+ super().__init__()
62
+ self.in_channels = in_channels
63
+ self.out_channels = out_channels
64
+ self.hidden_channels = hidden_channels
65
+ self.kernel_size = kernel_size
66
+ self.dilation_rate = dilation_rate
67
+ self.n_layers = n_layers
68
+ self.gin_channels = gin_channels
69
+
70
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
71
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
72
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
73
+
74
+ def forward(self, x, x_lengths, g=None):
75
+ # print(x.shape,x_lengths.shape)
76
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
77
+ x = self.pre(x) * x_mask
78
+ x = self.enc(x, x_mask, g=g)
79
+ stats = self.proj(x) * x_mask
80
+ m, logs = torch.split(stats, self.out_channels, dim=1)
81
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
82
+ return z, m, logs, x_mask
83
+
84
+
85
+ class TextEncoder(nn.Module):
86
+ def __init__(self,
87
+ out_channels,
88
+ hidden_channels,
89
+ kernel_size,
90
+ n_layers,
91
+ gin_channels=0,
92
+ filter_channels=None,
93
+ n_heads=None,
94
+ p_dropout=None):
95
+ super().__init__()
96
+ self.out_channels = out_channels
97
+ self.hidden_channels = hidden_channels
98
+ self.kernel_size = kernel_size
99
+ self.n_layers = n_layers
100
+ self.gin_channels = gin_channels
101
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
102
+ self.f0_emb = nn.Embedding(256, hidden_channels)
103
+
104
+ self.enc_ = attentions.Encoder(
105
+ hidden_channels,
106
+ filter_channels,
107
+ n_heads,
108
+ n_layers,
109
+ kernel_size,
110
+ p_dropout)
111
+
112
+ def forward(self, x, x_mask, f0=None, noice_scale=1):
113
+ x = x + self.f0_emb(f0).transpose(1,2)
114
+ x = self.enc_(x * x_mask, x_mask)
115
+ stats = self.proj(x) * x_mask
116
+ m, logs = torch.split(stats, self.out_channels, dim=1)
117
+ z = (m + torch.randn_like(m) * torch.exp(logs) * noice_scale) * x_mask
118
+
119
+ return z, m, logs, x_mask
120
+
121
+
122
+
123
+ class DiscriminatorP(torch.nn.Module):
124
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
125
+ super(DiscriminatorP, self).__init__()
126
+ self.period = period
127
+ self.use_spectral_norm = use_spectral_norm
128
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
129
+ self.convs = nn.ModuleList([
130
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
131
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
132
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
133
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
134
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
135
+ ])
136
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
137
+
138
+ def forward(self, x):
139
+ fmap = []
140
+
141
+ # 1d to 2d
142
+ b, c, t = x.shape
143
+ if t % self.period != 0: # pad first
144
+ n_pad = self.period - (t % self.period)
145
+ x = F.pad(x, (0, n_pad), "reflect")
146
+ t = t + n_pad
147
+ x = x.view(b, c, t // self.period, self.period)
148
+
149
+ for l in self.convs:
150
+ x = l(x)
151
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
152
+ fmap.append(x)
153
+ x = self.conv_post(x)
154
+ fmap.append(x)
155
+ x = torch.flatten(x, 1, -1)
156
+
157
+ return x, fmap
158
+
159
+
160
+ class DiscriminatorS(torch.nn.Module):
161
+ def __init__(self, use_spectral_norm=False):
162
+ super(DiscriminatorS, self).__init__()
163
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
164
+ self.convs = nn.ModuleList([
165
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
166
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
167
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
168
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
169
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
170
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
171
+ ])
172
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
173
+
174
+ def forward(self, x):
175
+ fmap = []
176
+
177
+ for l in self.convs:
178
+ x = l(x)
179
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
180
+ fmap.append(x)
181
+ x = self.conv_post(x)
182
+ fmap.append(x)
183
+ x = torch.flatten(x, 1, -1)
184
+
185
+ return x, fmap
186
+
187
+
188
+ class MultiPeriodDiscriminator(torch.nn.Module):
189
+ def __init__(self, use_spectral_norm=False):
190
+ super(MultiPeriodDiscriminator, self).__init__()
191
+ periods = [2,3,5,7,11]
192
+
193
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
194
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
195
+ self.discriminators = nn.ModuleList(discs)
196
+
197
+ def forward(self, y, y_hat):
198
+ y_d_rs = []
199
+ y_d_gs = []
200
+ fmap_rs = []
201
+ fmap_gs = []
202
+ for i, d in enumerate(self.discriminators):
203
+ y_d_r, fmap_r = d(y)
204
+ y_d_g, fmap_g = d(y_hat)
205
+ y_d_rs.append(y_d_r)
206
+ y_d_gs.append(y_d_g)
207
+ fmap_rs.append(fmap_r)
208
+ fmap_gs.append(fmap_g)
209
+
210
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
211
+
212
+
213
+ class SpeakerEncoder(torch.nn.Module):
214
+ def __init__(self, mel_n_channels=80, model_num_layers=3, model_hidden_size=256, model_embedding_size=256):
215
+ super(SpeakerEncoder, self).__init__()
216
+ self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True)
217
+ self.linear = nn.Linear(model_hidden_size, model_embedding_size)
218
+ self.relu = nn.ReLU()
219
+
220
+ def forward(self, mels):
221
+ self.lstm.flatten_parameters()
222
+ _, (hidden, _) = self.lstm(mels)
223
+ embeds_raw = self.relu(self.linear(hidden[-1]))
224
+ return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True)
225
+
226
+ def compute_partial_slices(self, total_frames, partial_frames, partial_hop):
227
+ mel_slices = []
228
+ for i in range(0, total_frames-partial_frames, partial_hop):
229
+ mel_range = torch.arange(i, i+partial_frames)
230
+ mel_slices.append(mel_range)
231
+
232
+ return mel_slices
233
+
234
+ def embed_utterance(self, mel, partial_frames=128, partial_hop=64):
235
+ mel_len = mel.size(1)
236
+ last_mel = mel[:,-partial_frames:]
237
+
238
+ if mel_len > partial_frames:
239
+ mel_slices = self.compute_partial_slices(mel_len, partial_frames, partial_hop)
240
+ mels = list(mel[:,s] for s in mel_slices)
241
+ mels.append(last_mel)
242
+ mels = torch.stack(tuple(mels), 0).squeeze(1)
243
+
244
+ with torch.no_grad():
245
+ partial_embeds = self(mels)
246
+ embed = torch.mean(partial_embeds, axis=0).unsqueeze(0)
247
+ #embed = embed / torch.linalg.norm(embed, 2)
248
+ else:
249
+ with torch.no_grad():
250
+ embed = self(last_mel)
251
+
252
+ return embed
253
+
254
+ class F0Decoder(nn.Module):
255
+ def __init__(self,
256
+ out_channels,
257
+ hidden_channels,
258
+ filter_channels,
259
+ n_heads,
260
+ n_layers,
261
+ kernel_size,
262
+ p_dropout,
263
+ spk_channels=0):
264
+ super().__init__()
265
+ self.out_channels = out_channels
266
+ self.hidden_channels = hidden_channels
267
+ self.filter_channels = filter_channels
268
+ self.n_heads = n_heads
269
+ self.n_layers = n_layers
270
+ self.kernel_size = kernel_size
271
+ self.p_dropout = p_dropout
272
+ self.spk_channels = spk_channels
273
+
274
+ self.prenet = nn.Conv1d(hidden_channels, hidden_channels, 3, padding=1)
275
+ self.decoder = attentions.FFT(
276
+ hidden_channels,
277
+ filter_channels,
278
+ n_heads,
279
+ n_layers,
280
+ kernel_size,
281
+ p_dropout)
282
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
283
+ self.f0_prenet = nn.Conv1d(1, hidden_channels , 3, padding=1)
284
+ self.cond = nn.Conv1d(spk_channels, hidden_channels, 1)
285
+
286
+ def forward(self, x, norm_f0, x_mask, spk_emb=None):
287
+ x = torch.detach(x)
288
+ if (spk_emb is not None):
289
+ x = x + self.cond(spk_emb)
290
+ x += self.f0_prenet(norm_f0)
291
+ x = self.prenet(x) * x_mask
292
+ x = self.decoder(x * x_mask, x_mask)
293
+ x = self.proj(x) * x_mask
294
+ return x
295
+
296
+
297
+ class SynthesizerTrn(nn.Module):
298
+ """
299
+ Synthesizer for Training
300
+ """
301
+
302
+ def __init__(self,
303
+ spec_channels,
304
+ segment_size,
305
+ inter_channels,
306
+ hidden_channels,
307
+ filter_channels,
308
+ n_heads,
309
+ n_layers,
310
+ kernel_size,
311
+ p_dropout,
312
+ resblock,
313
+ resblock_kernel_sizes,
314
+ resblock_dilation_sizes,
315
+ upsample_rates,
316
+ upsample_initial_channel,
317
+ upsample_kernel_sizes,
318
+ gin_channels,
319
+ ssl_dim,
320
+ n_speakers,
321
+ sampling_rate=44100,
322
+ **kwargs):
323
+
324
+ super().__init__()
325
+ self.spec_channels = spec_channels
326
+ self.inter_channels = inter_channels
327
+ self.hidden_channels = hidden_channels
328
+ self.filter_channels = filter_channels
329
+ self.n_heads = n_heads
330
+ self.n_layers = n_layers
331
+ self.kernel_size = kernel_size
332
+ self.p_dropout = p_dropout
333
+ self.resblock = resblock
334
+ self.resblock_kernel_sizes = resblock_kernel_sizes
335
+ self.resblock_dilation_sizes = resblock_dilation_sizes
336
+ self.upsample_rates = upsample_rates
337
+ self.upsample_initial_channel = upsample_initial_channel
338
+ self.upsample_kernel_sizes = upsample_kernel_sizes
339
+ self.segment_size = segment_size
340
+ self.gin_channels = gin_channels
341
+ self.ssl_dim = ssl_dim
342
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
343
+
344
+ self.pre = nn.Conv1d(ssl_dim, hidden_channels, kernel_size=5, padding=2)
345
+
346
+ self.enc_p = TextEncoder(
347
+ inter_channels,
348
+ hidden_channels,
349
+ filter_channels=filter_channels,
350
+ n_heads=n_heads,
351
+ n_layers=n_layers,
352
+ kernel_size=kernel_size,
353
+ p_dropout=p_dropout
354
+ )
355
+ hps = {
356
+ "sampling_rate": sampling_rate,
357
+ "inter_channels": inter_channels,
358
+ "resblock": resblock,
359
+ "resblock_kernel_sizes": resblock_kernel_sizes,
360
+ "resblock_dilation_sizes": resblock_dilation_sizes,
361
+ "upsample_rates": upsample_rates,
362
+ "upsample_initial_channel": upsample_initial_channel,
363
+ "upsample_kernel_sizes": upsample_kernel_sizes,
364
+ "gin_channels": gin_channels,
365
+ }
366
+ self.dec = Generator(h=hps)
367
+ self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
368
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
369
+ self.f0_decoder = F0Decoder(
370
+ 1,
371
+ hidden_channels,
372
+ filter_channels,
373
+ n_heads,
374
+ n_layers,
375
+ kernel_size,
376
+ p_dropout,
377
+ spk_channels=gin_channels
378
+ )
379
+ self.emb_uv = nn.Embedding(2, hidden_channels)
380
+
381
+ def forward(self, c, f0, uv, spec, g=None, c_lengths=None, spec_lengths=None):
382
+ g = self.emb_g(g).transpose(1,2)
383
+ # ssl prenet
384
+ x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
385
+ x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1,2)
386
+
387
+ # f0 predict
388
+ lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
389
+ norm_lf0 = utils.normalize_f0(lf0, x_mask, uv)
390
+ pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
391
+
392
+ # encoder
393
+ z_ptemp, m_p, logs_p, _ = self.enc_p(x, x_mask, f0=f0_to_coarse(f0))
394
+ z, m_q, logs_q, spec_mask = self.enc_q(spec, spec_lengths, g=g)
395
+
396
+ # flow
397
+ z_p = self.flow(z, spec_mask, g=g)
398
+ z_slice, pitch_slice, ids_slice = commons.rand_slice_segments_with_pitch(z, f0, spec_lengths, self.segment_size)
399
+
400
+ # nsf decoder
401
+ o = self.dec(z_slice, g=g, f0=pitch_slice)
402
+
403
+ return o, ids_slice, spec_mask, (z, z_p, m_p, logs_p, m_q, logs_q), pred_lf0, norm_lf0, lf0
404
+
405
+ def infer(self, c, f0, uv, g=None, noice_scale=0.35, predict_f0=False):
406
+ c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device)
407
+ g = self.emb_g(g).transpose(1,2)
408
+ x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
409
+ x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1,2)
410
+
411
+ if predict_f0:
412
+ lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
413
+ norm_lf0 = utils.normalize_f0(lf0, x_mask, uv, random_scale=False)
414
+ pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
415
+ f0 = (700 * (torch.pow(10, pred_lf0 * 500 / 2595) - 1)).squeeze(1)
416
+
417
+ z_p, m_p, logs_p, c_mask = self.enc_p(x, x_mask, f0=f0_to_coarse(f0), noice_scale=noice_scale)
418
+ z = self.flow(z_p, c_mask, g=g, reverse=True)
419
+ o = self.dec(z * c_mask, g=g, f0=f0)
420
+ return o
onnx_export.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from onnxexport.model_onnx import SynthesizerTrn
3
+ import utils
4
+
5
+ def main(NetExport):
6
+ path = "SoVits4.0"
7
+ if NetExport:
8
+ device = torch.device("cpu")
9
+ hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
10
+ SVCVITS = SynthesizerTrn(
11
+ hps.data.filter_length // 2 + 1,
12
+ hps.train.segment_size // hps.data.hop_length,
13
+ **hps.model)
14
+ _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", SVCVITS, None)
15
+ _ = SVCVITS.eval().to(device)
16
+ for i in SVCVITS.parameters():
17
+ i.requires_grad = False
18
+
19
+ n_frame = 10
20
+ test_hidden_unit = torch.rand(1, n_frame, 256)
21
+ test_pitch = torch.rand(1, n_frame)
22
+ test_mel2ph = torch.arange(0, n_frame, dtype=torch.int64)[None] # torch.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).unsqueeze(0)
23
+ test_uv = torch.ones(1, n_frame, dtype=torch.float32)
24
+ test_noise = torch.randn(1, 192, n_frame)
25
+ test_sid = torch.LongTensor([0])
26
+ input_names = ["c", "f0", "mel2ph", "uv", "noise", "sid"]
27
+ output_names = ["audio", ]
28
+
29
+ torch.onnx.export(SVCVITS,
30
+ (
31
+ test_hidden_unit.to(device),
32
+ test_pitch.to(device),
33
+ test_mel2ph.to(device),
34
+ test_uv.to(device),
35
+ test_noise.to(device),
36
+ test_sid.to(device)
37
+ ),
38
+ f"checkpoints/{path}/model.onnx",
39
+ dynamic_axes={
40
+ "c": [0, 1],
41
+ "f0": [1],
42
+ "mel2ph": [1],
43
+ "uv": [1],
44
+ "noise": [2],
45
+ },
46
+ do_constant_folding=False,
47
+ opset_version=16,
48
+ verbose=False,
49
+ input_names=input_names,
50
+ output_names=output_names)
51
+
52
+
53
+ if __name__ == '__main__':
54
+ main(True)
preprocess_flist_config.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import re
4
+
5
+ from tqdm import tqdm
6
+ from random import shuffle
7
+ import json
8
+ import wave
9
+
10
+ config_template = json.load(open("configs_template/config_template.json"))
11
+
12
+ pattern = re.compile(r'^[\.a-zA-Z0-9_\/]+$')
13
+
14
+ def get_wav_duration(file_path):
15
+ with wave.open(file_path, 'rb') as wav_file:
16
+ # 获取音频帧数
17
+ n_frames = wav_file.getnframes()
18
+ # 获取采样率
19
+ framerate = wav_file.getframerate()
20
+ # 计算时长(秒)
21
+ duration = n_frames / float(framerate)
22
+ return duration
23
+
24
+ if __name__ == "__main__":
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument("--train_list", type=str, default="./filelists/train.txt", help="path to train list")
27
+ parser.add_argument("--val_list", type=str, default="./filelists/val.txt", help="path to val list")
28
+ parser.add_argument("--source_dir", type=str, default="./dataset/44k", help="path to source dir")
29
+ args = parser.parse_args()
30
+
31
+ train = []
32
+ val = []
33
+ idx = 0
34
+ spk_dict = {}
35
+ spk_id = 0
36
+ for speaker in tqdm(os.listdir(args.source_dir)):
37
+ spk_dict[speaker] = spk_id
38
+ spk_id += 1
39
+ wavs = ["/".join([args.source_dir, speaker, i]) for i in os.listdir(os.path.join(args.source_dir, speaker))]
40
+ new_wavs = []
41
+ for file in wavs:
42
+ if not file.endswith("wav"):
43
+ continue
44
+ #if not pattern.match(file):
45
+ # print(f"warning:文件名{file}中包含非字母数字下划线,可能会导致错误。(也可能不会)")
46
+ if get_wav_duration(file) < 0.3:
47
+ print("skip too short audio:", file)
48
+ continue
49
+ new_wavs.append(file)
50
+ wavs = new_wavs
51
+ shuffle(wavs)
52
+ train += wavs[2:]
53
+ val += wavs[:2]
54
+
55
+ shuffle(train)
56
+ shuffle(val)
57
+
58
+ print("Writing", args.train_list)
59
+ with open(args.train_list, "w") as f:
60
+ for fname in tqdm(train):
61
+ wavpath = fname
62
+ f.write(wavpath + "\n")
63
+
64
+ print("Writing", args.val_list)
65
+ with open(args.val_list, "w") as f:
66
+ for fname in tqdm(val):
67
+ wavpath = fname
68
+ f.write(wavpath + "\n")
69
+
70
+ config_template["spk"] = spk_dict
71
+ config_template["model"]["n_speakers"] = spk_id
72
+
73
+ print("Writing configs/config.json")
74
+ with open("configs/config.json", "w") as f:
75
+ json.dump(config_template, f, indent=2)
preprocess_hubert_f0.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import multiprocessing
3
+ import os
4
+ import argparse
5
+ from random import shuffle
6
+
7
+ import torch
8
+ from glob import glob
9
+ from tqdm import tqdm
10
+ from modules.mel_processing import spectrogram_torch
11
+
12
+ import utils
13
+ import logging
14
+
15
+ logging.getLogger("numba").setLevel(logging.WARNING)
16
+ import librosa
17
+ import numpy as np
18
+
19
+ hps = utils.get_hparams_from_file("configs/config.json")
20
+ sampling_rate = hps.data.sampling_rate
21
+ hop_length = hps.data.hop_length
22
+
23
+
24
+ def process_one(filename, hmodel):
25
+ # print(filename)
26
+ wav, sr = librosa.load(filename, sr=sampling_rate)
27
+ soft_path = filename + ".soft.pt"
28
+ if not os.path.exists(soft_path):
29
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
+ wav16k = librosa.resample(wav, orig_sr=sampling_rate, target_sr=16000)
31
+ wav16k = torch.from_numpy(wav16k).to(device)
32
+ c = utils.get_hubert_content(hmodel, wav_16k_tensor=wav16k)
33
+ torch.save(c.cpu(), soft_path)
34
+
35
+ f0_path = filename + ".f0.npy"
36
+ if not os.path.exists(f0_path):
37
+ f0 = utils.compute_f0_dio(
38
+ wav, sampling_rate=sampling_rate, hop_length=hop_length
39
+ )
40
+ np.save(f0_path, f0)
41
+
42
+ spec_path = filename.replace(".wav", ".spec.pt")
43
+ if not os.path.exists(spec_path):
44
+ # Process spectrogram
45
+ # The following code can't be replaced by torch.FloatTensor(wav)
46
+ # because load_wav_to_torch return a tensor that need to be normalized
47
+
48
+ audio, sr = utils.load_wav_to_torch(filename)
49
+ if sr != hps.data.sampling_rate:
50
+ raise ValueError(
51
+ "{} SR doesn't match target {} SR".format(
52
+ sr, hps.data.sampling_rate
53
+ )
54
+ )
55
+
56
+ audio_norm = audio / hps.data.max_wav_value
57
+ audio_norm = audio_norm.unsqueeze(0)
58
+
59
+ spec = spectrogram_torch(
60
+ audio_norm,
61
+ hps.data.filter_length,
62
+ hps.data.sampling_rate,
63
+ hps.data.hop_length,
64
+ hps.data.win_length,
65
+ center=False,
66
+ )
67
+ spec = torch.squeeze(spec, 0)
68
+ torch.save(spec, spec_path)
69
+
70
+
71
+ def process_batch(filenames):
72
+ print("Loading hubert for content...")
73
+ device = "cuda" if torch.cuda.is_available() else "cpu"
74
+ hmodel = utils.get_hubert_model().to(device)
75
+ print("Loaded hubert.")
76
+ for filename in tqdm(filenames):
77
+ process_one(filename, hmodel)
78
+
79
+
80
+ if __name__ == "__main__":
81
+ parser = argparse.ArgumentParser()
82
+ parser.add_argument(
83
+ "--in_dir", type=str, default="dataset/44k", help="path to input dir"
84
+ )
85
+
86
+ args = parser.parse_args()
87
+ filenames = glob(f"{args.in_dir}/*/*.wav", recursive=True) # [:10]
88
+ shuffle(filenames)
89
+ multiprocessing.set_start_method("spawn", force=True)
90
+
91
+ num_processes = 1
92
+ chunk_size = int(math.ceil(len(filenames) / num_processes))
93
+ chunks = [
94
+ filenames[i : i + chunk_size] for i in range(0, len(filenames), chunk_size)
95
+ ]
96
+ print([len(c) for c in chunks])
97
+ processes = [
98
+ multiprocessing.Process(target=process_batch, args=(chunk,)) for chunk in chunks
99
+ ]
100
+ for p in processes:
101
+ p.start()
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask
2
+ Flask_Cors
3
+ gradio
4
+ numpy
5
+ pyworld==0.2.5
6
+ scipy==1.7.3
7
+ SoundFile==0.12.1
8
+ torch==1.13.1
9
+ torchaudio==0.13.1
10
+ torchcrepe
11
+ tqdm
12
+ scikit-maad
13
+ praat-parselmouth
14
+ onnx
15
+ onnxsim
16
+ onnxoptimizer
17
+ fairseq==0.12.2
18
+ librosa==0.9.1
19
+ tensorboard
20
+ tensorboardX
21
+ edge_tts
requirements_win.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ librosa==0.9.1
2
+ fairseq==0.12.2
3
+ Flask==2.1.2
4
+ Flask_Cors==3.0.10
5
+ gradio
6
+ numpy
7
+ playsound==1.3.0
8
+ PyAudio==0.2.12
9
+ pydub==0.25.1
10
+ pyworld==0.3.0
11
+ requests==2.28.1
12
+ scipy==1.7.3
13
+ sounddevice==0.4.5
14
+ SoundFile==0.10.3.post1
15
+ starlette==0.19.1
16
+ tqdm==4.63.0
17
+ torchcrepe
18
+ scikit-maad
19
+ praat-parselmouth
20
+ onnx
21
+ onnxsim
22
+ onnxoptimizer
23
+ tensorboardX
24
+ edge_tts
resample.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import librosa
4
+ import numpy as np
5
+ from multiprocessing import Pool, cpu_count
6
+ from scipy.io import wavfile
7
+ from tqdm import tqdm
8
+
9
+
10
+ def process(item):
11
+ spkdir, wav_name, args = item
12
+ # speaker 's5', 'p280', 'p315' are excluded,
13
+ speaker = spkdir.replace("\\", "/").split("/")[-1]
14
+ wav_path = os.path.join(args.in_dir, speaker, wav_name)
15
+ if os.path.exists(wav_path) and '.wav' in wav_path:
16
+ os.makedirs(os.path.join(args.out_dir2, speaker), exist_ok=True)
17
+ wav, sr = librosa.load(wav_path, sr=None)
18
+ wav, _ = librosa.effects.trim(wav, top_db=20)
19
+ peak = np.abs(wav).max()
20
+ if peak > 1.0:
21
+ wav = 0.98 * wav / peak
22
+ wav2 = librosa.resample(wav, orig_sr=sr, target_sr=args.sr2)
23
+ wav2 /= max(wav2.max(), -wav2.min())
24
+ save_name = wav_name
25
+ save_path2 = os.path.join(args.out_dir2, speaker, save_name)
26
+ wavfile.write(
27
+ save_path2,
28
+ args.sr2,
29
+ (wav2 * np.iinfo(np.int16).max).astype(np.int16)
30
+ )
31
+
32
+
33
+
34
+ if __name__ == "__main__":
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument("--sr2", type=int, default=44100, help="sampling rate")
37
+ parser.add_argument("--in_dir", type=str, default="./dataset_raw", help="path to source dir")
38
+ parser.add_argument("--out_dir2", type=str, default="./dataset/44k", help="path to target dir")
39
+ args = parser.parse_args()
40
+ processs = cpu_count()-2 if cpu_count() >4 else 1
41
+ pool = Pool(processes=processs)
42
+
43
+ for speaker in os.listdir(args.in_dir):
44
+ spk_dir = os.path.join(args.in_dir, speaker)
45
+ if os.path.isdir(spk_dir):
46
+ print(spk_dir)
47
+ for _ in tqdm(pool.imap_unordered(process, [(spk_dir, i, args) for i in os.listdir(spk_dir) if i.endswith("wav")])):
48
+ pass
setup.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import re
4
+ from pathlib import Path
5
+ import winreg
6
+ '''Old function
7
+ def detect_python_path():
8
+ path_list = os.environ['Path'].split(';')
9
+ python_path = None
10
+ python_version = None
11
+ python_pattern = re.compile(r'python (3[.][0-9]+([.][0-9]+)?)?')
12
+
13
+ for path in path_list:
14
+ if 'python' in path.lower():
15
+ python_exec = Path(path) / 'python.exe'
16
+ if python_exec.exists():
17
+ version_string = os.popen(f'"{python_exec}" --version').read().strip()
18
+ match = python_pattern.search(version_string.lower())
19
+ if match:
20
+ python_path = path
21
+ python_version = match.group(1)
22
+ break
23
+ print(version_string)
24
+ return python_path, python_version
25
+
26
+ def modify_pyvenv_cfg(python_path, python_version):
27
+ pyvenv_path = Path('.\\venv\\pyvenv.cfg')
28
+
29
+ if not pyvenv_path.exists():
30
+ print("Error: pyvenv.cfg not found.")
31
+ sys.exit(1)
32
+
33
+ with pyvenv_path.open('r') as f:
34
+ content = f.readlines()
35
+
36
+ if len(content) != 1:
37
+ print("Venv already created.")
38
+ sys.exit(1)
39
+
40
+ with pyvenv_path.open('w') as f:
41
+ f.write(f"home = {python_path}\n")
42
+ f.writelines(content)
43
+ f.write(f"version = {python_version}\n")
44
+
45
+
46
+ def create_venv(python_path, python_version):
47
+ pyvenv_path = Path('.\\venv\\pyvenv.cfg')
48
+ venv_path = Path('.\\venv')
49
+ venv_abs_path = os.path.abspath(venv_path)
50
+
51
+ if not pyvenv_path.exists():
52
+ print("Error: pyvenv.cfg not found.")
53
+ sys.exit(1)
54
+
55
+ with pyvenv_path.open('r') as f:
56
+ content = f.readlines()
57
+
58
+ home_line = None
59
+ version_line = None
60
+
61
+ for i, line in enumerate(content):
62
+ if line.startswith("home ="):
63
+ home_line = i
64
+ if line.startswith("version ="):
65
+ version_line = i
66
+
67
+ with pyvenv_path.open('w') as f:
68
+ if home_line is not None and version_line is not None:
69
+ for i, line in enumerate(content):
70
+ if i == home_line:
71
+ f.write(f"home = {python_path}\n")
72
+ elif i == version_line:
73
+ f.write(f"version = {python_version}\n")
74
+ else:
75
+ f.write(line)
76
+ else:
77
+ f.write(f"home = {python_path}\n")
78
+ f.writelines(content)
79
+ f.write(f"version = {python_version}\n")
80
+
81
+ with open(".\\venv\\Scripts\\activate", "r") as file:
82
+ content = file.readlines()
83
+
84
+ with open(".\\venv\\Scripts\\activate", "w") as file:
85
+ for line in content:
86
+ if line.startswith("VIRTUAL_ENV="):
87
+ line = f"VIRTUAL_ENV=\"{venv_abs_path}\"\n"
88
+ file.write(line)
89
+ '''
90
+ def check_ffmpeg_path():
91
+ path_list = os.environ['Path'].split(';')
92
+ ffmpeg_found = False
93
+
94
+ for path in path_list:
95
+ if 'ffmpeg' in path.lower() and 'bin' in path.lower():
96
+ ffmpeg_found = True
97
+ print("FFmpeg already installed, skipping...")
98
+ break
99
+
100
+ return ffmpeg_found
101
+
102
+ def add_ffmpeg_path_to_user_variable():
103
+ ffmpeg_bin_path = Path('.\\ffmpeg\\bin')
104
+ if ffmpeg_bin_path.is_dir():
105
+ abs_path = str(ffmpeg_bin_path.resolve())
106
+
107
+ try:
108
+ key = winreg.OpenKey(
109
+ winreg.HKEY_CURRENT_USER,
110
+ r"Environment",
111
+ 0,
112
+ winreg.KEY_READ | winreg.KEY_WRITE
113
+ )
114
+
115
+ try:
116
+ current_path, _ = winreg.QueryValueEx(key, "Path")
117
+ if abs_path not in current_path:
118
+ new_path = f"{current_path};{abs_path}"
119
+ winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
120
+ print(f"Added FFmpeg path to user variable 'Path': {abs_path}")
121
+ else:
122
+ print("FFmpeg path already exists in the user variable 'Path'.")
123
+ finally:
124
+ winreg.CloseKey(key)
125
+ except WindowsError:
126
+ print("Error: Unable to modify user variable 'Path'.")
127
+ sys.exit(1)
128
+
129
+ else:
130
+ print("Error: ffmpeg\\bin folder not found in the current path.")
131
+ sys.exit(1)
132
+
133
+ def main():
134
+ current_workdir_name = os.path.basename(os.getcwd())
135
+ if current_workdir_name != "so-vits-svc":
136
+ print("请将整合包文件夹名称修改为so-vits-svc,否则可能会导致运行出错")
137
+ sys.exit(1)
138
+ else:
139
+ if not check_ffmpeg_path():
140
+ add_ffmpeg_path_to_user_variable()
141
+
142
+ if __name__ == "__main__":
143
+ main()
train.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import multiprocessing
3
+ import time
4
+
5
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
6
+ logging.getLogger('numba').setLevel(logging.WARNING)
7
+
8
+ import os
9
+ import json
10
+ import argparse
11
+ import itertools
12
+ import math
13
+ import torch
14
+ from torch import nn, optim
15
+ from torch.nn import functional as F
16
+ from torch.utils.data import DataLoader
17
+ from torch.utils.tensorboard import SummaryWriter
18
+ import torch.multiprocessing as mp
19
+ import torch.distributed as dist
20
+ from torch.nn.parallel import DistributedDataParallel as DDP
21
+ from torch.cuda.amp import autocast, GradScaler
22
+
23
+ import modules.commons as commons
24
+ import utils
25
+ from data_utils import TextAudioSpeakerLoader, TextAudioCollate
26
+ from models import (
27
+ SynthesizerTrn,
28
+ MultiPeriodDiscriminator,
29
+ )
30
+ from modules.losses import (
31
+ kl_loss,
32
+ generator_loss, discriminator_loss, feature_loss
33
+ )
34
+
35
+ from modules.mel_processing import mel_spectrogram_torch, spec_to_mel_torch
36
+
37
+ torch.backends.cudnn.benchmark = True
38
+ global_step = 0
39
+ start_time = time.time()
40
+
41
+ # os.environ['TORCH_DISTRIBUTED_DEBUG'] = 'INFO'
42
+
43
+
44
+ def main():
45
+ """Assume Single Node Multi GPUs Training Only"""
46
+ assert torch.cuda.is_available(), "CPU training is not allowed."
47
+ hps = utils.get_hparams()
48
+
49
+ n_gpus = torch.cuda.device_count()
50
+ os.environ['MASTER_ADDR'] = 'localhost'
51
+ os.environ['MASTER_PORT'] = hps.train.port
52
+
53
+ mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))
54
+
55
+
56
+ def run(rank, n_gpus, hps):
57
+ global global_step
58
+ if rank == 0:
59
+ logger = utils.get_logger(hps.model_dir)
60
+ logger.info(hps)
61
+ utils.check_git_hash(hps.model_dir)
62
+ writer = SummaryWriter(log_dir=hps.model_dir)
63
+ writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval"))
64
+
65
+ # for pytorch on win, backend use gloo
66
+ dist.init_process_group(backend= 'gloo' if os.name == 'nt' else 'nccl', init_method='env://', world_size=n_gpus, rank=rank)
67
+ torch.manual_seed(hps.train.seed)
68
+ torch.cuda.set_device(rank)
69
+ collate_fn = TextAudioCollate()
70
+ all_in_mem = hps.train.all_in_mem # If you have enough memory, turn on this option to avoid disk IO and speed up training.
71
+ train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps, all_in_mem=all_in_mem)
72
+ num_workers = 5 if multiprocessing.cpu_count() > 4 else multiprocessing.cpu_count()
73
+ if all_in_mem:
74
+ num_workers = 0
75
+ train_loader = DataLoader(train_dataset, num_workers=num_workers, shuffle=False, pin_memory=True,
76
+ batch_size=hps.train.batch_size, collate_fn=collate_fn)
77
+ if rank == 0:
78
+ eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps, all_in_mem=all_in_mem)
79
+ eval_loader = DataLoader(eval_dataset, num_workers=1, shuffle=False,
80
+ batch_size=1, pin_memory=False,
81
+ drop_last=False, collate_fn=collate_fn)
82
+
83
+ net_g = SynthesizerTrn(
84
+ hps.data.filter_length // 2 + 1,
85
+ hps.train.segment_size // hps.data.hop_length,
86
+ **hps.model).cuda(rank)
87
+ net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank)
88
+ optim_g = torch.optim.AdamW(
89
+ net_g.parameters(),
90
+ hps.train.learning_rate,
91
+ betas=hps.train.betas,
92
+ eps=hps.train.eps)
93
+ optim_d = torch.optim.AdamW(
94
+ net_d.parameters(),
95
+ hps.train.learning_rate,
96
+ betas=hps.train.betas,
97
+ eps=hps.train.eps)
98
+ net_g = DDP(net_g, device_ids=[rank]) # , find_unused_parameters=True)
99
+ net_d = DDP(net_d, device_ids=[rank])
100
+
101
+ skip_optimizer = False
102
+ try:
103
+ _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g,
104
+ optim_g, skip_optimizer)
105
+ _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d,
106
+ optim_d, skip_optimizer)
107
+ epoch_str = max(epoch_str, 1)
108
+ global_step = (epoch_str - 1) * len(train_loader)
109
+ except:
110
+ print("load old checkpoint failed...")
111
+ epoch_str = 1
112
+ global_step = 0
113
+ if skip_optimizer:
114
+ epoch_str = 1
115
+ global_step = 0
116
+
117
+ scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
118
+ scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
119
+
120
+ scaler = GradScaler(enabled=hps.train.fp16_run)
121
+
122
+ for epoch in range(epoch_str, hps.train.epochs + 1):
123
+ if rank == 0:
124
+ train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler,
125
+ [train_loader, eval_loader], logger, [writer, writer_eval])
126
+ else:
127
+ train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler,
128
+ [train_loader, None], None, None)
129
+ scheduler_g.step()
130
+ scheduler_d.step()
131
+
132
+
133
+ def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):
134
+ net_g, net_d = nets
135
+ optim_g, optim_d = optims
136
+ scheduler_g, scheduler_d = schedulers
137
+ train_loader, eval_loader = loaders
138
+ if writers is not None:
139
+ writer, writer_eval = writers
140
+
141
+ # train_loader.batch_sampler.set_epoch(epoch)
142
+ global global_step
143
+
144
+ net_g.train()
145
+ net_d.train()
146
+ for batch_idx, items in enumerate(train_loader):
147
+ c, f0, spec, y, spk, lengths, uv = items
148
+ g = spk.cuda(rank, non_blocking=True)
149
+ spec, y = spec.cuda(rank, non_blocking=True), y.cuda(rank, non_blocking=True)
150
+ c = c.cuda(rank, non_blocking=True)
151
+ f0 = f0.cuda(rank, non_blocking=True)
152
+ uv = uv.cuda(rank, non_blocking=True)
153
+ lengths = lengths.cuda(rank, non_blocking=True)
154
+ mel = spec_to_mel_torch(
155
+ spec,
156
+ hps.data.filter_length,
157
+ hps.data.n_mel_channels,
158
+ hps.data.sampling_rate,
159
+ hps.data.mel_fmin,
160
+ hps.data.mel_fmax)
161
+
162
+ with autocast(enabled=hps.train.fp16_run):
163
+ y_hat, ids_slice, z_mask, \
164
+ (z, z_p, m_p, logs_p, m_q, logs_q), pred_lf0, norm_lf0, lf0 = net_g(c, f0, uv, spec, g=g, c_lengths=lengths,
165
+ spec_lengths=lengths)
166
+
167
+ y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)
168
+ y_hat_mel = mel_spectrogram_torch(
169
+ y_hat.squeeze(1),
170
+ hps.data.filter_length,
171
+ hps.data.n_mel_channels,
172
+ hps.data.sampling_rate,
173
+ hps.data.hop_length,
174
+ hps.data.win_length,
175
+ hps.data.mel_fmin,
176
+ hps.data.mel_fmax
177
+ )
178
+ y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice
179
+
180
+ # Discriminator
181
+ y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
182
+
183
+ with autocast(enabled=False):
184
+ loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g)
185
+ loss_disc_all = loss_disc
186
+
187
+ optim_d.zero_grad()
188
+ scaler.scale(loss_disc_all).backward()
189
+ scaler.unscale_(optim_d)
190
+ grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
191
+ scaler.step(optim_d)
192
+
193
+ with autocast(enabled=hps.train.fp16_run):
194
+ # Generator
195
+ y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
196
+ with autocast(enabled=False):
197
+ loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
198
+ loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
199
+ loss_fm = feature_loss(fmap_r, fmap_g)
200
+ loss_gen, losses_gen = generator_loss(y_d_hat_g)
201
+ loss_lf0 = F.mse_loss(pred_lf0, lf0)
202
+ loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl + loss_lf0
203
+ optim_g.zero_grad()
204
+ scaler.scale(loss_gen_all).backward()
205
+ scaler.unscale_(optim_g)
206
+ grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
207
+ scaler.step(optim_g)
208
+ scaler.update()
209
+
210
+ if rank == 0:
211
+ if global_step % hps.train.log_interval == 0:
212
+ lr = optim_g.param_groups[0]['lr']
213
+ losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_kl]
214
+ logger.info('Train Epoch: {} [{:.0f}%]'.format(
215
+ epoch,
216
+ 100. * batch_idx / len(train_loader)))
217
+ logger.info(f"Losses: {[x.item() for x in losses]}, step: {global_step}, lr: {lr}")
218
+
219
+ scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr,
220
+ "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g}
221
+ scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/kl": loss_kl,
222
+ "loss/g/lf0": loss_lf0})
223
+
224
+ # scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
225
+ # scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
226
+ # scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
227
+ image_dict = {
228
+ "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),
229
+ "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()),
230
+ "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),
231
+ "all/lf0": utils.plot_data_to_numpy(lf0[0, 0, :].cpu().numpy(),
232
+ pred_lf0[0, 0, :].detach().cpu().numpy()),
233
+ "all/norm_lf0": utils.plot_data_to_numpy(lf0[0, 0, :].cpu().numpy(),
234
+ norm_lf0[0, 0, :].detach().cpu().numpy())
235
+ }
236
+
237
+ utils.summarize(
238
+ writer=writer,
239
+ global_step=global_step,
240
+ images=image_dict,
241
+ scalars=scalar_dict
242
+ )
243
+
244
+ if global_step % hps.train.eval_interval == 0:
245
+ evaluate(hps, net_g, eval_loader, writer_eval)
246
+ utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch,
247
+ os.path.join(hps.model_dir, "G_{}.pth".format(global_step)))
248
+ utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch,
249
+ os.path.join(hps.model_dir, "D_{}.pth".format(global_step)))
250
+ keep_ckpts = getattr(hps.train, 'keep_ckpts', 0)
251
+ if keep_ckpts > 0:
252
+ utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True)
253
+
254
+ global_step += 1
255
+
256
+ if rank == 0:
257
+ global start_time
258
+ now = time.time()
259
+ durtaion = format(now - start_time, '.2f')
260
+ logger.info(f'====> Epoch: {epoch}, cost {durtaion} s')
261
+ start_time = now
262
+
263
+
264
+ def evaluate(hps, generator, eval_loader, writer_eval):
265
+ generator.eval()
266
+ image_dict = {}
267
+ audio_dict = {}
268
+ with torch.no_grad():
269
+ for batch_idx, items in enumerate(eval_loader):
270
+ c, f0, spec, y, spk, _, uv = items
271
+ g = spk[:1].cuda(0)
272
+ spec, y = spec[:1].cuda(0), y[:1].cuda(0)
273
+ c = c[:1].cuda(0)
274
+ f0 = f0[:1].cuda(0)
275
+ uv= uv[:1].cuda(0)
276
+ mel = spec_to_mel_torch(
277
+ spec,
278
+ hps.data.filter_length,
279
+ hps.data.n_mel_channels,
280
+ hps.data.sampling_rate,
281
+ hps.data.mel_fmin,
282
+ hps.data.mel_fmax)
283
+ y_hat = generator.module.infer(c, f0, uv, g=g)
284
+
285
+ y_hat_mel = mel_spectrogram_torch(
286
+ y_hat.squeeze(1).float(),
287
+ hps.data.filter_length,
288
+ hps.data.n_mel_channels,
289
+ hps.data.sampling_rate,
290
+ hps.data.hop_length,
291
+ hps.data.win_length,
292
+ hps.data.mel_fmin,
293
+ hps.data.mel_fmax
294
+ )
295
+
296
+ audio_dict.update({
297
+ f"gen/audio_{batch_idx}": y_hat[0],
298
+ f"gt/audio_{batch_idx}": y[0]
299
+ })
300
+ image_dict.update({
301
+ f"gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()),
302
+ "gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())
303
+ })
304
+ utils.summarize(
305
+ writer=writer_eval,
306
+ global_step=global_step,
307
+ images=image_dict,
308
+ audios=audio_dict,
309
+ audio_sampling_rate=hps.data.sampling_rate
310
+ )
311
+ generator.train()
312
+
313
+
314
+ if __name__ == "__main__":
315
+ main()
utils.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import re
4
+ import sys
5
+ import argparse
6
+ import logging
7
+ import json
8
+ import subprocess
9
+ import warnings
10
+ import random
11
+ import functools
12
+
13
+ import librosa
14
+ import numpy as np
15
+ from scipy.io.wavfile import read
16
+ import torch
17
+ from torch.nn import functional as F
18
+ from modules.commons import sequence_mask
19
+ from hubert import hubert_model
20
+ from modules.crepe import CrepePitchExtractor
21
+
22
+ MATPLOTLIB_FLAG = False
23
+
24
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
25
+ logger = logging
26
+
27
+ f0_bin = 256
28
+ f0_max = 1100.0
29
+ f0_min = 50.0
30
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
31
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
32
+
33
+
34
+ # def normalize_f0(f0, random_scale=True):
35
+ # f0_norm = f0.clone() # create a copy of the input Tensor
36
+ # batch_size, _, frame_length = f0_norm.shape
37
+ # for i in range(batch_size):
38
+ # means = torch.mean(f0_norm[i, 0, :])
39
+ # if random_scale:
40
+ # factor = random.uniform(0.8, 1.2)
41
+ # else:
42
+ # factor = 1
43
+ # f0_norm[i, 0, :] = (f0_norm[i, 0, :] - means) * factor
44
+ # return f0_norm
45
+ # def normalize_f0(f0, random_scale=True):
46
+ # means = torch.mean(f0[:, 0, :], dim=1, keepdim=True)
47
+ # if random_scale:
48
+ # factor = torch.Tensor(f0.shape[0],1).uniform_(0.8, 1.2).to(f0.device)
49
+ # else:
50
+ # factor = torch.ones(f0.shape[0], 1, 1).to(f0.device)
51
+ # f0_norm = (f0 - means.unsqueeze(-1)) * factor.unsqueeze(-1)
52
+ # return f0_norm
53
+
54
+ def deprecated(func):
55
+ """This is a decorator which can be used to mark functions
56
+ as deprecated. It will result in a warning being emitted
57
+ when the function is used."""
58
+ @functools.wraps(func)
59
+ def new_func(*args, **kwargs):
60
+ warnings.simplefilter('always', DeprecationWarning) # turn off filter
61
+ warnings.warn("Call to deprecated function {}.".format(func.__name__),
62
+ category=DeprecationWarning,
63
+ stacklevel=2)
64
+ warnings.simplefilter('default', DeprecationWarning) # reset filter
65
+ return func(*args, **kwargs)
66
+ return new_func
67
+
68
+ def normalize_f0(f0, x_mask, uv, random_scale=True):
69
+ # calculate means based on x_mask
70
+ uv_sum = torch.sum(uv, dim=1, keepdim=True)
71
+ uv_sum[uv_sum == 0] = 9999
72
+ means = torch.sum(f0[:, 0, :] * uv, dim=1, keepdim=True) / uv_sum
73
+
74
+ if random_scale:
75
+ factor = torch.Tensor(f0.shape[0], 1).uniform_(0.8, 1.2).to(f0.device)
76
+ else:
77
+ factor = torch.ones(f0.shape[0], 1).to(f0.device)
78
+ # normalize f0 based on means and factor
79
+ f0_norm = (f0 - means.unsqueeze(-1)) * factor.unsqueeze(-1)
80
+ if torch.isnan(f0_norm).any():
81
+ exit(0)
82
+ return f0_norm * x_mask
83
+
84
+ def compute_f0_uv_torchcrepe(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512,device=None):
85
+ x = wav_numpy
86
+ if p_len is None:
87
+ p_len = x.shape[0]//hop_length
88
+ else:
89
+ assert abs(p_len-x.shape[0]//hop_length) < 4, "pad length error"
90
+
91
+ f0_min = 50
92
+ f0_max = 1100
93
+ F0Creper = CrepePitchExtractor(hop_length=hop_length,f0_min=f0_min,f0_max=f0_max,device=device)
94
+ f0,uv = F0Creper(x[None,:].float(),sampling_rate,pad_to=p_len)
95
+ return f0,uv
96
+
97
+ def plot_data_to_numpy(x, y):
98
+ global MATPLOTLIB_FLAG
99
+ if not MATPLOTLIB_FLAG:
100
+ import matplotlib
101
+ matplotlib.use("Agg")
102
+ MATPLOTLIB_FLAG = True
103
+ mpl_logger = logging.getLogger('matplotlib')
104
+ mpl_logger.setLevel(logging.WARNING)
105
+ import matplotlib.pylab as plt
106
+ import numpy as np
107
+
108
+ fig, ax = plt.subplots(figsize=(10, 2))
109
+ plt.plot(x)
110
+ plt.plot(y)
111
+ plt.tight_layout()
112
+
113
+ fig.canvas.draw()
114
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
115
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
116
+ plt.close()
117
+ return data
118
+
119
+
120
+
121
+ def interpolate_f0(f0):
122
+ '''
123
+ 对F0进行插值处理
124
+ '''
125
+
126
+ data = np.reshape(f0, (f0.size, 1))
127
+
128
+ vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
129
+ vuv_vector[data > 0.0] = 1.0
130
+ vuv_vector[data <= 0.0] = 0.0
131
+
132
+ ip_data = data
133
+
134
+ frame_number = data.size
135
+ last_value = 0.0
136
+ for i in range(frame_number):
137
+ if data[i] <= 0.0:
138
+ j = i + 1
139
+ for j in range(i + 1, frame_number):
140
+ if data[j] > 0.0:
141
+ break
142
+ if j < frame_number - 1:
143
+ if last_value > 0.0:
144
+ step = (data[j] - data[i - 1]) / float(j - i)
145
+ for k in range(i, j):
146
+ ip_data[k] = data[i - 1] + step * (k - i + 1)
147
+ else:
148
+ for k in range(i, j):
149
+ ip_data[k] = data[j]
150
+ else:
151
+ for k in range(i, frame_number):
152
+ ip_data[k] = last_value
153
+ else:
154
+ ip_data[i] = data[i]
155
+ last_value = data[i]
156
+
157
+ return ip_data[:,0], vuv_vector[:,0]
158
+
159
+
160
+ def compute_f0_parselmouth(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512):
161
+ import parselmouth
162
+ x = wav_numpy
163
+ if p_len is None:
164
+ p_len = x.shape[0]//hop_length
165
+ else:
166
+ assert abs(p_len-x.shape[0]//hop_length) < 4, "pad length error"
167
+ time_step = hop_length / sampling_rate * 1000
168
+ f0_min = 50
169
+ f0_max = 1100
170
+ f0 = parselmouth.Sound(x, sampling_rate).to_pitch_ac(
171
+ time_step=time_step / 1000, voicing_threshold=0.6,
172
+ pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
173
+
174
+ pad_size=(p_len - len(f0) + 1) // 2
175
+ if(pad_size>0 or p_len - len(f0) - pad_size>0):
176
+ f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant')
177
+ return f0
178
+
179
+ def resize_f0(x, target_len):
180
+ source = np.array(x)
181
+ source[source<0.001] = np.nan
182
+ target = np.interp(np.arange(0, len(source)*target_len, len(source))/ target_len, np.arange(0, len(source)), source)
183
+ res = np.nan_to_num(target)
184
+ return res
185
+
186
+ def compute_f0_dio(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512):
187
+ import pyworld
188
+ if p_len is None:
189
+ p_len = wav_numpy.shape[0]//hop_length
190
+ f0, t = pyworld.dio(
191
+ wav_numpy.astype(np.double),
192
+ fs=sampling_rate,
193
+ f0_ceil=800,
194
+ frame_period=1000 * hop_length / sampling_rate,
195
+ )
196
+ f0 = pyworld.stonemask(wav_numpy.astype(np.double), f0, t, sampling_rate)
197
+ for index, pitch in enumerate(f0):
198
+ f0[index] = round(pitch, 1)
199
+ return resize_f0(f0, p_len)
200
+
201
+ def f0_to_coarse(f0):
202
+ is_torch = isinstance(f0, torch.Tensor)
203
+ f0_mel = 1127 * (1 + f0 / 700).log() if is_torch else 1127 * np.log(1 + f0 / 700)
204
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * (f0_bin - 2) / (f0_mel_max - f0_mel_min) + 1
205
+
206
+ f0_mel[f0_mel <= 1] = 1
207
+ f0_mel[f0_mel > f0_bin - 1] = f0_bin - 1
208
+ f0_coarse = (f0_mel + 0.5).long() if is_torch else np.rint(f0_mel).astype(np.int)
209
+ assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, (f0_coarse.max(), f0_coarse.min())
210
+ return f0_coarse
211
+
212
+
213
+ def get_hubert_model():
214
+ vec_path = "hubert/checkpoint_best_legacy_500.pt"
215
+ print("load model(s) from {}".format(vec_path))
216
+ from fairseq import checkpoint_utils
217
+ models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
218
+ [vec_path],
219
+ suffix="",
220
+ )
221
+ model = models[0]
222
+ model.eval()
223
+ return model
224
+
225
+ def get_hubert_content(hmodel, wav_16k_tensor):
226
+ feats = wav_16k_tensor
227
+ if feats.dim() == 2: # double channels
228
+ feats = feats.mean(-1)
229
+ assert feats.dim() == 1, feats.dim()
230
+ feats = feats.view(1, -1)
231
+ padding_mask = torch.BoolTensor(feats.shape).fill_(False)
232
+ inputs = {
233
+ "source": feats.to(wav_16k_tensor.device),
234
+ "padding_mask": padding_mask.to(wav_16k_tensor.device),
235
+ "output_layer": 9, # layer 9
236
+ }
237
+ with torch.no_grad():
238
+ logits = hmodel.extract_features(**inputs)
239
+ feats = hmodel.final_proj(logits[0])
240
+ return feats.transpose(1, 2)
241
+
242
+
243
+ def get_content(cmodel, y):
244
+ with torch.no_grad():
245
+ c = cmodel.extract_features(y.squeeze(1))[0]
246
+ c = c.transpose(1, 2)
247
+ return c
248
+
249
+
250
+
251
+ def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
252
+ assert os.path.isfile(checkpoint_path)
253
+ checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
254
+ iteration = checkpoint_dict['iteration']
255
+ learning_rate = checkpoint_dict['learning_rate']
256
+ if optimizer is not None and not skip_optimizer and checkpoint_dict['optimizer'] is not None:
257
+ optimizer.load_state_dict(checkpoint_dict['optimizer'])
258
+ saved_state_dict = checkpoint_dict['model']
259
+ if hasattr(model, 'module'):
260
+ state_dict = model.module.state_dict()
261
+ else:
262
+ state_dict = model.state_dict()
263
+ new_state_dict = {}
264
+ for k, v in state_dict.items():
265
+ try:
266
+ # assert "dec" in k or "disc" in k
267
+ # print("load", k)
268
+ new_state_dict[k] = saved_state_dict[k]
269
+ assert saved_state_dict[k].shape == v.shape, (saved_state_dict[k].shape, v.shape)
270
+ except:
271
+ print("error, %s is not in the checkpoint" % k)
272
+ logger.info("%s is not in the checkpoint" % k)
273
+ new_state_dict[k] = v
274
+ if hasattr(model, 'module'):
275
+ model.module.load_state_dict(new_state_dict)
276
+ else:
277
+ model.load_state_dict(new_state_dict)
278
+ print("load ")
279
+ logger.info("Loaded checkpoint '{}' (iteration {})".format(
280
+ checkpoint_path, iteration))
281
+ return model, optimizer, learning_rate, iteration
282
+
283
+
284
+ def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
285
+ logger.info("Saving model and optimizer state at iteration {} to {}".format(
286
+ iteration, checkpoint_path))
287
+ if hasattr(model, 'module'):
288
+ state_dict = model.module.state_dict()
289
+ else:
290
+ state_dict = model.state_dict()
291
+ torch.save({'model': state_dict,
292
+ 'iteration': iteration,
293
+ 'optimizer': optimizer.state_dict(),
294
+ 'learning_rate': learning_rate}, checkpoint_path)
295
+
296
+ def clean_checkpoints(path_to_models='logs/44k/', n_ckpts_to_keep=2, sort_by_time=True):
297
+ """Freeing up space by deleting saved ckpts
298
+
299
+ Arguments:
300
+ path_to_models -- Path to the model directory
301
+ n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
302
+ sort_by_time -- True -> chronologically delete ckpts
303
+ False -> lexicographically delete ckpts
304
+ """
305
+ ckpts_files = [f for f in os.listdir(path_to_models) if os.path.isfile(os.path.join(path_to_models, f))]
306
+ name_key = (lambda _f: int(re.compile('._(\d+)\.pth').match(_f).group(1)))
307
+ time_key = (lambda _f: os.path.getmtime(os.path.join(path_to_models, _f)))
308
+ sort_key = time_key if sort_by_time else name_key
309
+ x_sorted = lambda _x: sorted([f for f in ckpts_files if f.startswith(_x) and not f.endswith('_0.pth')], key=sort_key)
310
+ to_del = [os.path.join(path_to_models, fn) for fn in
311
+ (x_sorted('G')[:-n_ckpts_to_keep] + x_sorted('D')[:-n_ckpts_to_keep])]
312
+ del_info = lambda fn: logger.info(f".. Free up space by deleting ckpt {fn}")
313
+ del_routine = lambda x: [os.remove(x), del_info(x)]
314
+ rs = [del_routine(fn) for fn in to_del]
315
+
316
+ def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
317
+ for k, v in scalars.items():
318
+ writer.add_scalar(k, v, global_step)
319
+ for k, v in histograms.items():
320
+ writer.add_histogram(k, v, global_step)
321
+ for k, v in images.items():
322
+ writer.add_image(k, v, global_step, dataformats='HWC')
323
+ for k, v in audios.items():
324
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
325
+
326
+
327
+ def latest_checkpoint_path(dir_path, regex="G_*.pth"):
328
+ f_list = glob.glob(os.path.join(dir_path, regex))
329
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
330
+ x = f_list[-1]
331
+ print(x)
332
+ return x
333
+
334
+
335
+ def plot_spectrogram_to_numpy(spectrogram):
336
+ global MATPLOTLIB_FLAG
337
+ if not MATPLOTLIB_FLAG:
338
+ import matplotlib
339
+ matplotlib.use("Agg")
340
+ MATPLOTLIB_FLAG = True
341
+ mpl_logger = logging.getLogger('matplotlib')
342
+ mpl_logger.setLevel(logging.WARNING)
343
+ import matplotlib.pylab as plt
344
+ import numpy as np
345
+
346
+ fig, ax = plt.subplots(figsize=(10,2))
347
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
348
+ interpolation='none')
349
+ plt.colorbar(im, ax=ax)
350
+ plt.xlabel("Frames")
351
+ plt.ylabel("Channels")
352
+ plt.tight_layout()
353
+
354
+ fig.canvas.draw()
355
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
356
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
357
+ plt.close()
358
+ return data
359
+
360
+
361
+ def plot_alignment_to_numpy(alignment, info=None):
362
+ global MATPLOTLIB_FLAG
363
+ if not MATPLOTLIB_FLAG:
364
+ import matplotlib
365
+ matplotlib.use("Agg")
366
+ MATPLOTLIB_FLAG = True
367
+ mpl_logger = logging.getLogger('matplotlib')
368
+ mpl_logger.setLevel(logging.WARNING)
369
+ import matplotlib.pylab as plt
370
+ import numpy as np
371
+
372
+ fig, ax = plt.subplots(figsize=(6, 4))
373
+ im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
374
+ interpolation='none')
375
+ fig.colorbar(im, ax=ax)
376
+ xlabel = 'Decoder timestep'
377
+ if info is not None:
378
+ xlabel += '\n\n' + info
379
+ plt.xlabel(xlabel)
380
+ plt.ylabel('Encoder timestep')
381
+ plt.tight_layout()
382
+
383
+ fig.canvas.draw()
384
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
385
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
386
+ plt.close()
387
+ return data
388
+
389
+
390
+ def load_wav_to_torch(full_path):
391
+ sampling_rate, data = read(full_path)
392
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
393
+
394
+
395
+ def load_filepaths_and_text(filename, split="|"):
396
+ with open(filename, encoding='utf-8') as f:
397
+ filepaths_and_text = [line.strip().split(split) for line in f]
398
+ return filepaths_and_text
399
+
400
+
401
+ def get_hparams(init=True):
402
+ parser = argparse.ArgumentParser()
403
+ parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
404
+ help='JSON file for configuration')
405
+ parser.add_argument('-m', '--model', type=str, required=True,
406
+ help='Model name')
407
+
408
+ args = parser.parse_args()
409
+ model_dir = os.path.join("./logs", args.model)
410
+
411
+ if not os.path.exists(model_dir):
412
+ os.makedirs(model_dir)
413
+
414
+ config_path = args.config
415
+ config_save_path = os.path.join(model_dir, "config.json")
416
+ if init:
417
+ with open(config_path, "r") as f:
418
+ data = f.read()
419
+ with open(config_save_path, "w") as f:
420
+ f.write(data)
421
+ else:
422
+ with open(config_save_path, "r") as f:
423
+ data = f.read()
424
+ config = json.loads(data)
425
+
426
+ hparams = HParams(**config)
427
+ hparams.model_dir = model_dir
428
+ return hparams
429
+
430
+
431
+ def get_hparams_from_dir(model_dir):
432
+ config_save_path = os.path.join(model_dir, "config.json")
433
+ with open(config_save_path, "r") as f:
434
+ data = f.read()
435
+ config = json.loads(data)
436
+
437
+ hparams =HParams(**config)
438
+ hparams.model_dir = model_dir
439
+ return hparams
440
+
441
+
442
+ def get_hparams_from_file(config_path):
443
+ with open(config_path, "r") as f:
444
+ data = f.read()
445
+ config = json.loads(data)
446
+
447
+ hparams =HParams(**config)
448
+ return hparams
449
+
450
+
451
+ def check_git_hash(model_dir):
452
+ source_dir = os.path.dirname(os.path.realpath(__file__))
453
+ if not os.path.exists(os.path.join(source_dir, ".git")):
454
+ logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
455
+ source_dir
456
+ ))
457
+ return
458
+
459
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
460
+
461
+ path = os.path.join(model_dir, "githash")
462
+ if os.path.exists(path):
463
+ saved_hash = open(path).read()
464
+ if saved_hash != cur_hash:
465
+ logger.warn("git hash values are different. {}(saved) != {}(current)".format(
466
+ saved_hash[:8], cur_hash[:8]))
467
+ else:
468
+ open(path, "w").write(cur_hash)
469
+
470
+
471
+ def get_logger(model_dir, filename="train.log"):
472
+ global logger
473
+ logger = logging.getLogger(os.path.basename(model_dir))
474
+ logger.setLevel(logging.DEBUG)
475
+
476
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
477
+ if not os.path.exists(model_dir):
478
+ os.makedirs(model_dir)
479
+ h = logging.FileHandler(os.path.join(model_dir, filename))
480
+ h.setLevel(logging.DEBUG)
481
+ h.setFormatter(formatter)
482
+ logger.addHandler(h)
483
+ return logger
484
+
485
+
486
+ def repeat_expand_2d(content, target_len):
487
+ # content : [h, t]
488
+
489
+ src_len = content.shape[-1]
490
+ target = torch.zeros([content.shape[0], target_len], dtype=torch.float).to(content.device)
491
+ temp = torch.arange(src_len+1) * target_len / src_len
492
+ current_pos = 0
493
+ for i in range(target_len):
494
+ if i < temp[current_pos+1]:
495
+ target[:, i] = content[:, current_pos]
496
+ else:
497
+ current_pos += 1
498
+ target[:, i] = content[:, current_pos]
499
+
500
+ return target
501
+
502
+
503
+ class HParams():
504
+ def __init__(self, **kwargs):
505
+ for k, v in kwargs.items():
506
+ if type(v) == dict:
507
+ v = HParams(**v)
508
+ self[k] = v
509
+
510
+ def keys(self):
511
+ return self.__dict__.keys()
512
+
513
+ def items(self):
514
+ return self.__dict__.items()
515
+
516
+ def values(self):
517
+ return self.__dict__.values()
518
+
519
+ def __len__(self):
520
+ return len(self.__dict__)
521
+
522
+ def __getitem__(self, key):
523
+ return getattr(self, key)
524
+
525
+ def __setitem__(self, key, value):
526
+ return setattr(self, key, value)
527
+
528
+ def __contains__(self, key):
529
+ return key in self.__dict__
530
+
531
+ def __repr__(self):
532
+ return self.__dict__.__repr__()
533
+
wav_upload.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google.colab import files
2
+ import shutil
3
+ import os
4
+ import argparse
5
+ if __name__ == "__main__":
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument("--type", type=str, required=True, help="type of file to upload")
8
+ args = parser.parse_args()
9
+ file_type = args.type
10
+
11
+ basepath = os.getcwd()
12
+ uploaded = files.upload() # 上传文件
13
+ assert(file_type in ['zip', 'audio'])
14
+ if file_type == "zip":
15
+ upload_path = "./upload/"
16
+ for filename in uploaded.keys():
17
+ #将上传的文件移动到指定的位置上
18
+ shutil.move(os.path.join(basepath, filename), os.path.join(upload_path, "userzip.zip"))
19
+ elif file_type == "audio":
20
+ upload_path = "./raw/"
21
+ for filename in uploaded.keys():
22
+ #将上传的文件移动到指定的位置上
23
+ shutil.move(os.path.join(basepath, filename), os.path.join(upload_path, filename))
webUI.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+
4
+ # os.system("wget -P cvec/ https://huggingface.co/spaces/innnky/nanami/resolve/main/checkpoint_best_legacy_500.pt")
5
+ import gradio as gr
6
+ import gradio.processing_utils as gr_pu
7
+ import librosa
8
+ import numpy as np
9
+ import soundfile
10
+ from inference.infer_tool import Svc
11
+ import logging
12
+
13
+ import subprocess
14
+ import edge_tts
15
+ import asyncio
16
+ from scipy.io import wavfile
17
+ import librosa
18
+ import torch
19
+ import time
20
+
21
+ logging.getLogger('numba').setLevel(logging.WARNING)
22
+ logging.getLogger('markdown_it').setLevel(logging.WARNING)
23
+ logging.getLogger('urllib3').setLevel(logging.WARNING)
24
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
25
+ logging.getLogger('multipart').setLevel(logging.WARNING)
26
+
27
+ model = None
28
+ spk = None
29
+ cuda = []
30
+ if torch.cuda.is_available():
31
+ for i in range(torch.cuda.device_count()):
32
+ cuda.append("cuda:{}".format(i))
33
+
34
+ def vc_fn(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling):
35
+ global model
36
+ try:
37
+ if input_audio is None:
38
+ return "You need to upload an audio", None
39
+ if model is None:
40
+ return "You need to upload an model", None
41
+ sampling_rate, audio = input_audio
42
+ # print(audio.shape,sampling_rate)
43
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
44
+ if len(audio.shape) > 1:
45
+ audio = librosa.to_mono(audio.transpose(1, 0))
46
+ temp_path = "temp.wav"
47
+ soundfile.write(temp_path, audio, sampling_rate, format="wav")
48
+ _audio = model.slice_inference(temp_path, sid, vc_transform, slice_db, cluster_ratio, auto_f0, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling)
49
+ model.clear_empty()
50
+ os.remove(temp_path)
51
+ #构建保存文件的路径,并保存到results文件夹内
52
+ timestamp = str(int(time.time()))
53
+ output_file = os.path.join("results", sid + "_" + timestamp + ".wav")
54
+ soundfile.write(output_file, _audio, model.target_sample, format="wav")
55
+ return "Success", (model.target_sample, _audio)
56
+ except Exception as e:
57
+ return "异常信息:"+str(e)+"\n请排障后重试",None
58
+
59
+ def tts_func(_text,_rate):
60
+ #使用edge-tts把文字转成音频
61
+ # voice = "zh-CN-XiaoyiNeural"#女性,较高音
62
+ # voice = "zh-CN-YunxiNeural"#男性
63
+ voice = "zh-CN-YunxiNeural"#男性
64
+ output_file = _text[0:10]+".wav"
65
+ # communicate = edge_tts.Communicate(_text, voice)
66
+ # await communicate.save(output_file)
67
+ if _rate>=0:
68
+ ratestr="+{:.0%}".format(_rate)
69
+ elif _rate<0:
70
+ ratestr="{:.0%}".format(_rate)#减号自带
71
+
72
+ p=subprocess.Popen(["edge-tts",
73
+ "--text",_text,
74
+ "--write-media",output_file,
75
+ "--voice",voice,
76
+ "--rate="+ratestr]
77
+ ,shell=True,
78
+ stdout=subprocess.PIPE,
79
+ stdin=subprocess.PIPE)
80
+ p.wait()
81
+ return output_file
82
+
83
+ def vc_fn2(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,text2tts,tts_rate,F0_mean_pooling):
84
+ #使用edge-tts把文字转成音频
85
+ output_file=tts_func(text2tts,tts_rate)
86
+
87
+ #调整采样率
88
+ sr2=44100
89
+ wav, sr = librosa.load(output_file)
90
+ wav2 = librosa.resample(wav, orig_sr=sr, target_sr=sr2)
91
+ save_path2= text2tts[0:10]+"_44k"+".wav"
92
+ wavfile.write(save_path2,sr2,
93
+ (wav2 * np.iinfo(np.int16).max).astype(np.int16)
94
+ )
95
+
96
+ #读取音频
97
+ sample_rate, data=gr_pu.audio_from_file(save_path2)
98
+ vc_input=(sample_rate, data)
99
+
100
+ a,b=vc_fn(sid, vc_input, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling)
101
+ os.remove(output_file)
102
+ os.remove(save_path2)
103
+ return a,b
104
+
105
+ app = gr.Blocks()
106
+ with app:
107
+ with gr.Tabs():
108
+ with gr.TabItem("Sovits4.0"):
109
+ gr.Markdown(value="""
110
+ Sovits4.0 WebUI
111
+ """)
112
+
113
+ gr.Markdown(value="""
114
+ <font size=3>下面是模型文件选择:</font>
115
+ """)
116
+ model_path = gr.File(label="模型文件")
117
+ gr.Markdown(value="""
118
+ <font size=3>下面是配置文件选择:</font>
119
+ """)
120
+ config_path = gr.File(label="配置文件")
121
+ gr.Markdown(value="""
122
+ <font size=3>下面是聚类模型文件选择,没有可以不填:</font>
123
+ """)
124
+ cluster_model_path = gr.File(label="聚类模型文件")
125
+ device = gr.Dropdown(label="推理设备,默认为自动选择cpu和gpu",choices=["Auto",*cuda,"cpu"],value="Auto")
126
+ gr.Markdown(value="""
127
+ <font size=3>全部上传完毕后(全部文件模块显示download),点击模型解析进行解析:</font>
128
+ """)
129
+ model_analysis_button = gr.Button(value="模型解析")
130
+ sid = gr.Dropdown(label="音色(说话人)")
131
+ sid_output = gr.Textbox(label="Output Message")
132
+
133
+ text2tts=gr.Textbox(label="在此输入要转译的文字。注意,使用该功能建议打开F0预测,不然会很怪")
134
+ tts_rate = gr.Number(label="tts语速", value=0)
135
+
136
+ vc_input3 = gr.Audio(label="上传音频")
137
+ vc_transform = gr.Number(label="变调(整数,可以正负,半音数量,升高八度就是12)", value=0)
138
+ cluster_ratio = gr.Number(label="聚类模型混合比例,0-1之间,默认为0不启用聚类,能提升音色相似度,但会导致咬字下降(如果使用建议0.5左右)", value=0)
139
+ auto_f0 = gr.Checkbox(label="自动f0预测,配合聚类模型f0预测效果更好,会导致变调功能失效(仅限转换语音,歌声不要勾选此项会究极跑调)", value=False)
140
+ F0_mean_pooling = gr.Checkbox(label="是否对F0使用均值滤波器(池化),对部分哑音有改善。注意,启动该选项会导致推理速度下降,默认关闭", value=False)
141
+ slice_db = gr.Number(label="切片阈值", value=-40)
142
+ noise_scale = gr.Number(label="noise_scale 建议不要动,会影响音质,玄学参数", value=0.4)
143
+ cl_num = gr.Number(label="音频自动切片,0为不切片,单位为秒/s", value=0)
144
+ pad_seconds = gr.Number(label="推理音频pad秒数,由于未知原因开头结尾会有异响,pad一小段静音段后就不会出现", value=0.5)
145
+ lg_num = gr.Number(label="两端音频切片的交叉淡入长度,如果自动切片后出现人声不连贯可调整该数值,如果连贯建议采用默认值0,注意,该设置会影响推理速度,单位为秒/s", value=0)
146
+ lgr_num = gr.Number(label="自动音频切片后,需要舍弃每段切片的头尾。该参数设置交叉长度保留的比例,范围0-1,左开右闭", value=0.75,interactive=True)
147
+ vc_submit = gr.Button("音频直接转换", variant="primary")
148
+ vc_submit2 = gr.Button("文字转音频+转换", variant="primary")
149
+ vc_output1 = gr.Textbox(label="Output Message")
150
+ vc_output2 = gr.Audio(label="Output Audio")
151
+ def modelAnalysis(model_path,config_path,cluster_model_path,device):
152
+ global model
153
+ debug=False
154
+ if debug:
155
+ model = Svc(model_path.name, config_path.name,device=device if device!="Auto" else None,cluster_model_path= cluster_model_path.name if cluster_model_path!=None else "")
156
+ spks = list(model.spk2id.keys())
157
+ device_name = torch.cuda.get_device_properties(model.dev).name if "cuda" in str(model.dev) else str(model.dev)
158
+ return sid.update(choices = spks,value=spks[0]),"ok,模型被加载到了设备{}之上".format(device_name)
159
+ else:
160
+ try:
161
+ model = Svc(model_path.name, config_path.name,device=device if device!="Auto" else None,cluster_model_path= cluster_model_path.name if cluster_model_path!=None else "")
162
+ spks = list(model.spk2id.keys())
163
+ device_name = torch.cuda.get_device_properties(model.dev).name if "cuda" in str(model.dev) else str(model.dev)
164
+ return sid.update(choices = spks,value=spks[0]),"ok,模型被加载到了设备{}之上".format(device_name)
165
+ except Exception as e:
166
+ return "","异常信息:"+str(e)+"\n请排障后重试"
167
+ vc_submit.click(vc_fn, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,F0_mean_pooling], [vc_output1, vc_output2])
168
+ vc_submit2.click(vc_fn2, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale,pad_seconds,cl_num,lg_num,lgr_num,text2tts,tts_rate,F0_mean_pooling], [vc_output1, vc_output2])
169
+ model_analysis_button.click(modelAnalysis,[model_path,config_path,cluster_model_path,device],[sid,sid_output])
170
+ app.launch()
171
+
172
+
启动tensorboard.bat ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ chcp 65001
2
+ @echo off
3
+
4
+ echo 正在启动Tensorboard...
5
+ echo 如果看到输出了一条网址(大概率是localhost:6006)就可以访问该网址进入Tensorboard了
6
+
7
+ .\workenv\python.exe -m tensorboard.main --logdir=logs\44k
8
+
9
+ pause
启动webui.bat ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ chcp 65001
2
+ @echo off
3
+
4
+ echo 初始化并启动WebUI……初次启动可能会花上较长时间
5
+ .\workenv\python.exe setup.py
6
+ .\workenv\python.exe app.py
7
+
8
+ pause