PorYoung commited on
Commit
6e79ec6
1 Parent(s): 22bc264

add so-vits-svc (modified webUI.py)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +6 -2
  2. so-vits-svc +0 -1
  3. so-vits-svc/LICENSE +28 -0
  4. so-vits-svc/README.md +292 -0
  5. so-vits-svc/cluster/__init__.py +29 -0
  6. so-vits-svc/cluster/train_cluster.py +89 -0
  7. so-vits-svc/configs/config.json +0 -0
  8. so-vits-svc/configs_template/config_template.json +66 -0
  9. so-vits-svc/data_utils.py +155 -0
  10. so-vits-svc/dataset_raw/wav_structure.txt +20 -0
  11. so-vits-svc/filelists/test.txt +4 -0
  12. so-vits-svc/filelists/train.txt +15 -0
  13. so-vits-svc/filelists/val.txt +4 -0
  14. so-vits-svc/flask_api.py +62 -0
  15. so-vits-svc/flask_api_full_song.py +55 -0
  16. so-vits-svc/hubert/__init__.py +0 -0
  17. so-vits-svc/hubert/hubert_model.py +222 -0
  18. so-vits-svc/hubert/hubert_model_onnx.py +217 -0
  19. so-vits-svc/hubert/put_hubert_ckpt_here +0 -0
  20. so-vits-svc/inference/__init__.py +0 -0
  21. so-vits-svc/inference/infer_tool.py +354 -0
  22. so-vits-svc/inference/infer_tool_grad.py +160 -0
  23. so-vits-svc/inference/slicer.py +142 -0
  24. so-vits-svc/inference_main.py +161 -0
  25. so-vits-svc/logs/44k/put_pretrained_model_here +0 -0
  26. so-vits-svc/models.py +420 -0
  27. so-vits-svc/modules/__init__.py +0 -0
  28. so-vits-svc/modules/attentions.py +349 -0
  29. so-vits-svc/modules/commons.py +188 -0
  30. so-vits-svc/modules/crepe.py +331 -0
  31. so-vits-svc/modules/enhancer.py +105 -0
  32. so-vits-svc/modules/losses.py +61 -0
  33. so-vits-svc/modules/mel_processing.py +112 -0
  34. so-vits-svc/modules/modules.py +342 -0
  35. so-vits-svc/onnx_export.py +56 -0
  36. so-vits-svc/onnxexport/model_onnx.py +335 -0
  37. so-vits-svc/preprocess_flist_config.py +75 -0
  38. so-vits-svc/preprocess_hubert_f0.py +101 -0
  39. so-vits-svc/pretrain/nsf_hifigan/put_nsf_hifigan_ckpt_here +0 -0
  40. so-vits-svc/raw/put_raw_wav_here +0 -0
  41. so-vits-svc/requirements.txt +21 -0
  42. so-vits-svc/requirements_win.txt +24 -0
  43. so-vits-svc/resample.py +48 -0
  44. so-vits-svc/sovits4_for_colab.ipynb +0 -0
  45. so-vits-svc/train.py +330 -0
  46. so-vits-svc/utils.py +543 -0
  47. so-vits-svc/vdecoder/__init__.py +0 -0
  48. so-vits-svc/vdecoder/hifigan/__pycache__/env.cpython-38.pyc +0 -0
  49. so-vits-svc/vdecoder/hifigan/__pycache__/models.cpython-38.pyc +0 -0
  50. so-vits-svc/vdecoder/hifigan/__pycache__/utils.cpython-38.pyc +0 -0
Dockerfile CHANGED
@@ -6,10 +6,14 @@ RUN apt update
6
  RUN apt install -y git libsndfile1-dev python3 python3-dev python3-pip ffmpeg
7
  RUN python3 -m pip install --no-cache-dir --upgrade pip
8
 
9
- RUN git clone https://github.com/svc-develop-team/so-vits-svc.git && cd so-vits-svc
 
 
 
 
10
  RUN pip install --no-cache-dir --upgrade -r /work/so-vits-svc/requirements.txt
11
 
12
  ENV SERVER_NAME="0.0.0.0"
13
  ENV SERVER_PORT=7860
14
 
15
- CMD ["python", "webUI.py"]
 
6
  RUN apt install -y git libsndfile1-dev python3 python3-dev python3-pip ffmpeg
7
  RUN python3 -m pip install --no-cache-dir --upgrade pip
8
 
9
+ COPY ./so-vits-svc /work/
10
+ cd /work/so-vits/pretrain/nsf_hifigan
11
+ wget -c https://github.com/openvpi/vocoders/releases/download/nsf-hifigan-v1/nsf_hifigan_20221211.zip
12
+ unzip -q nsf_hifigan_20221211.zip
13
+ cd /work/so-vits-svc
14
  RUN pip install --no-cache-dir --upgrade -r /work/so-vits-svc/requirements.txt
15
 
16
  ENV SERVER_NAME="0.0.0.0"
17
  ENV SERVER_PORT=7860
18
 
19
+ RUN python webUI.py
so-vits-svc DELETED
@@ -1 +0,0 @@
1
- Subproject commit 5977fb41d9930440c4a5a18b4badf4a7444af5c8
 
 
so-vits-svc/LICENSE ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, SVC Develop Team
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
so-vits-svc/README.md ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SoftVC VITS Singing Voice Conversion
2
+
3
+ In the field of Singing Voice Conversion, there is not only one project, SoVitsSvc, but also many other projects, which will not be listed here. The project was officially discontinued for maintenance and Archived.
4
+ However, there are still other enthusiasts who have created their own branches and continue to maintain the SoVitsSvc project (still unrelated to SvcDevelopTeam and the repository maintainers) and have made some big changes to it for you to find out for yourself.
5
+
6
+ #### ✨ A fork with a greatly improved interface: [34j/so-vits-svc-fork](https://github.com/34j/so-vits-svc-fork)
7
+
8
+ #### ✨ A client supports real-time conversion: [w-okada/voice-changer](https://github.com/w-okada/voice-changer)
9
+
10
+ #### This project is fundamentally different from Vits. Vits is TTS and this project is SVC. TTS cannot be carried out in this project, and Vits cannot carry out SVC, and the two project models are not universal
11
+
12
+ ## Disclaimer
13
+
14
+ This project is an open source, offline project, and all members of SvcDevelopTeam and all developers and maintainers of this project (hereinafter referred to as contributors) have no control over this project. The contributor of this project has never provided any organization or individual with any form of assistance, including but not limited to data set extraction, data set processing, computing support, training support, infering, etc. Contributors to the project do not and cannot know what users are using the project for. Therefore, all AI models and synthesized audio based on the training of this project have nothing to do with the contributors of this project. All problems arising therefrom shall be borne by the user.
15
+
16
+ This project is run completely offline and cannot collect any user information or obtain user input data. Therefore, contributors to this project are not aware of all user input and models and therefore are not responsible for any user input.
17
+
18
+ This project is only a framework project, which does not have the function of speech synthesis itself, and all the functions require the user to train the model themselves. Meanwhile, there is no model attached to this project, and any secondary distributed project has nothing to do with the contributors of this project
19
+
20
+ ## 📏 Terms of Use
21
+
22
+ # 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!
23
+
24
+ 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.
25
+ 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.
26
+ 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.
27
+ 4. It is forbidden to use the project to engage in illegal activities, religious and political activities. The project developers firmly resist the above activities. If they do not agree with this article, the use of the project is prohibited.
28
+ 5. 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.
29
+ 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.
30
+
31
+ ## 🆕 Update!
32
+
33
+ > 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.
34
+
35
+ ## 📝 4.0 Feature list of branches
36
+
37
+ | Branch | Feature | whether compatible with the main branch model |
38
+ | :-------------: | :----------: | :------------: |
39
+ | 4.0 | main branch | - |
40
+ | 4.0v2 | The VISinger2 model is used | incompatibility |
41
+ | 4.0-Vec768-Layer12 | The feature input is the Layer 12 Transformer output of the Content Vec | incompatibility |
42
+
43
+ ## 📝 Model Introduction
44
+
45
+ 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.
46
+
47
+ ### 🆕 4.0 Version Update Content
48
+
49
+ - Feature input is changed to [Content Vec](https://github.com/auspicious3000/contentvec)
50
+ - The sampling rate is unified to use 44100Hz
51
+ - 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.
52
+ - Some code structures have been adjusted
53
+ - 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.
54
+ - 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.
55
+ - Added option 2: reduce timbre leakage through k-means clustering scheme, making the timbre more similar to the target timbre.
56
+ - Added option 3: Added [NSF-HIFIGAN Enhancer](https://github.com/yxlllc/DDSP-SVC), which has certain sound quality enhancement effect on some models with few train-sets, but has negative effect on well-trained models, so it is closed by default
57
+
58
+ ## 💬 About Python Version
59
+
60
+ After conducting tests, we believe that the project runs stably on `Python 3.8.9`.
61
+
62
+ ## 📥 Pre-trained Model Files
63
+
64
+ #### **Required**
65
+
66
+ - ContentVec: [checkpoint_best_legacy_500.pt](https://ibm.box.com/s/z1wgl1stco8ffooyatzdwsqn2psd9lrr)
67
+ - Place it under the `hubert` directory
68
+
69
+ ```shell
70
+ # contentvec
71
+ wget -P hubert/ http://obs.cstcloud.cn/share/obs/sankagenkeshi/checkpoint_best_legacy_500.pt
72
+ # Alternatively, you can manually download and place it in the hubert directory
73
+ ```
74
+
75
+ #### **Optional(Strongly recommend)**
76
+
77
+ - Pre-trained model files: `G_0.pth` `D_0.pth`
78
+ - Place them under the `logs/44k` directory
79
+
80
+ Get them from svc-develop-team(TBD) or anywhere else.
81
+
82
+ 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.
83
+
84
+ #### **Optional(Select as Required)**
85
+
86
+ If you are using the NSF-HIFIGAN enhancer, you will need to download the pre-trained NSF-HIFIGAN model, or not if you do not need it.
87
+
88
+ - Pre-trained NSF-HIFIGAN Vocoder: [nsf_hifigan_20221211.zip](https://github.com/openvpi/vocoders/releases/download/nsf-hifigan-v1/nsf_hifigan_20221211.zip)
89
+ - Unzip and place the four files under the `pretrain/nsf_hifigan` directory
90
+
91
+ ```shell
92
+ # nsf_hifigan
93
+ https://github.com/openvpi/vocoders/releases/download/nsf-hifigan-v1/nsf_hifigan_20221211.zip
94
+ # Alternatively, you can manually download and place it in the pretrain/nsf_hifigan directory
95
+ # URL:https://github.com/openvpi/vocoders/releases/tag/nsf-hifigan-v1
96
+ ```
97
+
98
+ ## 📊 Dataset Preparation
99
+
100
+ Simply place the dataset in the `dataset_raw` directory with the following file structure.
101
+
102
+ ```
103
+ dataset_raw
104
+ ├───speaker0
105
+ │ ├───xxx1-xxx1.wav
106
+ │ ├───...
107
+ │ └───Lxx-0xx8.wav
108
+ └───speaker1
109
+ ├───xx2-0xxx2.wav
110
+ ├───...
111
+ └───xxx7-xxx007.wav
112
+ ```
113
+
114
+ You can customize the speaker name.
115
+
116
+ ```
117
+ dataset_raw
118
+ └───suijiSUI
119
+ ├───1.wav
120
+ ├───...
121
+ └───25788785-20221210-200143-856_01_(Vocals)_0_0.wav
122
+ ```
123
+
124
+ ## 🛠️ Preprocessing
125
+
126
+ ### 0. Slice audio
127
+
128
+ Slice to `5s - 15s`, a bit longer is no problem. Too long may lead to `torch.cuda.OutOfMemoryError` during training or even pre-processing.
129
+
130
+ By using [audio-slicer-GUI](https://github.com/flutydeer/audio-slicer) or [audio-slicer-CLI](https://github.com/openvpi/audio-slicer)
131
+
132
+ In general, only the `Minimum Interval` needs to be adjusted. For statement audio it usually remains default. For singing audio it can be adjusted to `100` or even `50`.
133
+
134
+ After slicing, delete audio that is too long and too short.
135
+
136
+ ### 1. Resample to 44100Hz and mono
137
+
138
+ ```shell
139
+ python resample.py
140
+ ```
141
+
142
+ ### 2. Automatically split the dataset into training and validation sets, and generate configuration files.
143
+
144
+ ```shell
145
+ python preprocess_flist_config.py
146
+ ```
147
+
148
+ ### 3. Generate hubert and f0
149
+
150
+ ```shell
151
+ python preprocess_hubert_f0.py
152
+ ```
153
+
154
+ After completing the above steps, the dataset directory will contain the preprocessed data, and the dataset_raw folder can be deleted.
155
+
156
+ #### You can modify some parameters in the generated config.json
157
+
158
+ * `keep_ckpts`: Keep the last `keep_ckpts` models during training. Set to `0` will keep them all. Default is `3`.
159
+
160
+ * `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.
161
+
162
+ ## 🏋️‍♀️ Training
163
+
164
+ ```shell
165
+ python train.py -c configs/config.json -m 44k
166
+ ```
167
+
168
+ ## 🤖 Inference
169
+
170
+ Use [inference_main.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/inference_main.py)
171
+
172
+ ```shell
173
+ # Example
174
+ python inference_main.py -m "logs/44k/G_30400.pth" -c "configs/config.json" -s "nen" -n "君の知らない物語-src.wav" -t 0
175
+ ```
176
+
177
+ Required parameters:
178
+ - `-m` | `--model_path`: Path to the model.
179
+ - `-c` | `--config_path`: Path to the configuration file.
180
+ - `-s` | `--spk_list`: Target speaker name for conversion.
181
+ - `-n` | `--clean_names`: A list of wav file names located in the raw folder.
182
+ - `-t` | `--trans`: Pitch adjustment, supports positive and negative (semitone) values.
183
+
184
+ Optional parameters: see the next section
185
+ - `-a` | `--auto_predict_f0`: Automatic pitch prediction for voice conversion. Do not enable this when converting songs as it can cause serious pitch issues.
186
+ - `-cl` | `--clip`: Voice forced slicing. Set to 0 to turn off(default), duration in seconds.
187
+ - `-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. Default 0.
188
+ - `-cm` | `--cluster_model_path`: Path to the clustering model. Fill in any value if clustering is not trained.
189
+ - `-cr` | `--cluster_infer_ratio`: Proportion of the clustering solution, range 0-1. Fill in 0 if the clustering model is not trained.
190
+ - `-fmp` | `--f0_mean_pooling`: Apply mean filter (pooling) to f0, which may improve some hoarse sounds. Enabling this option will reduce inference speed.
191
+ - `-eh` | `--enhance`: Whether to use NSF_HIFIGAN enhancer. This option has certain effect on sound quality enhancement for some models with few training sets, but has negative effect on well-trained models, so it is turned off by default.
192
+
193
+ ## 🤔 Optional Settings
194
+
195
+ 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.)
196
+
197
+ ### Automatic f0 prediction
198
+
199
+ 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!
200
+ - Set `auto_predict_f0` to true in inference_main.
201
+
202
+ ### Cluster-based timbre leakage control
203
+
204
+ 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.
205
+
206
+ 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.
207
+
208
+ - Training process:
209
+ - Train on a machine with good CPU performance. According to my experience, it takes about 4 minutes to train each speaker on a Tencent Cloud machine with 6-core CPU.
210
+ - Execute `python cluster/train_cluster.py`. The output model will be saved in `logs/44k/kmeans_10000.pt`.
211
+ - Inference process:
212
+ - Specify `cluster_model_path` in `inference_main.py`.
213
+ - Specify `cluster_infer_ratio` in `inference_main.py`, where `0` means not using clustering at all, `1` means only using clustering, and usually `0.5` is sufficient.
214
+
215
+ ### F0 mean filtering
216
+
217
+ 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. However, some songs are out of tune. If the song appears dumb after reasoning, it can be considered to open.
218
+
219
+ - Set `f0_mean_pooling` to true in `inference_main.py`
220
+
221
+ ### [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/svc-develop-team/so-vits-svc/blob/4.0/sovits4_for_colab.ipynb) [sovits4_for_colab.ipynb](https://colab.research.google.com/github/svc-develop-team/so-vits-svc/blob/4.0/sovits4_for_colab.ipynb)
222
+
223
+ **[23/03/16] No longer need to download hubert manually**
224
+
225
+ **[23/04/14] Support NSF_HIFIGAN enhancer**
226
+
227
+ ## 📤 Exporting to Onnx
228
+
229
+ Use [onnx_export.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/onnx_export.py)
230
+
231
+ - Create a folder named `checkpoints` and open it
232
+ - Create a folder in the `checkpoints` folder as your project folder, naming it after your project, for example `aziplayer`
233
+ - Rename your model as `model.pth`, the configuration file as `config.json`, and place them in the `aziplayer` folder you just created
234
+ - 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"`
235
+ - Run [onnx_export.py](https://github.com/svc-develop-team/so-vits-svc/blob/4.0/onnx_export.py)
236
+ - Wait for it to finish running. A `model.onnx` will be generated in your project folder, which is the exported model.
237
+
238
+ ### UI support for Onnx models
239
+
240
+ - [MoeSS](https://github.com/NaruseMioShirakana/MoeSS)
241
+ - [Hubert4.0](https://huggingface.co/NaruseMioShirakana/MoeSS-SUBModel)
242
+
243
+ 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.)
244
+
245
+ CppDataProcess are some functions to preprocess data used in MoeSS
246
+
247
+ ## ☀️ Previous contributors
248
+
249
+ 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.
250
+
251
+ *Some members have not listed according to their personal wishes.*
252
+
253
+ <table>
254
+ <tr>
255
+ <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>
256
+ <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>
257
+ <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>
258
+ <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>
259
+ <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>
260
+ <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>
261
+ <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>
262
+ </tr>
263
+ </table>
264
+
265
+ ## 📚 Some legal provisions for reference
266
+
267
+ #### Any country, region, organization, or individual using this project must comply with the following laws.
268
+
269
+ #### 《民法典》
270
+
271
+ ##### 第一千零一十九条
272
+
273
+ 任何组织或者个人不得以丑化、污损,或者利用信息技术手段伪造等方式侵害他人的肖像权。未经肖像权人同意,不得制作、使用、公开肖像权人的肖像,但是法律另有规定的除外。未经肖像权人同意,肖像作品权利人不得以发表、复制、发行、出租、展览等方式使用或者公开肖像权人的肖像。对自然人声音的保护,参照适用肖像权保护的有关规定。
274
+
275
+ ##### 第一千零二十四条
276
+
277
+ 【名誉权】民事主体享有名誉权。任何组织或者个人不得以侮辱、诽谤等方式侵害他人的名誉权。
278
+
279
+ ##### 第一千零二十七条
280
+
281
+ 【作品侵害名誉权】行为人发表的文学、艺术作品以真人真事或者特定人为描述对象,含有侮辱、诽谤内容,侵害他人名誉权的,受害人有权依法请求该行为人承担民事责任。行为人发表的文学、艺术作品不以特定人为描述对象,仅其中的情节与该特定人的情况相似的,不承担民事责任。
282
+
283
+ #### 《[中华人民共和国宪法](http://www.gov.cn/guoqing/2018-03/22/content_5276318.htm)》
284
+
285
+ #### 《[中华人民共和国刑法](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)》
286
+
287
+ #### 《[中华人民共和国民法典](http://gongbao.court.gov.cn/Details/51eb6750b8361f79be8f90d09bc202.html)》
288
+
289
+ ## 💪 Thanks to all contributors for their efforts
290
+ <a href="https://github.com/svc-develop-team/so-vits-svc/graphs/contributors" target="_blank">
291
+ <img src="https://contrib.rocks/image?repo=svc-develop-team/so-vits-svc" />
292
+ </a>
so-vits-svc/cluster/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from sklearn.cluster import KMeans
4
+
5
+ def get_cluster_model(ckpt_path):
6
+ checkpoint = torch.load(ckpt_path)
7
+ kmeans_dict = {}
8
+ for spk, ckpt in checkpoint.items():
9
+ km = KMeans(ckpt["n_features_in_"])
10
+ km.__dict__["n_features_in_"] = ckpt["n_features_in_"]
11
+ km.__dict__["_n_threads"] = ckpt["_n_threads"]
12
+ km.__dict__["cluster_centers_"] = ckpt["cluster_centers_"]
13
+ kmeans_dict[spk] = km
14
+ return kmeans_dict
15
+
16
+ def get_cluster_result(model, x, speaker):
17
+ """
18
+ x: np.array [t, 256]
19
+ return cluster class result
20
+ """
21
+ return model[speaker].predict(x)
22
+
23
+ def get_cluster_center_result(model, x,speaker):
24
+ """x: np.array [t, 256]"""
25
+ predict = model[speaker].predict(x)
26
+ return model[speaker].cluster_centers_[predict]
27
+
28
+ def get_center(model, x,speaker):
29
+ return model[speaker].cluster_centers_[x]
so-vits-svc/cluster/train_cluster.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from glob import glob
3
+ from pathlib import Path
4
+ import torch
5
+ import logging
6
+ import argparse
7
+ import torch
8
+ import numpy as np
9
+ from sklearn.cluster import KMeans, MiniBatchKMeans
10
+ import tqdm
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+ import time
14
+ import random
15
+
16
+ def train_cluster(in_dir, n_clusters, use_minibatch=True, verbose=False):
17
+
18
+ logger.info(f"Loading features from {in_dir}")
19
+ features = []
20
+ nums = 0
21
+ for path in tqdm.tqdm(in_dir.glob("*.soft.pt")):
22
+ features.append(torch.load(path).squeeze(0).numpy().T)
23
+ # print(features[-1].shape)
24
+ features = np.concatenate(features, axis=0)
25
+ print(nums, features.nbytes/ 1024**2, "MB , shape:",features.shape, features.dtype)
26
+ features = features.astype(np.float32)
27
+ logger.info(f"Clustering features of shape: {features.shape}")
28
+ t = time.time()
29
+ if use_minibatch:
30
+ kmeans = MiniBatchKMeans(n_clusters=n_clusters,verbose=verbose, batch_size=4096, max_iter=80).fit(features)
31
+ else:
32
+ kmeans = KMeans(n_clusters=n_clusters,verbose=verbose).fit(features)
33
+ print(time.time()-t, "s")
34
+
35
+ x = {
36
+ "n_features_in_": kmeans.n_features_in_,
37
+ "_n_threads": kmeans._n_threads,
38
+ "cluster_centers_": kmeans.cluster_centers_,
39
+ }
40
+ print("end")
41
+
42
+ return x
43
+
44
+
45
+ if __name__ == "__main__":
46
+
47
+ parser = argparse.ArgumentParser()
48
+ parser.add_argument('--dataset', type=Path, default="./dataset/44k",
49
+ help='path of training data directory')
50
+ parser.add_argument('--output', type=Path, default="logs/44k",
51
+ help='path of model output directory')
52
+
53
+ args = parser.parse_args()
54
+
55
+ checkpoint_dir = args.output
56
+ dataset = args.dataset
57
+ n_clusters = 10000
58
+
59
+ ckpt = {}
60
+ for spk in os.listdir(dataset):
61
+ if os.path.isdir(dataset/spk):
62
+ print(f"train kmeans for {spk}...")
63
+ in_dir = dataset/spk
64
+ x = train_cluster(in_dir, n_clusters, verbose=False)
65
+ ckpt[spk] = x
66
+
67
+ checkpoint_path = checkpoint_dir / f"kmeans_{n_clusters}.pt"
68
+ checkpoint_path.parent.mkdir(exist_ok=True, parents=True)
69
+ torch.save(
70
+ ckpt,
71
+ checkpoint_path,
72
+ )
73
+
74
+
75
+ # import cluster
76
+ # for spk in tqdm.tqdm(os.listdir("dataset")):
77
+ # if os.path.isdir(f"dataset/{spk}"):
78
+ # print(f"start kmeans inference for {spk}...")
79
+ # for feature_path in tqdm.tqdm(glob(f"dataset/{spk}/*.discrete.npy", recursive=True)):
80
+ # mel_path = feature_path.replace(".discrete.npy",".mel.npy")
81
+ # mel_spectrogram = np.load(mel_path)
82
+ # feature_len = mel_spectrogram.shape[-1]
83
+ # c = np.load(feature_path)
84
+ # c = utils.tools.repeat_expand_2d(torch.FloatTensor(c), feature_len).numpy()
85
+ # feature = c.T
86
+ # feature_class = cluster.get_cluster_result(feature, spk)
87
+ # np.save(feature_path.replace(".discrete.npy", ".discrete_class.npy"), feature_class)
88
+
89
+
so-vits-svc/configs/config.json ADDED
File without changes
so-vits-svc/configs_template/config_template.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 800,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 0.0001,
8
+ "betas": [
9
+ 0.8,
10
+ 0.99
11
+ ],
12
+ "eps": 1e-09,
13
+ "batch_size": 6,
14
+ "fp16_run": false,
15
+ "lr_decay": 0.999875,
16
+ "segment_size": 10240,
17
+ "init_lr_ratio": 1,
18
+ "warmup_epochs": 0,
19
+ "c_mel": 45,
20
+ "c_kl": 1.0,
21
+ "use_sr": true,
22
+ "max_speclen": 512,
23
+ "port": "8001",
24
+ "keep_ckpts": 3,
25
+ "all_in_mem": false
26
+ },
27
+ "data": {
28
+ "training_files": "filelists/train.txt",
29
+ "validation_files": "filelists/val.txt",
30
+ "max_wav_value": 32768.0,
31
+ "sampling_rate": 44100,
32
+ "filter_length": 2048,
33
+ "hop_length": 512,
34
+ "win_length": 2048,
35
+ "n_mel_channels": 80,
36
+ "mel_fmin": 0.0,
37
+ "mel_fmax": 22050
38
+ },
39
+ "model": {
40
+ "inter_channels": 192,
41
+ "hidden_channels": 192,
42
+ "filter_channels": 768,
43
+ "n_heads": 2,
44
+ "n_layers": 6,
45
+ "kernel_size": 3,
46
+ "p_dropout": 0.1,
47
+ "resblock": "1",
48
+ "resblock_kernel_sizes": [3,7,11],
49
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
50
+ "upsample_rates": [ 8, 8, 2, 2, 2],
51
+ "upsample_initial_channel": 512,
52
+ "upsample_kernel_sizes": [16,16, 4, 4, 4],
53
+ "n_layers_q": 3,
54
+ "use_spectral_norm": false,
55
+ "gin_channels": 256,
56
+ "ssl_dim": 256,
57
+ "n_speakers": 200
58
+ },
59
+ "spk": {
60
+ "nyaru": 0,
61
+ "huiyu": 1,
62
+ "nen": 2,
63
+ "paimon": 3,
64
+ "yunhao": 4
65
+ }
66
+ }
so-vits-svc/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
so-vits-svc/dataset_raw/wav_structure.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 数据集准备
2
+
3
+ raw
4
+ ├───speaker0
5
+ │ ├───xxx1-xxx1.wav
6
+ │ ├───...
7
+ │ └───Lxx-0xx8.wav
8
+ └───speaker1
9
+ ├───xx2-0xxx2.wav
10
+ ├───...
11
+ └───xxx7-xxx007.wav
12
+
13
+ 此外还需要编辑config.json
14
+
15
+ "n_speakers": 10
16
+
17
+ "spk":{
18
+ "speaker0": 0,
19
+ "speaker1": 1,
20
+ }
so-vits-svc/filelists/test.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ./dataset/44k/taffy/000562.wav
2
+ ./dataset/44k/nyaru/000011.wav
3
+ ./dataset/44k/nyaru/000008.wav
4
+ ./dataset/44k/taffy/000563.wav
so-vits-svc/filelists/train.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ./dataset/44k/taffy/000549.wav
2
+ ./dataset/44k/nyaru/000004.wav
3
+ ./dataset/44k/nyaru/000006.wav
4
+ ./dataset/44k/taffy/000551.wav
5
+ ./dataset/44k/nyaru/000009.wav
6
+ ./dataset/44k/taffy/000561.wav
7
+ ./dataset/44k/nyaru/000001.wav
8
+ ./dataset/44k/taffy/000553.wav
9
+ ./dataset/44k/nyaru/000002.wav
10
+ ./dataset/44k/taffy/000560.wav
11
+ ./dataset/44k/taffy/000557.wav
12
+ ./dataset/44k/nyaru/000005.wav
13
+ ./dataset/44k/taffy/000554.wav
14
+ ./dataset/44k/taffy/000550.wav
15
+ ./dataset/44k/taffy/000559.wav
so-vits-svc/filelists/val.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ./dataset/44k/nyaru/000003.wav
2
+ ./dataset/44k/nyaru/000007.wav
3
+ ./dataset/44k/taffy/000558.wav
4
+ ./dataset/44k/taffy/000556.wav
so-vits-svc/flask_api.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # pitch changing information
24
+ f_pitch_change = float(request_form.get("fPitchChange", 0))
25
+ # DAW required sampling rate
26
+ daw_sample = int(float(request_form.get("sampleRate", 0)))
27
+ speaker_id = int(float(request_form.get("sSpeakId", 0)))
28
+ # get wav from http and convert
29
+ input_wav_path = io.BytesIO(wave_file.read())
30
+
31
+ # inference
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
+ # return
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
+ # True means splice directly. There may be explosive sounds at the splice.
50
+ # False means use cross fade. There may be slight overlapping sounds at the splice.
51
+ # Using 0.3-0.5s in VST plugin can reduce latency.
52
+ # You can adjust the maximum slicing time of VST plugin to 1 second and set it to ture here to get a stable sound quality and a relatively large delay。
53
+ # Choose an acceptable method on your own.
54
+ raw_infer = True
55
+ # each model and config are corresponding
56
+ model_name = "logs/32k/G_174000-Copy1.pth"
57
+ config_name = "configs/config.json"
58
+ cluster_model_path = "logs/44k/kmeans_10000.pt"
59
+ svc_model = Svc(model_name, config_name, cluster_model_path=cluster_model_path)
60
+ svc = RealTimeVC()
61
+ # corresponding to the vst plugin here
62
+ app.run(port=6842, host="0.0.0.0", debug=False, threaded=False)
so-vits-svc/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 path
16
+ tran = int(float(request_form.get("tran", 0))) # tone
17
+ spk = request_form.get("spk", 0) # speaker(id or name)
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"
54
+ svc_model = infer_tool.Svc(model_name, config_name)
55
+ app.run(port=1145, host="0.0.0.0", debug=False, threaded=False)
so-vits-svc/hubert/__init__.py ADDED
File without changes
so-vits-svc/hubert/hubert_model.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import random
3
+ from typing import Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as t_func
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+
11
+ class Hubert(nn.Module):
12
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
13
+ super().__init__()
14
+ self._mask = mask
15
+ self.feature_extractor = FeatureExtractor()
16
+ self.feature_projection = FeatureProjection()
17
+ self.positional_embedding = PositionalConvEmbedding()
18
+ self.norm = nn.LayerNorm(768)
19
+ self.dropout = nn.Dropout(0.1)
20
+ self.encoder = TransformerEncoder(
21
+ nn.TransformerEncoderLayer(
22
+ 768, 12, 3072, activation="gelu", batch_first=True
23
+ ),
24
+ 12,
25
+ )
26
+ self.proj = nn.Linear(768, 256)
27
+
28
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
29
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
30
+
31
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
32
+ mask = None
33
+ if self.training and self._mask:
34
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
35
+ x[mask] = self.masked_spec_embed.to(x.dtype)
36
+ return x, mask
37
+
38
+ def encode(
39
+ self, x: torch.Tensor, layer: Optional[int] = None
40
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
41
+ x = self.feature_extractor(x)
42
+ x = self.feature_projection(x.transpose(1, 2))
43
+ x, mask = self.mask(x)
44
+ x = x + self.positional_embedding(x)
45
+ x = self.dropout(self.norm(x))
46
+ x = self.encoder(x, output_layer=layer)
47
+ return x, mask
48
+
49
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
50
+ logits = torch.cosine_similarity(
51
+ x.unsqueeze(2),
52
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
53
+ dim=-1,
54
+ )
55
+ return logits / 0.1
56
+
57
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
58
+ x, mask = self.encode(x)
59
+ x = self.proj(x)
60
+ logits = self.logits(x)
61
+ return logits, mask
62
+
63
+
64
+ class HubertSoft(Hubert):
65
+ def __init__(self):
66
+ super().__init__()
67
+
68
+ @torch.inference_mode()
69
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
70
+ wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
71
+ x, _ = self.encode(wav)
72
+ return self.proj(x)
73
+
74
+
75
+ class FeatureExtractor(nn.Module):
76
+ def __init__(self):
77
+ super().__init__()
78
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
79
+ self.norm0 = nn.GroupNorm(512, 512)
80
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
81
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
82
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
83
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
84
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
85
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ x = t_func.gelu(self.norm0(self.conv0(x)))
89
+ x = t_func.gelu(self.conv1(x))
90
+ x = t_func.gelu(self.conv2(x))
91
+ x = t_func.gelu(self.conv3(x))
92
+ x = t_func.gelu(self.conv4(x))
93
+ x = t_func.gelu(self.conv5(x))
94
+ x = t_func.gelu(self.conv6(x))
95
+ return x
96
+
97
+
98
+ class FeatureProjection(nn.Module):
99
+ def __init__(self):
100
+ super().__init__()
101
+ self.norm = nn.LayerNorm(512)
102
+ self.projection = nn.Linear(512, 768)
103
+ self.dropout = nn.Dropout(0.1)
104
+
105
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
106
+ x = self.norm(x)
107
+ x = self.projection(x)
108
+ x = self.dropout(x)
109
+ return x
110
+
111
+
112
+ class PositionalConvEmbedding(nn.Module):
113
+ def __init__(self):
114
+ super().__init__()
115
+ self.conv = nn.Conv1d(
116
+ 768,
117
+ 768,
118
+ kernel_size=128,
119
+ padding=128 // 2,
120
+ groups=16,
121
+ )
122
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
123
+
124
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
125
+ x = self.conv(x.transpose(1, 2))
126
+ x = t_func.gelu(x[:, :, :-1])
127
+ return x.transpose(1, 2)
128
+
129
+
130
+ class TransformerEncoder(nn.Module):
131
+ def __init__(
132
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
133
+ ) -> None:
134
+ super(TransformerEncoder, self).__init__()
135
+ self.layers = nn.ModuleList(
136
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
137
+ )
138
+ self.num_layers = num_layers
139
+
140
+ def forward(
141
+ self,
142
+ src: torch.Tensor,
143
+ mask: torch.Tensor = None,
144
+ src_key_padding_mask: torch.Tensor = None,
145
+ output_layer: Optional[int] = None,
146
+ ) -> torch.Tensor:
147
+ output = src
148
+ for layer in self.layers[:output_layer]:
149
+ output = layer(
150
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
151
+ )
152
+ return output
153
+
154
+
155
+ def _compute_mask(
156
+ shape: Tuple[int, int],
157
+ mask_prob: float,
158
+ mask_length: int,
159
+ device: torch.device,
160
+ min_masks: int = 0,
161
+ ) -> torch.Tensor:
162
+ batch_size, sequence_length = shape
163
+
164
+ if mask_length < 1:
165
+ raise ValueError("`mask_length` has to be bigger than 0.")
166
+
167
+ if mask_length > sequence_length:
168
+ raise ValueError(
169
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
170
+ )
171
+
172
+ # compute number of masked spans in batch
173
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
174
+ num_masked_spans = max(num_masked_spans, min_masks)
175
+
176
+ # make sure num masked indices <= sequence_length
177
+ if num_masked_spans * mask_length > sequence_length:
178
+ num_masked_spans = sequence_length // mask_length
179
+
180
+ # SpecAugment mask to fill
181
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
182
+
183
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
184
+ uniform_dist = torch.ones(
185
+ (batch_size, sequence_length - (mask_length - 1)), device=device
186
+ )
187
+
188
+ # get random indices to mask
189
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
190
+
191
+ # expand masked indices to masked spans
192
+ mask_indices = (
193
+ mask_indices.unsqueeze(dim=-1)
194
+ .expand((batch_size, num_masked_spans, mask_length))
195
+ .reshape(batch_size, num_masked_spans * mask_length)
196
+ )
197
+ offsets = (
198
+ torch.arange(mask_length, device=device)[None, None, :]
199
+ .expand((batch_size, num_masked_spans, mask_length))
200
+ .reshape(batch_size, num_masked_spans * mask_length)
201
+ )
202
+ mask_idxs = mask_indices + offsets
203
+
204
+ # scatter indices to mask
205
+ mask = mask.scatter(1, mask_idxs, True)
206
+
207
+ return mask
208
+
209
+
210
+ def hubert_soft(
211
+ path: str,
212
+ ) -> HubertSoft:
213
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
214
+ Args:
215
+ path (str): path of a pretrained model
216
+ """
217
+ hubert = HubertSoft()
218
+ checkpoint = torch.load(path)
219
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
220
+ hubert.load_state_dict(checkpoint)
221
+ hubert.eval()
222
+ return hubert
so-vits-svc/hubert/hubert_model_onnx.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import random
3
+ from typing import Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as t_func
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+
11
+ class Hubert(nn.Module):
12
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
13
+ super().__init__()
14
+ self._mask = mask
15
+ self.feature_extractor = FeatureExtractor()
16
+ self.feature_projection = FeatureProjection()
17
+ self.positional_embedding = PositionalConvEmbedding()
18
+ self.norm = nn.LayerNorm(768)
19
+ self.dropout = nn.Dropout(0.1)
20
+ self.encoder = TransformerEncoder(
21
+ nn.TransformerEncoderLayer(
22
+ 768, 12, 3072, activation="gelu", batch_first=True
23
+ ),
24
+ 12,
25
+ )
26
+ self.proj = nn.Linear(768, 256)
27
+
28
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
29
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
30
+
31
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
32
+ mask = None
33
+ if self.training and self._mask:
34
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
35
+ x[mask] = self.masked_spec_embed.to(x.dtype)
36
+ return x, mask
37
+
38
+ def encode(
39
+ self, x: torch.Tensor, layer: Optional[int] = None
40
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
41
+ x = self.feature_extractor(x)
42
+ x = self.feature_projection(x.transpose(1, 2))
43
+ x, mask = self.mask(x)
44
+ x = x + self.positional_embedding(x)
45
+ x = self.dropout(self.norm(x))
46
+ x = self.encoder(x, output_layer=layer)
47
+ return x, mask
48
+
49
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
50
+ logits = torch.cosine_similarity(
51
+ x.unsqueeze(2),
52
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
53
+ dim=-1,
54
+ )
55
+ return logits / 0.1
56
+
57
+
58
+ class HubertSoft(Hubert):
59
+ def __init__(self):
60
+ super().__init__()
61
+
62
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
63
+ wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
64
+ x, _ = self.encode(wav)
65
+ return self.proj(x)
66
+
67
+ def forward(self, x):
68
+ return self.units(x)
69
+
70
+ class FeatureExtractor(nn.Module):
71
+ def __init__(self):
72
+ super().__init__()
73
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
74
+ self.norm0 = nn.GroupNorm(512, 512)
75
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
76
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
77
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
78
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
79
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
80
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
81
+
82
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
83
+ x = t_func.gelu(self.norm0(self.conv0(x)))
84
+ x = t_func.gelu(self.conv1(x))
85
+ x = t_func.gelu(self.conv2(x))
86
+ x = t_func.gelu(self.conv3(x))
87
+ x = t_func.gelu(self.conv4(x))
88
+ x = t_func.gelu(self.conv5(x))
89
+ x = t_func.gelu(self.conv6(x))
90
+ return x
91
+
92
+
93
+ class FeatureProjection(nn.Module):
94
+ def __init__(self):
95
+ super().__init__()
96
+ self.norm = nn.LayerNorm(512)
97
+ self.projection = nn.Linear(512, 768)
98
+ self.dropout = nn.Dropout(0.1)
99
+
100
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
101
+ x = self.norm(x)
102
+ x = self.projection(x)
103
+ x = self.dropout(x)
104
+ return x
105
+
106
+
107
+ class PositionalConvEmbedding(nn.Module):
108
+ def __init__(self):
109
+ super().__init__()
110
+ self.conv = nn.Conv1d(
111
+ 768,
112
+ 768,
113
+ kernel_size=128,
114
+ padding=128 // 2,
115
+ groups=16,
116
+ )
117
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
118
+
119
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
120
+ x = self.conv(x.transpose(1, 2))
121
+ x = t_func.gelu(x[:, :, :-1])
122
+ return x.transpose(1, 2)
123
+
124
+
125
+ class TransformerEncoder(nn.Module):
126
+ def __init__(
127
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
128
+ ) -> None:
129
+ super(TransformerEncoder, self).__init__()
130
+ self.layers = nn.ModuleList(
131
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
132
+ )
133
+ self.num_layers = num_layers
134
+
135
+ def forward(
136
+ self,
137
+ src: torch.Tensor,
138
+ mask: torch.Tensor = None,
139
+ src_key_padding_mask: torch.Tensor = None,
140
+ output_layer: Optional[int] = None,
141
+ ) -> torch.Tensor:
142
+ output = src
143
+ for layer in self.layers[:output_layer]:
144
+ output = layer(
145
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
146
+ )
147
+ return output
148
+
149
+
150
+ def _compute_mask(
151
+ shape: Tuple[int, int],
152
+ mask_prob: float,
153
+ mask_length: int,
154
+ device: torch.device,
155
+ min_masks: int = 0,
156
+ ) -> torch.Tensor:
157
+ batch_size, sequence_length = shape
158
+
159
+ if mask_length < 1:
160
+ raise ValueError("`mask_length` has to be bigger than 0.")
161
+
162
+ if mask_length > sequence_length:
163
+ raise ValueError(
164
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
165
+ )
166
+
167
+ # compute number of masked spans in batch
168
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
169
+ num_masked_spans = max(num_masked_spans, min_masks)
170
+
171
+ # make sure num masked indices <= sequence_length
172
+ if num_masked_spans * mask_length > sequence_length:
173
+ num_masked_spans = sequence_length // mask_length
174
+
175
+ # SpecAugment mask to fill
176
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
177
+
178
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
179
+ uniform_dist = torch.ones(
180
+ (batch_size, sequence_length - (mask_length - 1)), device=device
181
+ )
182
+
183
+ # get random indices to mask
184
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
185
+
186
+ # expand masked indices to masked spans
187
+ mask_indices = (
188
+ mask_indices.unsqueeze(dim=-1)
189
+ .expand((batch_size, num_masked_spans, mask_length))
190
+ .reshape(batch_size, num_masked_spans * mask_length)
191
+ )
192
+ offsets = (
193
+ torch.arange(mask_length, device=device)[None, None, :]
194
+ .expand((batch_size, num_masked_spans, mask_length))
195
+ .reshape(batch_size, num_masked_spans * mask_length)
196
+ )
197
+ mask_idxs = mask_indices + offsets
198
+
199
+ # scatter indices to mask
200
+ mask = mask.scatter(1, mask_idxs, True)
201
+
202
+ return mask
203
+
204
+
205
+ def hubert_soft(
206
+ path: str,
207
+ ) -> HubertSoft:
208
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
209
+ Args:
210
+ path (str): path of a pretrained model
211
+ """
212
+ hubert = HubertSoft()
213
+ checkpoint = torch.load(path)
214
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
215
+ hubert.load_state_dict(checkpoint)
216
+ hubert.eval()
217
+ return hubert
so-vits-svc/hubert/put_hubert_ckpt_here ADDED
File without changes
so-vits-svc/inference/__init__.py ADDED
File without changes
so-vits-svc/inference/infer_tool.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import io
3
+ import json
4
+ import logging
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+ from inference import slicer
9
+ import gc
10
+
11
+ import librosa
12
+ import numpy as np
13
+ # import onnxruntime
14
+ import parselmouth
15
+ import soundfile
16
+ import torch
17
+ import torchaudio
18
+
19
+ import cluster
20
+ from hubert import hubert_model
21
+ import utils
22
+ from models import SynthesizerTrn
23
+
24
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
25
+
26
+
27
+ def read_temp(file_name):
28
+ if not os.path.exists(file_name):
29
+ with open(file_name, "w") as f:
30
+ f.write(json.dumps({"info": "temp_dict"}))
31
+ return {}
32
+ else:
33
+ try:
34
+ with open(file_name, "r") as f:
35
+ data = f.read()
36
+ data_dict = json.loads(data)
37
+ if os.path.getsize(file_name) > 50 * 1024 * 1024:
38
+ f_name = file_name.replace("\\", "/").split("/")[-1]
39
+ print(f"clean {f_name}")
40
+ for wav_hash in list(data_dict.keys()):
41
+ if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600:
42
+ del data_dict[wav_hash]
43
+ except Exception as e:
44
+ print(e)
45
+ print(f"{file_name} error,auto rebuild file")
46
+ data_dict = {"info": "temp_dict"}
47
+ return data_dict
48
+
49
+
50
+ def write_temp(file_name, data):
51
+ with open(file_name, "w") as f:
52
+ f.write(json.dumps(data))
53
+
54
+
55
+ def timeit(func):
56
+ def run(*args, **kwargs):
57
+ t = time.time()
58
+ res = func(*args, **kwargs)
59
+ print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t))
60
+ return res
61
+
62
+ return run
63
+
64
+
65
+ def format_wav(audio_path):
66
+ if Path(audio_path).suffix == '.wav':
67
+ return
68
+ raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None)
69
+ soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate)
70
+
71
+
72
+ def get_end_file(dir_path, end):
73
+ file_lists = []
74
+ for root, dirs, files in os.walk(dir_path):
75
+ files = [f for f in files if f[0] != '.']
76
+ dirs[:] = [d for d in dirs if d[0] != '.']
77
+ for f_file in files:
78
+ if f_file.endswith(end):
79
+ file_lists.append(os.path.join(root, f_file).replace("\\", "/"))
80
+ return file_lists
81
+
82
+
83
+ def get_md5(content):
84
+ return hashlib.new("md5", content).hexdigest()
85
+
86
+ def fill_a_to_b(a, b):
87
+ if len(a) < len(b):
88
+ for _ in range(0, len(b) - len(a)):
89
+ a.append(a[0])
90
+
91
+ def mkdir(paths: list):
92
+ for path in paths:
93
+ if not os.path.exists(path):
94
+ os.mkdir(path)
95
+
96
+ def pad_array(arr, target_length):
97
+ current_length = arr.shape[0]
98
+ if current_length >= target_length:
99
+ return arr
100
+ else:
101
+ pad_width = target_length - current_length
102
+ pad_left = pad_width // 2
103
+ pad_right = pad_width - pad_left
104
+ padded_arr = np.pad(arr, (pad_left, pad_right), 'constant', constant_values=(0, 0))
105
+ return padded_arr
106
+
107
+ def split_list_by_n(list_collection, n, pre=0):
108
+ for i in range(0, len(list_collection), n):
109
+ yield list_collection[i-pre if i-pre>=0 else i: i + n]
110
+
111
+
112
+ class F0FilterException(Exception):
113
+ pass
114
+
115
+ class Svc(object):
116
+ def __init__(self, net_g_path, config_path,
117
+ device=None,
118
+ cluster_model_path="logs/44k/kmeans_10000.pt",
119
+ nsf_hifigan_enhance = False
120
+ ):
121
+ self.net_g_path = net_g_path
122
+ if device is None:
123
+ self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
124
+ else:
125
+ self.dev = torch.device(device)
126
+ self.net_g_ms = None
127
+ self.hps_ms = utils.get_hparams_from_file(config_path)
128
+ self.target_sample = self.hps_ms.data.sampling_rate
129
+ self.hop_size = self.hps_ms.data.hop_length
130
+ self.spk2id = self.hps_ms.spk
131
+ self.nsf_hifigan_enhance = nsf_hifigan_enhance
132
+ # load hubert
133
+ self.hubert_model = utils.get_hubert_model().to(self.dev)
134
+ self.load_model()
135
+ if os.path.exists(cluster_model_path):
136
+ self.cluster_model = cluster.get_cluster_model(cluster_model_path)
137
+ if self.nsf_hifigan_enhance:
138
+ from modules.enhancer import Enhancer
139
+ self.enhancer = Enhancer('nsf-hifigan', 'pretrain/nsf_hifigan/model',device=self.dev)
140
+
141
+ def load_model(self):
142
+ # get model configuration
143
+ self.net_g_ms = SynthesizerTrn(
144
+ self.hps_ms.data.filter_length // 2 + 1,
145
+ self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
146
+ **self.hps_ms.model)
147
+ _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
148
+ if "half" in self.net_g_path and torch.cuda.is_available():
149
+ _ = self.net_g_ms.half().eval().to(self.dev)
150
+ else:
151
+ _ = self.net_g_ms.eval().to(self.dev)
152
+
153
+
154
+
155
+ def get_unit_f0(self, in_path, tran, cluster_infer_ratio, speaker, f0_filter ,F0_mean_pooling,cr_threshold=0.05):
156
+
157
+ wav, sr = librosa.load(in_path, sr=self.target_sample)
158
+
159
+ if F0_mean_pooling == True:
160
+ f0, uv = utils.compute_f0_uv_torchcrepe(torch.FloatTensor(wav), sampling_rate=self.target_sample, hop_length=self.hop_size,device=self.dev,cr_threshold = cr_threshold)
161
+ if f0_filter and sum(f0) == 0:
162
+ raise F0FilterException("No voice detected")
163
+ f0 = torch.FloatTensor(list(f0))
164
+ uv = torch.FloatTensor(list(uv))
165
+ if F0_mean_pooling == False:
166
+ f0 = utils.compute_f0_parselmouth(wav, sampling_rate=self.target_sample, hop_length=self.hop_size)
167
+ if f0_filter and sum(f0) == 0:
168
+ raise F0FilterException("No voice detected")
169
+ f0, uv = utils.interpolate_f0(f0)
170
+ f0 = torch.FloatTensor(f0)
171
+ uv = torch.FloatTensor(uv)
172
+
173
+ f0 = f0 * 2 ** (tran / 12)
174
+ f0 = f0.unsqueeze(0).to(self.dev)
175
+ uv = uv.unsqueeze(0).to(self.dev)
176
+
177
+ wav16k = librosa.resample(wav, orig_sr=self.target_sample, target_sr=16000)
178
+ wav16k = torch.from_numpy(wav16k).to(self.dev)
179
+ c = utils.get_hubert_content(self.hubert_model, wav_16k_tensor=wav16k)
180
+ c = utils.repeat_expand_2d(c.squeeze(0), f0.shape[1])
181
+
182
+ if cluster_infer_ratio !=0:
183
+ cluster_c = cluster.get_cluster_center_result(self.cluster_model, c.cpu().numpy().T, speaker).T
184
+ cluster_c = torch.FloatTensor(cluster_c).to(self.dev)
185
+ c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c
186
+
187
+ c = c.unsqueeze(0)
188
+ return c, f0, uv
189
+
190
+ def infer(self, speaker, tran, raw_path,
191
+ cluster_infer_ratio=0,
192
+ auto_predict_f0=False,
193
+ noice_scale=0.4,
194
+ f0_filter=False,
195
+ F0_mean_pooling=False,
196
+ enhancer_adaptive_key = 0,
197
+ cr_threshold = 0.05
198
+ ):
199
+
200
+ speaker_id = self.spk2id.__dict__.get(speaker)
201
+ if not speaker_id and type(speaker) is int:
202
+ if len(self.spk2id.__dict__) >= speaker:
203
+ speaker_id = speaker
204
+ sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0)
205
+ c, f0, uv = self.get_unit_f0(raw_path, tran, cluster_infer_ratio, speaker, f0_filter,F0_mean_pooling,cr_threshold=cr_threshold)
206
+ if "half" in self.net_g_path and torch.cuda.is_available():
207
+ c = c.half()
208
+ with torch.no_grad():
209
+ start = time.time()
210
+ audio = self.net_g_ms.infer(c, f0=f0, g=sid, uv=uv, predict_f0=auto_predict_f0, noice_scale=noice_scale)[0,0].data.float()
211
+ if self.nsf_hifigan_enhance:
212
+ audio, _ = self.enhancer.enhance(
213
+ audio[None,:],
214
+ self.target_sample,
215
+ f0[:,:,None],
216
+ self.hps_ms.data.hop_length,
217
+ adaptive_key = enhancer_adaptive_key)
218
+ use_time = time.time() - start
219
+ print("vits use time:{}".format(use_time))
220
+ return audio, audio.shape[-1]
221
+
222
+ def clear_empty(self):
223
+ # clean up vram
224
+ torch.cuda.empty_cache()
225
+
226
+ def unload_model(self):
227
+ # unload model
228
+ self.net_g_ms = self.net_g_ms.to("cpu")
229
+ del self.net_g_ms
230
+ if hasattr(self,"enhancer"):
231
+ self.enhancer.enhancer = self.enhancer.enhancer.to("cpu")
232
+ del self.enhancer.enhancer
233
+ del self.enhancer
234
+ gc.collect()
235
+
236
+ def slice_inference(self,
237
+ raw_audio_path,
238
+ spk,
239
+ tran,
240
+ slice_db,
241
+ cluster_infer_ratio,
242
+ auto_predict_f0,
243
+ noice_scale,
244
+ pad_seconds=0.5,
245
+ clip_seconds=0,
246
+ lg_num=0,
247
+ lgr_num =0.75,
248
+ F0_mean_pooling = False,
249
+ enhancer_adaptive_key = 0,
250
+ cr_threshold = 0.05
251
+ ):
252
+ wav_path = raw_audio_path
253
+ chunks = slicer.cut(wav_path, db_thresh=slice_db)
254
+ audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks)
255
+ per_size = int(clip_seconds*audio_sr)
256
+ lg_size = int(lg_num*audio_sr)
257
+ lg_size_r = int(lg_size*lgr_num)
258
+ lg_size_c_l = (lg_size-lg_size_r)//2
259
+ lg_size_c_r = lg_size-lg_size_r-lg_size_c_l
260
+ lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0
261
+
262
+ audio = []
263
+ for (slice_tag, data) in audio_data:
264
+ print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======')
265
+ # padd
266
+ length = int(np.ceil(len(data) / audio_sr * self.target_sample))
267
+ if slice_tag:
268
+ print('jump empty segment')
269
+ _audio = np.zeros(length)
270
+ audio.extend(list(pad_array(_audio, length)))
271
+ continue
272
+ if per_size != 0:
273
+ datas = split_list_by_n(data, per_size,lg_size)
274
+ else:
275
+ datas = [data]
276
+ for k,dat in enumerate(datas):
277
+ per_length = int(np.ceil(len(dat) / audio_sr * self.target_sample)) if clip_seconds!=0 else length
278
+ if clip_seconds!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======')
279
+ # padd
280
+ pad_len = int(audio_sr * pad_seconds)
281
+ dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
282
+ raw_path = io.BytesIO()
283
+ soundfile.write(raw_path, dat, audio_sr, format="wav")
284
+ raw_path.seek(0)
285
+ out_audio, out_sr = self.infer(spk, tran, raw_path,
286
+ cluster_infer_ratio=cluster_infer_ratio,
287
+ auto_predict_f0=auto_predict_f0,
288
+ noice_scale=noice_scale,
289
+ F0_mean_pooling = F0_mean_pooling,
290
+ enhancer_adaptive_key = enhancer_adaptive_key,
291
+ cr_threshold = cr_threshold
292
+ )
293
+ _audio = out_audio.cpu().numpy()
294
+ pad_len = int(self.target_sample * pad_seconds)
295
+ _audio = _audio[pad_len:-pad_len]
296
+ _audio = pad_array(_audio, per_length)
297
+ if lg_size!=0 and k!=0:
298
+ lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr_num != 1 else audio[-lg_size:]
299
+ lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr_num != 1 else _audio[0:lg_size]
300
+ lg_pre = lg1*(1-lg)+lg2*lg
301
+ audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr_num != 1 else audio[0:-lg_size]
302
+ audio.extend(lg_pre)
303
+ _audio = _audio[lg_size_c_l+lg_size_r:] if lgr_num != 1 else _audio[lg_size:]
304
+ audio.extend(list(_audio))
305
+ return np.array(audio)
306
+
307
+ class RealTimeVC:
308
+ def __init__(self):
309
+ self.last_chunk = None
310
+ self.last_o = None
311
+ self.chunk_len = 16000 # chunk length
312
+ self.pre_len = 3840 # cross fade length, multiples of 640
313
+
314
+ # Input and output are 1-dimensional numpy waveform arrays
315
+
316
+ def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path,
317
+ cluster_infer_ratio=0,
318
+ auto_predict_f0=False,
319
+ noice_scale=0.4,
320
+ f0_filter=False):
321
+
322
+ import maad
323
+ audio, sr = torchaudio.load(input_wav_path)
324
+ audio = audio.cpu().numpy()[0]
325
+ temp_wav = io.BytesIO()
326
+ if self.last_chunk is None:
327
+ input_wav_path.seek(0)
328
+
329
+ audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path,
330
+ cluster_infer_ratio=cluster_infer_ratio,
331
+ auto_predict_f0=auto_predict_f0,
332
+ noice_scale=noice_scale,
333
+ f0_filter=f0_filter)
334
+
335
+ audio = audio.cpu().numpy()
336
+ self.last_chunk = audio[-self.pre_len:]
337
+ self.last_o = audio
338
+ return audio[-self.chunk_len:]
339
+ else:
340
+ audio = np.concatenate([self.last_chunk, audio])
341
+ soundfile.write(temp_wav, audio, sr, format="wav")
342
+ temp_wav.seek(0)
343
+
344
+ audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav,
345
+ cluster_infer_ratio=cluster_infer_ratio,
346
+ auto_predict_f0=auto_predict_f0,
347
+ noice_scale=noice_scale,
348
+ f0_filter=f0_filter)
349
+
350
+ audio = audio.cpu().numpy()
351
+ ret = maad.util.crossfade(self.last_o, audio, self.pre_len)
352
+ self.last_chunk = audio[-self.pre_len:]
353
+ self.last_o = audio
354
+ return ret[self.chunk_len:2 * self.chunk_len]
so-vits-svc/inference/infer_tool_grad.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import os
5
+ import time
6
+ from pathlib import Path
7
+ import io
8
+ import librosa
9
+ import maad
10
+ import numpy as np
11
+ from inference import slicer
12
+ import parselmouth
13
+ import soundfile
14
+ import torch
15
+ import torchaudio
16
+
17
+ from hubert import hubert_model
18
+ import utils
19
+ from models import SynthesizerTrn
20
+ logging.getLogger('numba').setLevel(logging.WARNING)
21
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
22
+
23
+ def resize2d_f0(x, target_len):
24
+ source = np.array(x)
25
+ source[source < 0.001] = np.nan
26
+ target = np.interp(np.arange(0, len(source) * target_len, len(source)) / target_len, np.arange(0, len(source)),
27
+ source)
28
+ res = np.nan_to_num(target)
29
+ return res
30
+
31
+ def get_f0(x, p_len,f0_up_key=0):
32
+
33
+ time_step = 160 / 16000 * 1000
34
+ f0_min = 50
35
+ f0_max = 1100
36
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
37
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
38
+
39
+ f0 = parselmouth.Sound(x, 16000).to_pitch_ac(
40
+ time_step=time_step / 1000, voicing_threshold=0.6,
41
+ pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
42
+
43
+ pad_size=(p_len - len(f0) + 1) // 2
44
+ if(pad_size>0 or p_len - len(f0) - pad_size>0):
45
+ f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant')
46
+
47
+ f0 *= pow(2, f0_up_key / 12)
48
+ f0_mel = 1127 * np.log(1 + f0 / 700)
49
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (f0_mel_max - f0_mel_min) + 1
50
+ f0_mel[f0_mel <= 1] = 1
51
+ f0_mel[f0_mel > 255] = 255
52
+ f0_coarse = np.rint(f0_mel).astype(np.int)
53
+ return f0_coarse, f0
54
+
55
+ def clean_pitch(input_pitch):
56
+ num_nan = np.sum(input_pitch == 1)
57
+ if num_nan / len(input_pitch) > 0.9:
58
+ input_pitch[input_pitch != 1] = 1
59
+ return input_pitch
60
+
61
+
62
+ def plt_pitch(input_pitch):
63
+ input_pitch = input_pitch.astype(float)
64
+ input_pitch[input_pitch == 1] = np.nan
65
+ return input_pitch
66
+
67
+
68
+ def f0_to_pitch(ff):
69
+ f0_pitch = 69 + 12 * np.log2(ff / 440)
70
+ return f0_pitch
71
+
72
+
73
+ def fill_a_to_b(a, b):
74
+ if len(a) < len(b):
75
+ for _ in range(0, len(b) - len(a)):
76
+ a.append(a[0])
77
+
78
+
79
+ def mkdir(paths: list):
80
+ for path in paths:
81
+ if not os.path.exists(path):
82
+ os.mkdir(path)
83
+
84
+
85
+ class VitsSvc(object):
86
+ def __init__(self):
87
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
88
+ self.SVCVITS = None
89
+ self.hps = None
90
+ self.speakers = None
91
+ self.hubert_soft = utils.get_hubert_model()
92
+
93
+ def set_device(self, device):
94
+ self.device = torch.device(device)
95
+ self.hubert_soft.to(self.device)
96
+ if self.SVCVITS != None:
97
+ self.SVCVITS.to(self.device)
98
+
99
+ def loadCheckpoint(self, path):
100
+ self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
101
+ self.SVCVITS = SynthesizerTrn(
102
+ self.hps.data.filter_length // 2 + 1,
103
+ self.hps.train.segment_size // self.hps.data.hop_length,
104
+ **self.hps.model)
105
+ _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", self.SVCVITS, None)
106
+ _ = self.SVCVITS.eval().to(self.device)
107
+ self.speakers = self.hps.spk
108
+
109
+ def get_units(self, source, sr):
110
+ source = source.unsqueeze(0).to(self.device)
111
+ with torch.inference_mode():
112
+ units = self.hubert_soft.units(source)
113
+ return units
114
+
115
+
116
+ def get_unit_pitch(self, in_path, tran):
117
+ source, sr = torchaudio.load(in_path)
118
+ source = torchaudio.functional.resample(source, sr, 16000)
119
+ if len(source.shape) == 2 and source.shape[1] >= 2:
120
+ source = torch.mean(source, dim=0).unsqueeze(0)
121
+ soft = self.get_units(source, sr).squeeze(0).cpu().numpy()
122
+ f0_coarse, f0 = get_f0(source.cpu().numpy()[0], soft.shape[0]*2, tran)
123
+ return soft, f0
124
+
125
+ def infer(self, speaker_id, tran, raw_path):
126
+ speaker_id = self.speakers[speaker_id]
127
+ sid = torch.LongTensor([int(speaker_id)]).to(self.device).unsqueeze(0)
128
+ soft, pitch = self.get_unit_pitch(raw_path, tran)
129
+ f0 = torch.FloatTensor(clean_pitch(pitch)).unsqueeze(0).to(self.device)
130
+ stn_tst = torch.FloatTensor(soft)
131
+ with torch.no_grad():
132
+ x_tst = stn_tst.unsqueeze(0).to(self.device)
133
+ x_tst = torch.repeat_interleave(x_tst, repeats=2, dim=1).transpose(1, 2)
134
+ audio = self.SVCVITS.infer(x_tst, f0=f0, g=sid)[0,0].data.float()
135
+ return audio, audio.shape[-1]
136
+
137
+ def inference(self,srcaudio,chara,tran,slice_db):
138
+ sampling_rate, audio = srcaudio
139
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
140
+ if len(audio.shape) > 1:
141
+ audio = librosa.to_mono(audio.transpose(1, 0))
142
+ if sampling_rate != 16000:
143
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
144
+ soundfile.write("tmpwav.wav", audio, 16000, format="wav")
145
+ chunks = slicer.cut("tmpwav.wav", db_thresh=slice_db)
146
+ audio_data, audio_sr = slicer.chunks2audio("tmpwav.wav", chunks)
147
+ audio = []
148
+ for (slice_tag, data) in audio_data:
149
+ length = int(np.ceil(len(data) / audio_sr * self.hps.data.sampling_rate))
150
+ raw_path = io.BytesIO()
151
+ soundfile.write(raw_path, data, audio_sr, format="wav")
152
+ raw_path.seek(0)
153
+ if slice_tag:
154
+ _audio = np.zeros(length)
155
+ else:
156
+ out_audio, out_sr = self.infer(chara, tran, raw_path)
157
+ _audio = out_audio.cpu().numpy()
158
+ audio.extend(list(_audio))
159
+ audio = (np.array(audio) * 32768.0).astype('int16')
160
+ return (self.hps.data.sampling_rate,audio)
so-vits-svc/inference/slicer.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import librosa
2
+ import torch
3
+ import torchaudio
4
+
5
+
6
+ class Slicer:
7
+ def __init__(self,
8
+ sr: int,
9
+ threshold: float = -40.,
10
+ min_length: int = 5000,
11
+ min_interval: int = 300,
12
+ hop_size: int = 20,
13
+ max_sil_kept: int = 5000):
14
+ if not min_length >= min_interval >= hop_size:
15
+ raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size')
16
+ if not max_sil_kept >= hop_size:
17
+ raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size')
18
+ min_interval = sr * min_interval / 1000
19
+ self.threshold = 10 ** (threshold / 20.)
20
+ self.hop_size = round(sr * hop_size / 1000)
21
+ self.win_size = min(round(min_interval), 4 * self.hop_size)
22
+ self.min_length = round(sr * min_length / 1000 / self.hop_size)
23
+ self.min_interval = round(min_interval / self.hop_size)
24
+ self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
25
+
26
+ def _apply_slice(self, waveform, begin, end):
27
+ if len(waveform.shape) > 1:
28
+ return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
29
+ else:
30
+ return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
31
+
32
+ # @timeit
33
+ def slice(self, waveform):
34
+ if len(waveform.shape) > 1:
35
+ samples = librosa.to_mono(waveform)
36
+ else:
37
+ samples = waveform
38
+ if samples.shape[0] <= self.min_length:
39
+ return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}}
40
+ rms_list = librosa.feature.rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
41
+ sil_tags = []
42
+ silence_start = None
43
+ clip_start = 0
44
+ for i, rms in enumerate(rms_list):
45
+ # Keep looping while frame is silent.
46
+ if rms < self.threshold:
47
+ # Record start of silent frames.
48
+ if silence_start is None:
49
+ silence_start = i
50
+ continue
51
+ # Keep looping while frame is not silent and silence start has not been recorded.
52
+ if silence_start is None:
53
+ continue
54
+ # Clear recorded silence start if interval is not enough or clip is too short
55
+ is_leading_silence = silence_start == 0 and i > self.max_sil_kept
56
+ need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
57
+ if not is_leading_silence and not need_slice_middle:
58
+ silence_start = None
59
+ continue
60
+ # Need slicing. Record the range of silent frames to be removed.
61
+ if i - silence_start <= self.max_sil_kept:
62
+ pos = rms_list[silence_start: i + 1].argmin() + silence_start
63
+ if silence_start == 0:
64
+ sil_tags.append((0, pos))
65
+ else:
66
+ sil_tags.append((pos, pos))
67
+ clip_start = pos
68
+ elif i - silence_start <= self.max_sil_kept * 2:
69
+ pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
70
+ pos += i - self.max_sil_kept
71
+ pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
72
+ pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
73
+ if silence_start == 0:
74
+ sil_tags.append((0, pos_r))
75
+ clip_start = pos_r
76
+ else:
77
+ sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
78
+ clip_start = max(pos_r, pos)
79
+ else:
80
+ pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
81
+ pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
82
+ if silence_start == 0:
83
+ sil_tags.append((0, pos_r))
84
+ else:
85
+ sil_tags.append((pos_l, pos_r))
86
+ clip_start = pos_r
87
+ silence_start = None
88
+ # Deal with trailing silence.
89
+ total_frames = rms_list.shape[0]
90
+ if silence_start is not None and total_frames - silence_start >= self.min_interval:
91
+ silence_end = min(total_frames, silence_start + self.max_sil_kept)
92
+ pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
93
+ sil_tags.append((pos, total_frames + 1))
94
+ # Apply and return slices.
95
+ if len(sil_tags) == 0:
96
+ return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}}
97
+ else:
98
+ chunks = []
99
+ # The first segment is not the beginning of the audio.
100
+ if sil_tags[0][0]:
101
+ chunks.append(
102
+ {"slice": False, "split_time": f"0,{min(waveform.shape[0], sil_tags[0][0] * self.hop_size)}"})
103
+ for i in range(0, len(sil_tags)):
104
+ # Mark audio segment. Skip the first segment.
105
+ if i:
106
+ chunks.append({"slice": False,
107
+ "split_time": f"{sil_tags[i - 1][1] * self.hop_size},{min(waveform.shape[0], sil_tags[i][0] * self.hop_size)}"})
108
+ # Mark all mute segments
109
+ chunks.append({"slice": True,
110
+ "split_time": f"{sil_tags[i][0] * self.hop_size},{min(waveform.shape[0], sil_tags[i][1] * self.hop_size)}"})
111
+ # The last segment is not the end.
112
+ if sil_tags[-1][1] * self.hop_size < len(waveform):
113
+ chunks.append({"slice": False, "split_time": f"{sil_tags[-1][1] * self.hop_size},{len(waveform)}"})
114
+ chunk_dict = {}
115
+ for i in range(len(chunks)):
116
+ chunk_dict[str(i)] = chunks[i]
117
+ return chunk_dict
118
+
119
+
120
+ def cut(audio_path, db_thresh=-30, min_len=5000):
121
+ audio, sr = librosa.load(audio_path, sr=None)
122
+ slicer = Slicer(
123
+ sr=sr,
124
+ threshold=db_thresh,
125
+ min_length=min_len
126
+ )
127
+ chunks = slicer.slice(audio)
128
+ return chunks
129
+
130
+
131
+ def chunks2audio(audio_path, chunks):
132
+ chunks = dict(chunks)
133
+ audio, sr = torchaudio.load(audio_path)
134
+ if len(audio.shape) == 2 and audio.shape[1] >= 2:
135
+ audio = torch.mean(audio, dim=0).unsqueeze(0)
136
+ audio = audio.cpu().numpy()[0]
137
+ result = []
138
+ for k, v in chunks.items():
139
+ tag = v["split_time"].split(",")
140
+ if tag[0] != tag[1]:
141
+ result.append((v["slice"], audio[int(tag[0]):int(tag[1])]))
142
+ return result, sr
so-vits-svc/inference_main.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Required
26
+ parser.add_argument('-m', '--model_path', type=str, default="logs/44k/G_0.pth",
27
+ help='Path to the model.')
28
+ parser.add_argument('-c', '--config_path', type=str, default="configs/config.json",
29
+ help='Path to the configuration file.')
30
+ parser.add_argument('-s', '--spk_list', type=str, nargs='+', default=['nen'],
31
+ help='Target speaker name for conversion.')
32
+ parser.add_argument('-n', '--clean_names', type=str, nargs='+', default=["君の知らない物語-src.wav"],
33
+ help='A list of wav file names located in the raw folder.')
34
+ parser.add_argument('-t', '--trans', type=int, nargs='+', default=[0],
35
+ help='Pitch adjustment, supports positive and negative (semitone) values.')
36
+
37
+ # Optional
38
+ parser.add_argument('-a', '--auto_predict_f0', action='store_true', default=False,
39
+ help='Automatic pitch prediction for voice conversion. Do not enable this when converting songs as it can cause serious pitch issues.')
40
+ parser.add_argument('-cl', '--clip', type=float, default=0,
41
+ help='Voice forced slicing. Set to 0 to turn off(default), duration in seconds.')
42
+ parser.add_argument('-lg', '--linear_gradient', type=float, default=0,
43
+ help='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. Default 0.')
44
+ parser.add_argument('-cm', '--cluster_model_path', type=str, default="logs/44k/kmeans_10000.pt",
45
+ help='Path to the clustering model. Fill in any value if clustering is not trained.')
46
+ parser.add_argument('-cr', '--cluster_infer_ratio', type=float, default=0,
47
+ help='Proportion of the clustering solution, range 0-1. Fill in 0 if the clustering model is not trained.')
48
+ parser.add_argument('-fmp', '--f0_mean_pooling', action='store_true', default=False,
49
+ help='Apply mean filter (pooling) to f0, which may improve some hoarse sounds. Enabling this option will reduce inference speed.')
50
+ parser.add_argument('-eh', '--enhance', action='store_true', default=False,
51
+ help='Whether to use NSF_HIFIGAN enhancer. This option has certain effect on sound quality enhancement for some models with few training sets, but has negative effect on well-trained models, so it is turned off by default.')
52
+
53
+ # generally keep default
54
+ parser.add_argument('-sd', '--slice_db', type=int, default=-40,
55
+ help='Loudness for automatic slicing. For noisy audio it can be set to -30')
56
+ parser.add_argument('-d', '--device', type=str, default=None,
57
+ help='Device used for inference. None means auto selecting.')
58
+ parser.add_argument('-ns', '--noice_scale', type=float, default=0.4,
59
+ help='Affect pronunciation and sound quality.')
60
+ parser.add_argument('-p', '--pad_seconds', type=float, default=0.5,
61
+ help='Due to unknown reasons, there may be abnormal noise at the beginning and end. It will disappear after padding a short silent segment.')
62
+ parser.add_argument('-wf', '--wav_format', type=str, default='flac',
63
+ help='output format')
64
+ parser.add_argument('-lgr', '--linear_gradient_retain', type=float, default=0.75,
65
+ help='Proportion of cross length retention, range (0-1]. After forced slicing, the beginning and end of each segment need to be discarded.')
66
+ parser.add_argument('-eak', '--enhancer_adaptive_key', type=int, default=0,
67
+ help='Adapt the enhancer to a higher range of sound. The unit is the semitones, default 0.')
68
+ parser.add_argument('-ft', '--f0_filter_threshold', type=float, default=0.05,
69
+ help='F0 Filtering threshold: This parameter is valid only when f0_mean_pooling is enabled. Values range from 0 to 1. Reducing this value reduces the probability of being out of tune, but increases matte.')
70
+
71
+
72
+ args = parser.parse_args()
73
+
74
+ clean_names = args.clean_names
75
+ trans = args.trans
76
+ spk_list = args.spk_list
77
+ slice_db = args.slice_db
78
+ wav_format = args.wav_format
79
+ auto_predict_f0 = args.auto_predict_f0
80
+ cluster_infer_ratio = args.cluster_infer_ratio
81
+ noice_scale = args.noice_scale
82
+ pad_seconds = args.pad_seconds
83
+ clip = args.clip
84
+ lg = args.linear_gradient
85
+ lgr = args.linear_gradient_retain
86
+ F0_mean_pooling = args.f0_mean_pooling
87
+ enhance = args.enhance
88
+ enhancer_adaptive_key = args.enhancer_adaptive_key
89
+ cr_threshold = args.f0_filter_threshold
90
+
91
+ svc_model = Svc(args.model_path, args.config_path, args.device, args.cluster_model_path,enhance)
92
+ infer_tool.mkdir(["raw", "results"])
93
+
94
+ infer_tool.fill_a_to_b(trans, clean_names)
95
+ for clean_name, tran in zip(clean_names, trans):
96
+ raw_audio_path = f"raw/{clean_name}"
97
+ if "." not in raw_audio_path:
98
+ raw_audio_path += ".wav"
99
+ infer_tool.format_wav(raw_audio_path)
100
+ wav_path = Path(raw_audio_path).with_suffix('.wav')
101
+ chunks = slicer.cut(wav_path, db_thresh=slice_db)
102
+ audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks)
103
+ per_size = int(clip*audio_sr)
104
+ lg_size = int(lg*audio_sr)
105
+ lg_size_r = int(lg_size*lgr)
106
+ lg_size_c_l = (lg_size-lg_size_r)//2
107
+ lg_size_c_r = lg_size-lg_size_r-lg_size_c_l
108
+ lg = np.linspace(0,1,lg_size_r) if lg_size!=0 else 0
109
+
110
+ for spk in spk_list:
111
+ audio = []
112
+ for (slice_tag, data) in audio_data:
113
+ print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======')
114
+
115
+ length = int(np.ceil(len(data) / audio_sr * svc_model.target_sample))
116
+ if slice_tag:
117
+ print('jump empty segment')
118
+ _audio = np.zeros(length)
119
+ audio.extend(list(infer_tool.pad_array(_audio, length)))
120
+ continue
121
+ if per_size != 0:
122
+ datas = infer_tool.split_list_by_n(data, per_size,lg_size)
123
+ else:
124
+ datas = [data]
125
+ for k,dat in enumerate(datas):
126
+ per_length = int(np.ceil(len(dat) / audio_sr * svc_model.target_sample)) if clip!=0 else length
127
+ if clip!=0: print(f'###=====segment clip start, {round(len(dat) / audio_sr, 3)}s======')
128
+ # padd
129
+ pad_len = int(audio_sr * pad_seconds)
130
+ dat = np.concatenate([np.zeros([pad_len]), dat, np.zeros([pad_len])])
131
+ raw_path = io.BytesIO()
132
+ soundfile.write(raw_path, dat, audio_sr, format="wav")
133
+ raw_path.seek(0)
134
+ out_audio, out_sr = svc_model.infer(spk, tran, raw_path,
135
+ cluster_infer_ratio=cluster_infer_ratio,
136
+ auto_predict_f0=auto_predict_f0,
137
+ noice_scale=noice_scale,
138
+ F0_mean_pooling = F0_mean_pooling,
139
+ enhancer_adaptive_key = enhancer_adaptive_key,
140
+ cr_threshold = cr_threshold
141
+ )
142
+ _audio = out_audio.cpu().numpy()
143
+ pad_len = int(svc_model.target_sample * pad_seconds)
144
+ _audio = _audio[pad_len:-pad_len]
145
+ _audio = infer_tool.pad_array(_audio, per_length)
146
+ if lg_size!=0 and k!=0:
147
+ lg1 = audio[-(lg_size_r+lg_size_c_r):-lg_size_c_r] if lgr != 1 else audio[-lg_size:]
148
+ lg2 = _audio[lg_size_c_l:lg_size_c_l+lg_size_r] if lgr != 1 else _audio[0:lg_size]
149
+ lg_pre = lg1*(1-lg)+lg2*lg
150
+ audio = audio[0:-(lg_size_r+lg_size_c_r)] if lgr != 1 else audio[0:-lg_size]
151
+ audio.extend(lg_pre)
152
+ _audio = _audio[lg_size_c_l+lg_size_r:] if lgr != 1 else _audio[lg_size:]
153
+ audio.extend(list(_audio))
154
+ key = "auto" if auto_predict_f0 else f"{tran}key"
155
+ cluster_name = "" if cluster_infer_ratio == 0 else f"_{cluster_infer_ratio}"
156
+ res_path = f'./results/{clean_name}_{key}_{spk}{cluster_name}.{wav_format}'
157
+ soundfile.write(res_path, audio, svc_model.target_sample, format=wav_format)
158
+ svc_model.clear_empty()
159
+
160
+ if __name__ == '__main__':
161
+ main()
so-vits-svc/logs/44k/put_pretrained_model_here ADDED
File without changes
so-vits-svc/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
so-vits-svc/modules/__init__.py ADDED
File without changes
so-vits-svc/modules/attentions.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import modules.commons as commons
9
+ import modules.modules as modules
10
+ from modules.modules import LayerNorm
11
+
12
+
13
+ class FFT(nn.Module):
14
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p_dropout=0.,
15
+ proximal_bias=False, proximal_init=True, **kwargs):
16
+ super().__init__()
17
+ self.hidden_channels = hidden_channels
18
+ self.filter_channels = filter_channels
19
+ self.n_heads = n_heads
20
+ self.n_layers = n_layers
21
+ self.kernel_size = kernel_size
22
+ self.p_dropout = p_dropout
23
+ self.proximal_bias = proximal_bias
24
+ self.proximal_init = proximal_init
25
+
26
+ self.drop = nn.Dropout(p_dropout)
27
+ self.self_attn_layers = nn.ModuleList()
28
+ self.norm_layers_0 = nn.ModuleList()
29
+ self.ffn_layers = nn.ModuleList()
30
+ self.norm_layers_1 = nn.ModuleList()
31
+ for i in range(self.n_layers):
32
+ self.self_attn_layers.append(
33
+ MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias,
34
+ proximal_init=proximal_init))
35
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
36
+ self.ffn_layers.append(
37
+ FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
38
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
39
+
40
+ def forward(self, x, x_mask):
41
+ """
42
+ x: decoder input
43
+ h: encoder output
44
+ """
45
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
46
+ x = x * x_mask
47
+ for i in range(self.n_layers):
48
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
49
+ y = self.drop(y)
50
+ x = self.norm_layers_0[i](x + y)
51
+
52
+ y = self.ffn_layers[i](x, x_mask)
53
+ y = self.drop(y)
54
+ x = self.norm_layers_1[i](x + y)
55
+ x = x * x_mask
56
+ return x
57
+
58
+
59
+ class Encoder(nn.Module):
60
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
61
+ super().__init__()
62
+ self.hidden_channels = hidden_channels
63
+ self.filter_channels = filter_channels
64
+ self.n_heads = n_heads
65
+ self.n_layers = n_layers
66
+ self.kernel_size = kernel_size
67
+ self.p_dropout = p_dropout
68
+ self.window_size = window_size
69
+
70
+ self.drop = nn.Dropout(p_dropout)
71
+ self.attn_layers = nn.ModuleList()
72
+ self.norm_layers_1 = nn.ModuleList()
73
+ self.ffn_layers = nn.ModuleList()
74
+ self.norm_layers_2 = nn.ModuleList()
75
+ for i in range(self.n_layers):
76
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
77
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
78
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
79
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
80
+
81
+ def forward(self, x, x_mask):
82
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
83
+ x = x * x_mask
84
+ for i in range(self.n_layers):
85
+ y = self.attn_layers[i](x, x, attn_mask)
86
+ y = self.drop(y)
87
+ x = self.norm_layers_1[i](x + y)
88
+
89
+ y = self.ffn_layers[i](x, x_mask)
90
+ y = self.drop(y)
91
+ x = self.norm_layers_2[i](x + y)
92
+ x = x * x_mask
93
+ return x
94
+
95
+
96
+ class Decoder(nn.Module):
97
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
98
+ super().__init__()
99
+ self.hidden_channels = hidden_channels
100
+ self.filter_channels = filter_channels
101
+ self.n_heads = n_heads
102
+ self.n_layers = n_layers
103
+ self.kernel_size = kernel_size
104
+ self.p_dropout = p_dropout
105
+ self.proximal_bias = proximal_bias
106
+ self.proximal_init = proximal_init
107
+
108
+ self.drop = nn.Dropout(p_dropout)
109
+ self.self_attn_layers = nn.ModuleList()
110
+ self.norm_layers_0 = nn.ModuleList()
111
+ self.encdec_attn_layers = nn.ModuleList()
112
+ self.norm_layers_1 = nn.ModuleList()
113
+ self.ffn_layers = nn.ModuleList()
114
+ self.norm_layers_2 = nn.ModuleList()
115
+ for i in range(self.n_layers):
116
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
117
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
118
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
119
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
120
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
121
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
122
+
123
+ def forward(self, x, x_mask, h, h_mask):
124
+ """
125
+ x: decoder input
126
+ h: encoder output
127
+ """
128
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
129
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
130
+ x = x * x_mask
131
+ for i in range(self.n_layers):
132
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
133
+ y = self.drop(y)
134
+ x = self.norm_layers_0[i](x + y)
135
+
136
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
137
+ y = self.drop(y)
138
+ x = self.norm_layers_1[i](x + y)
139
+
140
+ y = self.ffn_layers[i](x, x_mask)
141
+ y = self.drop(y)
142
+ x = self.norm_layers_2[i](x + y)
143
+ x = x * x_mask
144
+ return x
145
+
146
+
147
+ class MultiHeadAttention(nn.Module):
148
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
149
+ super().__init__()
150
+ assert channels % n_heads == 0
151
+
152
+ self.channels = channels
153
+ self.out_channels = out_channels
154
+ self.n_heads = n_heads
155
+ self.p_dropout = p_dropout
156
+ self.window_size = window_size
157
+ self.heads_share = heads_share
158
+ self.block_length = block_length
159
+ self.proximal_bias = proximal_bias
160
+ self.proximal_init = proximal_init
161
+ self.attn = None
162
+
163
+ self.k_channels = channels // n_heads
164
+ self.conv_q = nn.Conv1d(channels, channels, 1)
165
+ self.conv_k = nn.Conv1d(channels, channels, 1)
166
+ self.conv_v = nn.Conv1d(channels, channels, 1)
167
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
168
+ self.drop = nn.Dropout(p_dropout)
169
+
170
+ if window_size is not None:
171
+ n_heads_rel = 1 if heads_share else n_heads
172
+ rel_stddev = self.k_channels**-0.5
173
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
174
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
175
+
176
+ nn.init.xavier_uniform_(self.conv_q.weight)
177
+ nn.init.xavier_uniform_(self.conv_k.weight)
178
+ nn.init.xavier_uniform_(self.conv_v.weight)
179
+ if proximal_init:
180
+ with torch.no_grad():
181
+ self.conv_k.weight.copy_(self.conv_q.weight)
182
+ self.conv_k.bias.copy_(self.conv_q.bias)
183
+
184
+ def forward(self, x, c, attn_mask=None):
185
+ q = self.conv_q(x)
186
+ k = self.conv_k(c)
187
+ v = self.conv_v(c)
188
+
189
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
190
+
191
+ x = self.conv_o(x)
192
+ return x
193
+
194
+ def attention(self, query, key, value, mask=None):
195
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
196
+ b, d, t_s, t_t = (*key.size(), query.size(2))
197
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
198
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
199
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
200
+
201
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
202
+ if self.window_size is not None:
203
+ assert t_s == t_t, "Relative attention is only available for self-attention."
204
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
205
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
206
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
207
+ scores = scores + scores_local
208
+ if self.proximal_bias:
209
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
210
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
211
+ if mask is not None:
212
+ scores = scores.masked_fill(mask == 0, -1e4)
213
+ if self.block_length is not None:
214
+ assert t_s == t_t, "Local attention is only available for self-attention."
215
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
216
+ scores = scores.masked_fill(block_mask == 0, -1e4)
217
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
218
+ p_attn = self.drop(p_attn)
219
+ output = torch.matmul(p_attn, value)
220
+ if self.window_size is not None:
221
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
222
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
223
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
224
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
225
+ return output, p_attn
226
+
227
+ def _matmul_with_relative_values(self, x, y):
228
+ """
229
+ x: [b, h, l, m]
230
+ y: [h or 1, m, d]
231
+ ret: [b, h, l, d]
232
+ """
233
+ ret = torch.matmul(x, y.unsqueeze(0))
234
+ return ret
235
+
236
+ def _matmul_with_relative_keys(self, x, y):
237
+ """
238
+ x: [b, h, l, d]
239
+ y: [h or 1, m, d]
240
+ ret: [b, h, l, m]
241
+ """
242
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
243
+ return ret
244
+
245
+ def _get_relative_embeddings(self, relative_embeddings, length):
246
+ max_relative_position = 2 * self.window_size + 1
247
+ # Pad first before slice to avoid using cond ops.
248
+ pad_length = max(length - (self.window_size + 1), 0)
249
+ slice_start_position = max((self.window_size + 1) - length, 0)
250
+ slice_end_position = slice_start_position + 2 * length - 1
251
+ if pad_length > 0:
252
+ padded_relative_embeddings = F.pad(
253
+ relative_embeddings,
254
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
255
+ else:
256
+ padded_relative_embeddings = relative_embeddings
257
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
258
+ return used_relative_embeddings
259
+
260
+ def _relative_position_to_absolute_position(self, x):
261
+ """
262
+ x: [b, h, l, 2*l-1]
263
+ ret: [b, h, l, l]
264
+ """
265
+ batch, heads, length, _ = x.size()
266
+ # Concat columns of pad to shift from relative to absolute indexing.
267
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
268
+
269
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
270
+ x_flat = x.view([batch, heads, length * 2 * length])
271
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
272
+
273
+ # Reshape and slice out the padded elements.
274
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
275
+ return x_final
276
+
277
+ def _absolute_position_to_relative_position(self, x):
278
+ """
279
+ x: [b, h, l, l]
280
+ ret: [b, h, l, 2*l-1]
281
+ """
282
+ batch, heads, length, _ = x.size()
283
+ # padd along column
284
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
285
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
286
+ # add 0's in the beginning that will skew the elements after reshape
287
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
288
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
289
+ return x_final
290
+
291
+ def _attention_bias_proximal(self, length):
292
+ """Bias for self-attention to encourage attention to close positions.
293
+ Args:
294
+ length: an integer scalar.
295
+ Returns:
296
+ a Tensor with shape [1, 1, length, length]
297
+ """
298
+ r = torch.arange(length, dtype=torch.float32)
299
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
300
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
301
+
302
+
303
+ class FFN(nn.Module):
304
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
305
+ super().__init__()
306
+ self.in_channels = in_channels
307
+ self.out_channels = out_channels
308
+ self.filter_channels = filter_channels
309
+ self.kernel_size = kernel_size
310
+ self.p_dropout = p_dropout
311
+ self.activation = activation
312
+ self.causal = causal
313
+
314
+ if causal:
315
+ self.padding = self._causal_padding
316
+ else:
317
+ self.padding = self._same_padding
318
+
319
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
320
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
321
+ self.drop = nn.Dropout(p_dropout)
322
+
323
+ def forward(self, x, x_mask):
324
+ x = self.conv_1(self.padding(x * x_mask))
325
+ if self.activation == "gelu":
326
+ x = x * torch.sigmoid(1.702 * x)
327
+ else:
328
+ x = torch.relu(x)
329
+ x = self.drop(x)
330
+ x = self.conv_2(self.padding(x * x_mask))
331
+ return x * x_mask
332
+
333
+ def _causal_padding(self, x):
334
+ if self.kernel_size == 1:
335
+ return x
336
+ pad_l = self.kernel_size - 1
337
+ pad_r = 0
338
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
339
+ x = F.pad(x, commons.convert_pad_shape(padding))
340
+ return x
341
+
342
+ def _same_padding(self, x):
343
+ if self.kernel_size == 1:
344
+ return x
345
+ pad_l = (self.kernel_size - 1) // 2
346
+ pad_r = self.kernel_size // 2
347
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
348
+ x = F.pad(x, commons.convert_pad_shape(padding))
349
+ return x
so-vits-svc/modules/commons.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def slice_pitch_segments(x, ids_str, segment_size=4):
8
+ ret = torch.zeros_like(x[:, :segment_size])
9
+ for i in range(x.size(0)):
10
+ idx_str = ids_str[i]
11
+ idx_end = idx_str + segment_size
12
+ ret[i] = x[i, idx_str:idx_end]
13
+ return ret
14
+
15
+ def rand_slice_segments_with_pitch(x, pitch, x_lengths=None, segment_size=4):
16
+ b, d, t = x.size()
17
+ if x_lengths is None:
18
+ x_lengths = t
19
+ ids_str_max = x_lengths - segment_size + 1
20
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
21
+ ret = slice_segments(x, ids_str, segment_size)
22
+ ret_pitch = slice_pitch_segments(pitch, ids_str, segment_size)
23
+ return ret, ret_pitch, ids_str
24
+
25
+ def init_weights(m, mean=0.0, std=0.01):
26
+ classname = m.__class__.__name__
27
+ if classname.find("Conv") != -1:
28
+ m.weight.data.normal_(mean, std)
29
+
30
+
31
+ def get_padding(kernel_size, dilation=1):
32
+ return int((kernel_size*dilation - dilation)/2)
33
+
34
+
35
+ def convert_pad_shape(pad_shape):
36
+ l = pad_shape[::-1]
37
+ pad_shape = [item for sublist in l for item in sublist]
38
+ return pad_shape
39
+
40
+
41
+ def intersperse(lst, item):
42
+ result = [item] * (len(lst) * 2 + 1)
43
+ result[1::2] = lst
44
+ return result
45
+
46
+
47
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
48
+ """KL(P||Q)"""
49
+ kl = (logs_q - logs_p) - 0.5
50
+ kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
51
+ return kl
52
+
53
+
54
+ def rand_gumbel(shape):
55
+ """Sample from the Gumbel distribution, protect from overflows."""
56
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
57
+ return -torch.log(-torch.log(uniform_samples))
58
+
59
+
60
+ def rand_gumbel_like(x):
61
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
62
+ return g
63
+
64
+
65
+ def slice_segments(x, ids_str, segment_size=4):
66
+ ret = torch.zeros_like(x[:, :, :segment_size])
67
+ for i in range(x.size(0)):
68
+ idx_str = ids_str[i]
69
+ idx_end = idx_str + segment_size
70
+ ret[i] = x[i, :, idx_str:idx_end]
71
+ return ret
72
+
73
+
74
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
75
+ b, d, t = x.size()
76
+ if x_lengths is None:
77
+ x_lengths = t
78
+ ids_str_max = x_lengths - segment_size + 1
79
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
80
+ ret = slice_segments(x, ids_str, segment_size)
81
+ return ret, ids_str
82
+
83
+
84
+ def rand_spec_segments(x, x_lengths=None, segment_size=4):
85
+ b, d, t = x.size()
86
+ if x_lengths is None:
87
+ x_lengths = t
88
+ ids_str_max = x_lengths - segment_size
89
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
90
+ ret = slice_segments(x, ids_str, segment_size)
91
+ return ret, ids_str
92
+
93
+
94
+ def get_timing_signal_1d(
95
+ length, channels, min_timescale=1.0, max_timescale=1.0e4):
96
+ position = torch.arange(length, dtype=torch.float)
97
+ num_timescales = channels // 2
98
+ log_timescale_increment = (
99
+ math.log(float(max_timescale) / float(min_timescale)) /
100
+ (num_timescales - 1))
101
+ inv_timescales = min_timescale * torch.exp(
102
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
103
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
104
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
105
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
106
+ signal = signal.view(1, channels, length)
107
+ return signal
108
+
109
+
110
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
111
+ b, channels, length = x.size()
112
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
113
+ return x + signal.to(dtype=x.dtype, device=x.device)
114
+
115
+
116
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
117
+ b, channels, length = x.size()
118
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
119
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
120
+
121
+
122
+ def subsequent_mask(length):
123
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
124
+ return mask
125
+
126
+
127
+ @torch.jit.script
128
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
129
+ n_channels_int = n_channels[0]
130
+ in_act = input_a + input_b
131
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
132
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
133
+ acts = t_act * s_act
134
+ return acts
135
+
136
+
137
+ def convert_pad_shape(pad_shape):
138
+ l = pad_shape[::-1]
139
+ pad_shape = [item for sublist in l for item in sublist]
140
+ return pad_shape
141
+
142
+
143
+ def shift_1d(x):
144
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
145
+ return x
146
+
147
+
148
+ def sequence_mask(length, max_length=None):
149
+ if max_length is None:
150
+ max_length = length.max()
151
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
152
+ return x.unsqueeze(0) < length.unsqueeze(1)
153
+
154
+
155
+ def generate_path(duration, mask):
156
+ """
157
+ duration: [b, 1, t_x]
158
+ mask: [b, 1, t_y, t_x]
159
+ """
160
+ device = duration.device
161
+
162
+ b, _, t_y, t_x = mask.shape
163
+ cum_duration = torch.cumsum(duration, -1)
164
+
165
+ cum_duration_flat = cum_duration.view(b * t_x)
166
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
167
+ path = path.view(b, t_x, t_y)
168
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
169
+ path = path.unsqueeze(1).transpose(2,3) * mask
170
+ return path
171
+
172
+
173
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
174
+ if isinstance(parameters, torch.Tensor):
175
+ parameters = [parameters]
176
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
177
+ norm_type = float(norm_type)
178
+ if clip_value is not None:
179
+ clip_value = float(clip_value)
180
+
181
+ total_norm = 0
182
+ for p in parameters:
183
+ param_norm = p.grad.data.norm(norm_type)
184
+ total_norm += param_norm.item() ** norm_type
185
+ if clip_value is not None:
186
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
187
+ total_norm = total_norm ** (1. / norm_type)
188
+ return total_norm
so-vits-svc/modules/crepe.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional,Union
2
+ try:
3
+ from typing import Literal
4
+ except Exception as e:
5
+ from typing_extensions import Literal
6
+ import numpy as np
7
+ import torch
8
+ import torchcrepe
9
+ from torch import nn
10
+ from torch.nn import functional as F
11
+ import scipy
12
+
13
+ #from:https://github.com/fishaudio/fish-diffusion
14
+
15
+ def repeat_expand(
16
+ content: Union[torch.Tensor, np.ndarray], target_len: int, mode: str = "nearest"
17
+ ):
18
+ """Repeat content to target length.
19
+ This is a wrapper of torch.nn.functional.interpolate.
20
+
21
+ Args:
22
+ content (torch.Tensor): tensor
23
+ target_len (int): target length
24
+ mode (str, optional): interpolation mode. Defaults to "nearest".
25
+
26
+ Returns:
27
+ torch.Tensor: tensor
28
+ """
29
+
30
+ ndim = content.ndim
31
+
32
+ if content.ndim == 1:
33
+ content = content[None, None]
34
+ elif content.ndim == 2:
35
+ content = content[None]
36
+
37
+ assert content.ndim == 3
38
+
39
+ is_np = isinstance(content, np.ndarray)
40
+ if is_np:
41
+ content = torch.from_numpy(content)
42
+
43
+ results = torch.nn.functional.interpolate(content, size=target_len, mode=mode)
44
+
45
+ if is_np:
46
+ results = results.numpy()
47
+
48
+ if ndim == 1:
49
+ return results[0, 0]
50
+ elif ndim == 2:
51
+ return results[0]
52
+
53
+
54
+ class BasePitchExtractor:
55
+ def __init__(
56
+ self,
57
+ hop_length: int = 512,
58
+ f0_min: float = 50.0,
59
+ f0_max: float = 1100.0,
60
+ keep_zeros: bool = True,
61
+ ):
62
+ """Base pitch extractor.
63
+
64
+ Args:
65
+ hop_length (int, optional): Hop length. Defaults to 512.
66
+ f0_min (float, optional): Minimum f0. Defaults to 50.0.
67
+ f0_max (float, optional): Maximum f0. Defaults to 1100.0.
68
+ keep_zeros (bool, optional): Whether keep zeros in pitch. Defaults to True.
69
+ """
70
+
71
+ self.hop_length = hop_length
72
+ self.f0_min = f0_min
73
+ self.f0_max = f0_max
74
+ self.keep_zeros = keep_zeros
75
+
76
+ def __call__(self, x, sampling_rate=44100, pad_to=None):
77
+ raise NotImplementedError("BasePitchExtractor is not callable.")
78
+
79
+ def post_process(self, x, sampling_rate, f0, pad_to):
80
+ if isinstance(f0, np.ndarray):
81
+ f0 = torch.from_numpy(f0).float().to(x.device)
82
+
83
+ if pad_to is None:
84
+ return f0
85
+
86
+ f0 = repeat_expand(f0, pad_to)
87
+
88
+ if self.keep_zeros:
89
+ return f0
90
+
91
+ vuv_vector = torch.zeros_like(f0)
92
+ vuv_vector[f0 > 0.0] = 1.0
93
+ vuv_vector[f0 <= 0.0] = 0.0
94
+
95
+ # Remove 0 frequency and apply linear interpolation
96
+ nzindex = torch.nonzero(f0).squeeze()
97
+ f0 = torch.index_select(f0, dim=0, index=nzindex).cpu().numpy()
98
+ time_org = self.hop_length / sampling_rate * nzindex.cpu().numpy()
99
+ time_frame = np.arange(pad_to) * self.hop_length / sampling_rate
100
+
101
+ if f0.shape[0] <= 0:
102
+ return torch.zeros(pad_to, dtype=torch.float, device=x.device),torch.zeros(pad_to, dtype=torch.float, device=x.device)
103
+
104
+ if f0.shape[0] == 1:
105
+ return torch.ones(pad_to, dtype=torch.float, device=x.device) * f0[0],torch.ones(pad_to, dtype=torch.float, device=x.device)
106
+
107
+ # Probably can be rewritten with torch?
108
+ f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
109
+ vuv_vector = vuv_vector.cpu().numpy()
110
+ vuv_vector = np.ceil(scipy.ndimage.zoom(vuv_vector,pad_to/len(vuv_vector),order = 0))
111
+
112
+ return f0,vuv_vector
113
+
114
+
115
+ class MaskedAvgPool1d(nn.Module):
116
+ def __init__(
117
+ self, kernel_size: int, stride: Optional[int] = None, padding: Optional[int] = 0
118
+ ):
119
+ """An implementation of mean pooling that supports masked values.
120
+
121
+ Args:
122
+ kernel_size (int): The size of the median pooling window.
123
+ stride (int, optional): The stride of the median pooling window. Defaults to None.
124
+ padding (int, optional): The padding of the median pooling window. Defaults to 0.
125
+ """
126
+
127
+ super(MaskedAvgPool1d, self).__init__()
128
+ self.kernel_size = kernel_size
129
+ self.stride = stride or kernel_size
130
+ self.padding = padding
131
+
132
+ def forward(self, x, mask=None):
133
+ ndim = x.dim()
134
+ if ndim == 2:
135
+ x = x.unsqueeze(1)
136
+
137
+ assert (
138
+ x.dim() == 3
139
+ ), "Input tensor must have 2 or 3 dimensions (batch_size, channels, width)"
140
+
141
+ # Apply the mask by setting masked elements to zero, or make NaNs zero
142
+ if mask is None:
143
+ mask = ~torch.isnan(x)
144
+
145
+ # Ensure mask has the same shape as the input tensor
146
+ assert x.shape == mask.shape, "Input tensor and mask must have the same shape"
147
+
148
+ masked_x = torch.where(mask, x, torch.zeros_like(x))
149
+ # Create a ones kernel with the same number of channels as the input tensor
150
+ ones_kernel = torch.ones(x.size(1), 1, self.kernel_size, device=x.device)
151
+
152
+ # Perform sum pooling
153
+ sum_pooled = nn.functional.conv1d(
154
+ masked_x,
155
+ ones_kernel,
156
+ stride=self.stride,
157
+ padding=self.padding,
158
+ groups=x.size(1),
159
+ )
160
+
161
+ # Count the non-masked (valid) elements in each pooling window
162
+ valid_count = nn.functional.conv1d(
163
+ mask.float(),
164
+ ones_kernel,
165
+ stride=self.stride,
166
+ padding=self.padding,
167
+ groups=x.size(1),
168
+ )
169
+ valid_count = valid_count.clamp(min=1) # Avoid division by zero
170
+
171
+ # Perform masked average pooling
172
+ avg_pooled = sum_pooled / valid_count
173
+
174
+ # Fill zero values with NaNs
175
+ avg_pooled[avg_pooled == 0] = float("nan")
176
+
177
+ if ndim == 2:
178
+ return avg_pooled.squeeze(1)
179
+
180
+ return avg_pooled
181
+
182
+
183
+ class MaskedMedianPool1d(nn.Module):
184
+ def __init__(
185
+ self, kernel_size: int, stride: Optional[int] = None, padding: Optional[int] = 0
186
+ ):
187
+ """An implementation of median pooling that supports masked values.
188
+
189
+ This implementation is inspired by the median pooling implementation in
190
+ https://gist.github.com/rwightman/f2d3849281624be7c0f11c85c87c1598
191
+
192
+ Args:
193
+ kernel_size (int): The size of the median pooling window.
194
+ stride (int, optional): The stride of the median pooling window. Defaults to None.
195
+ padding (int, optional): The padding of the median pooling window. Defaults to 0.
196
+ """
197
+
198
+ super(MaskedMedianPool1d, self).__init__()
199
+ self.kernel_size = kernel_size
200
+ self.stride = stride or kernel_size
201
+ self.padding = padding
202
+
203
+ def forward(self, x, mask=None):
204
+ ndim = x.dim()
205
+ if ndim == 2:
206
+ x = x.unsqueeze(1)
207
+
208
+ assert (
209
+ x.dim() == 3
210
+ ), "Input tensor must have 2 or 3 dimensions (batch_size, channels, width)"
211
+
212
+ if mask is None:
213
+ mask = ~torch.isnan(x)
214
+
215
+ assert x.shape == mask.shape, "Input tensor and mask must have the same shape"
216
+
217
+ masked_x = torch.where(mask, x, torch.zeros_like(x))
218
+
219
+ x = F.pad(masked_x, (self.padding, self.padding), mode="reflect")
220
+ mask = F.pad(
221
+ mask.float(), (self.padding, self.padding), mode="constant", value=0
222
+ )
223
+
224
+ x = x.unfold(2, self.kernel_size, self.stride)
225
+ mask = mask.unfold(2, self.kernel_size, self.stride)
226
+
227
+ x = x.contiguous().view(x.size()[:3] + (-1,))
228
+ mask = mask.contiguous().view(mask.size()[:3] + (-1,)).to(x.device)
229
+
230
+ # Combine the mask with the input tensor
231
+ #x_masked = torch.where(mask.bool(), x, torch.fill_(torch.zeros_like(x),float("inf")))
232
+ x_masked = torch.where(mask.bool(), x, torch.FloatTensor([float("inf")]).to(x.device))
233
+
234
+ # Sort the masked tensor along the last dimension
235
+ x_sorted, _ = torch.sort(x_masked, dim=-1)
236
+
237
+ # Compute the count of non-masked (valid) values
238
+ valid_count = mask.sum(dim=-1)
239
+
240
+ # Calculate the index of the median value for each pooling window
241
+ median_idx = (torch.div((valid_count - 1), 2, rounding_mode='trunc')).clamp(min=0)
242
+
243
+ # Gather the median values using the calculated indices
244
+ median_pooled = x_sorted.gather(-1, median_idx.unsqueeze(-1).long()).squeeze(-1)
245
+
246
+ # Fill infinite values with NaNs
247
+ median_pooled[torch.isinf(median_pooled)] = float("nan")
248
+
249
+ if ndim == 2:
250
+ return median_pooled.squeeze(1)
251
+
252
+ return median_pooled
253
+
254
+
255
+ class CrepePitchExtractor(BasePitchExtractor):
256
+ def __init__(
257
+ self,
258
+ hop_length: int = 512,
259
+ f0_min: float = 50.0,
260
+ f0_max: float = 1100.0,
261
+ threshold: float = 0.05,
262
+ keep_zeros: bool = False,
263
+ device = None,
264
+ model: Literal["full", "tiny"] = "full",
265
+ use_fast_filters: bool = True,
266
+ ):
267
+ super().__init__(hop_length, f0_min, f0_max, keep_zeros)
268
+
269
+ self.threshold = threshold
270
+ self.model = model
271
+ self.use_fast_filters = use_fast_filters
272
+ self.hop_length = hop_length
273
+ if device is None:
274
+ self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
275
+ else:
276
+ self.dev = torch.device(device)
277
+ if self.use_fast_filters:
278
+ self.median_filter = MaskedMedianPool1d(3, 1, 1).to(device)
279
+ self.mean_filter = MaskedAvgPool1d(3, 1, 1).to(device)
280
+
281
+ def __call__(self, x, sampling_rate=44100, pad_to=None):
282
+ """Extract pitch using crepe.
283
+
284
+
285
+ Args:
286
+ x (torch.Tensor): Audio signal, shape (1, T).
287
+ sampling_rate (int, optional): Sampling rate. Defaults to 44100.
288
+ pad_to (int, optional): Pad to length. Defaults to None.
289
+
290
+ Returns:
291
+ torch.Tensor: Pitch, shape (T // hop_length,).
292
+ """
293
+
294
+ assert x.ndim == 2, f"Expected 2D tensor, got {x.ndim}D tensor."
295
+ assert x.shape[0] == 1, f"Expected 1 channel, got {x.shape[0]} channels."
296
+
297
+ x = x.to(self.dev)
298
+ f0, pd = torchcrepe.predict(
299
+ x,
300
+ sampling_rate,
301
+ self.hop_length,
302
+ self.f0_min,
303
+ self.f0_max,
304
+ pad=True,
305
+ model=self.model,
306
+ batch_size=1024,
307
+ device=x.device,
308
+ return_periodicity=True,
309
+ )
310
+
311
+ # Filter, remove silence, set uv threshold, refer to the original warehouse readme
312
+ if self.use_fast_filters:
313
+ pd = self.median_filter(pd)
314
+ else:
315
+ pd = torchcrepe.filter.median(pd, 3)
316
+
317
+ pd = torchcrepe.threshold.Silence(-60.0)(pd, x, sampling_rate, 512)
318
+ f0 = torchcrepe.threshold.At(self.threshold)(f0, pd)
319
+
320
+ if self.use_fast_filters:
321
+ f0 = self.mean_filter(f0)
322
+ else:
323
+ f0 = torchcrepe.filter.mean(f0, 3)
324
+
325
+ f0 = torch.where(torch.isnan(f0), torch.full_like(f0, 0), f0)[0]
326
+
327
+ if torch.all(f0 == 0):
328
+ rtn = f0.cpu().numpy() if pad_to==None else np.zeros(pad_to)
329
+ return rtn,rtn
330
+
331
+ return self.post_process(x, sampling_rate, f0, pad_to)
so-vits-svc/modules/enhancer.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from vdecoder.nsf_hifigan.nvSTFT import STFT
5
+ from vdecoder.nsf_hifigan.models import load_model
6
+ from torchaudio.transforms import Resample
7
+
8
+ class Enhancer:
9
+ def __init__(self, enhancer_type, enhancer_ckpt, device=None):
10
+ if device is None:
11
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
+ self.device = device
13
+
14
+ if enhancer_type == 'nsf-hifigan':
15
+ self.enhancer = NsfHifiGAN(enhancer_ckpt, device=self.device)
16
+ else:
17
+ raise ValueError(f" [x] Unknown enhancer: {enhancer_type}")
18
+
19
+ self.resample_kernel = {}
20
+ self.enhancer_sample_rate = self.enhancer.sample_rate()
21
+ self.enhancer_hop_size = self.enhancer.hop_size()
22
+
23
+ def enhance(self,
24
+ audio, # 1, T
25
+ sample_rate,
26
+ f0, # 1, n_frames, 1
27
+ hop_size,
28
+ adaptive_key = 0,
29
+ silence_front = 0
30
+ ):
31
+ # enhancer start time
32
+ start_frame = int(silence_front * sample_rate / hop_size)
33
+ real_silence_front = start_frame * hop_size / sample_rate
34
+ audio = audio[:, int(np.round(real_silence_front * sample_rate)) : ]
35
+ f0 = f0[: , start_frame :, :]
36
+
37
+ # adaptive parameters
38
+ adaptive_factor = 2 ** ( -adaptive_key / 12)
39
+ adaptive_sample_rate = 100 * int(np.round(self.enhancer_sample_rate / adaptive_factor / 100))
40
+ real_factor = self.enhancer_sample_rate / adaptive_sample_rate
41
+
42
+ # resample the ddsp output
43
+ if sample_rate == adaptive_sample_rate:
44
+ audio_res = audio
45
+ else:
46
+ key_str = str(sample_rate) + str(adaptive_sample_rate)
47
+ if key_str not in self.resample_kernel:
48
+ self.resample_kernel[key_str] = Resample(sample_rate, adaptive_sample_rate, lowpass_filter_width = 128).to(self.device)
49
+ audio_res = self.resample_kernel[key_str](audio)
50
+
51
+ n_frames = int(audio_res.size(-1) // self.enhancer_hop_size + 1)
52
+
53
+ # resample f0
54
+ f0_np = f0.squeeze(0).squeeze(-1).cpu().numpy()
55
+ f0_np *= real_factor
56
+ time_org = (hop_size / sample_rate) * np.arange(len(f0_np)) / real_factor
57
+ time_frame = (self.enhancer_hop_size / self.enhancer_sample_rate) * np.arange(n_frames)
58
+ f0_res = np.interp(time_frame, time_org, f0_np, left=f0_np[0], right=f0_np[-1])
59
+ f0_res = torch.from_numpy(f0_res).unsqueeze(0).float().to(self.device) # 1, n_frames
60
+
61
+ # enhance
62
+ enhanced_audio, enhancer_sample_rate = self.enhancer(audio_res, f0_res)
63
+
64
+ # resample the enhanced output
65
+ if adaptive_factor != 0:
66
+ key_str = str(adaptive_sample_rate) + str(enhancer_sample_rate)
67
+ if key_str not in self.resample_kernel:
68
+ self.resample_kernel[key_str] = Resample(adaptive_sample_rate, enhancer_sample_rate, lowpass_filter_width = 128).to(self.device)
69
+ enhanced_audio = self.resample_kernel[key_str](enhanced_audio)
70
+
71
+ # pad the silence frames
72
+ if start_frame > 0:
73
+ enhanced_audio = F.pad(enhanced_audio, (int(np.round(enhancer_sample_rate * real_silence_front)), 0))
74
+
75
+ return enhanced_audio, enhancer_sample_rate
76
+
77
+
78
+ class NsfHifiGAN(torch.nn.Module):
79
+ def __init__(self, model_path, device=None):
80
+ super().__init__()
81
+ if device is None:
82
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
83
+ self.device = device
84
+ print('| Load HifiGAN: ', model_path)
85
+ self.model, self.h = load_model(model_path, device=self.device)
86
+
87
+ def sample_rate(self):
88
+ return self.h.sampling_rate
89
+
90
+ def hop_size(self):
91
+ return self.h.hop_size
92
+
93
+ def forward(self, audio, f0):
94
+ stft = STFT(
95
+ self.h.sampling_rate,
96
+ self.h.num_mels,
97
+ self.h.n_fft,
98
+ self.h.win_size,
99
+ self.h.hop_size,
100
+ self.h.fmin,
101
+ self.h.fmax)
102
+ with torch.no_grad():
103
+ mel = stft.get_mel(audio)
104
+ enhanced_audio = self.model(mel, f0[:,:mel.size(-1)]).view(-1)
105
+ return enhanced_audio, self.h.sampling_rate
so-vits-svc/modules/losses.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import modules.commons as commons
5
+
6
+
7
+ def feature_loss(fmap_r, fmap_g):
8
+ loss = 0
9
+ for dr, dg in zip(fmap_r, fmap_g):
10
+ for rl, gl in zip(dr, dg):
11
+ rl = rl.float().detach()
12
+ gl = gl.float()
13
+ loss += torch.mean(torch.abs(rl - gl))
14
+
15
+ return loss * 2
16
+
17
+
18
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
19
+ loss = 0
20
+ r_losses = []
21
+ g_losses = []
22
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
23
+ dr = dr.float()
24
+ dg = dg.float()
25
+ r_loss = torch.mean((1-dr)**2)
26
+ g_loss = torch.mean(dg**2)
27
+ loss += (r_loss + g_loss)
28
+ r_losses.append(r_loss.item())
29
+ g_losses.append(g_loss.item())
30
+
31
+ return loss, r_losses, g_losses
32
+
33
+
34
+ def generator_loss(disc_outputs):
35
+ loss = 0
36
+ gen_losses = []
37
+ for dg in disc_outputs:
38
+ dg = dg.float()
39
+ l = torch.mean((1-dg)**2)
40
+ gen_losses.append(l)
41
+ loss += l
42
+
43
+ return loss, gen_losses
44
+
45
+
46
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
47
+ """
48
+ z_p, logs_q: [b, h, t_t]
49
+ m_p, logs_p: [b, h, t_t]
50
+ """
51
+ z_p = z_p.float()
52
+ logs_q = logs_q.float()
53
+ m_p = m_p.float()
54
+ logs_p = logs_p.float()
55
+ z_mask = z_mask.float()
56
+ #print(logs_p)
57
+ kl = logs_p - logs_q - 0.5
58
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
59
+ kl = torch.sum(kl * z_mask)
60
+ l = kl / torch.sum(z_mask)
61
+ return l
so-vits-svc/modules/mel_processing.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.data
8
+ import numpy as np
9
+ import librosa
10
+ import librosa.util as librosa_util
11
+ from librosa.util import normalize, pad_center, tiny
12
+ from scipy.signal import get_window
13
+ from scipy.io.wavfile import read
14
+ from librosa.filters import mel as librosa_mel_fn
15
+
16
+ MAX_WAV_VALUE = 32768.0
17
+
18
+
19
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
20
+ """
21
+ PARAMS
22
+ ------
23
+ C: compression factor
24
+ """
25
+ return torch.log(torch.clamp(x, min=clip_val) * C)
26
+
27
+
28
+ def dynamic_range_decompression_torch(x, C=1):
29
+ """
30
+ PARAMS
31
+ ------
32
+ C: compression factor used to compress
33
+ """
34
+ return torch.exp(x) / C
35
+
36
+
37
+ def spectral_normalize_torch(magnitudes):
38
+ output = dynamic_range_compression_torch(magnitudes)
39
+ return output
40
+
41
+
42
+ def spectral_de_normalize_torch(magnitudes):
43
+ output = dynamic_range_decompression_torch(magnitudes)
44
+ return output
45
+
46
+
47
+ mel_basis = {}
48
+ hann_window = {}
49
+
50
+
51
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
52
+ if torch.min(y) < -1.:
53
+ print('min value is ', torch.min(y))
54
+ if torch.max(y) > 1.:
55
+ print('max value is ', torch.max(y))
56
+
57
+ global hann_window
58
+ dtype_device = str(y.dtype) + '_' + str(y.device)
59
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
60
+ if wnsize_dtype_device not in hann_window:
61
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
62
+
63
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
64
+ y = y.squeeze(1)
65
+
66
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
67
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
68
+
69
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
70
+ return spec
71
+
72
+
73
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
74
+ global mel_basis
75
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
76
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
77
+ if fmax_dtype_device not in mel_basis:
78
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
79
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
80
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
81
+ spec = spectral_normalize_torch(spec)
82
+ return spec
83
+
84
+
85
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
86
+ if torch.min(y) < -1.:
87
+ print('min value is ', torch.min(y))
88
+ if torch.max(y) > 1.:
89
+ print('max value is ', torch.max(y))
90
+
91
+ global mel_basis, hann_window
92
+ dtype_device = str(y.dtype) + '_' + str(y.device)
93
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
94
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
95
+ if fmax_dtype_device not in mel_basis:
96
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
97
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
98
+ if wnsize_dtype_device not in hann_window:
99
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
100
+
101
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
102
+ y = y.squeeze(1)
103
+
104
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
105
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
106
+
107
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
108
+
109
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
110
+ spec = spectral_normalize_torch(spec)
111
+
112
+ return spec
so-vits-svc/modules/modules.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import scipy
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
+ from torch.nn.utils import weight_norm, remove_weight_norm
11
+
12
+ import modules.commons as commons
13
+ from modules.commons import init_weights, get_padding
14
+
15
+
16
+ LRELU_SLOPE = 0.1
17
+
18
+
19
+ class LayerNorm(nn.Module):
20
+ def __init__(self, channels, eps=1e-5):
21
+ super().__init__()
22
+ self.channels = channels
23
+ self.eps = eps
24
+
25
+ self.gamma = nn.Parameter(torch.ones(channels))
26
+ self.beta = nn.Parameter(torch.zeros(channels))
27
+
28
+ def forward(self, x):
29
+ x = x.transpose(1, -1)
30
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
31
+ return x.transpose(1, -1)
32
+
33
+
34
+ class ConvReluNorm(nn.Module):
35
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
36
+ super().__init__()
37
+ self.in_channels = in_channels
38
+ self.hidden_channels = hidden_channels
39
+ self.out_channels = out_channels
40
+ self.kernel_size = kernel_size
41
+ self.n_layers = n_layers
42
+ self.p_dropout = p_dropout
43
+ assert n_layers > 1, "Number of layers should be larger than 0."
44
+
45
+ self.conv_layers = nn.ModuleList()
46
+ self.norm_layers = nn.ModuleList()
47
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
48
+ self.norm_layers.append(LayerNorm(hidden_channels))
49
+ self.relu_drop = nn.Sequential(
50
+ nn.ReLU(),
51
+ nn.Dropout(p_dropout))
52
+ for _ in range(n_layers-1):
53
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
54
+ self.norm_layers.append(LayerNorm(hidden_channels))
55
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
56
+ self.proj.weight.data.zero_()
57
+ self.proj.bias.data.zero_()
58
+
59
+ def forward(self, x, x_mask):
60
+ x_org = x
61
+ for i in range(self.n_layers):
62
+ x = self.conv_layers[i](x * x_mask)
63
+ x = self.norm_layers[i](x)
64
+ x = self.relu_drop(x)
65
+ x = x_org + self.proj(x)
66
+ return x * x_mask
67
+
68
+
69
+ class DDSConv(nn.Module):
70
+ """
71
+ Dialted and Depth-Separable Convolution
72
+ """
73
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
74
+ super().__init__()
75
+ self.channels = channels
76
+ self.kernel_size = kernel_size
77
+ self.n_layers = n_layers
78
+ self.p_dropout = p_dropout
79
+
80
+ self.drop = nn.Dropout(p_dropout)
81
+ self.convs_sep = nn.ModuleList()
82
+ self.convs_1x1 = nn.ModuleList()
83
+ self.norms_1 = nn.ModuleList()
84
+ self.norms_2 = nn.ModuleList()
85
+ for i in range(n_layers):
86
+ dilation = kernel_size ** i
87
+ padding = (kernel_size * dilation - dilation) // 2
88
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
89
+ groups=channels, dilation=dilation, padding=padding
90
+ ))
91
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
92
+ self.norms_1.append(LayerNorm(channels))
93
+ self.norms_2.append(LayerNorm(channels))
94
+
95
+ def forward(self, x, x_mask, g=None):
96
+ if g is not None:
97
+ x = x + g
98
+ for i in range(self.n_layers):
99
+ y = self.convs_sep[i](x * x_mask)
100
+ y = self.norms_1[i](y)
101
+ y = F.gelu(y)
102
+ y = self.convs_1x1[i](y)
103
+ y = self.norms_2[i](y)
104
+ y = F.gelu(y)
105
+ y = self.drop(y)
106
+ x = x + y
107
+ return x * x_mask
108
+
109
+
110
+ class WN(torch.nn.Module):
111
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
112
+ super(WN, self).__init__()
113
+ assert(kernel_size % 2 == 1)
114
+ self.hidden_channels =hidden_channels
115
+ self.kernel_size = kernel_size,
116
+ self.dilation_rate = dilation_rate
117
+ self.n_layers = n_layers
118
+ self.gin_channels = gin_channels
119
+ self.p_dropout = p_dropout
120
+
121
+ self.in_layers = torch.nn.ModuleList()
122
+ self.res_skip_layers = torch.nn.ModuleList()
123
+ self.drop = nn.Dropout(p_dropout)
124
+
125
+ if gin_channels != 0:
126
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
127
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
128
+
129
+ for i in range(n_layers):
130
+ dilation = dilation_rate ** i
131
+ padding = int((kernel_size * dilation - dilation) / 2)
132
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
133
+ dilation=dilation, padding=padding)
134
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
135
+ self.in_layers.append(in_layer)
136
+
137
+ # last one is not necessary
138
+ if i < n_layers - 1:
139
+ res_skip_channels = 2 * hidden_channels
140
+ else:
141
+ res_skip_channels = hidden_channels
142
+
143
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
144
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
145
+ self.res_skip_layers.append(res_skip_layer)
146
+
147
+ def forward(self, x, x_mask, g=None, **kwargs):
148
+ output = torch.zeros_like(x)
149
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
150
+
151
+ if g is not None:
152
+ g = self.cond_layer(g)
153
+
154
+ for i in range(self.n_layers):
155
+ x_in = self.in_layers[i](x)
156
+ if g is not None:
157
+ cond_offset = i * 2 * self.hidden_channels
158
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
159
+ else:
160
+ g_l = torch.zeros_like(x_in)
161
+
162
+ acts = commons.fused_add_tanh_sigmoid_multiply(
163
+ x_in,
164
+ g_l,
165
+ n_channels_tensor)
166
+ acts = self.drop(acts)
167
+
168
+ res_skip_acts = self.res_skip_layers[i](acts)
169
+ if i < self.n_layers - 1:
170
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
171
+ x = (x + res_acts) * x_mask
172
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
173
+ else:
174
+ output = output + res_skip_acts
175
+ return output * x_mask
176
+
177
+ def remove_weight_norm(self):
178
+ if self.gin_channels != 0:
179
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
180
+ for l in self.in_layers:
181
+ torch.nn.utils.remove_weight_norm(l)
182
+ for l in self.res_skip_layers:
183
+ torch.nn.utils.remove_weight_norm(l)
184
+
185
+
186
+ class ResBlock1(torch.nn.Module):
187
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
188
+ super(ResBlock1, self).__init__()
189
+ self.convs1 = nn.ModuleList([
190
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
191
+ padding=get_padding(kernel_size, dilation[0]))),
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
193
+ padding=get_padding(kernel_size, dilation[1]))),
194
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
195
+ padding=get_padding(kernel_size, dilation[2])))
196
+ ])
197
+ self.convs1.apply(init_weights)
198
+
199
+ self.convs2 = nn.ModuleList([
200
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
201
+ padding=get_padding(kernel_size, 1))),
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1))),
204
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
205
+ padding=get_padding(kernel_size, 1)))
206
+ ])
207
+ self.convs2.apply(init_weights)
208
+
209
+ def forward(self, x, x_mask=None):
210
+ for c1, c2 in zip(self.convs1, self.convs2):
211
+ xt = F.leaky_relu(x, LRELU_SLOPE)
212
+ if x_mask is not None:
213
+ xt = xt * x_mask
214
+ xt = c1(xt)
215
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
216
+ if x_mask is not None:
217
+ xt = xt * x_mask
218
+ xt = c2(xt)
219
+ x = xt + x
220
+ if x_mask is not None:
221
+ x = x * x_mask
222
+ return x
223
+
224
+ def remove_weight_norm(self):
225
+ for l in self.convs1:
226
+ remove_weight_norm(l)
227
+ for l in self.convs2:
228
+ remove_weight_norm(l)
229
+
230
+
231
+ class ResBlock2(torch.nn.Module):
232
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
233
+ super(ResBlock2, self).__init__()
234
+ self.convs = nn.ModuleList([
235
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
236
+ padding=get_padding(kernel_size, dilation[0]))),
237
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
238
+ padding=get_padding(kernel_size, dilation[1])))
239
+ ])
240
+ self.convs.apply(init_weights)
241
+
242
+ def forward(self, x, x_mask=None):
243
+ for c in self.convs:
244
+ xt = F.leaky_relu(x, LRELU_SLOPE)
245
+ if x_mask is not None:
246
+ xt = xt * x_mask
247
+ xt = c(xt)
248
+ x = xt + x
249
+ if x_mask is not None:
250
+ x = x * x_mask
251
+ return x
252
+
253
+ def remove_weight_norm(self):
254
+ for l in self.convs:
255
+ remove_weight_norm(l)
256
+
257
+
258
+ class Log(nn.Module):
259
+ def forward(self, x, x_mask, reverse=False, **kwargs):
260
+ if not reverse:
261
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
262
+ logdet = torch.sum(-y, [1, 2])
263
+ return y, logdet
264
+ else:
265
+ x = torch.exp(x) * x_mask
266
+ return x
267
+
268
+
269
+ class Flip(nn.Module):
270
+ def forward(self, x, *args, reverse=False, **kwargs):
271
+ x = torch.flip(x, [1])
272
+ if not reverse:
273
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
274
+ return x, logdet
275
+ else:
276
+ return x
277
+
278
+
279
+ class ElementwiseAffine(nn.Module):
280
+ def __init__(self, channels):
281
+ super().__init__()
282
+ self.channels = channels
283
+ self.m = nn.Parameter(torch.zeros(channels,1))
284
+ self.logs = nn.Parameter(torch.zeros(channels,1))
285
+
286
+ def forward(self, x, x_mask, reverse=False, **kwargs):
287
+ if not reverse:
288
+ y = self.m + torch.exp(self.logs) * x
289
+ y = y * x_mask
290
+ logdet = torch.sum(self.logs * x_mask, [1,2])
291
+ return y, logdet
292
+ else:
293
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
294
+ return x
295
+
296
+
297
+ class ResidualCouplingLayer(nn.Module):
298
+ def __init__(self,
299
+ channels,
300
+ hidden_channels,
301
+ kernel_size,
302
+ dilation_rate,
303
+ n_layers,
304
+ p_dropout=0,
305
+ gin_channels=0,
306
+ mean_only=False):
307
+ assert channels % 2 == 0, "channels should be divisible by 2"
308
+ super().__init__()
309
+ self.channels = channels
310
+ self.hidden_channels = hidden_channels
311
+ self.kernel_size = kernel_size
312
+ self.dilation_rate = dilation_rate
313
+ self.n_layers = n_layers
314
+ self.half_channels = channels // 2
315
+ self.mean_only = mean_only
316
+
317
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
318
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
319
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
320
+ self.post.weight.data.zero_()
321
+ self.post.bias.data.zero_()
322
+
323
+ def forward(self, x, x_mask, g=None, reverse=False):
324
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
325
+ h = self.pre(x0) * x_mask
326
+ h = self.enc(h, x_mask, g=g)
327
+ stats = self.post(h) * x_mask
328
+ if not self.mean_only:
329
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
330
+ else:
331
+ m = stats
332
+ logs = torch.zeros_like(m)
333
+
334
+ if not reverse:
335
+ x1 = m + x1 * torch.exp(logs) * x_mask
336
+ x = torch.cat([x0, x1], 1)
337
+ logdet = torch.sum(logs, [1,2])
338
+ return x, logdet
339
+ else:
340
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
341
+ x = torch.cat([x0, x1], 1)
342
+ return x
so-vits-svc/onnx_export.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ hidden_channels = 256 #(Hubert's shape[2])
21
+
22
+ test_hidden_unit = torch.rand(1, n_frame, hidden_channels)
23
+ test_pitch = torch.rand(1, n_frame)
24
+ 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)
25
+ test_uv = torch.ones(1, n_frame, dtype=torch.float32)
26
+ test_noise = torch.randn(1, 192, n_frame)
27
+ test_sid = torch.LongTensor([0])
28
+ input_names = ["c", "f0", "mel2ph", "uv", "noise", "sid"]
29
+ output_names = ["audio", ]
30
+
31
+ torch.onnx.export(SVCVITS,
32
+ (
33
+ test_hidden_unit.to(device),
34
+ test_pitch.to(device),
35
+ test_mel2ph.to(device),
36
+ test_uv.to(device),
37
+ test_noise.to(device),
38
+ test_sid.to(device)
39
+ ),
40
+ f"checkpoints/{path}/model.onnx",
41
+ dynamic_axes={
42
+ "c": [0, 1],
43
+ "f0": [1],
44
+ "mel2ph": [1],
45
+ "uv": [1],
46
+ "noise": [2],
47
+ },
48
+ do_constant_folding=False,
49
+ opset_version=16,
50
+ verbose=False,
51
+ input_names=input_names,
52
+ output_names=output_names)
53
+
54
+
55
+ if __name__ == '__main__':
56
+ main(True)
so-vits-svc/onnxexport/model_onnx.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch.nn import functional as F
4
+
5
+ import modules.attentions as attentions
6
+ import modules.commons as commons
7
+ import modules.modules as modules
8
+
9
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
11
+
12
+ import utils
13
+ from modules.commons import init_weights, get_padding
14
+ from vdecoder.hifigan.models import Generator
15
+ from utils import f0_to_coarse
16
+
17
+
18
+ class ResidualCouplingBlock(nn.Module):
19
+ def __init__(self,
20
+ channels,
21
+ hidden_channels,
22
+ kernel_size,
23
+ dilation_rate,
24
+ n_layers,
25
+ n_flows=4,
26
+ gin_channels=0):
27
+ super().__init__()
28
+ self.channels = channels
29
+ self.hidden_channels = hidden_channels
30
+ self.kernel_size = kernel_size
31
+ self.dilation_rate = dilation_rate
32
+ self.n_layers = n_layers
33
+ self.n_flows = n_flows
34
+ self.gin_channels = gin_channels
35
+
36
+ self.flows = nn.ModuleList()
37
+ for i in range(n_flows):
38
+ self.flows.append(
39
+ modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers,
40
+ gin_channels=gin_channels, mean_only=True))
41
+ self.flows.append(modules.Flip())
42
+
43
+ def forward(self, x, x_mask, g=None, reverse=False):
44
+ if not reverse:
45
+ for flow in self.flows:
46
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
47
+ else:
48
+ for flow in reversed(self.flows):
49
+ x = flow(x, x_mask, g=g, reverse=reverse)
50
+ return x
51
+
52
+
53
+ class Encoder(nn.Module):
54
+ def __init__(self,
55
+ in_channels,
56
+ out_channels,
57
+ hidden_channels,
58
+ kernel_size,
59
+ dilation_rate,
60
+ n_layers,
61
+ gin_channels=0):
62
+ super().__init__()
63
+ self.in_channels = in_channels
64
+ self.out_channels = out_channels
65
+ self.hidden_channels = hidden_channels
66
+ self.kernel_size = kernel_size
67
+ self.dilation_rate = dilation_rate
68
+ self.n_layers = n_layers
69
+ self.gin_channels = gin_channels
70
+
71
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
72
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
73
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
74
+
75
+ def forward(self, x, x_lengths, g=None):
76
+ # print(x.shape,x_lengths.shape)
77
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
78
+ x = self.pre(x) * x_mask
79
+ x = self.enc(x, x_mask, g=g)
80
+ stats = self.proj(x) * x_mask
81
+ m, logs = torch.split(stats, self.out_channels, dim=1)
82
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
83
+ return z, m, logs, x_mask
84
+
85
+
86
+ class TextEncoder(nn.Module):
87
+ def __init__(self,
88
+ out_channels,
89
+ hidden_channels,
90
+ kernel_size,
91
+ n_layers,
92
+ gin_channels=0,
93
+ filter_channels=None,
94
+ n_heads=None,
95
+ p_dropout=None):
96
+ super().__init__()
97
+ self.out_channels = out_channels
98
+ self.hidden_channels = hidden_channels
99
+ self.kernel_size = kernel_size
100
+ self.n_layers = n_layers
101
+ self.gin_channels = gin_channels
102
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
103
+ self.f0_emb = nn.Embedding(256, hidden_channels)
104
+
105
+ self.enc_ = attentions.Encoder(
106
+ hidden_channels,
107
+ filter_channels,
108
+ n_heads,
109
+ n_layers,
110
+ kernel_size,
111
+ p_dropout)
112
+
113
+ def forward(self, x, x_mask, f0=None, z=None):
114
+ x = x + self.f0_emb(f0).transpose(1, 2)
115
+ x = self.enc_(x * x_mask, x_mask)
116
+ stats = self.proj(x) * x_mask
117
+ m, logs = torch.split(stats, self.out_channels, dim=1)
118
+ z = (m + z * torch.exp(logs)) * x_mask
119
+ return z, m, logs, x_mask
120
+
121
+
122
+ class DiscriminatorP(torch.nn.Module):
123
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
124
+ super(DiscriminatorP, self).__init__()
125
+ self.period = period
126
+ self.use_spectral_norm = use_spectral_norm
127
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
128
+ self.convs = nn.ModuleList([
129
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
130
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
131
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
132
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
133
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
134
+ ])
135
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
136
+
137
+ def forward(self, x):
138
+ fmap = []
139
+
140
+ # 1d to 2d
141
+ b, c, t = x.shape
142
+ if t % self.period != 0: # pad first
143
+ n_pad = self.period - (t % self.period)
144
+ x = F.pad(x, (0, n_pad), "reflect")
145
+ t = t + n_pad
146
+ x = x.view(b, c, t // self.period, self.period)
147
+
148
+ for l in self.convs:
149
+ x = l(x)
150
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
151
+ fmap.append(x)
152
+ x = self.conv_post(x)
153
+ fmap.append(x)
154
+ x = torch.flatten(x, 1, -1)
155
+
156
+ return x, fmap
157
+
158
+
159
+ class DiscriminatorS(torch.nn.Module):
160
+ def __init__(self, use_spectral_norm=False):
161
+ super(DiscriminatorS, self).__init__()
162
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
163
+ self.convs = nn.ModuleList([
164
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
165
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
166
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
167
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
168
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
169
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
170
+ ])
171
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
172
+
173
+ def forward(self, x):
174
+ fmap = []
175
+
176
+ for l in self.convs:
177
+ x = l(x)
178
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
179
+ fmap.append(x)
180
+ x = self.conv_post(x)
181
+ fmap.append(x)
182
+ x = torch.flatten(x, 1, -1)
183
+
184
+ return x, fmap
185
+
186
+
187
+ class F0Decoder(nn.Module):
188
+ def __init__(self,
189
+ out_channels,
190
+ hidden_channels,
191
+ filter_channels,
192
+ n_heads,
193
+ n_layers,
194
+ kernel_size,
195
+ p_dropout,
196
+ spk_channels=0):
197
+ super().__init__()
198
+ self.out_channels = out_channels
199
+ self.hidden_channels = hidden_channels
200
+ self.filter_channels = filter_channels
201
+ self.n_heads = n_heads
202
+ self.n_layers = n_layers
203
+ self.kernel_size = kernel_size
204
+ self.p_dropout = p_dropout
205
+ self.spk_channels = spk_channels
206
+
207
+ self.prenet = nn.Conv1d(hidden_channels, hidden_channels, 3, padding=1)
208
+ self.decoder = attentions.FFT(
209
+ hidden_channels,
210
+ filter_channels,
211
+ n_heads,
212
+ n_layers,
213
+ kernel_size,
214
+ p_dropout)
215
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
216
+ self.f0_prenet = nn.Conv1d(1, hidden_channels, 3, padding=1)
217
+ self.cond = nn.Conv1d(spk_channels, hidden_channels, 1)
218
+
219
+ def forward(self, x, norm_f0, x_mask, spk_emb=None):
220
+ x = torch.detach(x)
221
+ if spk_emb is not None:
222
+ x = x + self.cond(spk_emb)
223
+ x += self.f0_prenet(norm_f0)
224
+ x = self.prenet(x) * x_mask
225
+ x = self.decoder(x * x_mask, x_mask)
226
+ x = self.proj(x) * x_mask
227
+ return x
228
+
229
+
230
+ class SynthesizerTrn(nn.Module):
231
+ """
232
+ Synthesizer for Training
233
+ """
234
+
235
+ def __init__(self,
236
+ spec_channels,
237
+ segment_size,
238
+ inter_channels,
239
+ hidden_channels,
240
+ filter_channels,
241
+ n_heads,
242
+ n_layers,
243
+ kernel_size,
244
+ p_dropout,
245
+ resblock,
246
+ resblock_kernel_sizes,
247
+ resblock_dilation_sizes,
248
+ upsample_rates,
249
+ upsample_initial_channel,
250
+ upsample_kernel_sizes,
251
+ gin_channels,
252
+ ssl_dim,
253
+ n_speakers,
254
+ sampling_rate=44100,
255
+ **kwargs):
256
+ super().__init__()
257
+ self.spec_channels = spec_channels
258
+ self.inter_channels = inter_channels
259
+ self.hidden_channels = hidden_channels
260
+ self.filter_channels = filter_channels
261
+ self.n_heads = n_heads
262
+ self.n_layers = n_layers
263
+ self.kernel_size = kernel_size
264
+ self.p_dropout = p_dropout
265
+ self.resblock = resblock
266
+ self.resblock_kernel_sizes = resblock_kernel_sizes
267
+ self.resblock_dilation_sizes = resblock_dilation_sizes
268
+ self.upsample_rates = upsample_rates
269
+ self.upsample_initial_channel = upsample_initial_channel
270
+ self.upsample_kernel_sizes = upsample_kernel_sizes
271
+ self.segment_size = segment_size
272
+ self.gin_channels = gin_channels
273
+ self.ssl_dim = ssl_dim
274
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
275
+
276
+ self.pre = nn.Conv1d(ssl_dim, hidden_channels, kernel_size=5, padding=2)
277
+
278
+ self.enc_p = TextEncoder(
279
+ inter_channels,
280
+ hidden_channels,
281
+ filter_channels=filter_channels,
282
+ n_heads=n_heads,
283
+ n_layers=n_layers,
284
+ kernel_size=kernel_size,
285
+ p_dropout=p_dropout
286
+ )
287
+ hps = {
288
+ "sampling_rate": sampling_rate,
289
+ "inter_channels": inter_channels,
290
+ "resblock": resblock,
291
+ "resblock_kernel_sizes": resblock_kernel_sizes,
292
+ "resblock_dilation_sizes": resblock_dilation_sizes,
293
+ "upsample_rates": upsample_rates,
294
+ "upsample_initial_channel": upsample_initial_channel,
295
+ "upsample_kernel_sizes": upsample_kernel_sizes,
296
+ "gin_channels": gin_channels,
297
+ }
298
+ self.dec = Generator(h=hps)
299
+ self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
300
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
301
+ self.f0_decoder = F0Decoder(
302
+ 1,
303
+ hidden_channels,
304
+ filter_channels,
305
+ n_heads,
306
+ n_layers,
307
+ kernel_size,
308
+ p_dropout,
309
+ spk_channels=gin_channels
310
+ )
311
+ self.emb_uv = nn.Embedding(2, hidden_channels)
312
+ self.predict_f0 = False
313
+
314
+ def forward(self, c, f0, mel2ph, uv, noise=None, g=None):
315
+
316
+ decoder_inp = F.pad(c, [0, 0, 1, 0])
317
+ mel2ph_ = mel2ph.unsqueeze(2).repeat([1, 1, c.shape[-1]])
318
+ c = torch.gather(decoder_inp, 1, mel2ph_).transpose(1, 2) # [B, T, H]
319
+
320
+ c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device)
321
+ g = g.unsqueeze(0)
322
+ g = self.emb_g(g).transpose(1, 2)
323
+ x_mask = torch.unsqueeze(commons.sequence_mask(c_lengths, c.size(2)), 1).to(c.dtype)
324
+ x = self.pre(c) * x_mask + self.emb_uv(uv.long()).transpose(1, 2)
325
+
326
+ if self.predict_f0:
327
+ lf0 = 2595. * torch.log10(1. + f0.unsqueeze(1) / 700.) / 500
328
+ norm_lf0 = utils.normalize_f0(lf0, x_mask, uv, random_scale=False)
329
+ pred_lf0 = self.f0_decoder(x, norm_lf0, x_mask, spk_emb=g)
330
+ f0 = (700 * (torch.pow(10, pred_lf0 * 500 / 2595) - 1)).squeeze(1)
331
+
332
+ z_p, m_p, logs_p, c_mask = self.enc_p(x, x_mask, f0=f0_to_coarse(f0), z=noise)
333
+ z = self.flow(z_p, c_mask, g=g, reverse=True)
334
+ o = self.dec(z * c_mask, g=g, f0=f0)
335
+ return o
so-vits-svc/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
+ # get audio frames
17
+ n_frames = wav_file.getnframes()
18
+ # get sampling rate
19
+ framerate = wav_file.getframerate()
20
+ # calculate duration in seconds
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: The file name of {file} contains non-alphanumeric and underscores, which may cause issues. (or maybe not)")
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)
so-vits-svc/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()
so-vits-svc/pretrain/nsf_hifigan/put_nsf_hifigan_ckpt_here ADDED
File without changes
so-vits-svc/raw/put_raw_wav_here ADDED
File without changes
so-vits-svc/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask
2
+ Flask_Cors
3
+ gradio>=3.7.0
4
+ numpy==1.23.0
5
+ pyworld==0.2.5
6
+ scipy==1.10.0
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
so-vits-svc/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>=3.7.0
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
so-vits-svc/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 = 30 if cpu_count() > 60 else (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
so-vits-svc/sovits4_for_colab.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
so-vits-svc/train.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ name=utils.latest_checkpoint_path(hps.model_dir, "D_*.pth")
109
+ global_step=int(name[name.rfind("_")+1:name.rfind(".")])+1
110
+ #global_step = (epoch_str - 1) * len(train_loader)
111
+ except:
112
+ print("load old checkpoint failed...")
113
+ epoch_str = 1
114
+ global_step = 0
115
+ if skip_optimizer:
116
+ epoch_str = 1
117
+ global_step = 0
118
+
119
+ warmup_epoch = hps.train.warmup_epochs
120
+ scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
121
+ scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2)
122
+
123
+ scaler = GradScaler(enabled=hps.train.fp16_run)
124
+
125
+ for epoch in range(epoch_str, hps.train.epochs + 1):
126
+ # update learning rate
127
+ if epoch > 1:
128
+ scheduler_g.step()
129
+ scheduler_d.step()
130
+ # set up warm-up learning rate
131
+ if epoch <= warmup_epoch:
132
+ for param_group in optim_g.param_groups:
133
+ param_group['lr'] = hps.train.learning_rate / warmup_epoch * epoch
134
+ for param_group in optim_d.param_groups:
135
+ param_group['lr'] = hps.train.learning_rate / warmup_epoch * epoch
136
+ # training
137
+ if rank == 0:
138
+ train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler,
139
+ [train_loader, eval_loader], logger, [writer, writer_eval])
140
+ else:
141
+ train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler,
142
+ [train_loader, None], None, None)
143
+
144
+
145
+ def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):
146
+ net_g, net_d = nets
147
+ optim_g, optim_d = optims
148
+ scheduler_g, scheduler_d = schedulers
149
+ train_loader, eval_loader = loaders
150
+ if writers is not None:
151
+ writer, writer_eval = writers
152
+
153
+ # train_loader.batch_sampler.set_epoch(epoch)
154
+ global global_step
155
+
156
+ net_g.train()
157
+ net_d.train()
158
+ for batch_idx, items in enumerate(train_loader):
159
+ c, f0, spec, y, spk, lengths, uv = items
160
+ g = spk.cuda(rank, non_blocking=True)
161
+ spec, y = spec.cuda(rank, non_blocking=True), y.cuda(rank, non_blocking=True)
162
+ c = c.cuda(rank, non_blocking=True)
163
+ f0 = f0.cuda(rank, non_blocking=True)
164
+ uv = uv.cuda(rank, non_blocking=True)
165
+ lengths = lengths.cuda(rank, non_blocking=True)
166
+ mel = spec_to_mel_torch(
167
+ spec,
168
+ hps.data.filter_length,
169
+ hps.data.n_mel_channels,
170
+ hps.data.sampling_rate,
171
+ hps.data.mel_fmin,
172
+ hps.data.mel_fmax)
173
+
174
+ with autocast(enabled=hps.train.fp16_run):
175
+ y_hat, ids_slice, z_mask, \
176
+ (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,
177
+ spec_lengths=lengths)
178
+
179
+ y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)
180
+ y_hat_mel = mel_spectrogram_torch(
181
+ y_hat.squeeze(1),
182
+ hps.data.filter_length,
183
+ hps.data.n_mel_channels,
184
+ hps.data.sampling_rate,
185
+ hps.data.hop_length,
186
+ hps.data.win_length,
187
+ hps.data.mel_fmin,
188
+ hps.data.mel_fmax
189
+ )
190
+ y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice
191
+
192
+ # Discriminator
193
+ y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())
194
+
195
+ with autocast(enabled=False):
196
+ loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g)
197
+ loss_disc_all = loss_disc
198
+
199
+ optim_d.zero_grad()
200
+ scaler.scale(loss_disc_all).backward()
201
+ scaler.unscale_(optim_d)
202
+ grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None)
203
+ scaler.step(optim_d)
204
+
205
+ with autocast(enabled=hps.train.fp16_run):
206
+ # Generator
207
+ y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat)
208
+ with autocast(enabled=False):
209
+ loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
210
+ loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
211
+ loss_fm = feature_loss(fmap_r, fmap_g)
212
+ loss_gen, losses_gen = generator_loss(y_d_hat_g)
213
+ loss_lf0 = F.mse_loss(pred_lf0, lf0)
214
+ loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl + loss_lf0
215
+ optim_g.zero_grad()
216
+ scaler.scale(loss_gen_all).backward()
217
+ scaler.unscale_(optim_g)
218
+ grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)
219
+ scaler.step(optim_g)
220
+ scaler.update()
221
+
222
+ if rank == 0:
223
+ if global_step % hps.train.log_interval == 0:
224
+ lr = optim_g.param_groups[0]['lr']
225
+ losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_kl]
226
+ reference_loss=0
227
+ for i in losses:
228
+ reference_loss += i
229
+ logger.info('Train Epoch: {} [{:.0f}%]'.format(
230
+ epoch,
231
+ 100. * batch_idx / len(train_loader)))
232
+ logger.info(f"Losses: {[x.item() for x in losses]}, step: {global_step}, lr: {lr}, reference_loss: {reference_loss}")
233
+
234
+ scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr,
235
+ "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g}
236
+ scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/kl": loss_kl,
237
+ "loss/g/lf0": loss_lf0})
238
+
239
+ # scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)})
240
+ # scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)})
241
+ # scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)})
242
+ image_dict = {
243
+ "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),
244
+ "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()),
245
+ "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),
246
+ "all/lf0": utils.plot_data_to_numpy(lf0[0, 0, :].cpu().numpy(),
247
+ pred_lf0[0, 0, :].detach().cpu().numpy()),
248
+ "all/norm_lf0": utils.plot_data_to_numpy(lf0[0, 0, :].cpu().numpy(),
249
+ norm_lf0[0, 0, :].detach().cpu().numpy())
250
+ }
251
+
252
+ utils.summarize(
253
+ writer=writer,
254
+ global_step=global_step,
255
+ images=image_dict,
256
+ scalars=scalar_dict
257
+ )
258
+
259
+ if global_step % hps.train.eval_interval == 0:
260
+ evaluate(hps, net_g, eval_loader, writer_eval)
261
+ utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch,
262
+ os.path.join(hps.model_dir, "G_{}.pth".format(global_step)))
263
+ utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch,
264
+ os.path.join(hps.model_dir, "D_{}.pth".format(global_step)))
265
+ keep_ckpts = getattr(hps.train, 'keep_ckpts', 0)
266
+ if keep_ckpts > 0:
267
+ utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True)
268
+
269
+ global_step += 1
270
+
271
+ if rank == 0:
272
+ global start_time
273
+ now = time.time()
274
+ durtaion = format(now - start_time, '.2f')
275
+ logger.info(f'====> Epoch: {epoch}, cost {durtaion} s')
276
+ start_time = now
277
+
278
+
279
+ def evaluate(hps, generator, eval_loader, writer_eval):
280
+ generator.eval()
281
+ image_dict = {}
282
+ audio_dict = {}
283
+ with torch.no_grad():
284
+ for batch_idx, items in enumerate(eval_loader):
285
+ c, f0, spec, y, spk, _, uv = items
286
+ g = spk[:1].cuda(0)
287
+ spec, y = spec[:1].cuda(0), y[:1].cuda(0)
288
+ c = c[:1].cuda(0)
289
+ f0 = f0[:1].cuda(0)
290
+ uv= uv[:1].cuda(0)
291
+ mel = spec_to_mel_torch(
292
+ spec,
293
+ hps.data.filter_length,
294
+ hps.data.n_mel_channels,
295
+ hps.data.sampling_rate,
296
+ hps.data.mel_fmin,
297
+ hps.data.mel_fmax)
298
+ y_hat = generator.module.infer(c, f0, uv, g=g)
299
+
300
+ y_hat_mel = mel_spectrogram_torch(
301
+ y_hat.squeeze(1).float(),
302
+ hps.data.filter_length,
303
+ hps.data.n_mel_channels,
304
+ hps.data.sampling_rate,
305
+ hps.data.hop_length,
306
+ hps.data.win_length,
307
+ hps.data.mel_fmin,
308
+ hps.data.mel_fmax
309
+ )
310
+
311
+ audio_dict.update({
312
+ f"gen/audio_{batch_idx}": y_hat[0],
313
+ f"gt/audio_{batch_idx}": y[0]
314
+ })
315
+ image_dict.update({
316
+ f"gen/mel": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()),
317
+ "gt/mel": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())
318
+ })
319
+ utils.summarize(
320
+ writer=writer_eval,
321
+ global_step=global_step,
322
+ images=image_dict,
323
+ audios=audio_dict,
324
+ audio_sampling_rate=hps.data.sampling_rate
325
+ )
326
+ generator.train()
327
+
328
+
329
+ if __name__ == "__main__":
330
+ main()
so-vits-svc/utils.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
21
+ MATPLOTLIB_FLAG = False
22
+
23
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
24
+ logger = logging
25
+
26
+ f0_bin = 256
27
+ f0_max = 1100.0
28
+ f0_min = 50.0
29
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
30
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
31
+
32
+
33
+ # def normalize_f0(f0, random_scale=True):
34
+ # f0_norm = f0.clone() # create a copy of the input Tensor
35
+ # batch_size, _, frame_length = f0_norm.shape
36
+ # for i in range(batch_size):
37
+ # means = torch.mean(f0_norm[i, 0, :])
38
+ # if random_scale:
39
+ # factor = random.uniform(0.8, 1.2)
40
+ # else:
41
+ # factor = 1
42
+ # f0_norm[i, 0, :] = (f0_norm[i, 0, :] - means) * factor
43
+ # return f0_norm
44
+ # def normalize_f0(f0, random_scale=True):
45
+ # means = torch.mean(f0[:, 0, :], dim=1, keepdim=True)
46
+ # if random_scale:
47
+ # factor = torch.Tensor(f0.shape[0],1).uniform_(0.8, 1.2).to(f0.device)
48
+ # else:
49
+ # factor = torch.ones(f0.shape[0], 1, 1).to(f0.device)
50
+ # f0_norm = (f0 - means.unsqueeze(-1)) * factor.unsqueeze(-1)
51
+ # return f0_norm
52
+
53
+ def deprecated(func):
54
+ """This is a decorator which can be used to mark functions
55
+ as deprecated. It will result in a warning being emitted
56
+ when the function is used."""
57
+ @functools.wraps(func)
58
+ def new_func(*args, **kwargs):
59
+ warnings.simplefilter('always', DeprecationWarning) # turn off filter
60
+ warnings.warn("Call to deprecated function {}.".format(func.__name__),
61
+ category=DeprecationWarning,
62
+ stacklevel=2)
63
+ warnings.simplefilter('default', DeprecationWarning) # reset filter
64
+ return func(*args, **kwargs)
65
+ return new_func
66
+
67
+ def normalize_f0(f0, x_mask, uv, random_scale=True):
68
+ # calculate means based on x_mask
69
+ uv_sum = torch.sum(uv, dim=1, keepdim=True)
70
+ uv_sum[uv_sum == 0] = 9999
71
+ means = torch.sum(f0[:, 0, :] * uv, dim=1, keepdim=True) / uv_sum
72
+
73
+ if random_scale:
74
+ factor = torch.Tensor(f0.shape[0], 1).uniform_(0.8, 1.2).to(f0.device)
75
+ else:
76
+ factor = torch.ones(f0.shape[0], 1).to(f0.device)
77
+ # normalize f0 based on means and factor
78
+ f0_norm = (f0 - means.unsqueeze(-1)) * factor.unsqueeze(-1)
79
+ if torch.isnan(f0_norm).any():
80
+ exit(0)
81
+ return f0_norm * x_mask
82
+
83
+ def compute_f0_uv_torchcrepe(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512,device=None,cr_threshold=0.05):
84
+ from modules.crepe import CrepePitchExtractor
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,threshold=cr_threshold)
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
+ data = np.reshape(f0, (f0.size, 1))
124
+
125
+ vuv_vector = np.zeros((data.size, 1), dtype=np.float32)
126
+ vuv_vector[data > 0.0] = 1.0
127
+ vuv_vector[data <= 0.0] = 0.0
128
+
129
+ ip_data = data
130
+
131
+ frame_number = data.size
132
+ last_value = 0.0
133
+ for i in range(frame_number):
134
+ if data[i] <= 0.0:
135
+ j = i + 1
136
+ for j in range(i + 1, frame_number):
137
+ if data[j] > 0.0:
138
+ break
139
+ if j < frame_number - 1:
140
+ if last_value > 0.0:
141
+ step = (data[j] - data[i - 1]) / float(j - i)
142
+ for k in range(i, j):
143
+ ip_data[k] = data[i - 1] + step * (k - i + 1)
144
+ else:
145
+ for k in range(i, j):
146
+ ip_data[k] = data[j]
147
+ else:
148
+ for k in range(i, frame_number):
149
+ ip_data[k] = last_value
150
+ else:
151
+ ip_data[i] = data[i] # this may not be necessary
152
+ last_value = data[i]
153
+
154
+ return ip_data[:,0], vuv_vector[:,0]
155
+
156
+
157
+ def compute_f0_parselmouth(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512):
158
+ import parselmouth
159
+ x = wav_numpy
160
+ if p_len is None:
161
+ p_len = x.shape[0]//hop_length
162
+ else:
163
+ assert abs(p_len-x.shape[0]//hop_length) < 4, "pad length error"
164
+ time_step = hop_length / sampling_rate * 1000
165
+ f0_min = 50
166
+ f0_max = 1100
167
+ f0 = parselmouth.Sound(x, sampling_rate).to_pitch_ac(
168
+ time_step=time_step / 1000, voicing_threshold=0.6,
169
+ pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
170
+
171
+ pad_size=(p_len - len(f0) + 1) // 2
172
+ if(pad_size>0 or p_len - len(f0) - pad_size>0):
173
+ f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant')
174
+ return f0
175
+
176
+ def resize_f0(x, target_len):
177
+ source = np.array(x)
178
+ source[source<0.001] = np.nan
179
+ target = np.interp(np.arange(0, len(source)*target_len, len(source))/ target_len, np.arange(0, len(source)), source)
180
+ res = np.nan_to_num(target)
181
+ return res
182
+
183
+ def compute_f0_dio(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512):
184
+ import pyworld
185
+ if p_len is None:
186
+ p_len = wav_numpy.shape[0]//hop_length
187
+ f0, t = pyworld.dio(
188
+ wav_numpy.astype(np.double),
189
+ fs=sampling_rate,
190
+ f0_ceil=800,
191
+ frame_period=1000 * hop_length / sampling_rate,
192
+ )
193
+ f0 = pyworld.stonemask(wav_numpy.astype(np.double), f0, t, sampling_rate)
194
+ for index, pitch in enumerate(f0):
195
+ f0[index] = round(pitch, 1)
196
+ return resize_f0(f0, p_len)
197
+
198
+ def f0_to_coarse(f0):
199
+ is_torch = isinstance(f0, torch.Tensor)
200
+ f0_mel = 1127 * (1 + f0 / 700).log() if is_torch else 1127 * np.log(1 + f0 / 700)
201
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * (f0_bin - 2) / (f0_mel_max - f0_mel_min) + 1
202
+
203
+ f0_mel[f0_mel <= 1] = 1
204
+ f0_mel[f0_mel > f0_bin - 1] = f0_bin - 1
205
+ f0_coarse = (f0_mel + 0.5).int() if is_torch else np.rint(f0_mel).astype(np.int)
206
+ assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, (f0_coarse.max(), f0_coarse.min())
207
+ return f0_coarse
208
+
209
+
210
+ def get_hubert_model():
211
+ vec_path = "hubert/checkpoint_best_legacy_500.pt"
212
+ print("load model(s) from {}".format(vec_path))
213
+ from fairseq import checkpoint_utils
214
+ models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
215
+ [vec_path],
216
+ suffix="",
217
+ )
218
+ model = models[0]
219
+ model.eval()
220
+ return model
221
+
222
+ def get_hubert_content(hmodel, wav_16k_tensor):
223
+ feats = wav_16k_tensor
224
+ if feats.dim() == 2: # double channels
225
+ feats = feats.mean(-1)
226
+ assert feats.dim() == 1, feats.dim()
227
+ feats = feats.view(1, -1)
228
+ padding_mask = torch.BoolTensor(feats.shape).fill_(False)
229
+ inputs = {
230
+ "source": feats.to(wav_16k_tensor.device),
231
+ "padding_mask": padding_mask.to(wav_16k_tensor.device),
232
+ "output_layer": 9, # layer 9
233
+ }
234
+ with torch.no_grad():
235
+ logits = hmodel.extract_features(**inputs)
236
+ feats = hmodel.final_proj(logits[0])
237
+ return feats.transpose(1, 2)
238
+
239
+
240
+ def get_content(cmodel, y):
241
+ with torch.no_grad():
242
+ c = cmodel.extract_features(y.squeeze(1))[0]
243
+ c = c.transpose(1, 2)
244
+ return c
245
+
246
+
247
+
248
+ def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
249
+ assert os.path.isfile(checkpoint_path)
250
+ checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
251
+ iteration = checkpoint_dict['iteration']
252
+ learning_rate = checkpoint_dict['learning_rate']
253
+ if optimizer is not None and not skip_optimizer and checkpoint_dict['optimizer'] is not None:
254
+ optimizer.load_state_dict(checkpoint_dict['optimizer'])
255
+ saved_state_dict = checkpoint_dict['model']
256
+ if hasattr(model, 'module'):
257
+ state_dict = model.module.state_dict()
258
+ else:
259
+ state_dict = model.state_dict()
260
+ new_state_dict = {}
261
+ for k, v in state_dict.items():
262
+ try:
263
+ # assert "dec" in k or "disc" in k
264
+ # print("load", k)
265
+ new_state_dict[k] = saved_state_dict[k]
266
+ assert saved_state_dict[k].shape == v.shape, (saved_state_dict[k].shape, v.shape)
267
+ except:
268
+ print("error, %s is not in the checkpoint" % k)
269
+ logger.info("%s is not in the checkpoint" % k)
270
+ new_state_dict[k] = v
271
+ if hasattr(model, 'module'):
272
+ model.module.load_state_dict(new_state_dict)
273
+ else:
274
+ model.load_state_dict(new_state_dict)
275
+ print("load ")
276
+ logger.info("Loaded checkpoint '{}' (iteration {})".format(
277
+ checkpoint_path, iteration))
278
+ return model, optimizer, learning_rate, iteration
279
+
280
+
281
+ def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
282
+ logger.info("Saving model and optimizer state at iteration {} to {}".format(
283
+ iteration, checkpoint_path))
284
+ if hasattr(model, 'module'):
285
+ state_dict = model.module.state_dict()
286
+ else:
287
+ state_dict = model.state_dict()
288
+ torch.save({'model': state_dict,
289
+ 'iteration': iteration,
290
+ 'optimizer': optimizer.state_dict(),
291
+ 'learning_rate': learning_rate}, checkpoint_path)
292
+
293
+ def clean_checkpoints(path_to_models='logs/44k/', n_ckpts_to_keep=2, sort_by_time=True):
294
+ """Freeing up space by deleting saved ckpts
295
+
296
+ Arguments:
297
+ path_to_models -- Path to the model directory
298
+ n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
299
+ sort_by_time -- True -> chronologically delete ckpts
300
+ False -> lexicographically delete ckpts
301
+ """
302
+ ckpts_files = [f for f in os.listdir(path_to_models) if os.path.isfile(os.path.join(path_to_models, f))]
303
+ name_key = (lambda _f: int(re.compile('._(\d+)\.pth').match(_f).group(1)))
304
+ time_key = (lambda _f: os.path.getmtime(os.path.join(path_to_models, _f)))
305
+ sort_key = time_key if sort_by_time else name_key
306
+ x_sorted = lambda _x: sorted([f for f in ckpts_files if f.startswith(_x) and not f.endswith('_0.pth')], key=sort_key)
307
+ to_del = [os.path.join(path_to_models, fn) for fn in
308
+ (x_sorted('G')[:-n_ckpts_to_keep] + x_sorted('D')[:-n_ckpts_to_keep])]
309
+ del_info = lambda fn: logger.info(f".. Free up space by deleting ckpt {fn}")
310
+ del_routine = lambda x: [os.remove(x), del_info(x)]
311
+ rs = [del_routine(fn) for fn in to_del]
312
+
313
+ def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
314
+ for k, v in scalars.items():
315
+ writer.add_scalar(k, v, global_step)
316
+ for k, v in histograms.items():
317
+ writer.add_histogram(k, v, global_step)
318
+ for k, v in images.items():
319
+ writer.add_image(k, v, global_step, dataformats='HWC')
320
+ for k, v in audios.items():
321
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
322
+
323
+
324
+ def latest_checkpoint_path(dir_path, regex="G_*.pth"):
325
+ f_list = glob.glob(os.path.join(dir_path, regex))
326
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
327
+ x = f_list[-1]
328
+ print(x)
329
+ return x
330
+
331
+
332
+ def plot_spectrogram_to_numpy(spectrogram):
333
+ global MATPLOTLIB_FLAG
334
+ if not MATPLOTLIB_FLAG:
335
+ import matplotlib
336
+ matplotlib.use("Agg")
337
+ MATPLOTLIB_FLAG = True
338
+ mpl_logger = logging.getLogger('matplotlib')
339
+ mpl_logger.setLevel(logging.WARNING)
340
+ import matplotlib.pylab as plt
341
+ import numpy as np
342
+
343
+ fig, ax = plt.subplots(figsize=(10,2))
344
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
345
+ interpolation='none')
346
+ plt.colorbar(im, ax=ax)
347
+ plt.xlabel("Frames")
348
+ plt.ylabel("Channels")
349
+ plt.tight_layout()
350
+
351
+ fig.canvas.draw()
352
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
353
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
354
+ plt.close()
355
+ return data
356
+
357
+
358
+ def plot_alignment_to_numpy(alignment, info=None):
359
+ global MATPLOTLIB_FLAG
360
+ if not MATPLOTLIB_FLAG:
361
+ import matplotlib
362
+ matplotlib.use("Agg")
363
+ MATPLOTLIB_FLAG = True
364
+ mpl_logger = logging.getLogger('matplotlib')
365
+ mpl_logger.setLevel(logging.WARNING)
366
+ import matplotlib.pylab as plt
367
+ import numpy as np
368
+
369
+ fig, ax = plt.subplots(figsize=(6, 4))
370
+ im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
371
+ interpolation='none')
372
+ fig.colorbar(im, ax=ax)
373
+ xlabel = 'Decoder timestep'
374
+ if info is not None:
375
+ xlabel += '\n\n' + info
376
+ plt.xlabel(xlabel)
377
+ plt.ylabel('Encoder timestep')
378
+ plt.tight_layout()
379
+
380
+ fig.canvas.draw()
381
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
382
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
383
+ plt.close()
384
+ return data
385
+
386
+
387
+ def load_wav_to_torch(full_path):
388
+ sampling_rate, data = read(full_path)
389
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
390
+
391
+
392
+ def load_filepaths_and_text(filename, split="|"):
393
+ with open(filename, encoding='utf-8') as f:
394
+ filepaths_and_text = [line.strip().split(split) for line in f]
395
+ return filepaths_and_text
396
+
397
+
398
+ def get_hparams(init=True):
399
+ parser = argparse.ArgumentParser()
400
+ parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
401
+ help='JSON file for configuration')
402
+ parser.add_argument('-m', '--model', type=str, required=True,
403
+ help='Model name')
404
+
405
+ args = parser.parse_args()
406
+ model_dir = os.path.join("./logs", args.model)
407
+
408
+ if not os.path.exists(model_dir):
409
+ os.makedirs(model_dir)
410
+
411
+ config_path = args.config
412
+ config_save_path = os.path.join(model_dir, "config.json")
413
+ if init:
414
+ with open(config_path, "r") as f:
415
+ data = f.read()
416
+ with open(config_save_path, "w") as f:
417
+ f.write(data)
418
+ else:
419
+ with open(config_save_path, "r") as f:
420
+ data = f.read()
421
+ config = json.loads(data)
422
+
423
+ hparams = HParams(**config)
424
+ hparams.model_dir = model_dir
425
+ return hparams
426
+
427
+
428
+ def get_hparams_from_dir(model_dir):
429
+ config_save_path = os.path.join(model_dir, "config.json")
430
+ with open(config_save_path, "r") as f:
431
+ data = f.read()
432
+ config = json.loads(data)
433
+
434
+ hparams =HParams(**config)
435
+ hparams.model_dir = model_dir
436
+ return hparams
437
+
438
+
439
+ def get_hparams_from_file(config_path):
440
+ with open(config_path, "r") as f:
441
+ data = f.read()
442
+ config = json.loads(data)
443
+
444
+ hparams =HParams(**config)
445
+ return hparams
446
+
447
+
448
+ def check_git_hash(model_dir):
449
+ source_dir = os.path.dirname(os.path.realpath(__file__))
450
+ if not os.path.exists(os.path.join(source_dir, ".git")):
451
+ logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
452
+ source_dir
453
+ ))
454
+ return
455
+
456
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
457
+
458
+ path = os.path.join(model_dir, "githash")
459
+ if os.path.exists(path):
460
+ saved_hash = open(path).read()
461
+ if saved_hash != cur_hash:
462
+ logger.warn("git hash values are different. {}(saved) != {}(current)".format(
463
+ saved_hash[:8], cur_hash[:8]))
464
+ else:
465
+ open(path, "w").write(cur_hash)
466
+
467
+
468
+ def get_logger(model_dir, filename="train.log"):
469
+ global logger
470
+ logger = logging.getLogger(os.path.basename(model_dir))
471
+ logger.setLevel(logging.DEBUG)
472
+
473
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
474
+ if not os.path.exists(model_dir):
475
+ os.makedirs(model_dir)
476
+ h = logging.FileHandler(os.path.join(model_dir, filename))
477
+ h.setLevel(logging.DEBUG)
478
+ h.setFormatter(formatter)
479
+ logger.addHandler(h)
480
+ return logger
481
+
482
+
483
+ def repeat_expand_2d(content, target_len):
484
+ # content : [h, t]
485
+
486
+ src_len = content.shape[-1]
487
+ target = torch.zeros([content.shape[0], target_len], dtype=torch.float).to(content.device)
488
+ temp = torch.arange(src_len+1) * target_len / src_len
489
+ current_pos = 0
490
+ for i in range(target_len):
491
+ if i < temp[current_pos+1]:
492
+ target[:, i] = content[:, current_pos]
493
+ else:
494
+ current_pos += 1
495
+ target[:, i] = content[:, current_pos]
496
+
497
+ return target
498
+
499
+
500
+ def mix_model(model_paths,mix_rate,mode):
501
+ mix_rate = torch.FloatTensor(mix_rate)/100
502
+ model_tem = torch.load(model_paths[0])
503
+ models = [torch.load(path)["model"] for path in model_paths]
504
+ if mode == 0:
505
+ mix_rate = F.softmax(mix_rate,dim=0)
506
+ for k in model_tem["model"].keys():
507
+ model_tem["model"][k] = torch.zeros_like(model_tem["model"][k])
508
+ for i,model in enumerate(models):
509
+ model_tem["model"][k] += model[k]*mix_rate[i]
510
+ torch.save(model_tem,os.path.join(os.path.curdir,"output.pth"))
511
+ return os.path.join(os.path.curdir,"output.pth")
512
+
513
+ class HParams():
514
+ def __init__(self, **kwargs):
515
+ for k, v in kwargs.items():
516
+ if type(v) == dict:
517
+ v = HParams(**v)
518
+ self[k] = v
519
+
520
+ def keys(self):
521
+ return self.__dict__.keys()
522
+
523
+ def items(self):
524
+ return self.__dict__.items()
525
+
526
+ def values(self):
527
+ return self.__dict__.values()
528
+
529
+ def __len__(self):
530
+ return len(self.__dict__)
531
+
532
+ def __getitem__(self, key):
533
+ return getattr(self, key)
534
+
535
+ def __setitem__(self, key, value):
536
+ return setattr(self, key, value)
537
+
538
+ def __contains__(self, key):
539
+ return key in self.__dict__
540
+
541
+ def __repr__(self):
542
+ return self.__dict__.__repr__()
543
+
so-vits-svc/vdecoder/__init__.py ADDED
File without changes
so-vits-svc/vdecoder/hifigan/__pycache__/env.cpython-38.pyc ADDED
Binary file (824 Bytes). View file
 
so-vits-svc/vdecoder/hifigan/__pycache__/models.cpython-38.pyc ADDED
Binary file (15.1 kB). View file
 
so-vits-svc/vdecoder/hifigan/__pycache__/utils.cpython-38.pyc ADDED
Binary file (2.35 kB). View file