Spaces:
Build error
Build error
Commit ·
043fccd
0
Parent(s):
Duplicate from Harveenchadha/Vakyansh-Tamil-TTS
Browse filesCo-authored-by: Harveen Singh Chadha <Harveenchadha@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+28
- README.mdAdded+14
- app.pyAdded+28
- packages.txtAdded+1
- requirements.txtAdded+19
- ttsv/.gitignoreAdded+132
- ttsv/LICENSE.mdAdded+21
- ttsv/README.mdAdded+220
- ttsv/__init__.pyAdded
- ttsv/checkpoints/glow/.gitkeepAdded
- ttsv/checkpoints/hifi/.gitkeepAdded
- ttsv/config/.gitkeepAdded
- ttsv/config/glow/base.jsonAdded+54
- ttsv/config/glow/base_blank.jsonAdded+55
- ttsv/config/hifi/config_v1.jsonAdded+37
- ttsv/config/hifi/config_v2.jsonAdded+37
- ttsv/config/hifi/config_v3.jsonAdded+37
- ttsv/data/.gitkeepAdded
- ttsv/install.shAdded+6
- ttsv/logs/glow/.gitkeepAdded
- ttsv/logs/hifi/.gitkeepAdded
- ttsv/notebooks/vakyansh_tts_demo.ipynbAdded
- ttsv/results/api/.gitkeepAdded
- ttsv/scripts/data/duration.shAdded+9
- ttsv/scripts/data/resample.shAdded+14
- ttsv/scripts/glow/prepare_data.shAdded+12
- ttsv/scripts/glow/train_glow.shAdded+17
- ttsv/scripts/hifi/prepare_data.shAdded+10
- ttsv/scripts/hifi/train_hifi.shAdded+21
- ttsv/scripts/inference/advanced_infer.shAdded+22
- ttsv/scripts/inference/api.shAdded+8
- ttsv/scripts/inference/gradio.shAdded+8
- ttsv/scripts/inference/infer.shAdded+15
- ttsv/setup.pyAdded+55
- ttsv/src/glow_tts/attentions.pyAdded+378
- ttsv/src/glow_tts/audio_processing.pyAdded+100
- ttsv/src/glow_tts/commons.pyAdded+273
- ttsv/src/glow_tts/data_utils.pyAdded+274
- ttsv/src/glow_tts/generate_mels.pyAdded+70
- ttsv/src/glow_tts/hifi/__init__.pyAdded+5
- ttsv/src/glow_tts/hifi/env.pyAdded+15
- ttsv/src/glow_tts/hifi/models.pyAdded+403
- ttsv/src/glow_tts/hifi/utils.pyAdded+57
- ttsv/src/glow_tts/init.pyAdded+79
- ttsv/src/glow_tts/models.pyAdded+403
- ttsv/src/glow_tts/modules.pyAdded+276
- ttsv/src/glow_tts/monotonic_align/monotonic_align/__init__.pyAdded+5
- ttsv/src/glow_tts/monotonic_align/monotonic_align/core.pyxAdded+45
- ttsv/src/glow_tts/monotonic_align/monotonic_align/mas.pyAdded+57
- ttsv/src/glow_tts/monotonic_align/pyproject.tomlAdded+7
12345678910111213141516171819202122232425262728*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bin.* filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zstandard filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011121314---title: Vakyansh Tamil TTSemoji: 📈colorFrom: redcolorTo: yellowsdk: gradiosdk_version: 2.8.13app_file: app.pypinned: falselicense: apache-2.0duplicated_from: Harveenchadha/Vakyansh-Tamil-TTS---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference12345678910111213141516171819202122232425262728import osos.system('wget -q https://storage.googleapis.com/vakyansh-open-models/tts/tamil/ta-IN/female_voice_0/glow.zip && unzip -q glow.zip -d ttsv/checkpoints/female')os.system('wget -q https://storage.googleapis.com/vakyansh-open-models/tts/tamil/ta-IN/ma_fe_hifi/hifi.zip && unzip -q hifi.zip -d ttsv/checkpoints/female')os.system('rm glow.zip && rm hifi.zip')os.system('wget -q https://storage.googleapis.com/vakyansh-open-models/tts/tamil/ta-IN/male_voice_1/glow.zip && unzip -q glow.zip -d ttsv/checkpoints/male')os.system('wget -q https://storage.googleapis.com/vakyansh-open-models/tts/tamil/ta-IN/ma_fe_hifi/hifi.zip && unzip -q hifi.zip -d ttsv/checkpoints/male')os.system('wget -q https://storage.googleapis.com/vakyansh-open-models/translit_models.zip -P ttsv/checkpoints/ && unzip -q ttsv/checkpoints/translit_models.zip -d ttsv/checkpoints/')
for path, subdirs, files in os.walk('ttsv/checkpoints/'): print(subdirs) for name in files: print(os.path.join(path, name))
from ttsv.utils.inference.run_gradio import *from argparse import Namespace
#os.system('python ttsv/utils/inference/run_gradio.py -a ttsv/checkpoints/glow/male -v ttsv/checkpoints/hifi/male -d cpu -L hi')
args = { 'acoustic':'/home/user/app/ttsv/checkpoints/female/glow,/home/user/app/ttsv/checkpoints/male/glow', 'vocoder':'/home/user/app/ttsv/checkpoints/female/hifi,/home/user/app/ttsv/checkpoints/male/hifi', 'device':'cpu', 'lang':'ta'}
build_gradio(Namespace(**args))1libsndfile112345678910111213141516171819Cython==0.29.24layers==0.1.5librosa==0.8.1matplotlib==3.3.4numpy==1.21.0scipy==1.5.4tensorboardX==2.4tensorboard==2.7.0tqdm==4.62.3fastapi==0.70.0uvicorn==0.15.0gradio==2.5.2wavio==0.0.4mosestokenizer==1.2.1indic-nlp-library==0.81inflect==5.3.0Unidecode==1.3.2torchpydload123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# Byte-compiled / optimized / DLL files.DS_Store__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/pip-wheel-metadata/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuildertarget/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv.python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
.idea/123456789101112131415161718192021MIT License
Copyright (c) 2022 Open-Speech-EkStep
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220# vakyansh-ttsText to Speech for Indic languages
## 1. Installation and Setup for training
Clone repoNote : for multspeaker glow-tts training use branch [multispeaker](https://github.com/Open-Speech-EkStep/vakyansh-tts/tree/multispeaker)```git clone https://github.com/Open-Speech-EkStep/vakyansh-tts```Build conda virtual environment```cd ./vakyansh-ttsconda create --name <env_name> python=3.7conda activate <env_name>pip install -r requirements.txt```Install [apex](https://github.com/NVIDIA/apex); commit: 37cdaf4 for Mixed-precision training
Note : used only for glow-tts```cd ..git clone https://github.com/NVIDIA/apexcd apexgit checkout 37cdaf4pip install -v --disable-pip-version-check --no-cache-dir ./cd ../vakyansh-tts```Build Monotonic Alignment Search Code (Cython)
Note : used only for glow-tts```bash install.sh```
## 2. Data Resampling
The data format should have a folder containing all the .wav files for glow-tts and a text file containing filenames with their sentences.
Directory structure:
langauge_folder_name```language_folder_name|-- ./wav/*.wav|-- ./text_file_name.txt```The format for text_file_name.txt (Text file is only needed for glow-tts training)
```( audio1.wav "Sentence1." )( audio2.wav "Sentence2." )```
To resample the .wav files to 22050 sample rate, change the following parameters in the vakyansh-tts/scripts/data/resample.sh
```input_wav_path : absolute path to wav file folder in vakyansh_tts/data/output_wav_path : absolute path to vakyansh_tts/data/resampled_wav_folder_nameoutput_sample_rate : 22050 (or any other desired sample rate)```
To run: ```bashcd scripts/data/bash resample.sh```
## 3. Spectogram Training (glow-tts)
### 3.1 Data Preparation
To prepare the data edit the vakyansh-tts/scripts/glow/prepare_data.sh file and change the following parameters```input_text_path : absolute path to vakyansh_tts/data/text_file_name.txtinput_wav_path : absolute path to vakyansh_tts/data/resampled_wav_folder_namegender : female or male voice```To run: ```bashcd scripts/glow/bash prepare_data.sh```### 3.2 Training glow-tts
To start the spectogram-training edit the vakyansh-tts/scripts/glow/train_glow.sh file and change the following parameter:```gender : female or male voice```Make sure that the gender is same as that of the prepare_data.sh file
To start the training, run: ```bashcd scripts/glow/bash train_glow.sh```## 4. Vocoder Training (hifi-gan)
### 4.1 Data Preparation
To prepare the data edit the vakyansh-tts/scripts/hifi/prepare_data.sh file and change the following parameters```input_wav_path : absolute path to vakyansh_tts/data/resampled_wav_folder_namegender : female or male voice```To run: ```bashcd scripts/hifi/bash prepare_data.sh```### 4.2 Training hifi-gan
To start the spectogram-training edit the vakyansh-tts/scripts/hifi/train_hifi.sh file and change the following parameter:```gender : female or male voice```Make sure that the gender is same as that of the prepare_data.sh file
To start the training, run: ```bashcd scripts/hifi/bash train_hifi.sh```
## 5. Inference
### 5.1 Using Gradio
To use the gradio link edit the following parameters in the vakyansh-tts/scripts/inference/gradio.sh file:```gender : female or male voicedevice : cpu or cudalang : langauge code```
To run: ```bashcd scripts/inference/bash gradio.sh```### 5.2 Using fast API To use the fast api link edit the parameters in the vakyansh-tts/scripts/inference/api.sh file similar to section 5.1
To run: ```bashcd scripts/inference/bash api.sh```
### 5.3 Direct Inference using text To infer, edit the parameters in the vakyansh-tts/scripts/inference/infer.sh file similar to section 5.1 and set the text to the text variable
To run: ```bashcd scripts/inference/bash infer.sh```
To configure other parameters there is a version that runs the advanced inference as well. Additional Parameters:```noise_scale : can vary from 0 to 1 for noise factorlength_scale : can vary from 0 to 2 for changing the speed of the generated audio transliteration : whether to switch on/off transliteration. 1: ON, 0: OFFnumber_conversion : whether to switch on/off number to words conversion. 1: ON, 0: OFFsplit_sentences : whether to switch on/off splitting of sentences. 1: ON, 0: OFF```To run:```cd scripts/inference/bash advanced_infer.sh```
### 5.4 Installation of tts_infer package
In tts_infer package, we currently have two components: 1. Transliteration (AI4bharat's open sourced models) (Languages supported: {'hi', 'gu', 'mr', 'bn', 'te', 'ta', 'kn', 'pa', 'gom', 'mai', 'ml', 'sd', 'si', 'ur'} ) 2. Num to Word (Languages supported: {'en', 'hi', 'gu', 'mr', 'bn', 'te', 'ta', 'kn', 'or', 'pa'} )```git clone https://github.com/Open-Speech-EkStep/vakyansh-ttscd vakyansh-ttsbash install.shpython setup.py bdist_wheelpip install -e .cd tts_infergsutil -m cp -r gs://vakyaansh-open-models/translit_models .```
Usage: Refer to example file in tts_infer/```from tts_infer.tts import TextToMel, MelToWavfrom tts_infer.transliterate import XlitEnginefrom tts_infer.num_to_word_on_sent import normalize_nums
import refrom scipy.io.wavfile import write
text_to_mel = TextToMel(glow_model_dir='/path/to/glow-tts/checkpoint/dir', device='cuda')mel_to_wav = MelToWav(hifi_model_dir='/path/to/hifi/checkpoint/dir', device='cuda')
def translit(text, lang): reg = re.compile(r'[a-zA-Z]') engine = XlitEngine(lang) words = [engine.translit_word(word, topk=1)[lang][0] if reg.match(word) else word for word in text.split()] updated_sent = ' '.join(words) return updated_sent def run_tts(text, lang): text = text.replace('।', '.') # only for hindi models text_num_to_word = normalize_nums(text, lang) # converting numbers to words in lang text_num_to_word_and_transliterated = translit(text_num_to_word, lang) # transliterating english words to lang mel = text_to_mel.generate_mel(text_num_to_word_and_transliterated) audio, sr = mel_to_wav.generate_wav(mel) write(filename='temp.wav', rate=sr, data=audio) # for saving wav file, if needed return (sr, audio)```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{ "train": { "use_cuda": true, "log_interval": 20, "seed": 1234, "epochs": 10000, "learning_rate": 1e0, "betas": [0.9, 0.98], "eps": 1e-9, "warmup_steps": 4000, "scheduler": "noam", "batch_size": 16, "ddi": true, "fp16_run": true, "save_epoch": 1 }, "data": { "load_mel_from_disk": false, "training_files":"../data/training/train.txt", "validation_files":"../data/training/valid.txt", "chars":"", "punc":"", "text_cleaners":["basic_indic_cleaners"], "max_wav_value": 32768.0, "sampling_rate": 22050, "filter_length": 1024, "hop_length": 256, "win_length": 1024, "n_mel_channels": 80, "mel_fmin": 80.0, "mel_fmax": 7600.0, "add_noise": true }, "model": { "hidden_channels": 192, "filter_channels": 768, "filter_channels_dp": 256, "kernel_size": 3, "p_dropout": 0.1, "n_blocks_dec": 12, "n_layers_enc": 6, "n_heads": 2, "p_dropout_dec": 0.05, "dilation_rate": 1, "kernel_size_dec": 5, "n_block_layers": 4, "n_sqz": 2, "prenet": true, "mean_only": true, "hidden_channels_enc": 192, "hidden_channels_dec": 192, "window_size": 4 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{ "train": { "use_cuda": true, "log_interval": 20, "seed": 1234, "epochs": 10000, "learning_rate": 1e0, "betas": [0.9, 0.98], "eps": 1e-9, "warmup_steps": 4000, "scheduler": "noam", "batch_size": 16, "ddi": true, "fp16_run": true, "save_epoch": 1 }, "data": { "load_mel_from_disk": false, "training_files":"../data/training/train.txt", "validation_files":"../data/training/valid.txt", "chars":"", "punc":"", "text_cleaners":["basic_indic_cleaners"], "max_wav_value": 32768.0, "sampling_rate": 22050, "filter_length": 1024, "hop_length": 256, "win_length": 1024, "n_mel_channels": 80, "mel_fmin": 80.0, "mel_fmax": 7600.0, "add_noise": true, "add_blank": true }, "model": { "hidden_channels": 192, "filter_channels": 768, "filter_channels_dp": 256, "kernel_size": 3, "p_dropout": 0.1, "n_blocks_dec": 12, "n_layers_enc": 6, "n_heads": 2, "p_dropout_dec": 0.05, "dilation_rate": 1, "kernel_size_dec": 5, "n_block_layers": 4, "n_sqz": 2, "prenet": true, "mean_only": true, "hidden_channels_enc": 192, "hidden_channels_dec": 192, "window_size": 4 }}12345678910111213141516171819202122232425262728293031323334353637{ "resblock": "1", "num_gpus": 0, "batch_size": 24, "learning_rate": 0.0002, "adam_b1": 0.8, "adam_b2": 0.99, "lr_decay": 0.999, "seed": 1234,
"upsample_rates": [8,8,2,2], "upsample_kernel_sizes": [16,16,4,4], "upsample_initial_channel": 512, "resblock_kernel_sizes": [3,7,11], "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
"segment_size": 8192, "num_mels": 80, "num_freq": 1025, "n_fft": 1024, "hop_size": 256, "win_size": 1024,
"sampling_rate": 22050,
"fmin": 80, "fmax": 7600, "fmax_for_loss": null,
"num_workers": 4,
"dist_config": { "dist_backend": "nccl", "dist_url": "tcp://localhost:54321", "world_size": 1 }}12345678910111213141516171819202122232425262728293031323334353637{ "resblock": "1", "num_gpus": 0, "batch_size": 24, "learning_rate": 0.0002, "adam_b1": 0.8, "adam_b2": 0.99, "lr_decay": 0.999, "seed": 1234,
"upsample_rates": [8,8,2,2], "upsample_kernel_sizes": [16,16,4,4], "upsample_initial_channel": 128, "resblock_kernel_sizes": [3,7,11], "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
"segment_size": 8192, "num_mels": 80, "num_freq": 1025, "n_fft": 1024, "hop_size": 256, "win_size": 1024,
"sampling_rate": 22050,
"fmin": 80, "fmax": 7600, "fmax_for_loss": null,
"num_workers": 4,
"dist_config": { "dist_backend": "nccl", "dist_url": "tcp://localhost:54321", "world_size": 1 }}12345678910111213141516171819202122232425262728293031323334353637{ "resblock": "2", "num_gpus": 0, "batch_size": 24, "learning_rate": 0.0002, "adam_b1": 0.8, "adam_b2": 0.99, "lr_decay": 0.999, "seed": 1234,
"upsample_rates": [8,8,4], "upsample_kernel_sizes": [16,16,8], "upsample_initial_channel": 256, "resblock_kernel_sizes": [3,5,7], "resblock_dilation_sizes": [[1,2], [2,6], [3,12]],
"segment_size": 8192, "num_mels": 80, "num_freq": 1025, "n_fft": 1024, "hop_size": 256, "win_size": 1024,
"sampling_rate": 22050,
"fmin": 80, "fmax": 7600, "fmax_for_loss": null,
"num_workers": 4,
"dist_config": { "dist_backend": "nccl", "dist_url": "tcp://localhost:54321", "world_size": 1 }}123456cd src/glow_tts/monotonic_align/pip install .cd ../../../
# torchpip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html123456789wav_path='/home/harveen/en/iitm_data/english/wav_22k'#######################
dir=$PWDparentdir="$(dirname "$dir")"parentdir="$(dirname "$parentdir")"
python $parentdir/utils/data/duration.py $wav_path1234567891011121314input_wav_path='/home/harveen/en/iitm_data/english/wav/'output_wav_path='/home/harveen/en/iitm_data/english/wav_22k/'output_sample_rate=22050
#######################
dir=$PWDparentdir="$(dirname "$dir")"parentdir="$(dirname "$parentdir")"
mkdir -p $output_wav_pathpython $parentdir/utils/data/resample.py -i $input_wav_path -o $output_wav_path -s $output_sample_rate
python $parentdir/utils/data/duration.py $output_wav_path123456789101112input_text_path='/home/harveen/en/iitm_data/english/txt.done.data'input_wav_path='/home/harveen/en/iitm_data/english/wav_22k'gender='male'
output_data_path='../../data/glow/'$gender
valid_samples=100test_samples=10
mkdir -p $output_data_pathpython ../../utils/glow/prepare_iitm_data_glow_en.py -i $input_text_path -o $output_data_path -w $input_wav_path -v $valid_samples -t $test_samples1234567891011121314151617#!/bin/bash
gender='male'
config='../../config/glow/'$gender'.json'modeldir='../../checkpoints/glow/'$genderlogdir='../../logs/glow/'$genderinit=1 # 1 if start from scratch. 0 if start from last checkpoint
####################################################
if [[ $init -eq 1 ]]then python ../../src/glow_tts/init.py -c $config -m $modeldir -l $logdirfipython ../../src/glow_tts/train.py -c $config -m $modeldir -l $logdir12345678910input_wav_path='/home/harveen/en/iitm_data/english/wav_22k' #give multiple folders separated by comma(,)gender='male'
output_data_path='../../data/hifi/'$gender
valid_samples=100test_samples=10
mkdir -p $output_data_pathpython ../../utils/hifi/prepare_iitm_data_hifi.py -i $input_wav_path -v $valid_samples -t $test_samples -d $output_data_path123456789101112131415161718192021#!/bin/bash
gender='male'
config='../../config/hifi/config_v1.json'modeldir='../../checkpoints/hifi/'$genderlogdir='../../logs/hifi/'$gender
####################################################
python ../../src/hifi_gan/train.py \ --config $config \ --input_training_file '../../data/hifi/'$gender'/train.txt' \ --input_validation_file '../../data/hifi/'$gender'/valid.txt' \ --checkpoint_path $modeldir \ --logs_path $logdir \ --checkpoint_interval 10000 \ --stdout_interval 5012345678910111213141516171819202122gender='male'glowdir='../../checkpoints/glow/'$gender'/'hifidir='../../checkpoints/hifi/'$gender'/'device='cpu'text='Hey mr. I am testing this one. Now on multiple sentences. Just want to see the flow.'noise_scale='0.667'length_scale='1.0'transliteration=1number_conversion=1split_sentences=1lang='en'
timestamp=$(date +%s)wav='../../results/'$gender'/'wav_file=$wav/$timestamp'.wav'
mkdir -p $wav
python ../../utils/inference/advanced_tts.py -a $glowdir -v $hifidir -d $device -t "$text" -w $wav_file -L $lang -n $noise_scale -l $length_scale -T $transliteration -N $number_conversion -S $split_sentencesecho "File saved at: "$wav_file12345678gender='male'glowdir='../../checkpoints/glow/'$gender'/'hifidir='../../checkpoints/hifi/'$gender'/'device='cpu'lang='en'
python ../../utils/inference/api.py -a $glowdir -v $hifidir -d $device -L $lang12345678gender='male'glowdir='../../checkpoints/glow/'$gender'/'hifidir='../../checkpoints/hifi/'$gender'/'device='cpu'lang='en'
python ../../utils/inference/run_gradio.py -a $glowdir -v $hifidir -d $device -L $lang123456789101112131415gender='male'glowdir='../../checkpoints/glow/'$gender'/'hifidir='../../checkpoints/hifi/'$gender'/'device='cpu'text='testing this one'
timestamp=$(date +%s)wav='../../results/'$gender'/'wav_file=$wav/$timestamp'.wav'
mkdir -p $wavpython ../../utils/inference/tts.py -a $glowdir -v $hifidir -d $device -t "$text" -w $wav_file echo "File saved at: "$wav_file12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455from setuptools import setup, find_packages
with open("README.md", "r") as f: long_description = f.read()
setup( name="vakyansh-tts", version="0.0.5", description="Text to speech for Indic languages", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Open-Speech-EkStep/vakyansh-tts.git", keywords="nlp, tts, Indic languages, deep learning, text to speech", # package_dir={'': 'src'}, # packages=find_packages(where='src'), packages=["tts_infer"], python_requires=">=3.7, <4", install_requires=[ "Cython==0.29.24", "layers==0.1.5", "librosa==0.8.1", "matplotlib==3.3.4", "numpy==1.20.2", "scipy==1.5.4", "tensorboardX==2.4", "tensorboard==2.7.0", "tqdm==4.62.3", "fastapi==0.70.0", "uvicorn==0.15.0", "gradio==2.5.2", "wavio==0.0.4", "pydload==1.0.9", "mosestokenizer==1.2.1", "indic-nlp-library==0.81" ], classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable "Development Status :: 3 - Alpha", # Indicate who your project is intended for "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Text Processing :: Linguistic", # Pick your license as you wish (should match "license" above) "License :: OSI Approved :: MIT License", # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. "Programming Language :: Python :: 3.7", ], include_package_data=True,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378import copyimport mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as F
import commonsimport modulesfrom modules import LayerNorm
class Encoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, window_size=None, block_length=None, **kwargs ): super().__init__() self.hidden_channels = hidden_channels self.filter_channels = filter_channels self.n_heads = n_heads self.n_layers = n_layers self.kernel_size = kernel_size self.p_dropout = p_dropout self.window_size = window_size self.block_length = block_length
self.drop = nn.Dropout(p_dropout) self.attn_layers = nn.ModuleList() self.norm_layers_1 = nn.ModuleList() self.ffn_layers = nn.ModuleList() self.norm_layers_2 = nn.ModuleList() for i in range(self.n_layers): self.attn_layers.append( MultiHeadAttention( hidden_channels, hidden_channels, n_heads, window_size=window_size, p_dropout=p_dropout, block_length=block_length, ) ) self.norm_layers_1.append(LayerNorm(hidden_channels)) self.ffn_layers.append( FFN( hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, ) ) self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask): attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) for i in range(self.n_layers): x = x * x_mask y = self.attn_layers[i](x, x, attn_mask) y = self.drop(y) x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask) y = self.drop(y) x = self.norm_layers_2[i](x + y) x = x * x_mask return x
class CouplingBlock(nn.Module): def __init__( self, in_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0, sigmoid_scale=False, ): super().__init__() self.in_channels = in_channels self.hidden_channels = hidden_channels self.kernel_size = kernel_size self.dilation_rate = dilation_rate self.n_layers = n_layers self.gin_channels = gin_channels self.p_dropout = p_dropout self.sigmoid_scale = sigmoid_scale
start = torch.nn.Conv1d(in_channels // 2, hidden_channels, 1) start = torch.nn.utils.weight_norm(start) self.start = start # Initializing last layer to 0 makes the affine coupling layers # do nothing at first. It helps to stabilze training. end = torch.nn.Conv1d(hidden_channels, in_channels, 1) end.weight.data.zero_() end.bias.data.zero_() self.end = end
self.wn = modules.WN( in_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels, p_dropout, )
def forward(self, x, x_mask=None, reverse=False, g=None, **kwargs): b, c, t = x.size() if x_mask is None: x_mask = 1 x_0, x_1 = x[:, : self.in_channels // 2], x[:, self.in_channels // 2 :]
x = self.start(x_0) * x_mask x = self.wn(x, x_mask, g) out = self.end(x)
z_0 = x_0 m = out[:, : self.in_channels // 2, :] logs = out[:, self.in_channels // 2 :, :] if self.sigmoid_scale: logs = torch.log(1e-6 + torch.sigmoid(logs + 2))
if reverse: z_1 = (x_1 - m) * torch.exp(-logs) * x_mask logdet = None else: z_1 = (m + torch.exp(logs) * x_1) * x_mask logdet = torch.sum(logs * x_mask, [1, 2])
z = torch.cat([z_0, z_1], 1) return z, logdet
def store_inverse(self): self.wn.remove_weight_norm()
class MultiHeadAttention(nn.Module): def __init__( self, channels, out_channels, n_heads, window_size=None, heads_share=True, p_dropout=0.0, block_length=None, proximal_bias=False, proximal_init=False, ): super().__init__() assert channels % n_heads == 0
self.channels = channels self.out_channels = out_channels self.n_heads = n_heads self.window_size = window_size self.heads_share = heads_share self.block_length = block_length self.proximal_bias = proximal_bias self.p_dropout = p_dropout self.attn = None
self.k_channels = channels // n_heads self.conv_q = nn.Conv1d(channels, channels, 1) self.conv_k = nn.Conv1d(channels, channels, 1) self.conv_v = nn.Conv1d(channels, channels, 1) if window_size is not None: n_heads_rel = 1 if heads_share else n_heads rel_stddev = self.k_channels ** -0.5 self.emb_rel_k = nn.Parameter( torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev ) self.emb_rel_v = nn.Parameter( torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev ) self.conv_o = nn.Conv1d(channels, out_channels, 1) self.drop = nn.Dropout(p_dropout)
nn.init.xavier_uniform_(self.conv_q.weight) nn.init.xavier_uniform_(self.conv_k.weight) if proximal_init: self.conv_k.weight.data.copy_(self.conv_q.weight.data) self.conv_k.bias.data.copy_(self.conv_q.bias.data) nn.init.xavier_uniform_(self.conv_v.weight)
def forward(self, x, c, attn_mask=None): q = self.conv_q(x) k = self.conv_k(c) v = self.conv_v(c)
x, self.attn = self.attention(q, k, v, mask=attn_mask)
x = self.conv_o(x) return x
def attention(self, query, key, value, mask=None): # reshape [b, d, t] -> [b, n_h, t, d_k] b, d, t_s, t_t = (*key.size(), query.size(2)) query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.k_channels) if self.window_size is not None: assert ( t_s == t_t ), "Relative attention is only available for self-attention." key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) rel_logits = self._matmul_with_relative_keys(query, key_relative_embeddings) rel_logits = self._relative_position_to_absolute_position(rel_logits) scores_local = rel_logits / math.sqrt(self.k_channels) scores = scores + scores_local if self.proximal_bias: assert t_s == t_t, "Proximal bias is only available for self-attention." scores = scores + self._attention_bias_proximal(t_s).to( device=scores.device, dtype=scores.dtype ) if mask is not None: scores = scores.masked_fill(mask == 0, -1e4) if self.block_length is not None: block_mask = ( torch.ones_like(scores) .triu(-self.block_length) .tril(self.block_length) ) scores = scores * block_mask + -1e4 * (1 - block_mask) p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] p_attn = self.drop(p_attn) output = torch.matmul(p_attn, value) if self.window_size is not None: relative_weights = self._absolute_position_to_relative_position(p_attn) value_relative_embeddings = self._get_relative_embeddings( self.emb_rel_v, t_s ) output = output + self._matmul_with_relative_values( relative_weights, value_relative_embeddings ) output = ( output.transpose(2, 3).contiguous().view(b, d, t_t) ) # [b, n_h, t_t, d_k] -> [b, d, t_t] return output, p_attn
def _matmul_with_relative_values(self, x, y): """ x: [b, h, l, m] y: [h or 1, m, d] ret: [b, h, l, d] """ ret = torch.matmul(x, y.unsqueeze(0)) return ret
def _matmul_with_relative_keys(self, x, y): """ x: [b, h, l, d] y: [h or 1, m, d] ret: [b, h, l, m] """ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) return ret
def _get_relative_embeddings(self, relative_embeddings, length): max_relative_position = 2 * self.window_size + 1 # Pad first before slice to avoid using cond ops. pad_length = max(length - (self.window_size + 1), 0) slice_start_position = max((self.window_size + 1) - length, 0) slice_end_position = slice_start_position + 2 * length - 1 if pad_length > 0: padded_relative_embeddings = F.pad( relative_embeddings, commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]), ) else: padded_relative_embeddings = relative_embeddings used_relative_embeddings = padded_relative_embeddings[ :, slice_start_position:slice_end_position ] return used_relative_embeddings
def _relative_position_to_absolute_position(self, x): """ x: [b, h, l, 2*l-1] ret: [b, h, l, l] """ batch, heads, length, _ = x.size() # Concat columns of pad to shift from relative to absolute indexing. x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
# Concat extra elements so to add up to shape (len+1, 2*len-1). x_flat = x.view([batch, heads, length * 2 * length]) x_flat = F.pad( x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]) )
# Reshape and slice out the padded elements. x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[ :, :, :length, length - 1 : ] return x_final
def _absolute_position_to_relative_position(self, x): """ x: [b, h, l, l] ret: [b, h, l, 2*l-1] """ batch, heads, length, _ = x.size() # padd along column x = F.pad( x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]) ) x_flat = x.view([batch, heads, length ** 2 + length * (length - 1)]) # add 0's in the beginning that will skew the elements after reshape x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:] return x_final
def _attention_bias_proximal(self, length): """Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor with shape [1, 1, length, length] """ r = torch.arange(length, dtype=torch.float32) diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
class FFN(nn.Module): def __init__( self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0, activation=None, ): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.filter_channels = filter_channels self.kernel_size = kernel_size self.p_dropout = p_dropout self.activation = activation
self.conv_1 = nn.Conv1d( in_channels, filter_channels, kernel_size, padding=kernel_size // 2 ) self.conv_2 = nn.Conv1d( filter_channels, out_channels, kernel_size, padding=kernel_size // 2 ) self.drop = nn.Dropout(p_dropout)
def forward(self, x, x_mask): x = self.conv_1(x * x_mask) if self.activation == "gelu": x = x * torch.sigmoid(1.702 * x) else: x = torch.relu(x) x = self.drop(x) x = self.conv_2(x * x_mask) return x * x_mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import torchimport numpy as npfrom scipy.signal import get_windowimport librosa.util as librosa_util
def window_sumsquare( window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None,): """ # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length.
This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms.
Parameters ---------- window : string, tuple, number, callable, or list-like Window specification, as in `get_window`
n_frames : int > 0 The number of analysis frames
hop_length : int > 0 The number of samples to advance between frames
win_length : [optional] The length of the window function. By default, this matches `n_fft`.
n_fft : int > 0 The length of each analysis frame.
dtype : np.dtype The data type of the output
Returns ------- wss : np.ndarray, shape=`(n_fft + hop_length * (n_frames - 1))` The sum-squared envelope of the window function """ if win_length is None: win_length = n_fft
n = n_fft + hop_length * (n_frames - 1) x = np.zeros(n, dtype=dtype)
# Compute the squared window at the desired length win_sq = get_window(window, win_length, fftbins=True) win_sq = librosa_util.normalize(win_sq, norm=norm) ** 2 win_sq = librosa_util.pad_center(win_sq, n_fft)
# Fill the envelope for i in range(n_frames): sample = i * hop_length x[sample : min(n, sample + n_fft)] += win_sq[: max(0, min(n_fft, n - sample))] return x
def griffin_lim(magnitudes, stft_fn, n_iters=30): """ PARAMS ------ magnitudes: spectrogram magnitudes stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods """
angles = np.angle(np.exp(2j * np.pi * np.random.rand(*magnitudes.size()))) angles = angles.astype(np.float32) angles = torch.autograd.Variable(torch.from_numpy(angles)) signal = stft_fn.inverse(magnitudes, angles).squeeze(1)
for i in range(n_iters): _, angles = stft_fn.transform(signal) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) return signal
def dynamic_range_compression(x, C=1, clip_val=1e-5): """ PARAMS ------ C: compression factor """ return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression(x, C=1): """ PARAMS ------ C: compression factor used to compress """ return torch.exp(x) / C123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273import mathimport numpy as npimport torchfrom torch import nnfrom torch.nn import functional as F
from librosa.filters import mel as librosa_mel_fnfrom audio_processing import dynamic_range_compressionfrom audio_processing import dynamic_range_decompressionfrom stft import STFT
def intersperse(lst, item): result = [item] * (len(lst) * 2 + 1) result[1::2] = lst return result
def mle_loss(z, m, logs, logdet, mask): l = torch.sum(logs) + 0.5 * torch.sum( torch.exp(-2 * logs) * ((z - m) ** 2) ) # neg normal likelihood w/o the constant term l = l - torch.sum(logdet) # log jacobian determinant l = l / torch.sum( torch.ones_like(z) * mask ) # averaging across batch, channel and time axes l = l + 0.5 * math.log(2 * math.pi) # add the remaining constant term return l
def duration_loss(logw, logw_, lengths): l = torch.sum((logw - logw_) ** 2) / torch.sum(lengths) return l
@torch.jit.scriptdef fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): n_channels_int = n_channels[0] in_act = input_a + input_b t_act = torch.tanh(in_act[:, :n_channels_int, :]) s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) acts = t_act * s_act return acts
def convert_pad_shape(pad_shape): l = pad_shape[::-1] pad_shape = [item for sublist in l for item in sublist] return pad_shape
def shift_1d(x): x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] return x
def sequence_mask(length, max_length=None): if max_length is None: max_length = length.max() x = torch.arange(max_length, dtype=length.dtype, device=length.device) return x.unsqueeze(0) < length.unsqueeze(1)
def maximum_path(value, mask, max_neg_val=-np.inf): """Numpy-friendly version. It's about 4 times faster than torch version. value: [b, t_x, t_y] mask: [b, t_x, t_y] """ value = value * mask
device = value.device dtype = value.dtype value = value.cpu().detach().numpy() mask = mask.cpu().detach().numpy().astype(np.bool)
b, t_x, t_y = value.shape direction = np.zeros(value.shape, dtype=np.int64) v = np.zeros((b, t_x), dtype=np.float32) x_range = np.arange(t_x, dtype=np.float32).reshape(1, -1) for j in range(t_y): v0 = np.pad(v, [[0, 0], [1, 0]], mode="constant", constant_values=max_neg_val)[ :, :-1 ] v1 = v max_mask = v1 >= v0 v_max = np.where(max_mask, v1, v0) direction[:, :, j] = max_mask
index_mask = x_range <= j v = np.where(index_mask, v_max + value[:, :, j], max_neg_val) direction = np.where(mask, direction, 1)
path = np.zeros(value.shape, dtype=np.float32) index = mask[:, :, 0].sum(1).astype(np.int64) - 1 index_range = np.arange(b) for j in reversed(range(t_y)): path[index_range, index, j] = 1 index = index + direction[index_range, index, j] - 1 path = path * mask.astype(np.float32) path = torch.from_numpy(path).to(device=device, dtype=dtype) return path
def generate_path(duration, mask): """ duration: [b, t_x] mask: [b, t_x, t_y] """ device = duration.device
b, t_x, t_y = mask.shape cum_duration = torch.cumsum(duration, 1) path = torch.zeros(b, t_x, t_y, dtype=mask.dtype).to(device=device)
cum_duration_flat = cum_duration.view(b * t_x) path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) path = path.view(b, t_x, t_y) path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] path = path * mask return path
class Adam: def __init__( self, params, scheduler, dim_model, warmup_steps=4000, lr=1e0, betas=(0.9, 0.98), eps=1e-9, ): self.params = params self.scheduler = scheduler self.dim_model = dim_model self.warmup_steps = warmup_steps self.lr = lr self.betas = betas self.eps = eps
self.step_num = 1 self.cur_lr = lr * self._get_lr_scale()
self._optim = torch.optim.Adam(params, lr=self.cur_lr, betas=betas, eps=eps)
def _get_lr_scale(self): if self.scheduler == "noam": return np.power(self.dim_model, -0.5) * np.min( [ np.power(self.step_num, -0.5), self.step_num * np.power(self.warmup_steps, -1.5), ] ) else: return 1
def _update_learning_rate(self): self.step_num += 1 if self.scheduler == "noam": self.cur_lr = self.lr * self._get_lr_scale() for param_group in self._optim.param_groups: param_group["lr"] = self.cur_lr
def get_lr(self): return self.cur_lr
def step(self): self._optim.step() self._update_learning_rate()
def zero_grad(self): self._optim.zero_grad()
def load_state_dict(self, d): self._optim.load_state_dict(d)
def state_dict(self): return self._optim.state_dict()
class TacotronSTFT(nn.Module): def __init__( self, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, sampling_rate=22050, mel_fmin=0.0, mel_fmax=8000.0, ): super(TacotronSTFT, self).__init__() self.n_mel_channels = n_mel_channels self.sampling_rate = sampling_rate self.stft_fn = STFT(filter_length, hop_length, win_length) mel_basis = librosa_mel_fn( sampling_rate, filter_length, n_mel_channels, mel_fmin, mel_fmax ) mel_basis = torch.from_numpy(mel_basis).float() self.register_buffer("mel_basis", mel_basis)
def spectral_normalize(self, magnitudes): output = dynamic_range_compression(magnitudes) return output
def spectral_de_normalize(self, magnitudes): output = dynamic_range_decompression(magnitudes) return output
def mel_spectrogram(self, y): """Computes mel-spectrograms from a batch of waves PARAMS ------ y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1]
RETURNS ------- mel_output: torch.FloatTensor of shape (B, n_mel_channels, T) """ assert torch.min(y.data) >= -1 assert torch.max(y.data) <= 1
magnitudes, phases = self.stft_fn.transform(y) magnitudes = magnitudes.data mel_output = torch.matmul(self.mel_basis, magnitudes) mel_output = self.spectral_normalize(mel_output) return mel_output
def clip_grad_value_(parameters, clip_value, norm_type=2): if isinstance(parameters, torch.Tensor): parameters = [parameters] parameters = list(filter(lambda p: p.grad is not None, parameters)) norm_type = float(norm_type) clip_value = float(clip_value)
total_norm = 0 for p in parameters: param_norm = p.grad.data.norm(norm_type) total_norm += param_norm.item() ** norm_type
p.grad.data.clamp_(min=-clip_value, max=clip_value) total_norm = total_norm ** (1.0 / norm_type) return total_norm
def squeeze(x, x_mask=None, n_sqz=2): b, c, t = x.size()
t = (t // n_sqz) * n_sqz x = x[:, :, :t] x_sqz = x.view(b, c, t // n_sqz, n_sqz) x_sqz = x_sqz.permute(0, 3, 1, 2).contiguous().view(b, c * n_sqz, t // n_sqz)
if x_mask is not None: x_mask = x_mask[:, :, n_sqz - 1 :: n_sqz] else: x_mask = torch.ones(b, 1, t // n_sqz).to(device=x.device, dtype=x.dtype) return x_sqz * x_mask, x_mask
def unsqueeze(x, x_mask=None, n_sqz=2): b, c, t = x.size()
x_unsqz = x.view(b, n_sqz, c // n_sqz, t) x_unsqz = x_unsqz.permute(0, 2, 3, 1).contiguous().view(b, c // n_sqz, t * n_sqz)
if x_mask is not None: x_mask = x_mask.unsqueeze(-1).repeat(1, 1, 1, n_sqz).view(b, 1, t * n_sqz) else: x_mask = torch.ones(b, 1, t * n_sqz).to(device=x.device, dtype=x.dtype) return x_unsqz * x_mask, x_mask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274import randomimport numpy as npimport torchimport torch.utils.data
import commonsfrom utils import load_wav_to_torch, load_filepaths_and_textfrom text import text_to_sequence
class TextMelLoader(torch.utils.data.Dataset): """ 1) loads audio,text pairs 2) normalizes text and converts them to sequences of one-hot vectors 3) computes mel-spectrograms from audio files. """
def __init__(self, audiopaths_and_text, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.text_cleaners self.max_wav_value = hparams.max_wav_value self.sampling_rate = hparams.sampling_rate self.load_mel_from_disk = hparams.load_mel_from_disk self.add_noise = hparams.add_noise self.symbols = hparams.punc + hparams.chars self.add_blank = getattr(hparams, "add_blank", False) # improved version self.stft = commons.TacotronSTFT( hparams.filter_length, hparams.hop_length, hparams.win_length, hparams.n_mel_channels, hparams.sampling_rate, hparams.mel_fmin, hparams.mel_fmax, ) random.seed(1234) random.shuffle(self.audiopaths_and_text)
def get_mel_text_pair(self, audiopath_and_text): # separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] text = self.get_text(text) mel = self.get_mel(audiopath) return (text, mel)
def get_mel(self, filename): if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError( "{} {} SR doesn't match target {} SR".format( sampling_rate, self.stft.sampling_rate ) ) if self.add_noise: audio = audio + torch.rand_like(audio) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert ( melspec.size(0) == self.stft.n_mel_channels ), "Mel dimension mismatch: given {}, expected {}".format( melspec.size(0), self.stft.n_mel_channels )
return melspec
def get_text(self, text): text_norm = text_to_sequence(text, self.symbols, self.text_cleaners) if self.add_blank: text_norm = commons.intersperse( text_norm, len(self.symbols) ) # add a blank token, whose id number is len(symbols) text_norm = torch.IntTensor(text_norm) return text_norm
def __getitem__(self, index): return self.get_mel_text_pair(self.audiopaths_and_text[index])
def __len__(self): return len(self.audiopaths_and_text)
class TextMelCollate: """Zero-pads model inputs and targets based on number of frames per step"""
def __init__(self, n_frames_per_step=1): self.n_frames_per_step = n_frames_per_step
def __call__(self, batch): """Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] """ # Right zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True ) max_input_len = input_lengths[0]
text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, : text.size(0)] = text
# Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += ( self.n_frames_per_step - max_target_len % self.n_frames_per_step ) assert max_target_len % self.n_frames_per_step == 0
# include mel padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() output_lengths = torch.LongTensor(len(batch)) for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, : mel.size(1)] = mel output_lengths[i] = mel.size(1)
return text_padded, input_lengths, mel_padded, output_lengths
"""Multi speaker version"""
class TextMelSpeakerLoader(torch.utils.data.Dataset): """ 1) loads audio, speaker_id, text pairs 2) normalizes text and converts them to sequences of one-hot vectors 3) computes mel-spectrograms from audio files. """
def __init__(self, audiopaths_sid_text, hparams): self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text) self.text_cleaners = hparams.text_cleaners self.max_wav_value = hparams.max_wav_value self.sampling_rate = hparams.sampling_rate self.load_mel_from_disk = hparams.load_mel_from_disk self.add_noise = hparams.add_noise self.symbols = hparams.punc + hparams.chars self.add_blank = getattr(hparams, "add_blank", False) # improved version self.min_text_len = getattr(hparams, "min_text_len", 1) self.max_text_len = getattr(hparams, "max_text_len", 190) self.stft = commons.TacotronSTFT( hparams.filter_length, hparams.hop_length, hparams.win_length, hparams.n_mel_channels, hparams.sampling_rate, hparams.mel_fmin, hparams.mel_fmax, )
self._filter_text_len() random.seed(1234) random.shuffle(self.audiopaths_sid_text)
def _filter_text_len(self): audiopaths_sid_text_new = [] for audiopath, sid, text in self.audiopaths_sid_text: if self.min_text_len <= len(text) and len(text) <= self.max_text_len: audiopaths_sid_text_new.append([audiopath, sid, text]) self.audiopaths_sid_text = audiopaths_sid_text_new
def get_mel_text_speaker_pair(self, audiopath_sid_text): # separate filename, speaker_id and text audiopath, sid, text = ( audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2], ) text = self.get_text(text) mel = self.get_mel(audiopath) sid = self.get_sid(sid) return (text, mel, sid)
def get_mel(self, filename): if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError( "{} {} SR doesn't match target {} SR".format( sampling_rate, self.stft.sampling_rate ) ) if self.add_noise: audio = audio + torch.rand_like(audio) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert ( melspec.size(0) == self.stft.n_mel_channels ), "Mel dimension mismatch: given {}, expected {}".format( melspec.size(0), self.stft.n_mel_channels )
return melspec
def get_text(self, text): text_norm = text_to_sequence(text, self.symbols, self.text_cleaners) if self.add_blank: text_norm = commons.intersperse( text_norm, len(self.symbols) ) # add a blank token, whose id number is len(symbols) text_norm = torch.IntTensor(text_norm) return text_norm
def get_sid(self, sid): sid = torch.IntTensor([int(sid)]) return sid
def __getitem__(self, index): return self.get_mel_text_speaker_pair(self.audiopaths_sid_text[index])
def __len__(self): return len(self.audiopaths_sid_text)
class TextMelSpeakerCollate: """Zero-pads model inputs and targets based on number of frames per step"""
def __init__(self, n_frames_per_step=1): self.n_frames_per_step = n_frames_per_step
def __call__(self, batch): """Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] """ # Right zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True ) max_input_len = input_lengths[0]
text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, : text.size(0)] = text
# Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += ( self.n_frames_per_step - max_target_len % self.n_frames_per_step ) assert max_target_len % self.n_frames_per_step == 0
# include mel padded & sid mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() output_lengths = torch.LongTensor(len(batch)) sid = torch.LongTensor(len(batch)) for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, : mel.size(1)] = mel output_lengths[i] = mel.size(1) sid[i] = batch[ids_sorted_decreasing[i]][2]
return text_padded, input_lengths, mel_padded, output_lengths, sid12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import numpy as npimport osimport torchimport commons
import modelsimport utilsfrom argparse import ArgumentParserfrom tqdm import tqdmfrom text import text_to_sequence
if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("-m", "--model_dir", required=True, type=str) parser.add_argument("-s", "--mels_dir", required=True, type=str) args = parser.parse_args() MODEL_DIR = args.model_dir # path to model dir SAVE_MELS_DIR = args.mels_dir # path to save generated mels
if not os.path.exists(SAVE_MELS_DIR): os.makedirs(SAVE_MELS_DIR)
hps = utils.get_hparams_from_dir(MODEL_DIR) symbols = list(hps.data.punc) + list(hps.data.chars) checkpoint_path = utils.latest_checkpoint_path(MODEL_DIR) cleaner = hps.data.text_cleaners
model = models.FlowGenerator( len(symbols) + getattr(hps.data, "add_blank", False), out_channels=hps.data.n_mel_channels, **hps.model ).to("cuda")
utils.load_checkpoint(checkpoint_path, model) model.decoder.store_inverse() # do not calcuate jacobians for fast decoding _ = model.eval()
def get_mel(text, fpath): if getattr(hps.data, "add_blank", False): text_norm = text_to_sequence(text, symbols, cleaner) text_norm = commons.intersperse(text_norm, len(symbols)) else: # If not using "add_blank" option during training, adding spaces at the beginning and the end of utterance improves quality text = " " + text.strip() + " " text_norm = text_to_sequence(text, symbols, cleaner)
sequence = np.array(text_norm)[None, :]
x_tst = torch.autograd.Variable(torch.from_numpy(sequence)).cuda().long() x_tst_lengths = torch.tensor([x_tst.shape[1]]).cuda()
with torch.no_grad(): noise_scale = 0.667 length_scale = 1.0 (y_gen_tst, *_), *_, (attn_gen, *_) = model( x_tst, x_tst_lengths, gen=True, noise_scale=noise_scale, length_scale=length_scale, )
np.save(os.path.join(SAVE_MELS_DIR, fpath), y_gen_tst.cpu().detach().numpy())
for f in [hps.data.training_files, hps.data.validation_files]: file_lines = open(f).read().splitlines()
for line in tqdm(file_lines): fname, text = line.split("|") fname = os.path.basename(fname).replace(".wav", ".npy") get_mel(text, fname)12345from .env import AttrDictfrom .models import Generator
if __name__ == "__main__": pass123456789101112131415import osimport shutil
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
def build_env(config, config_name, path): t_path = os.path.join(path, config_name) if config != t_path: os.makedirs(path, exist_ok=True) shutil.copyfile(config, os.path.join(path, config_name))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403import torchimport torch.nn.functional as Fimport torch.nn as nnfrom torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2dfrom torch.nn.utils import weight_norm, remove_weight_norm, spectral_normfrom .utils import init_weights, get_padding
LRELU_SLOPE = 0.1
class ResBlock1(torch.nn.Module): def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)): super(ResBlock1, self).__init__() self.h = h self.convs1 = nn.ModuleList( [ weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=dilation[0], padding=get_padding(kernel_size, dilation[0]), ) ), weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=dilation[1], padding=get_padding(kernel_size, dilation[1]), ) ), weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=dilation[2], padding=get_padding(kernel_size, dilation[2]), ) ), ] ) self.convs1.apply(init_weights)
self.convs2 = nn.ModuleList( [ weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1), ) ), weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1), ) ), weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1), ) ), ] ) self.convs2.apply(init_weights)
def forward(self, x): for c1, c2 in zip(self.convs1, self.convs2): xt = F.leaky_relu(x, LRELU_SLOPE) xt = c1(xt) xt = F.leaky_relu(xt, LRELU_SLOPE) xt = c2(xt) x = xt + x return x
def remove_weight_norm(self): for l in self.convs1: remove_weight_norm(l) for l in self.convs2: remove_weight_norm(l)
class ResBlock2(torch.nn.Module): def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)): super(ResBlock2, self).__init__() self.h = h self.convs = nn.ModuleList( [ weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=dilation[0], padding=get_padding(kernel_size, dilation[0]), ) ), weight_norm( Conv1d( channels, channels, kernel_size, 1, dilation=dilation[1], padding=get_padding(kernel_size, dilation[1]), ) ), ] ) self.convs.apply(init_weights)
def forward(self, x): for c in self.convs: xt = F.leaky_relu(x, LRELU_SLOPE) xt = c(xt) x = xt + x return x
def remove_weight_norm(self): for l in self.convs: remove_weight_norm(l)
class Generator(torch.nn.Module): def __init__(self, h): super(Generator, self).__init__() self.h = h self.num_kernels = len(h.resblock_kernel_sizes) self.num_upsamples = len(h.upsample_rates) self.conv_pre = weight_norm( Conv1d(80, h.upsample_initial_channel, 7, 1, padding=3) ) resblock = ResBlock1 if h.resblock == "1" else ResBlock2
self.ups = nn.ModuleList() for i, (u, k) in enumerate(zip(h.upsample_rates, h.upsample_kernel_sizes)): self.ups.append( weight_norm( ConvTranspose1d( h.upsample_initial_channel // (2 ** i), h.upsample_initial_channel // (2 ** (i + 1)), k, u, padding=(k - u) // 2, ) ) )
self.resblocks = nn.ModuleList() for i in range(len(self.ups)): ch = h.upsample_initial_channel // (2 ** (i + 1)) for j, (k, d) in enumerate( zip(h.resblock_kernel_sizes, h.resblock_dilation_sizes) ): self.resblocks.append(resblock(h, ch, k, d))
self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3)) self.ups.apply(init_weights) self.conv_post.apply(init_weights)
def forward(self, x): x = self.conv_pre(x) for i in range(self.num_upsamples): x = F.leaky_relu(x, LRELU_SLOPE) x = self.ups[i](x) xs = None for j in range(self.num_kernels): if xs is None: xs = self.resblocks[i * self.num_kernels + j](x) else: xs += self.resblocks[i * self.num_kernels + j](x) x = xs / self.num_kernels x = F.leaky_relu(x) x = self.conv_post(x) x = torch.tanh(x)
return x
def remove_weight_norm(self): print("Removing weight norm...") for l in self.ups: remove_weight_norm(l) for l in self.resblocks: l.remove_weight_norm() remove_weight_norm(self.conv_pre) remove_weight_norm(self.conv_post)
class DiscriminatorP(torch.nn.Module): def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): super(DiscriminatorP, self).__init__() self.period = period norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList( [ norm_f( Conv2d( 1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0), ) ), norm_f( Conv2d( 32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0), ) ), norm_f( Conv2d( 128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0), ) ), norm_f( Conv2d( 512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0), ) ), norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))), ] ) self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
def forward(self, x): fmap = []
# 1d to 2d b, c, t = x.shape if t % self.period != 0: # pad first n_pad = self.period - (t % self.period) x = F.pad(x, (0, n_pad), "reflect") t = t + n_pad x = x.view(b, c, t // self.period, self.period)
for l in self.convs: x = l(x) x = F.leaky_relu(x, LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1)
return x, fmap
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self): super(MultiPeriodDiscriminator, self).__init__() self.discriminators = nn.ModuleList( [ DiscriminatorP(2), DiscriminatorP(3), DiscriminatorP(5), DiscriminatorP(7), DiscriminatorP(11), ] )
def forward(self, y, y_hat): y_d_rs = [] y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) y_d_rs.append(y_d_r) fmap_rs.append(fmap_r) y_d_gs.append(y_d_g) fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
class DiscriminatorS(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(DiscriminatorS, self).__init__() norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList( [ norm_f(Conv1d(1, 128, 15, 1, padding=7)), norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)), norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)), norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)), norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)), norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)), norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), ] ) self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
def forward(self, x): fmap = [] for l in self.convs: x = l(x) x = F.leaky_relu(x, LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1)
return x, fmap
class MultiScaleDiscriminator(torch.nn.Module): def __init__(self): super(MultiScaleDiscriminator, self).__init__() self.discriminators = nn.ModuleList( [ DiscriminatorS(use_spectral_norm=True), DiscriminatorS(), DiscriminatorS(), ] ) self.meanpools = nn.ModuleList( [AvgPool1d(4, 2, padding=2), AvgPool1d(4, 2, padding=2)] )
def forward(self, y, y_hat): y_d_rs = [] y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): if i != 0: y = self.meanpools[i - 1](y) y_hat = self.meanpools[i - 1](y_hat) y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) y_d_rs.append(y_d_r) fmap_rs.append(fmap_r) y_d_gs.append(y_d_g) fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
def feature_loss(fmap_r, fmap_g): loss = 0 for dr, dg in zip(fmap_r, fmap_g): for rl, gl in zip(dr, dg): loss += torch.mean(torch.abs(rl - gl))
return loss * 2
def discriminator_loss(disc_real_outputs, disc_generated_outputs): loss = 0 r_losses = [] g_losses = [] for dr, dg in zip(disc_real_outputs, disc_generated_outputs): r_loss = torch.mean((1 - dr) ** 2) g_loss = torch.mean(dg ** 2) loss += r_loss + g_loss r_losses.append(r_loss.item()) g_losses.append(g_loss.item())
return loss, r_losses, g_losses
def generator_loss(disc_outputs): loss = 0 gen_losses = [] for dg in disc_outputs: l = torch.mean((1 - dg) ** 2) gen_losses.append(l) loss += l
return loss, gen_losses123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import globimport osimport matplotlibimport torchfrom torch.nn.utils import weight_norm
matplotlib.use("Agg")import matplotlib.pylab as plt
def plot_spectrogram(spectrogram): fig, ax = plt.subplots(figsize=(10, 2)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none") plt.colorbar(im, ax=ax)
fig.canvas.draw() plt.close()
return fig
def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std)
def apply_weight_norm(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: weight_norm(m)
def get_padding(kernel_size, dilation=1): return int((kernel_size * dilation - dilation) / 2)
def load_checkpoint(filepath, device): assert os.path.isfile(filepath) print("Loading '{}'".format(filepath)) checkpoint_dict = torch.load(filepath, map_location=device) print("Complete.") return checkpoint_dict
def save_checkpoint(filepath, obj): print("Saving checkpoint to {}".format(filepath)) torch.save(obj, filepath) print("Complete.")
def scan_checkpoint(cp_dir, prefix): pattern = os.path.join(cp_dir, prefix + "????????") cp_list = glob.glob(pattern) if len(cp_list) == 0: return None return sorted(cp_list)[-1]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import osimport jsonimport argparseimport mathimport torchfrom torch import nn, optimfrom torch.nn import functional as Ffrom torch.utils.data import DataLoader
from data_utils import TextMelLoader, TextMelCollateimport modelsimport commonsimport utils
class FlowGenerator_DDI(models.FlowGenerator): """A helper for Data-dependent Initialization"""
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for f in self.decoder.flows: if getattr(f, "set_ddi", False): f.set_ddi(True)
def main(): hps = utils.get_hparams() logger = utils.get_logger(hps.log_dir) logger.info(hps) utils.check_git_hash(hps.log_dir)
torch.manual_seed(hps.train.seed)
train_dataset = TextMelLoader(hps.data.training_files, hps.data) collate_fn = TextMelCollate(1) train_loader = DataLoader( train_dataset, num_workers=8, shuffle=True, batch_size=hps.train.batch_size, pin_memory=True, drop_last=True, collate_fn=collate_fn, ) symbols = hps.data.punc + hps.data.chars generator = FlowGenerator_DDI( len(symbols) + getattr(hps.data, "add_blank", False), out_channels=hps.data.n_mel_channels, **hps.model ).cuda() optimizer_g = commons.Adam( generator.parameters(), scheduler=hps.train.scheduler, dim_model=hps.model.hidden_channels, warmup_steps=hps.train.warmup_steps, lr=hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, )
generator.train() for batch_idx, (x, x_lengths, y, y_lengths) in enumerate(train_loader): x, x_lengths = x.cuda(), x_lengths.cuda() y, y_lengths = y.cuda(), y_lengths.cuda()
_ = generator(x, x_lengths, y, y_lengths, gen=False) break
utils.save_checkpoint( generator, optimizer_g, hps.train.learning_rate, 0, os.path.join(hps.model_dir, "ddi_G.pth"), )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403import mathimport torchfrom torch import nnfrom torch.nn import functional as F
import modulesimport commonsimport attentionsimport monotonic_align
class DurationPredictor(nn.Module): def __init__(self, in_channels, filter_channels, kernel_size, p_dropout): super().__init__()
self.in_channels = in_channels self.filter_channels = filter_channels self.kernel_size = kernel_size self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout) self.conv_1 = nn.Conv1d( in_channels, filter_channels, kernel_size, padding=kernel_size // 2 ) self.norm_1 = attentions.LayerNorm(filter_channels) self.conv_2 = nn.Conv1d( filter_channels, filter_channels, kernel_size, padding=kernel_size // 2 ) self.norm_2 = attentions.LayerNorm(filter_channels) self.proj = nn.Conv1d(filter_channels, 1, 1)
def forward(self, x, x_mask): x = self.conv_1(x * x_mask) x = torch.relu(x) x = self.norm_1(x) x = self.drop(x) x = self.conv_2(x * x_mask) x = torch.relu(x) x = self.norm_2(x) x = self.drop(x) x = self.proj(x * x_mask) return x * x_mask
class TextEncoder(nn.Module): def __init__( self, n_vocab, out_channels, hidden_channels, filter_channels, filter_channels_dp, n_heads, n_layers, kernel_size, p_dropout, window_size=None, block_length=None, mean_only=False, prenet=False, gin_channels=0, ):
super().__init__()
self.n_vocab = n_vocab self.out_channels = out_channels self.hidden_channels = hidden_channels self.filter_channels = filter_channels self.filter_channels_dp = filter_channels_dp self.n_heads = n_heads self.n_layers = n_layers self.kernel_size = kernel_size self.p_dropout = p_dropout self.window_size = window_size self.block_length = block_length self.mean_only = mean_only self.prenet = prenet self.gin_channels = gin_channels
self.emb = nn.Embedding(n_vocab, hidden_channels) nn.init.normal_(self.emb.weight, 0.0, hidden_channels ** -0.5)
if prenet: self.pre = modules.ConvReluNorm( hidden_channels, hidden_channels, hidden_channels, kernel_size=5, n_layers=3, p_dropout=0.5, ) self.encoder = attentions.Encoder( hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, window_size=window_size, block_length=block_length, )
self.proj_m = nn.Conv1d(hidden_channels, out_channels, 1) if not mean_only: self.proj_s = nn.Conv1d(hidden_channels, out_channels, 1) self.proj_w = DurationPredictor( hidden_channels + gin_channels, filter_channels_dp, kernel_size, p_dropout )
def forward(self, x, x_lengths, g=None): x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h] x = torch.transpose(x, 1, -1) # [b, h, t] x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( x.dtype )
if self.prenet: x = self.pre(x, x_mask) x = self.encoder(x, x_mask)
if g is not None: g_exp = g.expand(-1, -1, x.size(-1)) x_dp = torch.cat([torch.detach(x), g_exp], 1) else: x_dp = torch.detach(x)
x_m = self.proj_m(x) * x_mask if not self.mean_only: x_logs = self.proj_s(x) * x_mask else: x_logs = torch.zeros_like(x_m)
logw = self.proj_w(x_dp, x_mask) return x_m, x_logs, logw, x_mask
class FlowSpecDecoder(nn.Module): def __init__( self, in_channels, hidden_channels, kernel_size, dilation_rate, n_blocks, n_layers, p_dropout=0.0, n_split=4, n_sqz=2, sigmoid_scale=False, gin_channels=0, ): super().__init__()
self.in_channels = in_channels self.hidden_channels = hidden_channels self.kernel_size = kernel_size self.dilation_rate = dilation_rate self.n_blocks = n_blocks self.n_layers = n_layers self.p_dropout = p_dropout self.n_split = n_split self.n_sqz = n_sqz self.sigmoid_scale = sigmoid_scale self.gin_channels = gin_channels
self.flows = nn.ModuleList() for b in range(n_blocks): self.flows.append(modules.ActNorm(channels=in_channels * n_sqz)) self.flows.append( modules.InvConvNear(channels=in_channels * n_sqz, n_split=n_split) ) self.flows.append( attentions.CouplingBlock( in_channels * n_sqz, hidden_channels, kernel_size=kernel_size, dilation_rate=dilation_rate, n_layers=n_layers, gin_channels=gin_channels, p_dropout=p_dropout, sigmoid_scale=sigmoid_scale, ) )
def forward(self, x, x_mask, g=None, reverse=False): if not reverse: flows = self.flows logdet_tot = 0 else: flows = reversed(self.flows) logdet_tot = None
if self.n_sqz > 1: x, x_mask = commons.squeeze(x, x_mask, self.n_sqz) for f in flows: if not reverse: x, logdet = f(x, x_mask, g=g, reverse=reverse) logdet_tot += logdet else: x, logdet = f(x, x_mask, g=g, reverse=reverse) if self.n_sqz > 1: x, x_mask = commons.unsqueeze(x, x_mask, self.n_sqz) return x, logdet_tot
def store_inverse(self): for f in self.flows: f.store_inverse()
class FlowGenerator(nn.Module): def __init__( self, n_vocab, hidden_channels, filter_channels, filter_channels_dp, out_channels, kernel_size=3, n_heads=2, n_layers_enc=6, p_dropout=0.0, n_blocks_dec=12, kernel_size_dec=5, dilation_rate=5, n_block_layers=4, p_dropout_dec=0.0, n_speakers=0, gin_channels=0, n_split=4, n_sqz=1, sigmoid_scale=False, window_size=None, block_length=None, mean_only=False, hidden_channels_enc=None, hidden_channels_dec=None, prenet=False, **kwargs ):
super().__init__() self.n_vocab = n_vocab self.hidden_channels = hidden_channels self.filter_channels = filter_channels self.filter_channels_dp = filter_channels_dp self.out_channels = out_channels self.kernel_size = kernel_size self.n_heads = n_heads self.n_layers_enc = n_layers_enc self.p_dropout = p_dropout self.n_blocks_dec = n_blocks_dec self.kernel_size_dec = kernel_size_dec self.dilation_rate = dilation_rate self.n_block_layers = n_block_layers self.p_dropout_dec = p_dropout_dec self.n_speakers = n_speakers self.gin_channels = gin_channels self.n_split = n_split self.n_sqz = n_sqz self.sigmoid_scale = sigmoid_scale self.window_size = window_size self.block_length = block_length self.mean_only = mean_only self.hidden_channels_enc = hidden_channels_enc self.hidden_channels_dec = hidden_channels_dec self.prenet = prenet
self.encoder = TextEncoder( n_vocab, out_channels, hidden_channels_enc or hidden_channels, filter_channels, filter_channels_dp, n_heads, n_layers_enc, kernel_size, p_dropout, window_size=window_size, block_length=block_length, mean_only=mean_only, prenet=prenet, gin_channels=gin_channels, )
self.decoder = FlowSpecDecoder( out_channels, hidden_channels_dec or hidden_channels, kernel_size_dec, dilation_rate, n_blocks_dec, n_block_layers, p_dropout=p_dropout_dec, n_split=n_split, n_sqz=n_sqz, sigmoid_scale=sigmoid_scale, gin_channels=gin_channels, )
if n_speakers > 1: self.emb_g = nn.Embedding(n_speakers, gin_channels) nn.init.uniform_(self.emb_g.weight, -0.1, 0.1)
def forward( self, x, x_lengths, y=None, y_lengths=None, g=None, gen=False, noise_scale=1.0, length_scale=1.0, ): if g is not None: g = F.normalize(self.emb_g(g)).unsqueeze(-1) # [b, h] x_m, x_logs, logw, x_mask = self.encoder(x, x_lengths, g=g)
if gen: w = torch.exp(logw) * x_mask * length_scale w_ceil = torch.ceil(w) y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long() y_max_length = None else: y_max_length = y.size(2) y, y_lengths, y_max_length = self.preprocess(y, y_lengths, y_max_length) z_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, y_max_length), 1).to( x_mask.dtype ) attn_mask = torch.unsqueeze(x_mask, -1) * torch.unsqueeze(z_mask, 2)
if gen: attn = commons.generate_path( w_ceil.squeeze(1), attn_mask.squeeze(1) ).unsqueeze(1) z_m = torch.matmul( attn.squeeze(1).transpose(1, 2), x_m.transpose(1, 2) ).transpose( 1, 2 ) # [b, t', t], [b, t, d] -> [b, d, t'] z_logs = torch.matmul( attn.squeeze(1).transpose(1, 2), x_logs.transpose(1, 2) ).transpose( 1, 2 ) # [b, t', t], [b, t, d] -> [b, d, t'] logw_ = torch.log(1e-8 + torch.sum(attn, -1)) * x_mask
z = (z_m + torch.exp(z_logs) * torch.randn_like(z_m) * noise_scale) * z_mask y, logdet = self.decoder(z, z_mask, g=g, reverse=True) return ( (y, z_m, z_logs, logdet, z_mask), (x_m, x_logs, x_mask), (attn, logw, logw_), ) else: z, logdet = self.decoder(y, z_mask, g=g, reverse=False) with torch.no_grad(): x_s_sq_r = torch.exp(-2 * x_logs) logp1 = torch.sum(-0.5 * math.log(2 * math.pi) - x_logs, [1]).unsqueeze( -1 ) # [b, t, 1] logp2 = torch.matmul( x_s_sq_r.transpose(1, 2), -0.5 * (z ** 2) ) # [b, t, d] x [b, d, t'] = [b, t, t'] logp3 = torch.matmul( (x_m * x_s_sq_r).transpose(1, 2), z ) # [b, t, d] x [b, d, t'] = [b, t, t'] logp4 = torch.sum(-0.5 * (x_m ** 2) * x_s_sq_r, [1]).unsqueeze( -1 ) # [b, t, 1] logp = logp1 + logp2 + logp3 + logp4 # [b, t, t']
attn = ( monotonic_align.maximum_path(logp, attn_mask.squeeze(1)) .unsqueeze(1) .detach() ) z_m = torch.matmul( attn.squeeze(1).transpose(1, 2), x_m.transpose(1, 2) ).transpose( 1, 2 ) # [b, t', t], [b, t, d] -> [b, d, t'] z_logs = torch.matmul( attn.squeeze(1).transpose(1, 2), x_logs.transpose(1, 2) ).transpose( 1, 2 ) # [b, t', t], [b, t, d] -> [b, d, t'] logw_ = torch.log(1e-8 + torch.sum(attn, -1)) * x_mask return ( (z, z_m, z_logs, logdet, z_mask), (x_m, x_logs, x_mask), (attn, logw, logw_), )
def preprocess(self, y, y_lengths, y_max_length): if y_max_length is not None: y_max_length = (y_max_length // self.n_sqz) * self.n_sqz y = y[:, :, :y_max_length] y_lengths = (y_lengths // self.n_sqz) * self.n_sqz return y, y_lengths, y_max_length
def store_inverse(self): self.decoder.store_inverse()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276import copyimport mathimport numpy as npimport scipyimport torchfrom torch import nnfrom torch.nn import functional as F
import commons
class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-4): super().__init__() self.channels = channels self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels)) self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x): n_dims = len(x.shape) mean = torch.mean(x, 1, keepdim=True) variance = torch.mean((x - mean) ** 2, 1, keepdim=True)
x = (x - mean) * torch.rsqrt(variance + self.eps)
shape = [1, -1] + [1] * (n_dims - 2) x = x * self.gamma.view(*shape) + self.beta.view(*shape) return x
class ConvReluNorm(nn.Module): def __init__( self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout, ): super().__init__() self.in_channels = in_channels self.hidden_channels = hidden_channels self.out_channels = out_channels self.kernel_size = kernel_size self.n_layers = n_layers self.p_dropout = p_dropout assert n_layers > 1, "Number of layers should be larger than 0."
self.conv_layers = nn.ModuleList() self.norm_layers = nn.ModuleList() self.conv_layers.append( nn.Conv1d( in_channels, hidden_channels, kernel_size, padding=kernel_size // 2 ) ) self.norm_layers.append(LayerNorm(hidden_channels)) self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout)) for _ in range(n_layers - 1): self.conv_layers.append( nn.Conv1d( hidden_channels, hidden_channels, kernel_size, padding=kernel_size // 2, ) ) self.norm_layers.append(LayerNorm(hidden_channels)) self.proj = nn.Conv1d(hidden_channels, out_channels, 1) self.proj.weight.data.zero_() self.proj.bias.data.zero_()
def forward(self, x, x_mask): x_org = x for i in range(self.n_layers): x = self.conv_layers[i](x * x_mask) x = self.norm_layers[i](x) x = self.relu_drop(x) x = x_org + self.proj(x) return x * x_mask
class WN(torch.nn.Module): def __init__( self, in_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0, ): super(WN, self).__init__() assert kernel_size % 2 == 1 assert hidden_channels % 2 == 0 self.in_channels = in_channels self.hidden_channels = hidden_channels self.kernel_size = (kernel_size,) self.dilation_rate = dilation_rate self.n_layers = n_layers self.gin_channels = gin_channels self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList() self.res_skip_layers = torch.nn.ModuleList() self.drop = nn.Dropout(p_dropout)
if gin_channels != 0: cond_layer = torch.nn.Conv1d( gin_channels, 2 * hidden_channels * n_layers, 1 ) self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
for i in range(n_layers): dilation = dilation_rate ** i padding = int((kernel_size * dilation - dilation) / 2) in_layer = torch.nn.Conv1d( hidden_channels, 2 * hidden_channels, kernel_size, dilation=dilation, padding=padding, ) in_layer = torch.nn.utils.weight_norm(in_layer, name="weight") self.in_layers.append(in_layer)
# last one is not necessary if i < n_layers - 1: res_skip_channels = 2 * hidden_channels else: res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1) res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight") self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask=None, g=None, **kwargs): output = torch.zeros_like(x) n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None: g = self.cond_layer(g)
for i in range(self.n_layers): x_in = self.in_layers[i](x) x_in = self.drop(x_in) if g is not None: cond_offset = i * 2 * self.hidden_channels g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :] else: g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
res_skip_acts = self.res_skip_layers[i](acts) if i < self.n_layers - 1: x = (x + res_skip_acts[:, : self.hidden_channels, :]) * x_mask output = output + res_skip_acts[:, self.hidden_channels :, :] else: output = output + res_skip_acts return output * x_mask
def remove_weight_norm(self): if self.gin_channels != 0: torch.nn.utils.remove_weight_norm(self.cond_layer) for l in self.in_layers: torch.nn.utils.remove_weight_norm(l) for l in self.res_skip_layers: torch.nn.utils.remove_weight_norm(l)
class ActNorm(nn.Module): def __init__(self, channels, ddi=False, **kwargs): super().__init__() self.channels = channels self.initialized = not ddi
self.logs = nn.Parameter(torch.zeros(1, channels, 1)) self.bias = nn.Parameter(torch.zeros(1, channels, 1))
def forward(self, x, x_mask=None, reverse=False, **kwargs): if x_mask is None: x_mask = torch.ones(x.size(0), 1, x.size(2)).to( device=x.device, dtype=x.dtype ) x_len = torch.sum(x_mask, [1, 2]) if not self.initialized: self.initialize(x, x_mask) self.initialized = True
if reverse: z = (x - self.bias) * torch.exp(-self.logs) * x_mask logdet = None else: z = (self.bias + torch.exp(self.logs) * x) * x_mask logdet = torch.sum(self.logs) * x_len # [b]
return z, logdet
def store_inverse(self): pass
def set_ddi(self, ddi): self.initialized = not ddi
def initialize(self, x, x_mask): with torch.no_grad(): denom = torch.sum(x_mask, [0, 2]) m = torch.sum(x * x_mask, [0, 2]) / denom m_sq = torch.sum(x * x * x_mask, [0, 2]) / denom v = m_sq - (m ** 2) logs = 0.5 * torch.log(torch.clamp_min(v, 1e-6))
bias_init = ( (-m * torch.exp(-logs)).view(*self.bias.shape).to(dtype=self.bias.dtype) ) logs_init = (-logs).view(*self.logs.shape).to(dtype=self.logs.dtype)
self.bias.data.copy_(bias_init) self.logs.data.copy_(logs_init)
class InvConvNear(nn.Module): def __init__(self, channels, n_split=4, no_jacobian=False, **kwargs): super().__init__() assert n_split % 2 == 0 self.channels = channels self.n_split = n_split self.no_jacobian = no_jacobian
w_init = torch.qr(torch.FloatTensor(self.n_split, self.n_split).normal_())[0] if torch.det(w_init) < 0: w_init[:, 0] = -1 * w_init[:, 0] self.weight = nn.Parameter(w_init)
def forward(self, x, x_mask=None, reverse=False, **kwargs): b, c, t = x.size() assert c % self.n_split == 0 if x_mask is None: x_mask = 1 x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t else: x_len = torch.sum(x_mask, [1, 2])
x = x.view(b, 2, c // self.n_split, self.n_split // 2, t) x = ( x.permute(0, 1, 3, 2, 4) .contiguous() .view(b, self.n_split, c // self.n_split, t) )
if reverse: if hasattr(self, "weight_inv"): weight = self.weight_inv else: weight = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype) logdet = None else: weight = self.weight if self.no_jacobian: logdet = 0 else: logdet = torch.logdet(self.weight) * (c / self.n_split) * x_len # [b]
weight = weight.view(self.n_split, self.n_split, 1, 1) z = F.conv2d(x, weight)
z = z.view(b, 2, self.n_split // 2, c // self.n_split, t) z = z.permute(0, 1, 3, 2, 4).contiguous().view(b, c, t) * x_mask return z, logdet
def store_inverse(self): self.weight_inv = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)12345import pkg_resources
__version__ = pkg_resources.get_distribution("monotonic_align").version
from monotonic_align.mas import *123456789101112131415161718192021222324252627282930313233343536373839404142434445import numpy as npcimport numpy as npcimport cythonfrom cython.parallel import prange
@cython.boundscheck(False)@cython.wraparound(False)cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_x, int t_y, float max_neg_val) nogil: cdef int x cdef int y cdef float v_prev cdef float v_cur cdef float tmp cdef int index = t_x - 1
for y in range(t_y): for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): if x == y: v_cur = max_neg_val else: v_cur = value[x, y-1] if x == 0: if y == 0: v_prev = 0. else: v_prev = max_neg_val else: v_prev = value[x-1, y-1] value[x, y] = max(v_cur, v_prev) + value[x, y]
for y in range(t_y - 1, -1, -1): path[index, y] = 1 if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): index = index - 1
@cython.boundscheck(False)@cython.wraparound(False)cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: cdef int b = values.shape[0]
cdef int i for i in prange(b, nogil=True): maximum_path_each(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657from typing import overloadimport numpy as npimport torchfrom monotonic_align.core import maximum_path_c
def mask_from_len(lens: torch.Tensor, max_len=None): """ Make a `mask` from lens.
:param inputs: (B, T, D) :param lens: (B)
:return: `mask`: (B, T) """ if max_len is None: max_len = lens.max() index = torch.arange(max_len).to(lens).view(1, -1) return index < lens.unsqueeze(1) # (B, T)
def mask_from_lens( similarity: torch.Tensor, symbol_lens: torch.Tensor, mel_lens: torch.Tensor,): """ :param similarity: (B, S, T) :param symbol_lens: (B,) :param mel_lens: (B,) """ _, S, T = similarity.size() mask_S = mask_from_len(symbol_lens, S) mask_T = mask_from_len(mel_lens, T) mask_ST = mask_S.unsqueeze(2) * mask_T.unsqueeze(1) return mask_ST.to(similarity)
def maximum_path(value, mask=None): """Cython optimised version. value: [b, t_x, t_y] mask: [b, t_x, t_y] """ if mask is None: mask = torch.zeros_like(value)
value = value * mask device = value.device dtype = value.dtype value = value.data.cpu().numpy().astype(np.float32) path = np.zeros_like(value).astype(np.int32) mask = mask.data.cpu().numpy() t_x_max = mask.sum(1)[:, 0].astype(np.int32) t_y_max = mask.sum(2)[:, 0].astype(np.int32) maximum_path_c(path, value, t_x_max, t_y_max) return torch.from_numpy(path).to(device=device, dtype=dtype)1234567[build-system]requires = [ "wheel", "setuptools", "cython>=0.24.0", "numpy<v1.20.0",].gitattributesAdded+28
README.mdAdded+14
app.pyAdded+28
packages.txtAdded+1
requirements.txtAdded+19
ttsv/.gitignoreAdded+132
ttsv/LICENSE.mdAdded+21
ttsv/README.mdAdded+220
ttsv/__init__.pyAdded
ttsv/checkpoints/glow/.gitkeepAdded
ttsv/checkpoints/hifi/.gitkeepAdded
ttsv/config/.gitkeepAdded
ttsv/config/glow/base.jsonAdded+54
ttsv/config/glow/base_blank.jsonAdded+55
ttsv/config/hifi/config_v1.jsonAdded+37
ttsv/config/hifi/config_v2.jsonAdded+37
ttsv/config/hifi/config_v3.jsonAdded+37
ttsv/data/.gitkeepAdded
ttsv/install.shAdded+6
ttsv/logs/glow/.gitkeepAdded
ttsv/logs/hifi/.gitkeepAdded
ttsv/notebooks/vakyansh_tts_demo.ipynbAdded
ttsv/results/api/.gitkeepAdded
ttsv/scripts/data/duration.shAdded+9
ttsv/scripts/data/resample.shAdded+14
ttsv/scripts/glow/prepare_data.shAdded+12
ttsv/scripts/glow/train_glow.shAdded+17
ttsv/scripts/hifi/prepare_data.shAdded+10
ttsv/scripts/hifi/train_hifi.shAdded+21
ttsv/scripts/inference/advanced_infer.shAdded+22
ttsv/scripts/inference/api.shAdded+8
ttsv/scripts/inference/gradio.shAdded+8
ttsv/scripts/inference/infer.shAdded+15
ttsv/setup.pyAdded+55
ttsv/src/glow_tts/attentions.pyAdded+378
ttsv/src/glow_tts/audio_processing.pyAdded+100
ttsv/src/glow_tts/commons.pyAdded+273
ttsv/src/glow_tts/data_utils.pyAdded+274
ttsv/src/glow_tts/generate_mels.pyAdded+70
ttsv/src/glow_tts/hifi/__init__.pyAdded+5
ttsv/src/glow_tts/hifi/env.pyAdded+15
ttsv/src/glow_tts/hifi/models.pyAdded+403
ttsv/src/glow_tts/hifi/utils.pyAdded+57
ttsv/src/glow_tts/init.pyAdded+79
ttsv/src/glow_tts/models.pyAdded+403
ttsv/src/glow_tts/modules.pyAdded+276
ttsv/src/glow_tts/monotonic_align/monotonic_align/__init__.pyAdded+5
ttsv/src/glow_tts/monotonic_align/monotonic_align/core.pyxAdded+45
ttsv/src/glow_tts/monotonic_align/monotonic_align/mas.pyAdded+57
ttsv/src/glow_tts/monotonic_align/pyproject.tomlAdded+7