├── .gitignore ├── CN-README.md ├── Eng_docs.md ├── LICENSE ├── README.md ├── app.py ├── cluster ├── __init__.py └── train_cluster.py ├── configs ├── config-legacy.json └── config.json ├── data_utils.py ├── dataset_raw └── wav_structure.txt ├── docs ├── 1.png └── 2.png ├── downloader_gui.py ├── filelists ├── test.txt ├── train.txt └── val.txt ├── flask_api.py ├── hubert ├── __init__.py ├── hubert_model.py ├── hubert_model_onnx.py └── put_hubert_ckpt_here ├── inference ├── __init__.py ├── infer_tool.py ├── infer_tool_grad.py └── slicer.py ├── inference_gui2.py ├── inference_main.py ├── logs └── 44k │ └── put_pretrained_model_here ├── models.py ├── modules ├── __init__.py ├── attentions.py ├── commons.py ├── losses.py ├── mel_processing.py └── modules.py ├── onnx ├── model_onnx.py ├── model_onnx_48k.py ├── onnx_export.py └── onnx_export_48k.py ├── onnx_export.py ├── onnxexport └── model_onnx.py ├── preprocess_flist_config.py ├── preprocess_hubert_f0.py ├── raw └── put_raw_wav_here ├── requirements.txt ├── requirements_win.txt ├── resample.py ├── sovits_utils.py ├── spec_gen.py ├── train.py ├── train_cpu.py ├── utils.py └── vdecoder ├── __init__.py └── hifigan ├── env.py ├── models.py ├── nvSTFT.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/python 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=python 4 | 5 | ### Python ### 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | pip-wheel-metadata/ 29 | share/python-wheels/ 30 | *.egg-info/ 31 | .installed.cfg 32 | *.egg 33 | MANIFEST 34 | 35 | # PyInstaller 36 | # Usually these files are written by a python script from a template 37 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 38 | *.manifest 39 | *.spec 40 | 41 | # Installer logs 42 | pip-log.txt 43 | pip-delete-this-directory.txt 44 | 45 | # Unit test / coverage reports 46 | htmlcov/ 47 | .tox/ 48 | .nox/ 49 | .coverage 50 | .coverage.* 51 | .cache 52 | nosetests.xml 53 | coverage.xml 54 | *.cover 55 | *.py,cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | pytestdebug.log 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | doc/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | # pytype static type analyzer 139 | .pytype/ 140 | 141 | # End of https://www.toptal.com/developers/gitignore/api/python 142 | 143 | dataset 144 | dataset_raw 145 | raw 146 | results 147 | inference/chunks_temp.json 148 | logs 149 | hubert/checkpoint_best_legacy_500.pt 150 | configs/config.json 151 | filelists/test.txt 152 | filelists/train.txt 153 | filelists/val.txt 154 | -------------------------------------------------------------------------------- /CN-README.md: -------------------------------------------------------------------------------- 1 | # SoftVC VITS Singing Voice Conversion 2 | 3 | 4 | ## Model Overview 5 | A singing voice coversion (SVC) model, using the SoftVC encoder to extract features from the input audio, sent into VITS along with the F0 to replace the original input to acheive a voice conversion effect. Additionally, changing the vocoder to [NSF HiFiGAN](https://github.com/openvpi/DiffSinger/tree/refactor/modules/nsf_hifigan) to fix the issue with unwanted staccato. 6 | 7 | ### 4.0 Features 8 | + Feature input replaced with [Content Vec](https://github.com/auspicious3000/contentvec) 9 | + Sampling rate changed to 44100hz 10 | + 由于更改了hop size等参数以及精简了部分模型结构,推理所需显存占用**大幅降低**,4.0版本44khz显存占用甚至小于3.0版本的32khz 11 | + 调整了部分代码结构 12 | + 数据集制作、训练过程和3.0保持一致,但模型完全不通用,数据集也需要全部重新预处理 13 | + 增加了可选项 1:vc模式自动预测音高f0,即转换语音时不需要手动输入变调key,男女声的调能自动转换,但仅限语音转换,该模式转换歌声会跑调 14 | + 增加了可选项 2:通过kmeans聚类方案减小音色泄漏,即使得音色更加像目标音色 15 | 16 | 在线demo:[![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/innnky/sovits4) 17 | 18 | ## 预先下载的模型文件 19 | + contentvec :[checkpoint_best_legacy_500.pt](https://ibm.box.com/s/z1wgl1stco8ffooyatzdwsqn2psd9lrr) 20 | + 放在`hubert`目录下 21 | + 预训练底模文件: [G_0.pth](https://huggingface.co/innnky/sovits_pretrained/resolve/main/sovits4/G_0.pth) 与 [D_0.pth](https://huggingface.co/innnky/sovits_pretrained/resolve/main/sovits4/D_0.pth) 22 | + 放在`logs/44k`目录下 23 | + 预训练底模训练数据集包含云灏 即霜 辉宇·星AI 派蒙 绫地宁宁,覆盖男女生常见音域,可以认为是相对通用的底模 24 | ```shell 25 | # 一键下载 26 | # contentvec 27 | # 由于作者提供的网盘没有直链,所以需要手动下载放在hubert目录 28 | # G与D预训练模型: 29 | wget -P logs/44k/ https://huggingface.co/innnky/sovits_pretrained/resolve/main/sovits4/G_0.pth 30 | wget -P logs/44k/ https://huggingface.co/innnky/sovits_pretrained/resolve/main/sovits4/D_0.pth 31 | 32 | ``` 33 | 34 | ## colab一键数据集制作、训练脚本 35 | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/19fxpo-ZoL_ShEUeZIZi6Di-YioWrEyhR#scrollTo=0gQcIZ8RsOkn) 36 | 37 | ## 数据集准备 38 | 仅需要以以下文件结构将数据集放入dataset_raw目录即可 39 | ```shell 40 | dataset_raw 41 | ├───speaker0 42 | │ ├───xxx1-xxx1.wav 43 | │ ├───... 44 | │ └───Lxx-0xx8.wav 45 | └───speaker1 46 | ├───xx2-0xxx2.wav 47 | ├───... 48 | └───xxx7-xxx007.wav 49 | ``` 50 | 51 | 52 | ## 数据预处理 53 | 1. 重采样至 44100hz 54 | 55 | ```shell 56 | python resample.py 57 | ``` 58 | 2. 自动划分训练集 验证集 测试集 以及自动生成配置文件 59 | ```shell 60 | python preprocess_flist_config.py 61 | ``` 62 | 3. 生成hubert与f0 63 | ```shell 64 | python preprocess_hubert_f0.py 65 | ``` 66 | 执行完以上步骤后 dataset 目录便是预处理完成的数据,可以删除dataset_raw文件夹了 67 | 68 | 69 | ## 训练 70 | ```shell 71 | python train.py -c configs/config.json -m 44k 72 | ``` 73 | 注:训练时会自动清除老的模型,只保留最新3个模型,如果想防止过拟合需要自己手动备份模型记录点,或修改配置文件keep_ckpts 0为永不清除 74 | 75 | ## 推理 76 | 使用 [inference_main.py](inference_main.py) 77 | 78 | 截止此处,4.0使用方法(训练、推理)和3.0完全一致,没有任何变化(推理增加了命令行支持) 79 | 80 | ```shell 81 | # 例 82 | python inference_main.py -m "logs/44k/G_30400.pth" -c "configs/config.json" -n "君の知らない物語-src.wav" -t 0 -s "nen" 83 | ``` 84 | 必填项部分 85 | + -m, --model_path:模型路径。 86 | + -c, --config_path:配置文件路径。 87 | + -n, --clean_names:wav 文件名列表,放在 raw 文件夹下。 88 | + -t, --trans:音高调整,支持正负(半音)。 89 | + -s, --spk_list:合成目标说话人名称。 90 | 91 | 可选项部分:见下一节 92 | + -a, --auto_predict_f0:语音转换自动预测音高,转换歌声时不要打开这个会严重跑调。 93 | + -cm, --cluster_model_path:聚类模型路径,如果没有训练聚类则随便填。 94 | + -cr, --cluster_infer_ratio:聚类方案占比,范围 0-1,若没有训练聚类模型则填 0 即可。 95 | 96 | ## 可选项 97 | 如果前面的效果已经满意,或者没看明白下面在讲啥,那后面的内容都可以忽略,不影响模型使用。(这些可选项影响比较小,可能在某些特定数据上有点效果,但大部分情况似乎都感知不太明显), 98 | ### 自动f0预测 99 | 4.0模型训练过程会训练一个f0预测器,对于语音转换可以开启自动音高预测,如果效果不好也可以使用手动的,但转换歌声时请不要启用此功能!!!会严重跑调!! 100 | + 在inference_main中设置auto_predict_f0为true即可 101 | ### 聚类音色泄漏控制 102 | 介绍:聚类方案可以减小音色泄漏,使得模型训练出来更像目标的音色(但其实不是特别明显),但是单纯的聚类方案会降低模型的咬字(会口齿不清)(这个很明显),本模型采用了融合的方式, 103 | 可以线性控制聚类方案与非聚类方案的占比,也就是可以手动在"像目标音色" 和 "咬字清晰" 之间调整比例,找到合适的折中点。 104 | 105 | 使用聚类前面的已有步骤不用进行任何的变动,只需要额外训练一个聚类模型,虽然效果比较有限,但训练成本也比较低 106 | + 训练过程: 107 | + 使用cpu性能较好的机器训练,据我的经验在腾讯云6核cpu训练每个speaker需要约4分钟即可完成训练 108 | + 执行python cluster/train_cluster.py ,模型的输出会在 logs/44k/kmeans_10000.pt 109 | + 推理过程: 110 | + inference_main中指定cluster_model_path 111 | + inference_main中指定cluster_infer_ratio,0为完全不使用聚类,1为只使用聚类,通常设置0.5即可 112 | 113 | ## Onnx导出 114 | 使用 [onnx_export.py](onnx_export.py) 115 | + 新建文件夹:`checkpoints` 并打开 116 | + 在`checkpoints`文件夹中新建一个文件夹作为项目文件夹,文件夹名为你的项目名称,比如`aziplayer` 117 | + 将你的模型更名为`model.pth`,配置文件更名为`config.json`,并放置到刚才创建的`aziplayer`文件夹下 118 | + 将 [onnx_export.py](onnx_export.py) 中`path = "NyaruTaffy"` 的 `"NyaruTaffy"` 修改为你的项目名称,`path = "aziplayer"` 119 | + 运行 [onnx_export.py](onnx_export.py) 120 | + 等待执行完毕,在你的项目文件夹下会生成一个`model.onnx`,即为导出的模型 121 | ### Onnx模型支持的UI 122 | + [MoeSS](https://github.com/NaruseMioShirakana/MoeSS) 123 | + 我去除了所有的训练用函数和一切复杂的转置,一行都没有保留,因为我认为只有去除了这些东西,才知道你用的是Onnx 124 | 125 | -------------------------------------------------------------------------------- /Eng_docs.md: -------------------------------------------------------------------------------- 1 | # SoftVC VITS Singing Voice Conversion 2 | 3 | ## Updates 4 | > According to incomplete statistics, it seems that training with multiple speakers may lead to **worsened leaking of voice timbre**. It is not recommended to train models with more than 5 speakers. The current suggestion is to try to train models with only a single speaker if you want to achieve a voice timbre that is more similar to the target. 5 | > Fixed the issue with unwanted staccato, improving audio quality by a decent amount.\ 6 | > The 2.0 version has been moved to the 2.0 branch.\ 7 | > Version 3.0 uses the code structure of FreeVC, which isn't compatible with older versions.\ 8 | > Compared to [DiffSVC](https://github.com/prophesier/diff-svc) , diffsvc performs much better when the training data is of extremely high quality, but this repository may perform better on datasets with lower quality. Additionally, this repository is much faster in terms of inference speed compared to diffsvc. 9 | 10 | ## Model Overview 11 | A singing voice coversion (SVC) model, using the SoftVC encoder to extract features from the input audio, sent into VITS along with the F0 to replace the original input to acheive a voice conversion effect. Additionally, changing the vocoder to [NSF HiFiGAN](https://github.com/openvpi/DiffSinger/tree/refactor/modules/nsf_hifigan) to fix the issue with unwanted staccato. 12 | 13 | ## Notice 14 | + The current branch is the 32kHz version, which requires less vram during inferencing, as well as faster inferencing speeds, and datasets for said branch take up less disk space. Thus the 32 kHz branch is recommended for use. 15 | + If you want to train 48 kHz variant models, switch to the [main branch](https://github.com/innnky/so-vits-svc/tree/main). 16 | 17 | 18 | ## Required models 19 | + soft vc hubert:[hubert-soft-0d54a1f4.pt](https://github.com/bshall/hubert/releases/download/v0.1/hubert-soft-0d54a1f4.pt) 20 | + Place under `hubert`. 21 | + Pretrained models [G_0.pth](https://huggingface.co/innnky/sovits_pretrained/resolve/main/G_0.pth) and [D_0.pth](https://huggingface.co/innnky/sovits_pretrained/resolve/main/D_0.pth) 22 | + Place under `logs/32k`. 23 | + Pretrained models are required, because from experiments, training from scratch can be rather unpredictable to say the least, and training with a pretrained model can greatly improve training speeds. 24 | + The pretrained model includes云灏, 即霜, 辉宇·星AI, 派蒙, and 绫地宁宁, covering the common ranges of both male and female voices, and so it can be seen as a rather universal pretrained model. 25 | + The pretrained model exludes the `optimizer speaker_embedding` section, rendering it only usable for pretraining and incapable of inferencing with. 26 | ```shell 27 | # For simple downloading. 28 | # hubert 29 | wget -P hubert/ https://github.com/bshall/hubert/releases/download/v0.1/hubert-soft-0d54a1f4.pt 30 | # G&D pretrained models 31 | wget -P logs/32k/ https://huggingface.co/innnky/sovits_pretrained/resolve/main/G_0.pth 32 | wget -P logs/32k/ https://huggingface.co/innnky/sovits_pretrained/resolve/main/D_0.pth 33 | 34 | ``` 35 | 36 | ## Colab notebook script for dataset creation and training. 37 | [colab training notebook](https://colab.research.google.com/drive/1rCUOOVG7-XQlVZuWRAj5IpGrMM8t07pE?usp=sharing) 38 | 39 | ## Dataset preparation 40 | All that is required is that the data be put under the `dataset_raw` folder in the structure format provided below. 41 | ```shell 42 | dataset_raw 43 | ├───speaker0 44 | │ ├───xxx1-xxx1.wav 45 | │ ├───... 46 | │ └───Lxx-0xx8.wav 47 | └───speaker1 48 | ├───xx2-0xxx2.wav 49 | ├───... 50 | └───xxx7-xxx007.wav 51 | ``` 52 | 53 | ## Data pre-processing. 54 | 1. Resample to 32khz 55 | 56 | ```shell 57 | python resample.py 58 | ``` 59 | 2. Automatically sort out training set, validation set, test set, and automatically generate configuration files. 60 | ```shell 61 | python preprocess_flist_config.py 62 | # Notice. 63 | # The n_speakers value in the config will be set automatically according to the amount of speakers in the dataset. 64 | # To reserve space for additionally added speakers in the dataset, the n_speakers value will be be set to twice the actual amount. 65 | # If you want even more space for adding more data, you can edit the n_speakers value in the config after runing this step. 66 | # This can not be changed after training starts. 67 | ``` 68 | 3. Generate hubert and F0 features/ 69 | ```shell 70 | python preprocess_hubert_f0.py 71 | ``` 72 | After running the step above, the `dataset` folder will contain all the pre-processed data, you can delete the `dataset_raw` folder after that. 73 | 74 | ## Training. 75 | ```shell 76 | python train.py -c configs/config.json -m 32k 77 | ``` 78 | 79 | ## Inferencing. 80 | 81 | Use [inference_main.py](inference_main.py) 82 | + Edit `model_path` to your newest checkpoint. 83 | + Place the input audio under the `raw` folder. 84 | + Change `clean_names` to the output file name. 85 | + Use `trans` to edit the pitch shifting amount (semitones). 86 | + Change `spk_list` to the speaker name. 87 | 88 | ## Onnx Exporting. 89 | ### **When exporting Onnx, please make sure you re-clone the whole repository!!!** 90 | Use [onnx_export.py](onnx_export.py) 91 | + Create a new folder called `checkpoints`. 92 | + Create a project folder in `checkpoints` folder with the desired name for your project, let's use `myproject` as example. Folder structure looks like `./checkpoints/myproject`. 93 | + Rename your model to `model.pth`, rename your config file to `config.json` then move them into `myproject` folder. 94 | + Modify [onnx_export.py](onnx_export.py) where `path = "NyaruTaffy"`, change `NyaruTaffy` to your project name, here it will be `path = "myproject"`. 95 | + Run [onnx_export.py](onnx_export.py) 96 | + Once it finished, a `model.onnx` will be generated in `myproject` folder, that's the model you just exported. 97 | + Notice: if you want to export a 48K model, please follow the instruction below or use `model_onnx_48k.py` directly. 98 | + Open [model_onnx.py](model_onnx.py) and change `hps={"sampling_rate": 32000...}` to `hps={"sampling_rate": 48000}` in class `SynthesizerTrn`. 99 | + Open [nvSTFT](/vdecoder/hifigan/nvSTFT.py) and replace all `32000` with `48000` 100 | ### Onnx Model UI Support 101 | + [MoeSS](https://github.com/NaruseMioShirakana/MoeSS) 102 | + All training function and transformation are removed, only if they are all removed you are actually using Onnx. 103 | 104 | ## Gradio (WebUI) 105 | Use [sovits_gradio.py](sovits_gradio.py) to run Gradio WebUI 106 | + Create a new folder called `checkpoints`. 107 | + Create a project folder in `checkpoints` folder with the desired name for your project, let's use `myproject` as example. Folder structure looks like `./checkpoints/myproject`. 108 | + Rename your model to `model.pth`, rename your config file to `config.json` then move them into `myproject` folder. 109 | + Run [sovits_gradio.py](sovits_gradio.py) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Jingyi Li 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | 4 | # os.system("wget -P cvec/ https://huggingface.co/spaces/innnky/nanami/resolve/main/checkpoint_best_legacy_500.pt") 5 | import gradio as gr 6 | import librosa 7 | import numpy as np 8 | import soundfile 9 | from inference.infer_tool import Svc 10 | import logging 11 | 12 | logging.getLogger('numba').setLevel(logging.WARNING) 13 | logging.getLogger('markdown_it').setLevel(logging.WARNING) 14 | logging.getLogger('urllib3').setLevel(logging.WARNING) 15 | logging.getLogger('matplotlib').setLevel(logging.WARNING) 16 | 17 | config_path = "configs/config.json" 18 | 19 | model = Svc("logs/44k/G_114400.pth", "configs/config.json", cluster_model_path="logs/44k/kmeans_10000.pt") 20 | 21 | 22 | 23 | def vc_fn(sid, input_audio, vc_transform, auto_f0,cluster_ratio, slice_db, noise_scale): 24 | if input_audio is None: 25 | return "You need to upload an audio", None 26 | sampling_rate, audio = input_audio 27 | # print(audio.shape,sampling_rate) 28 | duration = audio.shape[0] / sampling_rate 29 | if duration > 90: 30 | return "请上传小于90s的音频,需要转换长音频请本地进行转换", None 31 | audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32) 32 | if len(audio.shape) > 1: 33 | audio = librosa.to_mono(audio.transpose(1, 0)) 34 | if sampling_rate != 16000: 35 | audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000) 36 | print(audio.shape) 37 | out_wav_path = "temp.wav" 38 | soundfile.write(out_wav_path, audio, 16000, format="wav") 39 | print( cluster_ratio, auto_f0, noise_scale) 40 | _audio = model.slice_inference(out_wav_path, sid, vc_transform, slice_db, cluster_ratio, auto_f0, noise_scale) 41 | return "Success", (44100, _audio) 42 | 43 | 44 | app = gr.Blocks() 45 | with app: 46 | with gr.Tabs(): 47 | with gr.TabItem("Basic"): 48 | gr.Markdown(value=""" 49 | sovits4.0 在线demo 50 | 51 | 此demo为预训练底模在线demo,使用数据:云灏 即霜 辉宇·星AI 派蒙 绫地宁宁 52 | """) 53 | spks = list(model.spk2id.keys()) 54 | sid = gr.Dropdown(label="音色", choices=spks, value=spks[0]) 55 | vc_input3 = gr.Audio(label="上传音频(长度小于90秒)") 56 | vc_transform = gr.Number(label="变调(整数,可以正负,半音数量,升高八度就是12)", value=0) 57 | cluster_ratio = gr.Number(label="聚类模型混合比例,0-1之间,默认为0不启用聚类,能提升音色相似度,但会导致咬字下降(如果使用建议0.5左右)", value=0) 58 | auto_f0 = gr.Checkbox(label="自动f0预测,配合聚类模型f0预测效果更好,会导致变调功能失效(仅限转换语音,歌声不要勾选此项会究极跑调)", value=False) 59 | slice_db = gr.Number(label="切片阈值", value=-40) 60 | noise_scale = gr.Number(label="noise_scale 建议不要动,会影响音质,玄学参数", value=0.4) 61 | vc_submit = gr.Button("转换", variant="primary") 62 | vc_output1 = gr.Textbox(label="Output Message") 63 | vc_output2 = gr.Audio(label="Output Audio") 64 | vc_submit.click(vc_fn, [sid, vc_input3, vc_transform,auto_f0,cluster_ratio, slice_db, noise_scale], [vc_output1, vc_output2]) 65 | 66 | app.launch() 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /cluster/__init__.py: -------------------------------------------------------------------------------- 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 | if model.get(speaker) is None: 26 | print("Warning -- speaker "+speaker+" not found in cluster model.") 27 | print("Cluster model keys: ",model.keys()) 28 | print("Running anyways...") 29 | first_key = list(model.keys())[0] 30 | predict = model[first_key].predict(x) 31 | return model[first_key].cluster_centers_[predict] 32 | else: 33 | predict = model[speaker].predict(x) 34 | return model[speaker].cluster_centers_[predict] 35 | 36 | def get_center(model, x,speaker): 37 | return model[speaker].cluster_centers_[x] 38 | -------------------------------------------------------------------------------- /cluster/train_cluster.py: -------------------------------------------------------------------------------- 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 = 4000 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 | 90 | -------------------------------------------------------------------------------- /configs/config-legacy.json: -------------------------------------------------------------------------------- 1 | { 2 | "train": { 3 | "log_interval": 200, 4 | "eval_interval": 1000, 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 | }, 26 | "data": { 27 | "training_files": "filelists/train.txt", 28 | "validation_files": "filelists/val.txt", 29 | "max_wav_value": 32768.0, 30 | "sampling_rate": 44100, 31 | "filter_length": 2048, 32 | "hop_length": 512, 33 | "win_length": 2048, 34 | "n_mel_channels": 80, 35 | "mel_fmin": 0.0, 36 | "mel_fmax": 22050 37 | }, 38 | "model": { 39 | "inter_channels": 192, 40 | "hidden_channels": 192, 41 | "filter_channels": 768, 42 | "n_heads": 2, 43 | "n_layers": 6, 44 | "kernel_size": 3, 45 | "p_dropout": 0.1, 46 | "resblock": "1", 47 | "resblock_kernel_sizes": [3,7,11], 48 | "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]], 49 | "upsample_rates": [ 8, 8, 2, 2, 2], 50 | "upsample_initial_channel": 512, 51 | "upsample_kernel_sizes": [16,16, 4, 4, 4], 52 | "n_layers_q": 3, 53 | "use_spectral_norm": false, 54 | "gin_channels": 256, 55 | "ssl_dim": 256, 56 | "n_speakers": 200 57 | }, 58 | "spk": { 59 | "nyaru": 0, 60 | "huiyu": 1, 61 | "nen": 2, 62 | "paimon": 3, 63 | "yunhao": 4 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /configs/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "train": { 3 | "log_interval": 200, 4 | "eval_interval": 1000, 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 | }, 26 | "data": { 27 | "training_files": "filelists/train.txt", 28 | "validation_files": "filelists/val.txt", 29 | "max_wav_value": 32768.0, 30 | "sampling_rate": 44100, 31 | "filter_length": 2048, 32 | "hop_length": 512, 33 | "win_length": 2048, 34 | "n_mel_channels": 80, 35 | "mel_fmin": 0.0, 36 | "mel_fmax": 22050, 37 | "contentvec_final_proj": false 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": [ 49 | 3, 50 | 7, 51 | 11 52 | ], 53 | "resblock_dilation_sizes": [ 54 | [ 55 | 1, 56 | 3, 57 | 5 58 | ], 59 | [ 60 | 1, 61 | 3, 62 | 5 63 | ], 64 | [ 65 | 1, 66 | 3, 67 | 5 68 | ] 69 | ], 70 | "upsample_rates": [ 71 | 8, 72 | 8, 73 | 2, 74 | 2, 75 | 2 76 | ], 77 | "upsample_initial_channel": 512, 78 | "upsample_kernel_sizes": [ 79 | 16, 80 | 16, 81 | 4, 82 | 4, 83 | 4 84 | ], 85 | "n_layers_q": 3, 86 | "use_spectral_norm": false, 87 | "gin_channels": 256, 88 | "ssl_dim": 768, 89 | "n_speakers": 200 90 | }, 91 | "spk": { 92 | "Cheerilee": 0, 93 | "Chrysalis": 1, 94 | "Cozy Glow": 2, 95 | "Diamond Tiara": 3, 96 | "Moon Dancer": 4, 97 | "Mr. Cake": 5, 98 | "Mrs. Cake": 6, 99 | "Octavia": 7, 100 | "Spike": 8, 101 | "Spitfire": 9, 102 | "Tirek": 10 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /data_utils.py: -------------------------------------------------------------------------------- 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 sovits_utils 10 | from modules.mel_processing import spectrogram_torch, spec_to_mel_torch 11 | from sovits_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): 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 | def get_audio(self, filename): 42 | filename = filename.replace("\\", "/") 43 | audio, sampling_rate = load_wav_to_torch(filename) 44 | if sampling_rate != self.sampling_rate: 45 | raise ValueError("{} SR doesn't match target {} SR".format( 46 | sampling_rate, self.sampling_rate)) 47 | audio_norm = audio / self.max_wav_value 48 | audio_norm = audio_norm.unsqueeze(0) 49 | spec_filename = filename.replace(".wav", ".spec.pt") 50 | if os.path.exists(spec_filename): 51 | spec = torch.load(spec_filename) 52 | else: 53 | spec = spectrogram_torch(audio_norm, self.filter_length, 54 | self.sampling_rate, self.hop_length, self.win_length, 55 | center=False) 56 | spec = torch.squeeze(spec, 0) 57 | torch.save(spec, spec_filename) 58 | 59 | spk = filename.split("/")[-2] 60 | spk = torch.LongTensor([self.spk_map[spk]]) 61 | 62 | f0 = np.load(filename + ".f0.npy") 63 | f0, uv = sovits_utils.interpolate_f0(f0) 64 | f0 = torch.FloatTensor(f0) 65 | uv = torch.FloatTensor(uv) 66 | 67 | c = torch.load(filename+ ".soft.pt") 68 | c = sovits_utils.repeat_expand_2d(c.squeeze(0), f0.shape[0]) 69 | 70 | 71 | lmin = min(c.size(-1), spec.size(-1)) 72 | assert abs(c.size(-1) - spec.size(-1)) < 3, (c.size(-1), spec.size(-1), f0.shape, filename) 73 | assert abs(audio_norm.shape[1]-lmin * self.hop_length) < 3 * self.hop_length 74 | spec, c, f0, uv = spec[:, :lmin], c[:, :lmin], f0[:lmin], uv[:lmin] 75 | audio_norm = audio_norm[:, :lmin * self.hop_length] 76 | # if spec.shape[1] < 30: 77 | # print("skip too short audio:", filename) 78 | # return None 79 | if spec.shape[1] > 800: 80 | start = random.randint(0, spec.shape[1]-800) 81 | end = start + 790 82 | spec, c, f0, uv = spec[:, start:end], c[:, start:end], f0[start:end], uv[start:end] 83 | audio_norm = audio_norm[:, start * self.hop_length : end * self.hop_length] 84 | 85 | return c, f0, spec, audio_norm, spk, uv 86 | 87 | def __getitem__(self, index): 88 | return self.get_audio(self.audiopaths[index][0]) 89 | 90 | def __len__(self): 91 | return len(self.audiopaths) 92 | 93 | 94 | class TextAudioCollate: 95 | 96 | def __call__(self, batch): 97 | batch = [b for b in batch if b is not None] 98 | 99 | input_lengths, ids_sorted_decreasing = torch.sort( 100 | torch.LongTensor([x[0].shape[1] for x in batch]), 101 | dim=0, descending=True) 102 | 103 | max_c_len = max([x[0].size(1) for x in batch]) 104 | max_wav_len = max([x[3].size(1) for x in batch]) 105 | 106 | lengths = torch.LongTensor(len(batch)) 107 | 108 | c_padded = torch.FloatTensor(len(batch), batch[0][0].shape[0], max_c_len) 109 | f0_padded = torch.FloatTensor(len(batch), max_c_len) 110 | spec_padded = torch.FloatTensor(len(batch), batch[0][2].shape[0], max_c_len) 111 | wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) 112 | spkids = torch.LongTensor(len(batch), 1) 113 | uv_padded = torch.FloatTensor(len(batch), max_c_len) 114 | 115 | c_padded.zero_() 116 | spec_padded.zero_() 117 | f0_padded.zero_() 118 | wav_padded.zero_() 119 | uv_padded.zero_() 120 | 121 | for i in range(len(ids_sorted_decreasing)): 122 | row = batch[ids_sorted_decreasing[i]] 123 | 124 | c = row[0] 125 | c_padded[i, :, :c.size(1)] = c 126 | lengths[i] = c.size(1) 127 | 128 | f0 = row[1] 129 | f0_padded[i, :f0.size(0)] = f0 130 | 131 | spec = row[2] 132 | spec_padded[i, :, :spec.size(1)] = spec 133 | 134 | wav = row[3] 135 | wav_padded[i, :, :wav.size(1)] = wav 136 | 137 | spkids[i, 0] = row[4] 138 | 139 | uv = row[5] 140 | uv_padded[i, :uv.size(0)] = uv 141 | 142 | return c_padded, f0_padded, spec_padded, wav_padded, spkids, lengths, uv_padded 143 | -------------------------------------------------------------------------------- /dataset_raw/wav_structure.txt: -------------------------------------------------------------------------------- 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 | } 21 | -------------------------------------------------------------------------------- /docs/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/docs/1.png -------------------------------------------------------------------------------- /docs/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/docs/2.png -------------------------------------------------------------------------------- /downloader_gui.py: -------------------------------------------------------------------------------- 1 | from inference_gui2 import MODELS_DIR 2 | from PyQt5.QtWidgets import (QMainWindow, QPushButton, QCheckBox, QTableWidget, 3 | QApplication, QFrame, QVBoxLayout, QTableWidget, QTableWidgetItem, 4 | QAbstractScrollArea, QSizePolicy) 5 | from PyQt5.QtCore import Qt, QSize 6 | import huggingface_hub 7 | import os 8 | import glob 9 | import shutil 10 | import sys 11 | import requests 12 | from pathlib import Path 13 | 14 | # Only enable this if you plan on training off a downloaded model. 15 | DOWNLOAD_DISCRIMINATORS = False 16 | MODELS_DIR = os.path.join("so-vits-svc",MODELS_DIR) 17 | class DownloadStrategy: 18 | def __init__(self, repo_id : str, model_dir : str): 19 | """ Pull from HF to find available models """ 20 | pass 21 | 22 | def get_available_model_names(self) -> list: 23 | """ Returns a list of model names """ 24 | pass 25 | 26 | def check_present_model_name(self, name : str) -> bool: 27 | """ Returns True if model is already installed """ 28 | return False 29 | 30 | def download_model(self, name : str): 31 | """ Downloads model corresponding to name """ 32 | pass 33 | 34 | class FolderStrategy(DownloadStrategy): 35 | def __init__(self, repo_id, model_dir): 36 | self.repo_id = repo_id 37 | self.model_dir = model_dir 38 | self.model_repo = huggingface_hub.Repository( 39 | local_dir=self.model_dir, clone_from=self.repo_id, 40 | skip_lfs_files=True) 41 | self.model_repo.git_pull(lfs=False) 42 | self.model_folders = os.listdir(model_dir) 43 | self.model_folders.remove('.git') 44 | self.model_folders.remove('.gitattributes') 45 | 46 | def get_available_model_names(self): 47 | return self.model_folders 48 | 49 | def check_present_model_name(self, name): 50 | return bool(name in os.listdir(MODELS_DIR)) 51 | 52 | def download_model(self, model_name): 53 | print("Downloading "+model_name) 54 | basepath = os.path.join(self.model_dir, model_name) 55 | targetpath = os.path.join(MODELS_DIR, model_name) 56 | gen_pt = next(x for x in os.listdir(basepath) if x.startswith("G_")) 57 | disc_pt = next(x for x in os.listdir(basepath) if x.startswith("D_")) 58 | cfg = next(x for x in os.listdir(basepath) if x.endswith("json")) 59 | clust = [x for x in os.listdir(basepath) if x.endswith("pt")] 60 | 61 | huggingface_hub.hf_hub_download(repo_id = self.repo_id, 62 | filename = model_name + "/" + gen_pt, local_dir = MODELS_DIR, 63 | cache_dir = './cache', local_dir_use_symlinks=False, 64 | force_download=True) 65 | 66 | if DOWNLOAD_DISCRIMINATORS: 67 | huggingface_hub.hf_hub_download(repo_id = self.repo_id, 68 | filename = model_name + "/" + disc_pt, local_dir = MODELS_DIR, 69 | cache_dir = './cache', local_dir_use_symlinks=False, 70 | force_download=True) 71 | if len(clust) != 0: 72 | for c in clust: 73 | huggingface_hub.hf_hub_download(repo_id = self.repo_id, 74 | filename = model_name + "/" + c, local_dir = MODELS_DIR, 75 | cache_dir = './cache', local_dir_use_symlinks=False, 76 | force_download=True) 77 | shutil.copy(os.path.join(basepath, cfg), os.path.join(targetpath, cfg)) 78 | 79 | from zipfile import ZipFile 80 | 81 | class ZipStrategy(DownloadStrategy): 82 | def __init__(self, repo_id, model_dir, is_model=True): 83 | self.repo_id = repo_id 84 | self.model_dir = model_dir 85 | self.is_model = is_model # model or dataset 86 | self.model_repo = huggingface_hub.Repository( 87 | local_dir=self.model_dir, clone_from=self.repo_id, 88 | skip_lfs_files=True, repo_type=("model" if is_model else "dataset") 89 | ) 90 | self.model_repo.git_pull(lfs=False) 91 | self.model_zips = glob.glob(model_dir + "/**/*.zip", recursive=True) 92 | 93 | self.model_names = [Path(x).stem for x in self.model_zips] 94 | self.rel_paths = {Path(x).stem : 95 | str(Path(x).relative_to(model_dir)).replace('\\','/') 96 | for x in self.model_zips} 97 | 98 | def get_available_model_names(self): 99 | return self.model_names 100 | 101 | def check_present_model_name(self, name): 102 | return bool(name in os.listdir(MODELS_DIR)) 103 | 104 | def download_model(self, model_name): 105 | print("Downloading "+self.rel_paths[model_name]) 106 | huggingface_hub.hf_hub_download(repo_id = self.repo_id, 107 | filename = self.rel_paths[model_name], local_dir = MODELS_DIR, 108 | cache_dir="./cache", local_dir_use_symlinks=False, 109 | force_download=True, repo_type=( 110 | "model" if self.is_model else "dataset")) 111 | 112 | zip_path = os.path.join(MODELS_DIR,self.rel_paths[model_name]) 113 | with ZipFile(zip_path, 'r') as zipObj: 114 | zip_contents = zipObj.namelist() 115 | print(os.path.dirname(zip_contents[0])) 116 | if len(zip_contents) and len( 117 | os.path.dirname(zip_contents[0])) > 0: 118 | # assume that this zip is structured with 1 or more folders 119 | # containing speaker models directly 120 | zipObj.extractall(MODELS_DIR) 121 | else: 122 | # assume that this zip contains speaker models directly 123 | zipObj.extractall(os.path.join(MODELS_DIR, model_name)) 124 | os.remove(zip_path) 125 | 126 | # clean stub directories 127 | for root, dirs, files in os.walk(MODELS_DIR, topdown=False): 128 | if not dirs and not files: 129 | os.rmdir(root) 130 | 131 | 132 | class UrlZipStrategy(DownloadStrategy): 133 | def __init__(self, repo_id=None, model_dir=None): 134 | self.model_urls = ["https://huggingface.co/datasets/HazySkies/SV3/" 135 | "resolve/main/sovits_athena_44khz_10000_sv4.zip", 136 | "https://huggingface.co/datasets/HazySkies/SV3/resolve/main/" 137 | "sovits_athena_44khz_25000_sv4.zip", 138 | "https://huggingface.co/datasets/HazySkies/SV3/resolve/main/" 139 | "sovits_tfh_arizona_44khz_20000_sv4.zip", 140 | "https://huggingface.co/datasets/HazySkies/SV3/resolve/main" 141 | "sovits_tfh_velvet_44khz_20000_sv4.zip"] 142 | 143 | self.model_names = [Path(x).stem for x in self.model_urls] 144 | self.name_url_map = { Path(x).stem : x for x in self.model_urls } 145 | 146 | def get_available_model_names(self): 147 | return self.model_names 148 | 149 | def check_present_model_name(self, name): 150 | return bool(name in os.listdir(MODELS_DIR)) 151 | 152 | def download_model(self, model_name): 153 | print("Downloading "+model_name) 154 | zip_path = os.path.join(MODELS_DIR,model_name+'.zip') 155 | zip_url = self.name_url_map[model_name] 156 | r = requests.get(zip_url, allow_redirects=True) 157 | with open(zip_path) as f: 158 | f.write(r.content) 159 | with ZipFile(zip_path, 'r') as zipObj: 160 | zipObj.extractall(MODELS_DIR) 161 | os.remove(zip_path) 162 | 163 | class DownloaderGui (QMainWindow): 164 | def __init__(self): 165 | super().__init__() 166 | print("Downloading repos...") 167 | self.strategies = [ 168 | FolderStrategy("therealvul/so-vits-svc-4.0", 169 | "repositories/hf_vul_model"), 170 | FolderStrategy("OlivineEllva/so-vits-svc-4.0-models", 171 | "repositories/hf_oe_model"), 172 | ZipStrategy("Amo/so-vits-svc-4.0_GA", 173 | "repositories/hf_amo_models"), 174 | ZipStrategy("HazySkies/SV3", 175 | "repositories/hf_hazy_models", False)] 176 | print("Finished downloading repos") 177 | 178 | self.setWindowTitle("so-vits-svc 4.0 Downloader") 179 | self.central_widget = QFrame() 180 | self.layout = QVBoxLayout(self.central_widget) 181 | self.setCentralWidget(self.central_widget) 182 | 183 | self.model_table = QTableWidget() 184 | self.layout.addWidget(self.model_table) 185 | self.model_table.setColumnCount(3) 186 | self.model_table.setHorizontalHeaderLabels( 187 | ['Model name', 'Check to install', 'Detected?']) 188 | self.model_table.setSizeAdjustPolicy( 189 | QAbstractScrollArea.AdjustToContents) 190 | 191 | self.available_models = {} 192 | self.present_map = {} 193 | self.checkbox_map = {} 194 | for i,v in enumerate(self.strategies): 195 | available_models = v.get_available_model_names() 196 | for m in available_models: 197 | self.available_models[m] = i 198 | self.present_map[m] = v.check_present_model_name(m) 199 | self.checkbox_map[m] = QCheckBox() 200 | self.checkbox_map[m].setStyleSheet("margin-left:50%;" 201 | "margin-right:50;") 202 | 203 | # Populate table 204 | self.model_table.setRowCount(len(self.available_models.items())) 205 | for i,v0 in enumerate(self.available_models.items()): 206 | k,v = v0 207 | # Model name 208 | model_name = QTableWidgetItem(str(k)) 209 | self.model_table.setItem(i,0,model_name) 210 | model_name.setFlags(model_name.flags() ^ Qt.ItemIsEditable) 211 | # Check to install 212 | self.model_table.setCellWidget(i,1,self.checkbox_map[k]) 213 | # Detected on system? 214 | detected = QTableWidgetItem(str(self.present_map[k])) 215 | detected.setFlags(detected.flags() ^ Qt.ItemIsEditable) 216 | self.model_table.setItem(i,2,detected) 217 | 218 | self.model_table.resizeColumnsToContents() 219 | self.model_table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 220 | self.model_table.setSizePolicy(QSizePolicy.Expanding, 221 | QSizePolicy.Expanding) 222 | 223 | size = QSize(600,1000) 224 | self.model_table.setMinimumSize(size) 225 | self.model_table.setMaximumSize(size) 226 | 227 | self.download_button = QPushButton("Download selected") 228 | self.layout.addWidget(self.download_button) 229 | self.download_button.clicked.connect(self.download_selected) 230 | 231 | def download_selected(self): 232 | for i,v0 in enumerate(self.available_models.items()): 233 | k,v = v0 234 | if self.checkbox_map[k].isChecked(): 235 | self.strategies[self.available_models[k]].download_model(k) 236 | self.update_available() 237 | 238 | def update_available(self): 239 | self.model_table.clearContents() 240 | 241 | for i,v0 in enumerate(self.available_models.items()): 242 | k,v = v0 243 | self.present_map[k] = self.strategies[v].check_present_model_name( 244 | k) 245 | 246 | # Model name 247 | model_name = QTableWidgetItem(str(k)) 248 | self.model_table.setItem(i,0,model_name) 249 | model_name.setFlags(model_name.flags() ^ Qt.ItemIsEditable) 250 | # Check to install 251 | self.checkbox_map[k] = QCheckBox() 252 | self.checkbox_map[k].setStyleSheet("margin-left:50%;" 253 | "margin-right:50;") 254 | self.model_table.setCellWidget(i,1,self.checkbox_map[k]) 255 | # Detected on system? 256 | detected = QTableWidgetItem(str(self.present_map[k])) 257 | detected.setFlags(detected.flags() ^ Qt.ItemIsEditable) 258 | self.model_table.setItem(i,2,detected) 259 | 260 | if __name__ == '__main__': 261 | if (Path(os.getcwd()).stem == 'so-vits-svc' or 262 | ("inference_gui2.py" in os.listdir())): 263 | os.chdir('..') 264 | 265 | if not os.path.exists(MODELS_DIR): 266 | os.makedirs(MODELS_DIR, exist_ok=True) 267 | 268 | app = QApplication(sys.argv) 269 | w = DownloaderGui() 270 | w.show() 271 | app.exec() 272 | -------------------------------------------------------------------------------- /filelists/test.txt: -------------------------------------------------------------------------------- 1 | ./dataset/44k/taffy/000562.wav 2 | ./dataset/44k/nyaru/000011.wav 3 | ./dataset/44k/nyaru/000008.wav 4 | ./dataset/44k/taffy/000563.wav 5 | -------------------------------------------------------------------------------- /filelists/train.txt: -------------------------------------------------------------------------------- 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 16 | -------------------------------------------------------------------------------- /filelists/val.txt: -------------------------------------------------------------------------------- 1 | ./dataset/44k/nyaru/000003.wav 2 | ./dataset/44k/nyaru/000007.wav 3 | ./dataset/44k/taffy/000558.wav 4 | ./dataset/44k/taffy/000556.wav 5 | -------------------------------------------------------------------------------- /flask_api.py: -------------------------------------------------------------------------------- 1 | import io 2 | import logging 3 | 4 | import soundfile 5 | import torch 6 | import torchaudio 7 | from flask import Flask, request, send_file 8 | from flask_cors import CORS 9 | 10 | from inference.infer_tool import Svc, RealTimeVC 11 | 12 | app = Flask(__name__) 13 | 14 | CORS(app) 15 | 16 | logging.getLogger('numba').setLevel(logging.WARNING) 17 | 18 | 19 | @app.route("/voiceChangeModel", methods=["POST"]) 20 | def voice_change_model(): 21 | request_form = request.form 22 | wave_file = request.files.get("sample", None) 23 | # 变调信息 24 | f_pitch_change = float(request_form.get("fPitchChange", 0)) 25 | # DAW所需的采样率 26 | daw_sample = int(float(request_form.get("sampleRate", 0))) 27 | speaker_id = int(float(request_form.get("sSpeakId", 0))) 28 | # http获得wav文件并转换 29 | input_wav_path = io.BytesIO(wave_file.read()) 30 | 31 | # 模型推理 32 | if raw_infer: 33 | out_audio, out_sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path) 34 | tar_audio = torchaudio.functional.resample(out_audio, svc_model.target_sample, daw_sample) 35 | else: 36 | out_audio = svc.process(svc_model, speaker_id, f_pitch_change, input_wav_path) 37 | tar_audio = torchaudio.functional.resample(torch.from_numpy(out_audio), svc_model.target_sample, daw_sample) 38 | # 返回音频 39 | out_wav_path = io.BytesIO() 40 | soundfile.write(out_wav_path, tar_audio.cpu().numpy(), daw_sample, format="wav") 41 | out_wav_path.seek(0) 42 | return send_file(out_wav_path, download_name="temp.wav", as_attachment=True) 43 | 44 | 45 | if __name__ == '__main__': 46 | # 启用则为直接切片合成,False为交叉淡化方式 47 | # vst插件调整0.3-0.5s切片时间可以降低延迟,直接切片方法会有连接处爆音、交叉淡化会有轻微重叠声音 48 | # 自行选择能接受的方法,或将vst最大切片时间调整为1s,此处设为Ture,延迟大音质稳定一些 49 | raw_infer = True 50 | # 每个模型和config是唯一对应的 51 | model_name = "logs/32k/G_174000-Copy1.pth" 52 | config_name = "configs/config.json" 53 | svc_model = Svc(model_name, config_name) 54 | svc = RealTimeVC() 55 | # 此处与vst插件对应,不建议更改 56 | app.run(port=6842, host="0.0.0.0", debug=False, threaded=False) 57 | -------------------------------------------------------------------------------- /hubert/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/hubert/__init__.py -------------------------------------------------------------------------------- /hubert/hubert_model.py: -------------------------------------------------------------------------------- 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 223 | -------------------------------------------------------------------------------- /hubert/hubert_model_onnx.py: -------------------------------------------------------------------------------- 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 218 | -------------------------------------------------------------------------------- /hubert/put_hubert_ckpt_here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/hubert/put_hubert_ckpt_here -------------------------------------------------------------------------------- /inference/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/inference/__init__.py -------------------------------------------------------------------------------- /inference/infer_tool.py: -------------------------------------------------------------------------------- 1 | import zlib 2 | import hashlib 3 | import io 4 | import json 5 | import logging 6 | import os 7 | import time 8 | import sys 9 | from pathlib import Path 10 | from inference import slicer 11 | 12 | import librosa 13 | import numpy as np 14 | # import onnxruntime 15 | import parselmouth 16 | import soundfile 17 | import torch 18 | import torchaudio 19 | import pyworld 20 | 21 | import cluster 22 | from hubert import hubert_model 23 | import sovits_utils 24 | from models import SynthesizerTrn 25 | 26 | logging.getLogger('matplotlib').setLevel(logging.WARNING) 27 | 28 | def read_temp(file_name): 29 | if not os.path.exists(file_name): 30 | with open(file_name, "w") as f: 31 | f.write(json.dumps({"info": "temp_dict"})) 32 | return {} 33 | else: 34 | try: 35 | with open(file_name, "r") as f: 36 | data = f.read() 37 | data_dict = json.loads(data) 38 | if os.path.getsize(file_name) > 50 * 1024 * 1024: 39 | f_name = file_name.replace("\\", "/").split("/")[-1] 40 | print(f"clean {f_name}") 41 | for wav_hash in list(data_dict.keys()): 42 | if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600: 43 | del data_dict[wav_hash] 44 | except Exception as e: 45 | print(e) 46 | print(f"{file_name} error,auto rebuild file") 47 | data_dict = {"info": "temp_dict"} 48 | return data_dict 49 | 50 | 51 | def write_temp(file_name, data): 52 | with open(file_name, "w") as f: 53 | f.write(json.dumps(data)) 54 | 55 | 56 | def timeit(func): 57 | def run(*args, **kwargs): 58 | t = time.time() 59 | res = func(*args, **kwargs) 60 | print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t)) 61 | return res 62 | 63 | return run 64 | 65 | 66 | def format_wav(audio_path): 67 | if Path(audio_path).suffix == '.wav': 68 | return 69 | raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None) 70 | soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate) 71 | 72 | 73 | def get_end_file(dir_path, end): 74 | file_lists = [] 75 | for root, dirs, files in os.walk(dir_path): 76 | files = [f for f in files if f[0] != '.'] 77 | dirs[:] = [d for d in dirs if d[0] != '.'] 78 | for f_file in files: 79 | if f_file.endswith(end): 80 | file_lists.append(os.path.join(root, f_file).replace("\\", "/")) 81 | return file_lists 82 | 83 | 84 | def get_md5(content): 85 | return hashlib.new("md5", content).hexdigest() 86 | 87 | def fill_a_to_b(a, b): 88 | if len(a) < len(b): 89 | for _ in range(0, len(b) - len(a)): 90 | a.append(a[0]) 91 | 92 | def mkdir(paths: list): 93 | for path in paths: 94 | if not os.path.exists(path): 95 | os.mkdir(path) 96 | 97 | def pad_array(arr, target_length): 98 | current_length = arr.shape[0] 99 | if current_length >= target_length: 100 | return arr 101 | else: 102 | pad_width = target_length - current_length 103 | pad_left = pad_width // 2 104 | pad_right = pad_width - pad_left 105 | padded_arr = np.pad(arr, (pad_left, pad_right), 'constant', constant_values=(0, 0)) 106 | return padded_arr 107 | 108 | 109 | class Svc(object): 110 | def __init__(self, net_g_path, config_path, 111 | device=None, 112 | cluster_model_path="logs/44k/kmeans_10000.pt", 113 | quiet=False): 114 | self.net_g_path = net_g_path 115 | if device is None: 116 | self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") 117 | else: 118 | self.dev = torch.device(device) 119 | self.net_g_ms = None 120 | self.hps_ms = sovits_utils.get_hparams_from_file(config_path) 121 | self.target_sample = self.hps_ms.data.sampling_rate 122 | self.hop_size = self.hps_ms.data.hop_length 123 | self.spk2id = self.hps_ms.spk 124 | self.use_old_f0 = False 125 | self.use_crepe = False 126 | self.quiet_mode = quiet 127 | self.voice_threshold = 0.6 128 | self.f0_cache = {} 129 | 130 | # 加载hubert 131 | self.hubert_model = sovits_utils.get_hubert_model( 132 | self.quiet_mode).to(self.dev) 133 | self.load_model() 134 | if os.path.exists(cluster_model_path): 135 | self.cluster_model = cluster.get_cluster_model(cluster_model_path) 136 | 137 | def hotload_cluster(self, cluster_model_path): 138 | if os.path.exists(cluster_model_path): 139 | self.cluster_model = cluster.get_cluster_model(cluster_model_path) 140 | 141 | def load_model(self): 142 | # 获取模型配置 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 | _ = sovits_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, 156 | f0_method="harvest"): 157 | 158 | wav, sr = librosa.load(in_path, sr=self.target_sample) 159 | 160 | f0_key = (zlib.adler32(bytes(wav)), self.voice_threshold, 161 | self.use_crepe, self.use_old_f0) 162 | 163 | #if f0_key in self.f0_cache: 164 | if False: 165 | f0 = self.f0_cache[f0_key] 166 | elif f0_method == "crepe": 167 | f0 = sovits_utils.compute_f0_crepe(wav, 168 | sampling_rate=self.target_sample, 169 | hop_length=self.hop_size, voice_thresh=self.voice_threshold) 170 | elif f0_method == "parselmouth_old": 171 | f0 = sovits_utils.compute_f0_parselmouth(wav, 172 | sampling_rate=self.target_sample, hop_length=self.hop_size) 173 | elif f0_method == "parselmouth_new": 174 | f0 = sovits_utils.compute_f0_parselmouth_alt(wav, 175 | sampling_rate=self.target_sample, 176 | hop_length=self.hop_size, voice_thresh=self.voice_threshold) 177 | elif f0_method == "dio": 178 | f0 = sovits_utils.compute_f0_dio(wav, sampling_rate= 179 | self.target_sample, hop_length=self.hop_size) 180 | elif f0_method == "harvest": # preferred for low SNR 181 | f0 = sovits_utils.compute_f0_harvest(wav, sampling_rate= 182 | self.target_sample, hop_length=self.hop_size) 183 | 184 | self.f0_cache[f0_key] = f0 185 | f0, uv = sovits_utils.interpolate_f0(f0) 186 | f0 = torch.FloatTensor(f0) 187 | uv = torch.FloatTensor(uv) 188 | f0 = f0 * 2 ** (tran / 12) 189 | f0 = f0.unsqueeze(0).to(self.dev) 190 | uv = uv.unsqueeze(0).to(self.dev) 191 | 192 | wav16k = librosa.resample(wav, orig_sr=self.target_sample, target_sr=16000) 193 | wav16k = torch.from_numpy(wav16k).to(self.dev) 194 | c = sovits_utils.get_hubert_content( 195 | self.hubert_model, 196 | wav_16k_tensor=wav16k, 197 | legacy_final_proj=self.hps_ms.data.get( 198 | "contentvec_final_proj", True)) 199 | c = sovits_utils.repeat_expand_2d(c.squeeze(0), f0.shape[1]) 200 | 201 | if cluster_infer_ratio !=0: 202 | cluster_c = cluster.get_cluster_center_result( 203 | self.cluster_model, c.cpu().numpy().T, speaker).T 204 | cluster_c = torch.FloatTensor(cluster_c).to(self.dev) 205 | c = cluster_infer_ratio * cluster_c + (1 - cluster_infer_ratio) * c 206 | 207 | c = c.unsqueeze(0) 208 | return c, f0, uv 209 | 210 | def infer(self, speaker, tran, raw_path, 211 | cluster_infer_ratio=0, 212 | auto_predict_f0=False, 213 | noice_scale=0.8, 214 | f0_method="harvest"): 215 | speaker_id = self.spk2id[speaker] 216 | sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0) 217 | c, f0, uv = self.get_unit_f0( 218 | raw_path, tran, cluster_infer_ratio, speaker, f0_method) 219 | if "half" in self.net_g_path and torch.cuda.is_available(): 220 | c = c.half() 221 | with torch.no_grad(): 222 | start = time.time() 223 | 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() 224 | use_time = time.time() - start 225 | if not self.quiet_mode: 226 | print("vits use time:{}".format(use_time)) 227 | return audio, audio.shape[-1] 228 | 229 | def slice_inference(self,raw_audio_path, spk, tran, slice_db,cluster_infer_ratio, auto_predict_f0,noice_scale, pad_seconds=0.5): 230 | wav_path = raw_audio_path 231 | chunks = slicer.cut(wav_path, db_thresh=slice_db) 232 | audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks) 233 | 234 | audio = [] 235 | for (slice_tag, data) in audio_data: 236 | if not self.quiet_mode: 237 | print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======') 238 | # padd 239 | pad_len = int(audio_sr * pad_seconds) 240 | data = np.concatenate([np.zeros([pad_len]), data, np.zeros([pad_len])]) 241 | length = int(np.ceil(len(data) / audio_sr * self.target_sample)) 242 | raw_path = io.BytesIO() 243 | soundfile.write(raw_path, data, audio_sr, format="wav") 244 | raw_path.seek(0) 245 | if slice_tag: 246 | if not self.quiet_mode: 247 | print('jump empty segment') 248 | _audio = np.zeros(length) 249 | else: 250 | out_audio, out_sr = self.infer(spk, tran, raw_path, 251 | cluster_infer_ratio=cluster_infer_ratio, 252 | auto_predict_f0=auto_predict_f0, 253 | noice_scale=noice_scale 254 | ) 255 | _audio = out_audio.cpu().numpy() 256 | 257 | pad_len = int(self.target_sample * pad_seconds) 258 | _audio = _audio[pad_len:-pad_len] 259 | audio.extend(list(_audio)) 260 | return np.array(audio) 261 | 262 | 263 | class RealTimeVC: 264 | def __init__(self): 265 | self.last_chunk = None 266 | self.last_o = None 267 | self.chunk_len = 16000 # 区块长度 268 | self.pre_len = 3840 # 交叉淡化长度,640的倍数 269 | 270 | """输入输出都是1维numpy 音频波形数组""" 271 | 272 | def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path): 273 | import maad 274 | audio, sr = torchaudio.load(input_wav_path) 275 | audio = audio.cpu().numpy()[0] 276 | temp_wav = io.BytesIO() 277 | if self.last_chunk is None: 278 | input_wav_path.seek(0) 279 | audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path) 280 | audio = audio.cpu().numpy() 281 | self.last_chunk = audio[-self.pre_len:] 282 | self.last_o = audio 283 | return audio[-self.chunk_len:] 284 | else: 285 | audio = np.concatenate([self.last_chunk, audio]) 286 | soundfile.write(temp_wav, audio, sr, format="wav") 287 | temp_wav.seek(0) 288 | audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav) 289 | audio = audio.cpu().numpy() 290 | ret = maad.util.crossfade(self.last_o, audio, self.pre_len) 291 | self.last_chunk = audio[-self.pre_len:] 292 | self.last_o = audio 293 | return ret[self.chunk_len:2 * self.chunk_len] 294 | -------------------------------------------------------------------------------- /inference/infer_tool_grad.py: -------------------------------------------------------------------------------- 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) 161 | -------------------------------------------------------------------------------- /inference/slicer.py: -------------------------------------------------------------------------------- 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 | # 第一段静音并非从头开始,补上有声片段 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 | # 标识有声片段(跳过第一段) 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 | # 标识所有静音片段 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 | # 最后一段静音并非结尾,补上结尾片段 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 143 | -------------------------------------------------------------------------------- /inference_main.py: -------------------------------------------------------------------------------- 1 | import io 2 | import logging 3 | import time 4 | from pathlib import Path 5 | 6 | import librosa 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | import soundfile 10 | 11 | from inference import infer_tool 12 | from inference import slicer 13 | from inference.infer_tool import Svc 14 | 15 | logging.getLogger('numba').setLevel(logging.WARNING) 16 | chunks_dict = infer_tool.read_temp("inference/chunks_temp.json") 17 | 18 | 19 | 20 | def main(): 21 | import argparse 22 | 23 | parser = argparse.ArgumentParser(description='sovits4 inference') 24 | 25 | # 一定要设置的部分 26 | parser.add_argument('-m', '--model_path', type=str, default="logs/44k/G_0.pth", help='模型路径') 27 | parser.add_argument('-c', '--config_path', type=str, default="configs/config.json", help='配置文件路径') 28 | parser.add_argument('-n', '--clean_names', type=str, nargs='+', default=["君の知らない物語-src.wav"], help='wav文件名列表,放在raw文件夹下') 29 | parser.add_argument('-t', '--trans', type=int, nargs='+', default=[0], help='音高调整,支持正负(半音)') 30 | parser.add_argument('-s', '--spk_list', type=str, nargs='+', default=['nen'], help='合成目标说话人名称') 31 | 32 | # 可选项部分 33 | parser.add_argument('-a', '--auto_predict_f0', action='store_true', default=False, 34 | help='语音转换自动预测音高,转换歌声时不要打开这个会严重跑调') 35 | parser.add_argument('-cm', '--cluster_model_path', type=str, default="logs/44k/kmeans_10000.pt", help='聚类模型路径,如果没有训练聚类则随便填') 36 | parser.add_argument('-cr', '--cluster_infer_ratio', type=float, default=0, help='聚类方案占比,范围0-1,若没有训练聚类模型则填0即可') 37 | 38 | # 不用动的部分 39 | parser.add_argument('-sd', '--slice_db', type=int, default=-40, help='默认-40,嘈杂的音频可以-30,干声保留呼吸可以-50') 40 | parser.add_argument('-d', '--device', type=str, default=None, help='推理设备,None则为自动选择cpu和gpu') 41 | parser.add_argument('-ns', '--noice_scale', type=float, default=0.4, help='噪音级别,会影响咬字和音质,较为玄学') 42 | parser.add_argument('-p', '--pad_seconds', type=float, default=0.5, help='推理音频pad秒数,由于未知原因开头结尾会有异响,pad一小段静音段后就不会出现') 43 | parser.add_argument('-wf', '--wav_format', type=str, default='flac', help='音频输出格式') 44 | 45 | args = parser.parse_args() 46 | 47 | svc_model = Svc(args.model_path, args.config_path, args.device, args.cluster_model_path) 48 | infer_tool.mkdir(["raw", "results"]) 49 | clean_names = args.clean_names 50 | trans = args.trans 51 | spk_list = args.spk_list 52 | slice_db = args.slice_db 53 | wav_format = args.wav_format 54 | auto_predict_f0 = args.auto_predict_f0 55 | cluster_infer_ratio = args.cluster_infer_ratio 56 | noice_scale = args.noice_scale 57 | pad_seconds = args.pad_seconds 58 | 59 | infer_tool.fill_a_to_b(trans, clean_names) 60 | for clean_name, tran in zip(clean_names, trans): 61 | raw_audio_path = f"raw/{clean_name}" 62 | if "." not in raw_audio_path: 63 | raw_audio_path += ".wav" 64 | infer_tool.format_wav(raw_audio_path) 65 | wav_path = Path(raw_audio_path).with_suffix('.wav') 66 | chunks = slicer.cut(wav_path, db_thresh=slice_db) 67 | audio_data, audio_sr = slicer.chunks2audio(wav_path, chunks) 68 | 69 | for spk in spk_list: 70 | audio = [] 71 | for (slice_tag, data) in audio_data: 72 | print(f'#=====segment start, {round(len(data) / audio_sr, 3)}s======') 73 | 74 | length = int(np.ceil(len(data) / audio_sr * svc_model.target_sample)) 75 | if slice_tag: 76 | print('jump empty segment') 77 | _audio = np.zeros(length) 78 | else: 79 | # padd 80 | pad_len = int(audio_sr * pad_seconds) 81 | data = np.concatenate([np.zeros([pad_len]), data, np.zeros([pad_len])]) 82 | raw_path = io.BytesIO() 83 | soundfile.write(raw_path, data, audio_sr, format="wav") 84 | raw_path.seek(0) 85 | out_audio, out_sr = svc_model.infer(spk, tran, raw_path, 86 | cluster_infer_ratio=cluster_infer_ratio, 87 | auto_predict_f0=auto_predict_f0, 88 | noice_scale=noice_scale 89 | ) 90 | _audio = out_audio.cpu().numpy() 91 | pad_len = int(svc_model.target_sample * pad_seconds) 92 | _audio = _audio[pad_len:-pad_len] 93 | 94 | audio.extend(list(infer_tool.pad_array(_audio, length))) 95 | key = "auto" if auto_predict_f0 else f"{tran}key" 96 | cluster_name = "" if cluster_infer_ratio == 0 else f"_{cluster_infer_ratio}" 97 | res_path = f'./results/{clean_name}_{key}_{spk}{cluster_name}.{wav_format}' 98 | soundfile.write(res_path, audio, svc_model.target_sample, format=wav_format) 99 | 100 | if __name__ == '__main__': 101 | main() 102 | -------------------------------------------------------------------------------- /logs/44k/put_pretrained_model_here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/logs/44k/put_pretrained_model_here -------------------------------------------------------------------------------- /modules/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/modules/__init__.py -------------------------------------------------------------------------------- /modules/attentions.py: -------------------------------------------------------------------------------- 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 350 | -------------------------------------------------------------------------------- /modules/commons.py: -------------------------------------------------------------------------------- 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 189 | -------------------------------------------------------------------------------- /modules/losses.py: -------------------------------------------------------------------------------- 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 62 | -------------------------------------------------------------------------------- /modules/mel_processing.py: -------------------------------------------------------------------------------- 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 113 | -------------------------------------------------------------------------------- /modules/modules.py: -------------------------------------------------------------------------------- 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 343 | -------------------------------------------------------------------------------- /onnx/model_onnx.py: -------------------------------------------------------------------------------- 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 | from modules.commons import init_weights, get_padding 14 | from vdecoder.hifigan.models import Generator 15 | from utils import f0_to_coarse 16 | 17 | class ResidualCouplingBlock(nn.Module): 18 | def __init__(self, 19 | channels, 20 | hidden_channels, 21 | kernel_size, 22 | dilation_rate, 23 | n_layers, 24 | n_flows=4, 25 | gin_channels=0): 26 | super().__init__() 27 | self.channels = channels 28 | self.hidden_channels = hidden_channels 29 | self.kernel_size = kernel_size 30 | self.dilation_rate = dilation_rate 31 | self.n_layers = n_layers 32 | self.n_flows = n_flows 33 | self.gin_channels = gin_channels 34 | 35 | self.flows = nn.ModuleList() 36 | for i in range(n_flows): 37 | self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True)) 38 | self.flows.append(modules.Flip()) 39 | 40 | def forward(self, x, x_mask, g=None, reverse=False): 41 | if not reverse: 42 | for flow in self.flows: 43 | x, _ = flow(x, x_mask, g=g, reverse=reverse) 44 | else: 45 | for flow in reversed(self.flows): 46 | x = flow(x, x_mask, g=g, reverse=reverse) 47 | return x 48 | 49 | 50 | class Encoder(nn.Module): 51 | def __init__(self, 52 | in_channels, 53 | out_channels, 54 | hidden_channels, 55 | kernel_size, 56 | dilation_rate, 57 | n_layers, 58 | gin_channels=0): 59 | super().__init__() 60 | self.in_channels = in_channels 61 | self.out_channels = out_channels 62 | self.hidden_channels = hidden_channels 63 | self.kernel_size = kernel_size 64 | self.dilation_rate = dilation_rate 65 | self.n_layers = n_layers 66 | self.gin_channels = gin_channels 67 | 68 | self.pre = nn.Conv1d(in_channels, hidden_channels, 1) 69 | self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) 70 | self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) 71 | 72 | def forward(self, x, x_lengths, g=None): 73 | # print(x.shape,x_lengths.shape) 74 | x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) 75 | x = self.pre(x) * x_mask 76 | x = self.enc(x, x_mask, g=g) 77 | stats = self.proj(x) * x_mask 78 | m, logs = torch.split(stats, self.out_channels, dim=1) 79 | z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask 80 | return z, m, logs, x_mask 81 | 82 | 83 | class TextEncoder(nn.Module): 84 | def __init__(self, 85 | in_channels, 86 | out_channels, 87 | hidden_channels, 88 | kernel_size, 89 | dilation_rate, 90 | n_layers, 91 | gin_channels=0, 92 | filter_channels=None, 93 | n_heads=None, 94 | p_dropout=None): 95 | super().__init__() 96 | self.in_channels = in_channels 97 | self.out_channels = out_channels 98 | self.hidden_channels = hidden_channels 99 | self.kernel_size = kernel_size 100 | self.dilation_rate = dilation_rate 101 | self.n_layers = n_layers 102 | self.gin_channels = gin_channels 103 | self.pre = nn.Conv1d(in_channels, hidden_channels, 1) 104 | self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) 105 | self.f0_emb = nn.Embedding(256, hidden_channels) 106 | 107 | self.enc_ = attentions.Encoder( 108 | hidden_channels, 109 | filter_channels, 110 | n_heads, 111 | n_layers, 112 | kernel_size, 113 | p_dropout) 114 | 115 | def forward(self, x, x_lengths, f0=None): 116 | x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) 117 | x = self.pre(x) * x_mask 118 | x = x + self.f0_emb(f0.long()).transpose(1,2) 119 | x = self.enc_(x * x_mask, x_mask) 120 | stats = self.proj(x) * x_mask 121 | m, logs = torch.split(stats, self.out_channels, dim=1) 122 | z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask 123 | 124 | return z, m, logs, x_mask 125 | 126 | 127 | 128 | class DiscriminatorP(torch.nn.Module): 129 | def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): 130 | super(DiscriminatorP, self).__init__() 131 | self.period = period 132 | self.use_spectral_norm = use_spectral_norm 133 | norm_f = weight_norm if use_spectral_norm == False else spectral_norm 134 | self.convs = nn.ModuleList([ 135 | norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 136 | norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 137 | norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 138 | norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 139 | norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), 140 | ]) 141 | self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) 142 | 143 | def forward(self, x): 144 | fmap = [] 145 | 146 | # 1d to 2d 147 | b, c, t = x.shape 148 | if t % self.period != 0: # pad first 149 | n_pad = self.period - (t % self.period) 150 | x = F.pad(x, (0, n_pad), "reflect") 151 | t = t + n_pad 152 | x = x.view(b, c, t // self.period, self.period) 153 | 154 | for l in self.convs: 155 | x = l(x) 156 | x = F.leaky_relu(x, modules.LRELU_SLOPE) 157 | fmap.append(x) 158 | x = self.conv_post(x) 159 | fmap.append(x) 160 | x = torch.flatten(x, 1, -1) 161 | 162 | return x, fmap 163 | 164 | 165 | class DiscriminatorS(torch.nn.Module): 166 | def __init__(self, use_spectral_norm=False): 167 | super(DiscriminatorS, self).__init__() 168 | norm_f = weight_norm if use_spectral_norm == False else spectral_norm 169 | self.convs = nn.ModuleList([ 170 | norm_f(Conv1d(1, 16, 15, 1, padding=7)), 171 | norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), 172 | norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), 173 | norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), 174 | norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), 175 | norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), 176 | ]) 177 | self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) 178 | 179 | def forward(self, x): 180 | fmap = [] 181 | 182 | for l in self.convs: 183 | x = l(x) 184 | x = F.leaky_relu(x, modules.LRELU_SLOPE) 185 | fmap.append(x) 186 | x = self.conv_post(x) 187 | fmap.append(x) 188 | x = torch.flatten(x, 1, -1) 189 | 190 | return x, fmap 191 | 192 | 193 | class MultiPeriodDiscriminator(torch.nn.Module): 194 | def __init__(self, use_spectral_norm=False): 195 | super(MultiPeriodDiscriminator, self).__init__() 196 | periods = [2,3,5,7,11] 197 | 198 | discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] 199 | discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] 200 | self.discriminators = nn.ModuleList(discs) 201 | 202 | def forward(self, y, y_hat): 203 | y_d_rs = [] 204 | y_d_gs = [] 205 | fmap_rs = [] 206 | fmap_gs = [] 207 | for i, d in enumerate(self.discriminators): 208 | y_d_r, fmap_r = d(y) 209 | y_d_g, fmap_g = d(y_hat) 210 | y_d_rs.append(y_d_r) 211 | y_d_gs.append(y_d_g) 212 | fmap_rs.append(fmap_r) 213 | fmap_gs.append(fmap_g) 214 | 215 | return y_d_rs, y_d_gs, fmap_rs, fmap_gs 216 | 217 | 218 | class SpeakerEncoder(torch.nn.Module): 219 | def __init__(self, mel_n_channels=80, model_num_layers=3, model_hidden_size=256, model_embedding_size=256): 220 | super(SpeakerEncoder, self).__init__() 221 | self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True) 222 | self.linear = nn.Linear(model_hidden_size, model_embedding_size) 223 | self.relu = nn.ReLU() 224 | 225 | def forward(self, mels): 226 | self.lstm.flatten_parameters() 227 | _, (hidden, _) = self.lstm(mels) 228 | embeds_raw = self.relu(self.linear(hidden[-1])) 229 | return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True) 230 | 231 | def compute_partial_slices(self, total_frames, partial_frames, partial_hop): 232 | mel_slices = [] 233 | for i in range(0, total_frames-partial_frames, partial_hop): 234 | mel_range = torch.arange(i, i+partial_frames) 235 | mel_slices.append(mel_range) 236 | 237 | return mel_slices 238 | 239 | def embed_utterance(self, mel, partial_frames=128, partial_hop=64): 240 | mel_len = mel.size(1) 241 | last_mel = mel[:,-partial_frames:] 242 | 243 | if mel_len > partial_frames: 244 | mel_slices = self.compute_partial_slices(mel_len, partial_frames, partial_hop) 245 | mels = list(mel[:,s] for s in mel_slices) 246 | mels.append(last_mel) 247 | mels = torch.stack(tuple(mels), 0).squeeze(1) 248 | 249 | with torch.no_grad(): 250 | partial_embeds = self(mels) 251 | embed = torch.mean(partial_embeds, axis=0).unsqueeze(0) 252 | #embed = embed / torch.linalg.norm(embed, 2) 253 | else: 254 | with torch.no_grad(): 255 | embed = self(last_mel) 256 | 257 | return embed 258 | 259 | 260 | class SynthesizerTrn(nn.Module): 261 | """ 262 | Synthesizer for Training 263 | """ 264 | 265 | def __init__(self, 266 | spec_channels, 267 | segment_size, 268 | inter_channels, 269 | hidden_channels, 270 | filter_channels, 271 | n_heads, 272 | n_layers, 273 | kernel_size, 274 | p_dropout, 275 | resblock, 276 | resblock_kernel_sizes, 277 | resblock_dilation_sizes, 278 | upsample_rates, 279 | upsample_initial_channel, 280 | upsample_kernel_sizes, 281 | gin_channels, 282 | ssl_dim, 283 | n_speakers, 284 | **kwargs): 285 | 286 | super().__init__() 287 | self.spec_channels = spec_channels 288 | self.inter_channels = inter_channels 289 | self.hidden_channels = hidden_channels 290 | self.filter_channels = filter_channels 291 | self.n_heads = n_heads 292 | self.n_layers = n_layers 293 | self.kernel_size = kernel_size 294 | self.p_dropout = p_dropout 295 | self.resblock = resblock 296 | self.resblock_kernel_sizes = resblock_kernel_sizes 297 | self.resblock_dilation_sizes = resblock_dilation_sizes 298 | self.upsample_rates = upsample_rates 299 | self.upsample_initial_channel = upsample_initial_channel 300 | self.upsample_kernel_sizes = upsample_kernel_sizes 301 | self.segment_size = segment_size 302 | self.gin_channels = gin_channels 303 | self.ssl_dim = ssl_dim 304 | self.emb_g = nn.Embedding(n_speakers, gin_channels) 305 | 306 | self.enc_p_ = TextEncoder(ssl_dim, inter_channels, hidden_channels, 5, 1, 16,0, filter_channels, n_heads, p_dropout) 307 | hps = { 308 | "sampling_rate": 32000, 309 | "inter_channels": 192, 310 | "resblock": "1", 311 | "resblock_kernel_sizes": [3, 7, 11], 312 | "resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]], 313 | "upsample_rates": [10, 8, 2, 2], 314 | "upsample_initial_channel": 512, 315 | "upsample_kernel_sizes": [16, 16, 4, 4], 316 | "gin_channels": 256, 317 | } 318 | self.dec = Generator(h=hps) 319 | self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels) 320 | self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels) 321 | 322 | def forward(self, c, c_lengths, f0, g=None): 323 | g = self.emb_g(g.unsqueeze(0)).transpose(1,2) 324 | z_p, m_p, logs_p, c_mask = self.enc_p_(c.transpose(1,2), c_lengths, f0=f0_to_coarse(f0)) 325 | z = self.flow(z_p, c_mask, g=g, reverse=True) 326 | o = self.dec(z * c_mask, g=g, f0=f0.float()) 327 | return o 328 | 329 | -------------------------------------------------------------------------------- /onnx/model_onnx_48k.py: -------------------------------------------------------------------------------- 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 | from modules.commons import init_weights, get_padding 14 | from vdecoder.hifigan.models import Generator 15 | from utils import f0_to_coarse 16 | 17 | class ResidualCouplingBlock(nn.Module): 18 | def __init__(self, 19 | channels, 20 | hidden_channels, 21 | kernel_size, 22 | dilation_rate, 23 | n_layers, 24 | n_flows=4, 25 | gin_channels=0): 26 | super().__init__() 27 | self.channels = channels 28 | self.hidden_channels = hidden_channels 29 | self.kernel_size = kernel_size 30 | self.dilation_rate = dilation_rate 31 | self.n_layers = n_layers 32 | self.n_flows = n_flows 33 | self.gin_channels = gin_channels 34 | 35 | self.flows = nn.ModuleList() 36 | for i in range(n_flows): 37 | self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True)) 38 | self.flows.append(modules.Flip()) 39 | 40 | def forward(self, x, x_mask, g=None, reverse=False): 41 | if not reverse: 42 | for flow in self.flows: 43 | x, _ = flow(x, x_mask, g=g, reverse=reverse) 44 | else: 45 | for flow in reversed(self.flows): 46 | x = flow(x, x_mask, g=g, reverse=reverse) 47 | return x 48 | 49 | 50 | class Encoder(nn.Module): 51 | def __init__(self, 52 | in_channels, 53 | out_channels, 54 | hidden_channels, 55 | kernel_size, 56 | dilation_rate, 57 | n_layers, 58 | gin_channels=0): 59 | super().__init__() 60 | self.in_channels = in_channels 61 | self.out_channels = out_channels 62 | self.hidden_channels = hidden_channels 63 | self.kernel_size = kernel_size 64 | self.dilation_rate = dilation_rate 65 | self.n_layers = n_layers 66 | self.gin_channels = gin_channels 67 | 68 | self.pre = nn.Conv1d(in_channels, hidden_channels, 1) 69 | self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels) 70 | self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) 71 | 72 | def forward(self, x, x_lengths, g=None): 73 | # print(x.shape,x_lengths.shape) 74 | x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) 75 | x = self.pre(x) * x_mask 76 | x = self.enc(x, x_mask, g=g) 77 | stats = self.proj(x) * x_mask 78 | m, logs = torch.split(stats, self.out_channels, dim=1) 79 | z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask 80 | return z, m, logs, x_mask 81 | 82 | 83 | class TextEncoder(nn.Module): 84 | def __init__(self, 85 | in_channels, 86 | out_channels, 87 | hidden_channels, 88 | kernel_size, 89 | dilation_rate, 90 | n_layers, 91 | gin_channels=0, 92 | filter_channels=None, 93 | n_heads=None, 94 | p_dropout=None): 95 | super().__init__() 96 | self.in_channels = in_channels 97 | self.out_channels = out_channels 98 | self.hidden_channels = hidden_channels 99 | self.kernel_size = kernel_size 100 | self.dilation_rate = dilation_rate 101 | self.n_layers = n_layers 102 | self.gin_channels = gin_channels 103 | self.pre = nn.Conv1d(in_channels, hidden_channels, 1) 104 | self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) 105 | self.f0_emb = nn.Embedding(256, hidden_channels) 106 | 107 | self.enc_ = attentions.Encoder( 108 | hidden_channels, 109 | filter_channels, 110 | n_heads, 111 | n_layers, 112 | kernel_size, 113 | p_dropout) 114 | 115 | def forward(self, x, x_lengths, f0=None): 116 | x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype) 117 | x = self.pre(x) * x_mask 118 | x = x + self.f0_emb(f0.long()).transpose(1,2) 119 | x = self.enc_(x * x_mask, x_mask) 120 | stats = self.proj(x) * x_mask 121 | m, logs = torch.split(stats, self.out_channels, dim=1) 122 | z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask 123 | 124 | return z, m, logs, x_mask 125 | 126 | 127 | 128 | class DiscriminatorP(torch.nn.Module): 129 | def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): 130 | super(DiscriminatorP, self).__init__() 131 | self.period = period 132 | self.use_spectral_norm = use_spectral_norm 133 | norm_f = weight_norm if use_spectral_norm == False else spectral_norm 134 | self.convs = nn.ModuleList([ 135 | norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 136 | norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 137 | norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 138 | norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))), 139 | norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))), 140 | ]) 141 | self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) 142 | 143 | def forward(self, x): 144 | fmap = [] 145 | 146 | # 1d to 2d 147 | b, c, t = x.shape 148 | if t % self.period != 0: # pad first 149 | n_pad = self.period - (t % self.period) 150 | x = F.pad(x, (0, n_pad), "reflect") 151 | t = t + n_pad 152 | x = x.view(b, c, t // self.period, self.period) 153 | 154 | for l in self.convs: 155 | x = l(x) 156 | x = F.leaky_relu(x, modules.LRELU_SLOPE) 157 | fmap.append(x) 158 | x = self.conv_post(x) 159 | fmap.append(x) 160 | x = torch.flatten(x, 1, -1) 161 | 162 | return x, fmap 163 | 164 | 165 | class DiscriminatorS(torch.nn.Module): 166 | def __init__(self, use_spectral_norm=False): 167 | super(DiscriminatorS, self).__init__() 168 | norm_f = weight_norm if use_spectral_norm == False else spectral_norm 169 | self.convs = nn.ModuleList([ 170 | norm_f(Conv1d(1, 16, 15, 1, padding=7)), 171 | norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), 172 | norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), 173 | norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), 174 | norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), 175 | norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), 176 | ]) 177 | self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) 178 | 179 | def forward(self, x): 180 | fmap = [] 181 | 182 | for l in self.convs: 183 | x = l(x) 184 | x = F.leaky_relu(x, modules.LRELU_SLOPE) 185 | fmap.append(x) 186 | x = self.conv_post(x) 187 | fmap.append(x) 188 | x = torch.flatten(x, 1, -1) 189 | 190 | return x, fmap 191 | 192 | 193 | class MultiPeriodDiscriminator(torch.nn.Module): 194 | def __init__(self, use_spectral_norm=False): 195 | super(MultiPeriodDiscriminator, self).__init__() 196 | periods = [2,3,5,7,11] 197 | 198 | discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] 199 | discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods] 200 | self.discriminators = nn.ModuleList(discs) 201 | 202 | def forward(self, y, y_hat): 203 | y_d_rs = [] 204 | y_d_gs = [] 205 | fmap_rs = [] 206 | fmap_gs = [] 207 | for i, d in enumerate(self.discriminators): 208 | y_d_r, fmap_r = d(y) 209 | y_d_g, fmap_g = d(y_hat) 210 | y_d_rs.append(y_d_r) 211 | y_d_gs.append(y_d_g) 212 | fmap_rs.append(fmap_r) 213 | fmap_gs.append(fmap_g) 214 | 215 | return y_d_rs, y_d_gs, fmap_rs, fmap_gs 216 | 217 | 218 | class SpeakerEncoder(torch.nn.Module): 219 | def __init__(self, mel_n_channels=80, model_num_layers=3, model_hidden_size=256, model_embedding_size=256): 220 | super(SpeakerEncoder, self).__init__() 221 | self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True) 222 | self.linear = nn.Linear(model_hidden_size, model_embedding_size) 223 | self.relu = nn.ReLU() 224 | 225 | def forward(self, mels): 226 | self.lstm.flatten_parameters() 227 | _, (hidden, _) = self.lstm(mels) 228 | embeds_raw = self.relu(self.linear(hidden[-1])) 229 | return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True) 230 | 231 | def compute_partial_slices(self, total_frames, partial_frames, partial_hop): 232 | mel_slices = [] 233 | for i in range(0, total_frames-partial_frames, partial_hop): 234 | mel_range = torch.arange(i, i+partial_frames) 235 | mel_slices.append(mel_range) 236 | 237 | return mel_slices 238 | 239 | def embed_utterance(self, mel, partial_frames=128, partial_hop=64): 240 | mel_len = mel.size(1) 241 | last_mel = mel[:,-partial_frames:] 242 | 243 | if mel_len > partial_frames: 244 | mel_slices = self.compute_partial_slices(mel_len, partial_frames, partial_hop) 245 | mels = list(mel[:,s] for s in mel_slices) 246 | mels.append(last_mel) 247 | mels = torch.stack(tuple(mels), 0).squeeze(1) 248 | 249 | with torch.no_grad(): 250 | partial_embeds = self(mels) 251 | embed = torch.mean(partial_embeds, axis=0).unsqueeze(0) 252 | #embed = embed / torch.linalg.norm(embed, 2) 253 | else: 254 | with torch.no_grad(): 255 | embed = self(last_mel) 256 | 257 | return embed 258 | 259 | 260 | class SynthesizerTrn(nn.Module): 261 | """ 262 | Synthesizer for Training 263 | """ 264 | 265 | def __init__(self, 266 | spec_channels, 267 | segment_size, 268 | inter_channels, 269 | hidden_channels, 270 | filter_channels, 271 | n_heads, 272 | n_layers, 273 | kernel_size, 274 | p_dropout, 275 | resblock, 276 | resblock_kernel_sizes, 277 | resblock_dilation_sizes, 278 | upsample_rates, 279 | upsample_initial_channel, 280 | upsample_kernel_sizes, 281 | gin_channels, 282 | ssl_dim, 283 | n_speakers, 284 | **kwargs): 285 | 286 | super().__init__() 287 | self.spec_channels = spec_channels 288 | self.inter_channels = inter_channels 289 | self.hidden_channels = hidden_channels 290 | self.filter_channels = filter_channels 291 | self.n_heads = n_heads 292 | self.n_layers = n_layers 293 | self.kernel_size = kernel_size 294 | self.p_dropout = p_dropout 295 | self.resblock = resblock 296 | self.resblock_kernel_sizes = resblock_kernel_sizes 297 | self.resblock_dilation_sizes = resblock_dilation_sizes 298 | self.upsample_rates = upsample_rates 299 | self.upsample_initial_channel = upsample_initial_channel 300 | self.upsample_kernel_sizes = upsample_kernel_sizes 301 | self.segment_size = segment_size 302 | self.gin_channels = gin_channels 303 | self.ssl_dim = ssl_dim 304 | self.emb_g = nn.Embedding(n_speakers, gin_channels) 305 | 306 | self.enc_p_ = TextEncoder(ssl_dim, inter_channels, hidden_channels, 5, 1, 16,0, filter_channels, n_heads, p_dropout) 307 | hps = { 308 | "sampling_rate": 48000, 309 | "inter_channels": 192, 310 | "resblock": "1", 311 | "resblock_kernel_sizes": [3, 7, 11], 312 | "resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]], 313 | "upsample_rates": [10, 8, 2, 2], 314 | "upsample_initial_channel": 512, 315 | "upsample_kernel_sizes": [16, 16, 4, 4], 316 | "gin_channels": 256, 317 | } 318 | self.dec = Generator(h=hps) 319 | self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels) 320 | self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels) 321 | 322 | def forward(self, c, c_lengths, f0, g=None): 323 | g = self.emb_g(g.unsqueeze(0)).transpose(1,2) 324 | z_p, m_p, logs_p, c_mask = self.enc_p_(c.transpose(1,2), c_lengths, f0=f0_to_coarse(f0)) 325 | z = self.flow(z_p, c_mask, g=g, reverse=True) 326 | o = self.dec(z * c_mask, g=g, f0=f0.float()) 327 | return o 328 | 329 | -------------------------------------------------------------------------------- /onnx/onnx_export.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import time 3 | import numpy as np 4 | import onnx 5 | from onnxsim import simplify 6 | import onnxruntime as ort 7 | import onnxoptimizer 8 | import torch 9 | from model_onnx import SynthesizerTrn 10 | import utils 11 | from hubert import hubert_model_onnx 12 | 13 | def main(HubertExport,NetExport): 14 | 15 | path = "NyaruTaffy" 16 | 17 | if(HubertExport): 18 | device = torch.device("cuda") 19 | hubert_soft = utils.get_hubert_model() 20 | test_input = torch.rand(1, 1, 16000) 21 | input_names = ["source"] 22 | output_names = ["embed"] 23 | torch.onnx.export(hubert_soft.to(device), 24 | test_input.to(device), 25 | "hubert3.0.onnx", 26 | dynamic_axes={ 27 | "source": { 28 | 2: "sample_length" 29 | } 30 | }, 31 | verbose=False, 32 | opset_version=13, 33 | input_names=input_names, 34 | output_names=output_names) 35 | if(NetExport): 36 | device = torch.device("cuda") 37 | hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json") 38 | SVCVITS = SynthesizerTrn( 39 | hps.data.filter_length // 2 + 1, 40 | hps.train.segment_size // hps.data.hop_length, 41 | **hps.model) 42 | _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", SVCVITS, None) 43 | _ = SVCVITS.eval().to(device) 44 | for i in SVCVITS.parameters(): 45 | i.requires_grad = False 46 | test_hidden_unit = torch.rand(1, 50, 256) 47 | test_lengths = torch.LongTensor([50]) 48 | test_pitch = torch.rand(1, 50) 49 | test_sid = torch.LongTensor([0]) 50 | input_names = ["hidden_unit", "lengths", "pitch", "sid"] 51 | output_names = ["audio", ] 52 | SVCVITS.eval() 53 | torch.onnx.export(SVCVITS, 54 | ( 55 | test_hidden_unit.to(device), 56 | test_lengths.to(device), 57 | test_pitch.to(device), 58 | test_sid.to(device) 59 | ), 60 | f"checkpoints/{path}/model.onnx", 61 | dynamic_axes={ 62 | "hidden_unit": [0, 1], 63 | "pitch": [1] 64 | }, 65 | do_constant_folding=False, 66 | opset_version=16, 67 | verbose=False, 68 | input_names=input_names, 69 | output_names=output_names) 70 | 71 | 72 | if __name__ == '__main__': 73 | main(False,True) 74 | -------------------------------------------------------------------------------- /onnx/onnx_export_48k.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import time 3 | import numpy as np 4 | import onnx 5 | from onnxsim import simplify 6 | import onnxruntime as ort 7 | import onnxoptimizer 8 | import torch 9 | from model_onnx_48k import SynthesizerTrn 10 | import utils 11 | from hubert import hubert_model_onnx 12 | 13 | def main(HubertExport,NetExport): 14 | 15 | path = "NyaruTaffy" 16 | 17 | if(HubertExport): 18 | device = torch.device("cuda") 19 | hubert_soft = hubert_model_onnx.hubert_soft("hubert/model.pt") 20 | test_input = torch.rand(1, 1, 16000) 21 | input_names = ["source"] 22 | output_names = ["embed"] 23 | torch.onnx.export(hubert_soft.to(device), 24 | test_input.to(device), 25 | "hubert3.0.onnx", 26 | dynamic_axes={ 27 | "source": { 28 | 2: "sample_length" 29 | } 30 | }, 31 | verbose=False, 32 | opset_version=13, 33 | input_names=input_names, 34 | output_names=output_names) 35 | if(NetExport): 36 | device = torch.device("cuda") 37 | hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json") 38 | SVCVITS = SynthesizerTrn( 39 | hps.data.filter_length // 2 + 1, 40 | hps.train.segment_size // hps.data.hop_length, 41 | **hps.model) 42 | _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", SVCVITS, None) 43 | _ = SVCVITS.eval().to(device) 44 | for i in SVCVITS.parameters(): 45 | i.requires_grad = False 46 | test_hidden_unit = torch.rand(1, 50, 256) 47 | test_lengths = torch.LongTensor([50]) 48 | test_pitch = torch.rand(1, 50) 49 | test_sid = torch.LongTensor([0]) 50 | input_names = ["hidden_unit", "lengths", "pitch", "sid"] 51 | output_names = ["audio", ] 52 | SVCVITS.eval() 53 | torch.onnx.export(SVCVITS, 54 | ( 55 | test_hidden_unit.to(device), 56 | test_lengths.to(device), 57 | test_pitch.to(device), 58 | test_sid.to(device) 59 | ), 60 | f"checkpoints/{path}/model.onnx", 61 | dynamic_axes={ 62 | "hidden_unit": [0, 1], 63 | "pitch": [1] 64 | }, 65 | do_constant_folding=False, 66 | opset_version=16, 67 | verbose=False, 68 | input_names=input_names, 69 | output_names=output_names) 70 | 71 | 72 | if __name__ == '__main__': 73 | main(False,True) 74 | -------------------------------------------------------------------------------- /onnx_export.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torchaudio.models.wav2vec2.utils import import_fairseq_model 3 | from fairseq import checkpoint_utils 4 | from onnxexport.model_onnx import SynthesizerTrn 5 | import sovits_utils 6 | 7 | def get_hubert_model(): 8 | vec_path = "hubert/checkpoint_best_legacy_500.pt" 9 | print("load model(s) from {}".format(vec_path)) 10 | models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task( 11 | [vec_path], 12 | suffix="", 13 | ) 14 | model = models[0] 15 | model.eval() 16 | return model 17 | 18 | 19 | def main(HubertExport, NetExport): 20 | path = "SoVits4.0" 21 | 22 | '''if HubertExport: 23 | device = torch.device("cpu") 24 | vec_path = "hubert/checkpoint_best_legacy_500.pt" 25 | models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task( 26 | [vec_path], 27 | suffix="", 28 | ) 29 | original = models[0] 30 | original.eval() 31 | model = original 32 | test_input = torch.rand(1, 1, 16000) 33 | model(test_input) 34 | torch.onnx.export(model, 35 | test_input, 36 | "hubert4.0.onnx", 37 | export_params=True, 38 | opset_version=16, 39 | do_constant_folding=True, 40 | input_names=['source'], 41 | output_names=['embed'], 42 | dynamic_axes={ 43 | 'source': 44 | { 45 | 2: "sample_length" 46 | }, 47 | } 48 | )''' 49 | if NetExport: 50 | device = torch.device("cpu") 51 | hps = sovits_utils.get_hparams_from_file(f"checkpoints/{path}/config.json") 52 | SVCVITS = SynthesizerTrn( 53 | hps.data.filter_length // 2 + 1, 54 | hps.train.segment_size // hps.data.hop_length, 55 | **hps.model) 56 | _ = sovits_utils.load_checkpoint(f"checkpoints/{path}/model.pth", SVCVITS, None) 57 | _ = SVCVITS.eval().to(device) 58 | for i in SVCVITS.parameters(): 59 | i.requires_grad = False 60 | test_hidden_unit = torch.rand(1, 10, 256) 61 | test_pitch = torch.rand(1, 10) 62 | test_mel2ph = torch.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).unsqueeze(0) 63 | test_uv = torch.ones(1, 10, dtype=torch.float32) 64 | test_noise = torch.randn(1, 192, 10) 65 | test_sid = torch.LongTensor([0]) 66 | input_names = ["c", "f0", "mel2ph", "uv", "noise", "sid"] 67 | output_names = ["audio", ] 68 | SVCVITS.eval() 69 | torch.onnx.export(SVCVITS, 70 | ( 71 | test_hidden_unit.to(device), 72 | test_pitch.to(device), 73 | test_mel2ph.to(device), 74 | test_uv.to(device), 75 | test_noise.to(device), 76 | test_sid.to(device) 77 | ), 78 | f"checkpoints/{path}/model.onnx", 79 | dynamic_axes={ 80 | "c": [0, 1], 81 | "f0": [1], 82 | "mel2ph": [1], 83 | "uv": [1], 84 | "noise": [2], 85 | }, 86 | do_constant_folding=False, 87 | opset_version=16, 88 | verbose=False, 89 | input_names=input_names, 90 | output_names=output_names) 91 | 92 | 93 | if __name__ == '__main__': 94 | main(False, True) 95 | -------------------------------------------------------------------------------- /onnxexport/model_onnx.py: -------------------------------------------------------------------------------- 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 336 | -------------------------------------------------------------------------------- /preprocess_flist_config.py: -------------------------------------------------------------------------------- 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/config.json")) 11 | 12 | pattern = re.compile(r'^[\.a-zA-Z0-9_\/]+$') 13 | 14 | def get_wav_duration(file_path): 15 | with wave.open(file_path, 'rb') as wav_file: 16 | # 获取音频帧数 17 | n_frames = wav_file.getnframes() 18 | # 获取采样率 19 | framerate = wav_file.getframerate() 20 | # 计算时长(秒) 21 | duration = n_frames / float(framerate) 22 | return duration 23 | 24 | if __name__ == "__main__": 25 | parser = argparse.ArgumentParser() 26 | parser.add_argument("--train_list", type=str, default="./filelists/train.txt", help="path to train list") 27 | parser.add_argument("--val_list", type=str, default="./filelists/val.txt", help="path to val list") 28 | parser.add_argument("--test_list", type=str, default="./filelists/test.txt", help="path to test list") 29 | parser.add_argument("--source_dir", type=str, default="./dataset/44k", help="path to source dir") 30 | args = parser.parse_args() 31 | 32 | train = [] 33 | val = [] 34 | test = [] 35 | idx = 0 36 | spk_dict = {} 37 | spk_id = 0 38 | for speaker in tqdm(os.listdir(args.source_dir)): 39 | spk_dict[speaker] = spk_id 40 | spk_id += 1 41 | wavs = ["/".join([args.source_dir, speaker, i]) for i in os.listdir(os.path.join(args.source_dir, speaker))] 42 | new_wavs = [] 43 | for file in wavs: 44 | if not file.endswith("wav"): 45 | continue 46 | if not pattern.match(file): 47 | #print(f"warning:文件名{file}中包含非字母数字下划线,可能会导致错误。(也可能不会)") 48 | pass 49 | if get_wav_duration(file) < 0.3: 50 | print("skip too short audio:", file) 51 | continue 52 | new_wavs.append(file) 53 | wavs = new_wavs 54 | shuffle(wavs) 55 | train += wavs[2:-2] 56 | val += wavs[:2] 57 | test += wavs[-2:] 58 | 59 | shuffle(train) 60 | shuffle(val) 61 | shuffle(test) 62 | 63 | print("Writing", args.train_list) 64 | with open(args.train_list, "w") as f: 65 | for fname in tqdm(train): 66 | wavpath = fname 67 | f.write(wavpath + "\n") 68 | 69 | print("Writing", args.val_list) 70 | with open(args.val_list, "w") as f: 71 | for fname in tqdm(val): 72 | wavpath = fname 73 | f.write(wavpath + "\n") 74 | 75 | print("Writing", args.test_list) 76 | with open(args.test_list, "w") as f: 77 | for fname in tqdm(test): 78 | wavpath = fname 79 | f.write(wavpath + "\n") 80 | 81 | config_template["spk"] = spk_dict 82 | print("Writing configs/config.json") 83 | with open("configs/config.json", "w") as f: 84 | json.dump(config_template, f, indent=2) 85 | -------------------------------------------------------------------------------- /preprocess_hubert_f0.py: -------------------------------------------------------------------------------- 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 | 11 | import sovits_utils 12 | import logging 13 | logging.getLogger('numba').setLevel(logging.WARNING) 14 | import librosa 15 | import numpy as np 16 | 17 | hps = sovits_utils.get_hparams_from_file("configs/config.json") 18 | sampling_rate = hps.data.sampling_rate 19 | hop_length = hps.data.hop_length 20 | 21 | 22 | def process_one(filename, hmodel): 23 | # print(filename) 24 | wav, sr = librosa.load(filename, sr=sampling_rate) 25 | soft_path = filename + ".soft.pt" 26 | if not os.path.exists(soft_path): 27 | devive = torch.device("cuda" if torch.cuda.is_available() else "cpu") 28 | wav16k = librosa.resample(wav, orig_sr=sampling_rate, target_sr=16000) 29 | wav16k = torch.from_numpy(wav16k).to(devive) 30 | c = sovits_utils.get_hubert_content(hmodel, wav_16k_tensor=wav16k, 31 | legacy_final_proj=hps.data.get("contentvec_final_proj", True)) 32 | torch.save(c.cpu(), soft_path) 33 | f0_path = filename + ".f0.npy" 34 | if not os.path.exists(f0_path): 35 | f0 = sovits_utils.compute_f0_dio(wav, sampling_rate=sampling_rate, hop_length=hop_length) 36 | #f0 = sovits_utils.compute_f0_crepe(wav, sampling_rate=sampling_rate, hop_length=hop_length) 37 | np.save(f0_path, f0) 38 | 39 | 40 | def process_batch(filenames): 41 | print("Loading hubert for content...") 42 | device = "cuda" if torch.cuda.is_available() else "cpu" 43 | hmodel = sovits_utils.get_hubert_model().to(device) 44 | print("Loaded hubert.") 45 | for filename in tqdm(filenames): 46 | process_one(filename, hmodel) 47 | 48 | 49 | if __name__ == "__main__": 50 | parser = argparse.ArgumentParser() 51 | parser.add_argument("--in_dir", type=str, default="dataset/44k", help="path to input dir") 52 | 53 | args = parser.parse_args() 54 | filenames = glob(f'{args.in_dir}/*/*.wav', recursive=True) # [:10] 55 | shuffle(filenames) 56 | multiprocessing.set_start_method('spawn',force=True) 57 | 58 | num_processes = 1 59 | chunk_size = int(math.ceil(len(filenames) / num_processes)) 60 | chunks = [filenames[i:i + chunk_size] for i in range(0, len(filenames), chunk_size)] 61 | print([len(c) for c in chunks]) 62 | processes = [multiprocessing.Process(target=process_batch, args=(chunk,)) for chunk in chunks] 63 | for p in processes: 64 | p.start() 65 | -------------------------------------------------------------------------------- /raw/put_raw_wav_here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/raw/put_raw_wav_here -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Flask 2 | Flask_Cors 3 | gradio 4 | numpy==1.26.0 5 | numba==0.56.4 6 | pyworld==0.3.2 7 | scipy==1.10.1 8 | SoundFile==0.12.1 9 | torch==1.13.1 10 | torchaudio==0.13.1 11 | tqdm 12 | scikit-maad 13 | praat-parselmouth 14 | onnx 15 | onnxsim 16 | onnxoptimizer 17 | fairseq==0.12.2 18 | librosa==0.10.2 19 | tensorboard 20 | PyQt5 21 | huggingface_hub 22 | datasets 23 | -------------------------------------------------------------------------------- /requirements_win.txt: -------------------------------------------------------------------------------- 1 | librosa==0.9.2 2 | fairseq==0.12.2 3 | Flask==2.1.2 4 | Flask_Cors==3.0.10 5 | gradio==3.35.2 6 | numpy==1.24.3 7 | numba==0.57.0 8 | playsound==1.3.0 9 | PyAudio==0.2.12 10 | pydub==0.25.1 11 | pyworld==0.3.3 12 | requests==2.28.1 13 | scipy==1.8.0 14 | sounddevice==0.4.5 15 | SoundFile==0.10.3.post1 16 | starlette==0.19.1 17 | --extra-index-url https://download.pytorch.org/whl/cu116 18 | torch==1.12.0+cu116 19 | torchvision==0.13.0+cu116 20 | torchaudio==0.12.0 21 | tqdm==4.63.0 22 | scikit-maad 23 | praat-parselmouth 24 | matplotlib 25 | onnx 26 | onnxsim 27 | onnxoptimizer 28 | fairseq 29 | tensorboard 30 | PyQt5 31 | huggingface_hub 32 | datasets 33 | Pillow==9.1.0 34 | -------------------------------------------------------------------------------- /resample.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | import librosa 4 | import numpy as np 5 | from multiprocessing import Pool, cpu_count 6 | from scipy.io import wavfile 7 | from tqdm import tqdm 8 | 9 | 10 | def process(item): 11 | spkdir, wav_name, args = item 12 | # speaker 's5', 'p280', 'p315' are excluded, 13 | speaker = spkdir.replace("\\", "/").split("/")[-1] 14 | wav_path = os.path.join(args.in_dir, speaker, wav_name) 15 | if os.path.exists(wav_path) and '.wav' in wav_path: 16 | os.makedirs(os.path.join(args.out_dir2, speaker), exist_ok=True) 17 | wav, sr = librosa.load(wav_path, sr=None) 18 | wav, _ = librosa.effects.trim(wav, top_db=20) 19 | peak = np.abs(wav).max() 20 | if peak > 1.0: 21 | wav = 0.98 * wav / peak 22 | wav2 = librosa.resample(wav, orig_sr=sr, target_sr=args.sr2) 23 | wav2 /= max(wav2.max(), -wav2.min()) 24 | save_name = wav_name 25 | save_path2 = os.path.join(args.out_dir2, speaker, save_name) 26 | wavfile.write( 27 | save_path2, 28 | args.sr2, 29 | (wav2 * np.iinfo(np.int16).max).astype(np.int16) 30 | ) 31 | 32 | 33 | 34 | if __name__ == "__main__": 35 | parser = argparse.ArgumentParser() 36 | parser.add_argument("--sr2", type=int, default=44100, help="sampling rate") 37 | parser.add_argument("--in_dir", type=str, default="./dataset_raw", help="path to source dir") 38 | parser.add_argument("--out_dir2", type=str, default="./dataset/44k", help="path to target dir") 39 | args = parser.parse_args() 40 | processs = cpu_count()-2 if cpu_count() >4 else 1 41 | pool = Pool(processes=processs) 42 | 43 | for speaker in os.listdir(args.in_dir): 44 | spk_dir = os.path.join(args.in_dir, speaker) 45 | if os.path.isdir(spk_dir): 46 | print(spk_dir) 47 | for _ in tqdm(pool.imap_unordered(process, [(spk_dir, i, args) for i in os.listdir(spk_dir) if i.endswith("wav")])): 48 | pass 49 | -------------------------------------------------------------------------------- /spec_gen.py: -------------------------------------------------------------------------------- 1 | from data_utils import TextAudioSpeakerLoader 2 | import json 3 | from tqdm import tqdm 4 | 5 | from sovits_utils import HParams 6 | 7 | config_path = 'configs/config.json' 8 | with open(config_path, "r") as f: 9 | data = f.read() 10 | config = json.loads(data) 11 | hps = HParams(**config) 12 | 13 | train_dataset = TextAudioSpeakerLoader("filelists/train.txt", hps) 14 | test_dataset = TextAudioSpeakerLoader("filelists/test.txt", hps) 15 | eval_dataset = TextAudioSpeakerLoader("filelists/val.txt", hps) 16 | 17 | for _ in tqdm(train_dataset): 18 | pass 19 | for _ in tqdm(eval_dataset): 20 | pass 21 | for _ in tqdm(test_dataset): 22 | pass 23 | -------------------------------------------------------------------------------- /train_cpu.py: -------------------------------------------------------------------------------- 1 | # Note - from initial testing it seems that CPU training is ~10-20x slower than 2 | # GPU training 3 | import logging 4 | import multiprocessing 5 | import time 6 | 7 | logging.getLogger('matplotlib').setLevel(logging.WARNING) 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 | 22 | import modules.commons as commons 23 | import sovits_utils 24 | from data_utils import TextAudioSpeakerLoader, TextAudioCollate 25 | from models import ( 26 | SynthesizerTrn, 27 | MultiPeriodDiscriminator, 28 | ) 29 | from modules.losses import ( 30 | kl_loss, 31 | generator_loss, discriminator_loss, feature_loss 32 | ) 33 | 34 | from modules.mel_processing import mel_spectrogram_torch, spec_to_mel_torch 35 | 36 | torch.backends.cudnn.benchmark = True 37 | global_step = 0 38 | start_time = time.time() 39 | os.environ["CUDA_VISIBLE_DEVICES"]="" 40 | 41 | # os.environ['TORCH_DISTRIBUTED_DEBUG'] = 'INFO' 42 | 43 | def validate(hps): 44 | # Errors that might occur: 45 | # dataset/44k has more than one character (generally not preferred) 46 | #assert len(os.listdir('dataset/44k')) == 1, "more than one character present!!!" 47 | ckpt = sovits_utils.latest_checkpoint_path(hps.model_dir, "G_*.pth") 48 | # no pretrained model present 49 | assert ckpt is not None, "no pretrained model present!!!" 50 | # pretrained model still present - no way to check for this? 51 | if hps.train.fp16_run: 52 | raise Exception("fp16 not supported on CPU training") 53 | pass 54 | 55 | def main(): 56 | hps = sovits_utils.get_hparams() 57 | 58 | n_gpus = 1 59 | os.environ['MASTER_ADDR'] = 'localhost' 60 | os.environ['MASTER_PORT'] = hps.train.port 61 | 62 | validate(hps) 63 | 64 | mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,)) 65 | 66 | 67 | def run(rank, n_gpus, hps): 68 | global global_step 69 | if rank == 0: 70 | logger = sovits_utils.get_logger(hps.model_dir) 71 | logger.info(hps) 72 | sovits_utils.check_git_hash(hps.model_dir) 73 | writer = SummaryWriter(log_dir=hps.model_dir) 74 | writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) 75 | 76 | # for pytorch on win, backend use gloo 77 | dist.init_process_group(backend= 'gloo' if os.name == 'nt' else 'nccl', init_method='env://', world_size=n_gpus, rank=rank) 78 | torch.manual_seed(hps.train.seed) 79 | collate_fn = TextAudioCollate() 80 | train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps) 81 | num_workers = 5 if multiprocessing.cpu_count() > 4 else multiprocessing.cpu_count() 82 | train_loader = DataLoader(train_dataset, num_workers=num_workers, shuffle=False, pin_memory=True, 83 | batch_size=hps.train.batch_size, collate_fn=collate_fn) 84 | if rank == 0: 85 | eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps) 86 | eval_loader = DataLoader(eval_dataset, num_workers=1, shuffle=False, 87 | batch_size=1, pin_memory=False, 88 | drop_last=False, collate_fn=collate_fn) 89 | 90 | net_g = SynthesizerTrn( 91 | hps.data.filter_length // 2 + 1, 92 | hps.train.segment_size // hps.data.hop_length, 93 | **hps.model) 94 | net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm) 95 | optim_g = torch.optim.AdamW( 96 | net_g.parameters(), 97 | hps.train.learning_rate, 98 | betas=hps.train.betas, 99 | eps=hps.train.eps) 100 | optim_d = torch.optim.AdamW( 101 | net_d.parameters(), 102 | hps.train.learning_rate, 103 | betas=hps.train.betas, 104 | eps=hps.train.eps) 105 | net_g = DDP(net_g, device_ids=[]) # , find_unused_parameters=True) 106 | net_d = DDP(net_d, device_ids=[]) 107 | 108 | skip_optimizer = False 109 | try: 110 | _, _, _, epoch_str = sovits_utils.load_checkpoint(sovits_utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, 111 | optim_g, skip_optimizer) 112 | _, _, _, epoch_str = sovits_utils.load_checkpoint(sovits_utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, 113 | optim_d, skip_optimizer) 114 | epoch_str = max(epoch_str, 1) 115 | global_step = (epoch_str - 1) * len(train_loader) 116 | if hps.reset: 117 | print("Resetting model steps!!!") 118 | epoch_str = 1 119 | global_step = 0 120 | except: 121 | raise Exception("No pretrained model found") 122 | print("Load old checkpoint failed!!!") 123 | epoch_str = 1 124 | global_step = 0 125 | if skip_optimizer: 126 | epoch_str = 1 127 | global_step = 0 128 | 129 | scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) 130 | scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) 131 | 132 | for epoch in range(epoch_str, hps.train.epochs + 1): 133 | if rank == 0: 134 | train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], 135 | [train_loader, eval_loader], logger, [writer, writer_eval]) 136 | else: 137 | train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], 138 | [train_loader, None], None, None) 139 | scheduler_g.step() 140 | scheduler_d.step() 141 | 142 | 143 | def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, loaders, logger, writers): 144 | net_g, net_d = nets 145 | optim_g, optim_d = optims 146 | scheduler_g, scheduler_d = schedulers 147 | train_loader, eval_loader = loaders 148 | if writers is not None: 149 | writer, writer_eval = writers 150 | 151 | # train_loader.batch_sampler.set_epoch(epoch) 152 | global global_step 153 | 154 | net_g.train() 155 | net_d.train() 156 | for batch_idx, items in enumerate(train_loader): 157 | c, f0, spec, y, spk, lengths, uv = items 158 | g = spk 159 | spec, y = spec, y 160 | c = c 161 | f0 = f0 162 | uv = uv 163 | lengths = lengths 164 | mel = spec_to_mel_torch( 165 | spec, 166 | hps.data.filter_length, 167 | hps.data.n_mel_channels, 168 | hps.data.sampling_rate, 169 | hps.data.mel_fmin, 170 | hps.data.mel_fmax) 171 | 172 | y_hat, ids_slice, z_mask, \ 173 | (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, 174 | spec_lengths=lengths) 175 | 176 | y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) 177 | y_hat_mel = mel_spectrogram_torch( 178 | y_hat.squeeze(1), 179 | hps.data.filter_length, 180 | hps.data.n_mel_channels, 181 | hps.data.sampling_rate, 182 | hps.data.hop_length, 183 | hps.data.win_length, 184 | hps.data.mel_fmin, 185 | hps.data.mel_fmax 186 | ) 187 | y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice 188 | 189 | # Discriminator 190 | y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) 191 | 192 | loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) 193 | loss_disc_all = loss_disc 194 | 195 | optim_d.zero_grad() 196 | loss_disc_all.backward() 197 | grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) 198 | optim_d.step() 199 | 200 | # Generator 201 | y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) 202 | loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel 203 | loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl 204 | loss_fm = feature_loss(fmap_r, fmap_g) 205 | loss_gen, losses_gen = generator_loss(y_d_hat_g) 206 | loss_lf0 = F.mse_loss(pred_lf0, lf0) 207 | loss_gen_all = loss_gen + loss_fm + loss_mel + loss_kl + loss_lf0 208 | 209 | optim_g.zero_grad() 210 | loss_gen_all.backward() 211 | grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) 212 | optim_g.step() 213 | 214 | if rank == 0: 215 | if global_step % hps.train.log_interval == 0: 216 | lr = optim_g.param_groups[0]['lr'] 217 | losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_kl] 218 | logger.info('Train Epoch: {} [{:.0f}%]'.format( 219 | epoch, 220 | 100. * batch_idx / len(train_loader))) 221 | logger.info(f"Losses: {[x.item() for x in losses]}, step: {global_step}, lr: {lr}") 222 | 223 | scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, 224 | "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g} 225 | scalar_dict.update({"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/kl": loss_kl, 226 | "loss/g/lf0": loss_lf0}) 227 | 228 | # scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}) 229 | # scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}) 230 | # scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)}) 231 | image_dict = { 232 | "slice/mel_org": sovits_utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()), 233 | "slice/mel_gen": sovits_utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()), 234 | "all/mel": sovits_utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()), 235 | "all/lf0": sovits_utils.plot_data_to_numpy(lf0[0, 0, :].cpu().numpy(), 236 | pred_lf0[0, 0, :].detach().cpu().numpy()), 237 | "all/norm_lf0": sovits_utils.plot_data_to_numpy(lf0[0, 0, :].cpu().numpy(), 238 | norm_lf0[0, 0, :].detach().cpu().numpy()) 239 | } 240 | 241 | sovits_utils.summarize( 242 | writer=writer, 243 | global_step=global_step, 244 | images=image_dict, 245 | scalars=scalar_dict 246 | ) 247 | 248 | if global_step % hps.train.eval_interval == 0: 249 | evaluate(hps, net_g, eval_loader, writer_eval) 250 | sovits_utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, 251 | os.path.join(hps.model_dir, "G_{}.pth".format(global_step))) 252 | sovits_utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, 253 | os.path.join(hps.model_dir, "D_{}.pth".format(global_step))) 254 | keep_ckpts = getattr(hps.train, 'keep_ckpts', 0) 255 | if keep_ckpts > 0: 256 | sovits_utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True) 257 | 258 | global_step += 1 259 | 260 | if rank == 0: 261 | global start_time 262 | now = time.time() 263 | durtaion = format(now - start_time, '.2f') 264 | logger.info(f'====> Epoch: {epoch}, cost {durtaion} s') 265 | start_time = now 266 | 267 | 268 | def evaluate(hps, generator, eval_loader, writer_eval): 269 | generator.eval() 270 | image_dict = {} 271 | audio_dict = {} 272 | with torch.no_grad(): 273 | for batch_idx, items in enumerate(eval_loader): 274 | c, f0, spec, y, spk, _, uv = items 275 | g = spk[:1] 276 | spec, y = spec[:1], y[:1] 277 | c = c[:1] 278 | f0 = f0[:1] 279 | uv= uv[:1] 280 | mel = spec_to_mel_torch( 281 | spec, 282 | hps.data.filter_length, 283 | hps.data.n_mel_channels, 284 | hps.data.sampling_rate, 285 | hps.data.mel_fmin, 286 | hps.data.mel_fmax) 287 | y_hat = generator.module.infer(c, f0, uv, g=g) 288 | 289 | y_hat_mel = mel_spectrogram_torch( 290 | y_hat.squeeze(1).float(), 291 | hps.data.filter_length, 292 | hps.data.n_mel_channels, 293 | hps.data.sampling_rate, 294 | hps.data.hop_length, 295 | hps.data.win_length, 296 | hps.data.mel_fmin, 297 | hps.data.mel_fmax 298 | ) 299 | 300 | audio_dict.update({ 301 | f"gen/audio_{batch_idx}": y_hat[0], 302 | f"gt/audio_{batch_idx}": y[0] 303 | }) 304 | image_dict.update({ 305 | f"gen/mel": sovits_utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()), 306 | "gt/mel": sovits_utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy()) 307 | }) 308 | sovits_utils.summarize( 309 | writer=writer_eval, 310 | global_step=global_step, 311 | images=image_dict, 312 | audios=audio_dict, 313 | audio_sampling_rate=hps.data.sampling_rate 314 | ) 315 | generator.train() 316 | 317 | 318 | if __name__ == "__main__": 319 | main() 320 | -------------------------------------------------------------------------------- /vdecoder/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/effusiveperiscope/so-vits-svc/2bb4b094b8ea820a1b82b6f5ca5051c53819cb83/vdecoder/__init__.py -------------------------------------------------------------------------------- /vdecoder/hifigan/env.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | 4 | 5 | class AttrDict(dict): 6 | def __init__(self, *args, **kwargs): 7 | super(AttrDict, self).__init__(*args, **kwargs) 8 | self.__dict__ = self 9 | 10 | 11 | def build_env(config, config_name, path): 12 | t_path = os.path.join(path, config_name) 13 | if config != t_path: 14 | os.makedirs(path, exist_ok=True) 15 | shutil.copyfile(config, os.path.join(path, config_name)) 16 | -------------------------------------------------------------------------------- /vdecoder/hifigan/nvSTFT.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os 3 | os.environ["LRU_CACHE_CAPACITY"] = "3" 4 | import random 5 | import torch 6 | import torch.utils.data 7 | import numpy as np 8 | import librosa 9 | from librosa.util import normalize 10 | from librosa.filters import mel as librosa_mel_fn 11 | from scipy.io.wavfile import read 12 | import soundfile as sf 13 | 14 | def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False): 15 | sampling_rate = None 16 | try: 17 | data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile. 18 | except Exception as ex: 19 | print(f"'{full_path}' failed to load.\nException:") 20 | print(ex) 21 | if return_empty_on_exception: 22 | return [], sampling_rate or target_sr or 32000 23 | else: 24 | raise Exception(ex) 25 | 26 | if len(data.shape) > 1: 27 | data = data[:, 0] 28 | assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension) 29 | 30 | if np.issubdtype(data.dtype, np.integer): # if audio data is type int 31 | max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX 32 | else: # if audio data is type fp32 33 | max_mag = max(np.amax(data), -np.amin(data)) 34 | max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32 35 | 36 | data = torch.FloatTensor(data.astype(np.float32))/max_mag 37 | 38 | if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except 39 | return [], sampling_rate or target_sr or 32000 40 | if target_sr is not None and sampling_rate != target_sr: 41 | data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr)) 42 | sampling_rate = target_sr 43 | 44 | return data, sampling_rate 45 | 46 | def dynamic_range_compression(x, C=1, clip_val=1e-5): 47 | return np.log(np.clip(x, a_min=clip_val, a_max=None) * C) 48 | 49 | def dynamic_range_decompression(x, C=1): 50 | return np.exp(x) / C 51 | 52 | def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): 53 | return torch.log(torch.clamp(x, min=clip_val) * C) 54 | 55 | def dynamic_range_decompression_torch(x, C=1): 56 | return torch.exp(x) / C 57 | 58 | class STFT(): 59 | def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5): 60 | self.target_sr = sr 61 | 62 | self.n_mels = n_mels 63 | self.n_fft = n_fft 64 | self.win_size = win_size 65 | self.hop_length = hop_length 66 | self.fmin = fmin 67 | self.fmax = fmax 68 | self.clip_val = clip_val 69 | self.mel_basis = {} 70 | self.hann_window = {} 71 | 72 | def get_mel(self, y, center=False): 73 | sampling_rate = self.target_sr 74 | n_mels = self.n_mels 75 | n_fft = self.n_fft 76 | win_size = self.win_size 77 | hop_length = self.hop_length 78 | fmin = self.fmin 79 | fmax = self.fmax 80 | clip_val = self.clip_val 81 | 82 | if torch.min(y) < -1.: 83 | print('min value is ', torch.min(y)) 84 | if torch.max(y) > 1.: 85 | print('max value is ', torch.max(y)) 86 | 87 | if fmax not in self.mel_basis: 88 | mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax) 89 | self.mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device) 90 | self.hann_window[str(y.device)] = torch.hann_window(self.win_size).to(y.device) 91 | 92 | y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_length)/2), int((n_fft-hop_length)/2)), mode='reflect') 93 | y = y.squeeze(1) 94 | 95 | spec = torch.stft(y, n_fft, hop_length=hop_length, win_length=win_size, window=self.hann_window[str(y.device)], 96 | center=center, pad_mode='reflect', normalized=False, onesided=True) 97 | # print(111,spec) 98 | spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9)) 99 | # print(222,spec) 100 | spec = torch.matmul(self.mel_basis[str(fmax)+'_'+str(y.device)], spec) 101 | # print(333,spec) 102 | spec = dynamic_range_compression_torch(spec, clip_val=clip_val) 103 | # print(444,spec) 104 | return spec 105 | 106 | def __call__(self, audiopath): 107 | audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr) 108 | spect = self.get_mel(audio.unsqueeze(0)).squeeze(0) 109 | return spect 110 | 111 | stft = STFT() 112 | -------------------------------------------------------------------------------- /vdecoder/hifigan/utils.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import matplotlib 4 | import torch 5 | from torch.nn.utils import weight_norm 6 | # matplotlib.use("Agg") 7 | import matplotlib.pylab as plt 8 | 9 | 10 | def plot_spectrogram(spectrogram): 11 | fig, ax = plt.subplots(figsize=(10, 2)) 12 | im = ax.imshow(spectrogram, aspect="auto", origin="lower", 13 | interpolation='none') 14 | plt.colorbar(im, ax=ax) 15 | 16 | fig.canvas.draw() 17 | plt.close() 18 | 19 | return fig 20 | 21 | 22 | def init_weights(m, mean=0.0, std=0.01): 23 | classname = m.__class__.__name__ 24 | if classname.find("Conv") != -1: 25 | m.weight.data.normal_(mean, std) 26 | 27 | 28 | def apply_weight_norm(m): 29 | classname = m.__class__.__name__ 30 | if classname.find("Conv") != -1: 31 | weight_norm(m) 32 | 33 | 34 | def get_padding(kernel_size, dilation=1): 35 | return int((kernel_size*dilation - dilation)/2) 36 | 37 | 38 | def load_checkpoint(filepath, device): 39 | assert os.path.isfile(filepath) 40 | print("Loading '{}'".format(filepath)) 41 | checkpoint_dict = torch.load(filepath, map_location=device) 42 | print("Complete.") 43 | return checkpoint_dict 44 | 45 | 46 | def save_checkpoint(filepath, obj): 47 | print("Saving checkpoint to {}".format(filepath)) 48 | torch.save(obj, filepath) 49 | print("Complete.") 50 | 51 | 52 | def del_old_checkpoints(cp_dir, prefix, n_models=2): 53 | pattern = os.path.join(cp_dir, prefix + '????????') 54 | cp_list = glob.glob(pattern) # get checkpoint paths 55 | cp_list = sorted(cp_list)# sort by iter 56 | if len(cp_list) > n_models: # if more than n_models models are found 57 | for cp in cp_list[:-n_models]:# delete the oldest models other than lastest n_models 58 | open(cp, 'w').close()# empty file contents 59 | os.unlink(cp)# delete file (move to trash when using Colab) 60 | 61 | 62 | def scan_checkpoint(cp_dir, prefix): 63 | pattern = os.path.join(cp_dir, prefix + '????????') 64 | cp_list = glob.glob(pattern) 65 | if len(cp_list) == 0: 66 | return None 67 | return sorted(cp_list)[-1] 68 | 69 | --------------------------------------------------------------------------------