Commit
·
a92164f
1
Parent(s):
82da400
Update inference.py and meldataset.py
Browse files- Models/del_training.ipynb +0 -62
- Models/{model.pth → inference/model.pth} +0 -0
- inference.py +30 -44
- meldataset.py +307 -0
Models/del_training.ipynb
DELETED
@@ -1,62 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"cells": [
|
3 |
-
{
|
4 |
-
"cell_type": "code",
|
5 |
-
"execution_count": 1,
|
6 |
-
"id": "2b6bb4be",
|
7 |
-
"metadata": {},
|
8 |
-
"outputs": [],
|
9 |
-
"source": [
|
10 |
-
"import os\n",
|
11 |
-
"import torch"
|
12 |
-
]
|
13 |
-
},
|
14 |
-
{
|
15 |
-
"cell_type": "code",
|
16 |
-
"execution_count": null,
|
17 |
-
"id": "dc802b47",
|
18 |
-
"metadata": {},
|
19 |
-
"outputs": [],
|
20 |
-
"source": [
|
21 |
-
"models_path = \"./current_model_120k_vi.pth\"\n",
|
22 |
-
"name = \"./model.pth\"\n",
|
23 |
-
"params_whole = torch.load(models_path, map_location='cpu')\n",
|
24 |
-
"\n",
|
25 |
-
"for key in list(params_whole.keys()):\n",
|
26 |
-
" if key != 'net':\n",
|
27 |
-
" params_whole.pop(key)\n",
|
28 |
-
"\n",
|
29 |
-
"keep = ['decoder', 'predictor', 'text_encoder', 'style_encoder']\n",
|
30 |
-
"for module_name in list(params_whole['net'].keys()):\n",
|
31 |
-
" if module_name not in keep:\n",
|
32 |
-
" params_whole['net'].pop(module_name)\n",
|
33 |
-
"\n",
|
34 |
-
"torch.save(params_whole, name)\n",
|
35 |
-
"\n",
|
36 |
-
"\n",
|
37 |
-
"#os.remove(models_path)"
|
38 |
-
]
|
39 |
-
}
|
40 |
-
],
|
41 |
-
"metadata": {
|
42 |
-
"kernelspec": {
|
43 |
-
"display_name": "base",
|
44 |
-
"language": "python",
|
45 |
-
"name": "python3"
|
46 |
-
},
|
47 |
-
"language_info": {
|
48 |
-
"codemirror_mode": {
|
49 |
-
"name": "ipython",
|
50 |
-
"version": 3
|
51 |
-
},
|
52 |
-
"file_extension": ".py",
|
53 |
-
"mimetype": "text/x-python",
|
54 |
-
"name": "python",
|
55 |
-
"nbconvert_exporter": "python",
|
56 |
-
"pygments_lexer": "ipython3",
|
57 |
-
"version": "3.11.7"
|
58 |
-
}
|
59 |
-
},
|
60 |
-
"nbformat": 4,
|
61 |
-
"nbformat_minor": 5
|
62 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Models/{model.pth → inference/model.pth}
RENAMED
File without changes
|
inference.py
CHANGED
@@ -1,13 +1,10 @@
|
|
1 |
import re
|
2 |
-
import sys
|
3 |
import yaml
|
4 |
from munch import Munch
|
5 |
-
import unicodedata
|
6 |
import numpy as np
|
7 |
import librosa
|
8 |
import noisereduce as nr
|
9 |
-
import
|
10 |
-
|
11 |
import torch
|
12 |
import torchaudio
|
13 |
from nltk.tokenize import word_tokenize
|
@@ -17,6 +14,8 @@ nltk.download('punkt_tab')
|
|
17 |
from models import ProsodyPredictor, TextEncoder, StyleEncoder
|
18 |
from Modules.hifigan import Decoder
|
19 |
|
|
|
|
|
20 |
if sys.platform.startswith("win"):
|
21 |
try:
|
22 |
from phonemizer.backend.espeak.wrapper import EspeakWrapper
|
@@ -32,48 +31,13 @@ def espeak_phn(text, lang):
|
|
32 |
except Exception as e:
|
33 |
print(e)
|
34 |
|
35 |
-
# IPA Phonemizer: https://github.com/bootphon/phonemizer
|
36 |
-
# Total including extend chars 189
|
37 |
-
|
38 |
-
_pad = "$"
|
39 |
-
_punctuation = ';:,.!?¡¿—…"«»“” '
|
40 |
-
_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
41 |
-
_letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
|
42 |
-
_extend = "∫̆ăη͡123456"
|
43 |
-
|
44 |
-
# Export all symbols:
|
45 |
-
symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa) + list(_extend)
|
46 |
-
|
47 |
-
dicts = {}
|
48 |
-
for i in range(len((symbols))):
|
49 |
-
dicts[symbols[i]] = i
|
50 |
-
|
51 |
-
class TextCleaner:
|
52 |
-
def __init__(self, dummy=None):
|
53 |
-
self.word_index_dictionary = dicts
|
54 |
-
#print(len(dicts))
|
55 |
-
def __call__(self, text):
|
56 |
-
indexes = []
|
57 |
-
for char in text:
|
58 |
-
try:
|
59 |
-
indexes.append(self.word_index_dictionary[char])
|
60 |
-
except KeyError as e:
|
61 |
-
#print(char)
|
62 |
-
continue
|
63 |
-
return indexes
|
64 |
-
|
65 |
class Preprocess:
|
66 |
def __text_normalize(self, text):
|
67 |
punctuation = [",", "、", "،", ";", "(", ".", "。", "…", "!", "–", ":", "?"]
|
68 |
map_to = "."
|
69 |
punctuation_pattern = re.compile(f"[{''.join(re.escape(p) for p in punctuation)}]")
|
70 |
-
#ensure consistency.
|
71 |
-
text = unicodedata.normalize('NFKC', text)
|
72 |
#replace punctuation that acts like a comma or period
|
73 |
-
#text = re.sub(r'\.{2,}', '.', text)
|
74 |
text = punctuation_pattern.sub(map_to, text)
|
75 |
-
#remove or replace special chars except . , { } % $ & ' - \ /
|
76 |
-
text = re.sub(r'[^\w\s.,{}%$&\'\-\[\]\/]', ' ', text)
|
77 |
#replace consecutive whitespace chars with a single space and strip leading/trailing spaces
|
78 |
text = re.sub(r'\s+', ' ', text).strip()
|
79 |
return text
|
@@ -102,7 +66,7 @@ class Preprocess:
|
|
102 |
mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std
|
103 |
return mel_tensor
|
104 |
def text_preprocess(self, text, n_merge=12):
|
105 |
-
text_norm = self.__text_normalize(text).
|
106 |
text_norm = [s.strip() for s in text_norm]
|
107 |
text_norm = list(filter(lambda x: x != '', text_norm)) #filter empty index
|
108 |
text_norm = self.__merge_fragments(text_norm, n=n_merge) #merge if a sentence has less that n
|
@@ -118,9 +82,31 @@ class StyleTTS2(torch.nn.Module):
|
|
118 |
super().__init__()
|
119 |
self.register_buffer("get_device", torch.empty(0))
|
120 |
self.preprocess = Preprocess()
|
121 |
-
|
122 |
-
config = yaml.safe_load(open(config_path))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
args = self.__recursive_munch(config['model_params'])
|
|
|
|
|
|
|
124 |
|
125 |
assert args.decoder.type in ['hifigan'], 'Decoder type unknown'
|
126 |
|
@@ -225,7 +211,7 @@ class StyleTTS2(torch.nn.Module):
|
|
225 |
for i in range(jump, total_len, jump):
|
226 |
if i+jump >= total_len:
|
227 |
left_dur = (total_len-i)/sr
|
228 |
-
if left_dur >=
|
229 |
mel_tensor = self.preprocess.wave_preprocess(audio[i:total_len]).to(device)
|
230 |
ref_s += self.style_encoder(mel_tensor.unsqueeze(1))
|
231 |
count += 1
|
@@ -245,7 +231,7 @@ class StyleTTS2(torch.nn.Module):
|
|
245 |
speed = min(max(speed, 0.0001), 2) #speed range [0, 2]
|
246 |
|
247 |
phonem = ' '.join(word_tokenize(phonem))
|
248 |
-
tokens =
|
249 |
tokens.insert(0, 0)
|
250 |
tokens.append(0)
|
251 |
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
|
|
|
1 |
import re
|
|
|
2 |
import yaml
|
3 |
from munch import Munch
|
|
|
4 |
import numpy as np
|
5 |
import librosa
|
6 |
import noisereduce as nr
|
7 |
+
from meldataset import TextCleaner
|
|
|
8 |
import torch
|
9 |
import torchaudio
|
10 |
from nltk.tokenize import word_tokenize
|
|
|
14 |
from models import ProsodyPredictor, TextEncoder, StyleEncoder
|
15 |
from Modules.hifigan import Decoder
|
16 |
|
17 |
+
import sys
|
18 |
+
import phonemizer
|
19 |
if sys.platform.startswith("win"):
|
20 |
try:
|
21 |
from phonemizer.backend.espeak.wrapper import EspeakWrapper
|
|
|
31 |
except Exception as e:
|
32 |
print(e)
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
class Preprocess:
|
35 |
def __text_normalize(self, text):
|
36 |
punctuation = [",", "、", "،", ";", "(", ".", "。", "…", "!", "–", ":", "?"]
|
37 |
map_to = "."
|
38 |
punctuation_pattern = re.compile(f"[{''.join(re.escape(p) for p in punctuation)}]")
|
|
|
|
|
39 |
#replace punctuation that acts like a comma or period
|
|
|
40 |
text = punctuation_pattern.sub(map_to, text)
|
|
|
|
|
41 |
#replace consecutive whitespace chars with a single space and strip leading/trailing spaces
|
42 |
text = re.sub(r'\s+', ' ', text).strip()
|
43 |
return text
|
|
|
66 |
mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std
|
67 |
return mel_tensor
|
68 |
def text_preprocess(self, text, n_merge=12):
|
69 |
+
text_norm = self.__text_normalize(text).split(".")#split by sentences.
|
70 |
text_norm = [s.strip() for s in text_norm]
|
71 |
text_norm = list(filter(lambda x: x != '', text_norm)) #filter empty index
|
72 |
text_norm = self.__merge_fragments(text_norm, n=n_merge) #merge if a sentence has less that n
|
|
|
82 |
super().__init__()
|
83 |
self.register_buffer("get_device", torch.empty(0))
|
84 |
self.preprocess = Preprocess()
|
85 |
+
self.ref_s = None
|
86 |
+
config = yaml.safe_load(open(config_path, "r", encoding="utf-8"))
|
87 |
+
|
88 |
+
try:
|
89 |
+
symbols = (
|
90 |
+
list(config['symbol']['pad']) +
|
91 |
+
list(config['symbol']['punctuation']) +
|
92 |
+
list(config['symbol']['letters']) +
|
93 |
+
list(config['symbol']['letters_ipa']) +
|
94 |
+
list(config['symbol']['extend'])
|
95 |
+
)
|
96 |
+
symbol_dict = {}
|
97 |
+
for i in range(len((symbols))):
|
98 |
+
symbol_dict[symbols[i]] = i
|
99 |
+
|
100 |
+
n_token = len(symbol_dict) + 1
|
101 |
+
print("\nFound:", n_token, "symbols")
|
102 |
+
except Exception as e:
|
103 |
+
print(f"\nERROR: Cannot find {e} in config file!\nYour config file is likely outdated, please download updated version from the repository.")
|
104 |
+
raise SystemExit(1)
|
105 |
+
|
106 |
args = self.__recursive_munch(config['model_params'])
|
107 |
+
args['n_token'] = n_token
|
108 |
+
|
109 |
+
self.cleaner = TextCleaner(symbol_dict, debug=False)
|
110 |
|
111 |
assert args.decoder.type in ['hifigan'], 'Decoder type unknown'
|
112 |
|
|
|
211 |
for i in range(jump, total_len, jump):
|
212 |
if i+jump >= total_len:
|
213 |
left_dur = (total_len-i)/sr
|
214 |
+
if left_dur >= 1: #Still count if left over dur is >= 1s
|
215 |
mel_tensor = self.preprocess.wave_preprocess(audio[i:total_len]).to(device)
|
216 |
ref_s += self.style_encoder(mel_tensor.unsqueeze(1))
|
217 |
count += 1
|
|
|
231 |
speed = min(max(speed, 0.0001), 2) #speed range [0, 2]
|
232 |
|
233 |
phonem = ' '.join(word_tokenize(phonem))
|
234 |
+
tokens = self.cleaner(phonem)
|
235 |
tokens.insert(0, 0)
|
236 |
tokens.append(0)
|
237 |
tokens = torch.LongTensor(tokens).to(device).unsqueeze(0)
|
meldataset.py
ADDED
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#coding: utf-8
|
2 |
+
import os.path as osp
|
3 |
+
import random
|
4 |
+
import numpy as np
|
5 |
+
import random
|
6 |
+
import soundfile as sf
|
7 |
+
import librosa
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torchaudio
|
11 |
+
import torch.utils.data
|
12 |
+
import torch.distributed as dist
|
13 |
+
from multiprocessing import Pool
|
14 |
+
|
15 |
+
import logging
|
16 |
+
logger = logging.getLogger(__name__)
|
17 |
+
logger.setLevel(logging.DEBUG)
|
18 |
+
|
19 |
+
import pandas as pd
|
20 |
+
|
21 |
+
class TextCleaner:
|
22 |
+
def __init__(self, symbol_dict, debug=True):
|
23 |
+
self.word_index_dictionary = symbol_dict
|
24 |
+
self.debug = debug
|
25 |
+
def __call__(self, text):
|
26 |
+
indexes = []
|
27 |
+
for char in text:
|
28 |
+
try:
|
29 |
+
indexes.append(self.word_index_dictionary[char])
|
30 |
+
except KeyError as e:
|
31 |
+
if self.debug:
|
32 |
+
print("\nWARNING UNKNOWN IPA CHARACTERS/LETTERS: ", char)
|
33 |
+
print("To ignore set 'debug' to false in the config")
|
34 |
+
continue
|
35 |
+
return indexes
|
36 |
+
|
37 |
+
np.random.seed(1)
|
38 |
+
random.seed(1)
|
39 |
+
SPECT_PARAMS = {
|
40 |
+
"n_fft": 2048,
|
41 |
+
"win_length": 1200,
|
42 |
+
"hop_length": 300
|
43 |
+
}
|
44 |
+
MEL_PARAMS = {
|
45 |
+
"n_mels": 80,
|
46 |
+
}
|
47 |
+
|
48 |
+
to_mel = torchaudio.transforms.MelSpectrogram(
|
49 |
+
n_mels=80, n_fft=2048, win_length=1200, hop_length=300)
|
50 |
+
mean, std = -4, 4
|
51 |
+
|
52 |
+
def preprocess(wave):
|
53 |
+
wave_tensor = torch.from_numpy(wave).float()
|
54 |
+
mel_tensor = to_mel(wave_tensor)
|
55 |
+
mel_tensor = (torch.log(1e-5 + mel_tensor.unsqueeze(0)) - mean) / std
|
56 |
+
return mel_tensor
|
57 |
+
|
58 |
+
class FilePathDataset(torch.utils.data.Dataset):
|
59 |
+
def __init__(self,
|
60 |
+
data_list,
|
61 |
+
root_path,
|
62 |
+
symbol_dict,
|
63 |
+
sr=24000,
|
64 |
+
data_augmentation=False,
|
65 |
+
validation=False,
|
66 |
+
debug=True
|
67 |
+
):
|
68 |
+
|
69 |
+
_data_list = [l.strip().split('|') for l in data_list]
|
70 |
+
self.data_list = _data_list #[data if len(data) == 3 else (*data, 0) for data in _data_list] #append speakerid=0 for all
|
71 |
+
self.text_cleaner = TextCleaner(symbol_dict, debug)
|
72 |
+
self.sr = sr
|
73 |
+
|
74 |
+
self.df = pd.DataFrame(self.data_list)
|
75 |
+
|
76 |
+
self.to_melspec = torchaudio.transforms.MelSpectrogram(**MEL_PARAMS)
|
77 |
+
|
78 |
+
self.mean, self.std = -4, 4
|
79 |
+
self.data_augmentation = data_augmentation and (not validation)
|
80 |
+
self.max_mel_length = 192
|
81 |
+
|
82 |
+
self.root_path = root_path
|
83 |
+
|
84 |
+
def __len__(self):
|
85 |
+
return len(self.data_list)
|
86 |
+
|
87 |
+
def __getitem__(self, idx):
|
88 |
+
data = self.data_list[idx]
|
89 |
+
path = data[0]
|
90 |
+
|
91 |
+
wave, text_tensor = self._load_tensor(data)
|
92 |
+
|
93 |
+
mel_tensor = preprocess(wave).squeeze()
|
94 |
+
|
95 |
+
acoustic_feature = mel_tensor.squeeze()
|
96 |
+
length_feature = acoustic_feature.size(1)
|
97 |
+
acoustic_feature = acoustic_feature[:, :(length_feature - length_feature % 2)]
|
98 |
+
|
99 |
+
return acoustic_feature, text_tensor, path, wave
|
100 |
+
|
101 |
+
def _load_tensor(self, data):
|
102 |
+
wave_path, text = data
|
103 |
+
wave, sr = sf.read(osp.join(self.root_path, wave_path))
|
104 |
+
if wave.shape[-1] == 2:
|
105 |
+
wave = wave[:, 0].squeeze()
|
106 |
+
if sr != 24000:
|
107 |
+
wave = librosa.resample(wave, orig_sr=sr, target_sr=24000)
|
108 |
+
print(wave_path, sr)
|
109 |
+
|
110 |
+
# Adding half a second padding.
|
111 |
+
wave = np.concatenate([np.zeros([12000]), wave, np.zeros([12000])], axis=0)
|
112 |
+
|
113 |
+
text = self.text_cleaner(text)
|
114 |
+
|
115 |
+
text.insert(0, 0)
|
116 |
+
text.append(0)
|
117 |
+
|
118 |
+
text = torch.LongTensor(text)
|
119 |
+
|
120 |
+
return wave, text
|
121 |
+
|
122 |
+
def _load_data(self, data):
|
123 |
+
wave, text_tensor = self._load_tensor(data)
|
124 |
+
mel_tensor = preprocess(wave).squeeze()
|
125 |
+
|
126 |
+
mel_length = mel_tensor.size(1)
|
127 |
+
if mel_length > self.max_mel_length:
|
128 |
+
random_start = np.random.randint(0, mel_length - self.max_mel_length)
|
129 |
+
mel_tensor = mel_tensor[:, random_start:random_start + self.max_mel_length]
|
130 |
+
|
131 |
+
return mel_tensor
|
132 |
+
|
133 |
+
|
134 |
+
class Collater(object):
|
135 |
+
"""
|
136 |
+
Args:
|
137 |
+
adaptive_batch_size (bool): if true, decrease batch size when long data comes.
|
138 |
+
"""
|
139 |
+
|
140 |
+
def __init__(self, return_wave=False):
|
141 |
+
self.text_pad_index = 0
|
142 |
+
self.min_mel_length = 192
|
143 |
+
self.max_mel_length = 192
|
144 |
+
self.return_wave = return_wave
|
145 |
+
|
146 |
+
|
147 |
+
def __call__(self, batch):
|
148 |
+
batch_size = len(batch)
|
149 |
+
|
150 |
+
# sort by mel length
|
151 |
+
lengths = [b[0].shape[1] for b in batch]
|
152 |
+
batch_indexes = np.argsort(lengths)[::-1]
|
153 |
+
batch = [batch[bid] for bid in batch_indexes]
|
154 |
+
|
155 |
+
nmels = batch[0][0].size(0)
|
156 |
+
max_mel_length = max([b[0].shape[1] for b in batch])
|
157 |
+
max_text_length = max([b[1].shape[0] for b in batch])
|
158 |
+
|
159 |
+
mels = torch.zeros((batch_size, nmels, max_mel_length)).float()
|
160 |
+
texts = torch.zeros((batch_size, max_text_length)).long()
|
161 |
+
|
162 |
+
input_lengths = torch.zeros(batch_size).long()
|
163 |
+
output_lengths = torch.zeros(batch_size).long()
|
164 |
+
paths = ['' for _ in range(batch_size)]
|
165 |
+
waves = [None for _ in range(batch_size)]
|
166 |
+
|
167 |
+
for bid, (mel, text, path, wave) in enumerate(batch):
|
168 |
+
mel_size = mel.size(1)
|
169 |
+
text_size = text.size(0)
|
170 |
+
mels[bid, :, :mel_size] = mel
|
171 |
+
texts[bid, :text_size] = text
|
172 |
+
input_lengths[bid] = text_size
|
173 |
+
output_lengths[bid] = mel_size
|
174 |
+
paths[bid] = path
|
175 |
+
|
176 |
+
waves[bid] = wave
|
177 |
+
|
178 |
+
return waves, texts, input_lengths, mels, output_lengths
|
179 |
+
|
180 |
+
|
181 |
+
def get_length(wave_path, root_path):
|
182 |
+
info = sf.info(osp.join(root_path, wave_path))
|
183 |
+
return info.frames * (24000 / info.samplerate)
|
184 |
+
|
185 |
+
def build_dataloader(path_list,
|
186 |
+
root_path,
|
187 |
+
symbol_dict,
|
188 |
+
validation=False,
|
189 |
+
batch_size=4,
|
190 |
+
num_workers=1,
|
191 |
+
device='cpu',
|
192 |
+
collate_config={},
|
193 |
+
dataset_config={}):
|
194 |
+
|
195 |
+
dataset = FilePathDataset(path_list, root_path, symbol_dict, validation=validation, **dataset_config)
|
196 |
+
collate_fn = Collater(**collate_config)
|
197 |
+
|
198 |
+
print("Getting sample lengths...")
|
199 |
+
|
200 |
+
num_processes = num_workers * 2
|
201 |
+
if num_processes != 0:
|
202 |
+
list_of_tuples = [(d[0], root_path) for d in dataset.data_list]
|
203 |
+
with Pool(processes=num_processes) as pool:
|
204 |
+
sample_lengths = pool.starmap(get_length, list_of_tuples, chunksize=16)
|
205 |
+
else:
|
206 |
+
sample_lengths = []
|
207 |
+
for d in dataset.data_list:
|
208 |
+
sample_lengths.append(get_length(d[0], root_path))
|
209 |
+
|
210 |
+
data_loader = torch.utils.data.DataLoader(
|
211 |
+
dataset,
|
212 |
+
num_workers=num_workers,
|
213 |
+
batch_sampler=BatchSampler(
|
214 |
+
sample_lengths,
|
215 |
+
batch_size,
|
216 |
+
shuffle=(not validation),
|
217 |
+
drop_last=(not validation),
|
218 |
+
num_replicas=1,
|
219 |
+
rank=0,
|
220 |
+
),
|
221 |
+
collate_fn=collate_fn,
|
222 |
+
pin_memory=(device != "cpu"),
|
223 |
+
)
|
224 |
+
|
225 |
+
return data_loader
|
226 |
+
|
227 |
+
#https://github.com/duerig/StyleTTS2/
|
228 |
+
class BatchSampler(torch.utils.data.Sampler):
|
229 |
+
def __init__(
|
230 |
+
self,
|
231 |
+
sample_lengths,
|
232 |
+
batch_sizes,
|
233 |
+
num_replicas=None,
|
234 |
+
rank=None,
|
235 |
+
shuffle=True,
|
236 |
+
drop_last=False,
|
237 |
+
):
|
238 |
+
self.batch_sizes = batch_sizes
|
239 |
+
if num_replicas is None:
|
240 |
+
self.num_replicas = dist.get_world_size()
|
241 |
+
else:
|
242 |
+
self.num_replicas = num_replicas
|
243 |
+
if rank is None:
|
244 |
+
self.rank = dist.get_rank()
|
245 |
+
else:
|
246 |
+
self.rank = rank
|
247 |
+
self.shuffle = shuffle
|
248 |
+
self.drop_last = drop_last
|
249 |
+
|
250 |
+
self.time_bins = {}
|
251 |
+
self.epoch = 0
|
252 |
+
self.total_len = 0
|
253 |
+
self.last_bin = None
|
254 |
+
|
255 |
+
for i in range(len(sample_lengths)):
|
256 |
+
bin_num = self.get_time_bin(sample_lengths[i])
|
257 |
+
if bin_num != -1:
|
258 |
+
if bin_num not in self.time_bins:
|
259 |
+
self.time_bins[bin_num] = []
|
260 |
+
self.time_bins[bin_num].append(i)
|
261 |
+
|
262 |
+
for key in self.time_bins.keys():
|
263 |
+
val = self.time_bins[key]
|
264 |
+
total_batch = self.batch_sizes * num_replicas
|
265 |
+
self.total_len += len(val) // total_batch
|
266 |
+
if not self.drop_last and len(val) % total_batch != 0:
|
267 |
+
self.total_len += 1
|
268 |
+
|
269 |
+
def __iter__(self):
|
270 |
+
sampler_order = list(self.time_bins.keys())
|
271 |
+
sampler_indices = []
|
272 |
+
|
273 |
+
if self.shuffle:
|
274 |
+
sampler_indices = torch.randperm(len(sampler_order)).tolist()
|
275 |
+
else:
|
276 |
+
sampler_indices = list(range(len(sampler_order)))
|
277 |
+
|
278 |
+
for index in sampler_indices:
|
279 |
+
key = sampler_order[index]
|
280 |
+
current_bin = self.time_bins[key]
|
281 |
+
dist = torch.utils.data.distributed.DistributedSampler(
|
282 |
+
current_bin,
|
283 |
+
num_replicas=self.num_replicas,
|
284 |
+
rank=self.rank,
|
285 |
+
shuffle=self.shuffle,
|
286 |
+
drop_last=self.drop_last,
|
287 |
+
)
|
288 |
+
dist.set_epoch(self.epoch)
|
289 |
+
sampler = torch.utils.data.sampler.BatchSampler(
|
290 |
+
dist, self.batch_sizes, self.drop_last
|
291 |
+
)
|
292 |
+
for item_list in sampler:
|
293 |
+
self.last_bin = key
|
294 |
+
yield [current_bin[i] for i in item_list]
|
295 |
+
|
296 |
+
def __len__(self):
|
297 |
+
return self.total_len
|
298 |
+
|
299 |
+
def set_epoch(self, epoch):
|
300 |
+
self.epoch = epoch
|
301 |
+
|
302 |
+
def get_time_bin(self, sample_count):
|
303 |
+
result = -1
|
304 |
+
frames = sample_count // 300
|
305 |
+
if frames >= 20:
|
306 |
+
result = (frames - 20) // 20
|
307 |
+
return result
|