Spaces:
Configuration error
Configuration error
Commit ·
f447071
1
Parent(s): ac78075
Delete preprocessing
Browse files- preprocessing/SVCpre.py +0 -63
- preprocessing/__pycache__/SVCpre.cpython-38.pyc +0 -0
- preprocessing/__pycache__/base_binarizer.cpython-38.pyc +0 -0
- preprocessing/__pycache__/data_gen_utils.cpython-38.pyc +0 -0
- preprocessing/__pycache__/hubertinfer.cpython-38.pyc +0 -0
- preprocessing/__pycache__/process_pipeline.cpython-38.pyc +0 -0
- preprocessing/base_binarizer.py +0 -237
- preprocessing/binarize.py +0 -20
- preprocessing/data_gen_utils.py +0 -426
- preprocessing/hubertinfer.py +0 -42
- preprocessing/process_pipeline.py +0 -199
preprocessing/SVCpre.py
DELETED
|
@@ -1,63 +0,0 @@
|
|
| 1 |
-
'''
|
| 2 |
-
|
| 3 |
-
item: one piece of data
|
| 4 |
-
item_name: data id
|
| 5 |
-
wavfn: wave file path
|
| 6 |
-
txt: lyrics
|
| 7 |
-
ph: phoneme
|
| 8 |
-
tgfn: text grid file path (unused)
|
| 9 |
-
spk: dataset name
|
| 10 |
-
wdb: word boundary
|
| 11 |
-
ph_durs: phoneme durations
|
| 12 |
-
midi: pitch as midi notes
|
| 13 |
-
midi_dur: midi duration
|
| 14 |
-
is_slur: keep singing upon note changes
|
| 15 |
-
'''
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
from copy import deepcopy
|
| 19 |
-
|
| 20 |
-
import logging
|
| 21 |
-
|
| 22 |
-
from preprocessing.process_pipeline import File2Batch
|
| 23 |
-
from utils.hparams import hparams
|
| 24 |
-
from preprocessing.base_binarizer import BaseBinarizer
|
| 25 |
-
|
| 26 |
-
SVCSINGING_ITEM_ATTRIBUTES = ['wav_fn', 'spk_id']
|
| 27 |
-
class SVCBinarizer(BaseBinarizer):
|
| 28 |
-
def __init__(self, item_attributes=SVCSINGING_ITEM_ATTRIBUTES):
|
| 29 |
-
super().__init__(item_attributes)
|
| 30 |
-
print('spkers: ', set(item['spk_id'] for item in self.items.values()))
|
| 31 |
-
self.item_names = sorted(list(self.items.keys()))
|
| 32 |
-
self._train_item_names, self._test_item_names = self.split_train_test_set(self.item_names)
|
| 33 |
-
# self._valid_item_names=[]
|
| 34 |
-
|
| 35 |
-
def split_train_test_set(self, item_names):
|
| 36 |
-
item_names = deepcopy(item_names)
|
| 37 |
-
if hparams['choose_test_manually']:
|
| 38 |
-
test_item_names = [x for x in item_names if any([x.startswith(ts) for ts in hparams['test_prefixes']])]
|
| 39 |
-
else:
|
| 40 |
-
test_item_names = item_names[-5:]
|
| 41 |
-
train_item_names = [x for x in item_names if x not in set(test_item_names)]
|
| 42 |
-
logging.info("train {}".format(len(train_item_names)))
|
| 43 |
-
logging.info("test {}".format(len(test_item_names)))
|
| 44 |
-
return train_item_names, test_item_names
|
| 45 |
-
|
| 46 |
-
@property
|
| 47 |
-
def train_item_names(self):
|
| 48 |
-
return self._train_item_names
|
| 49 |
-
|
| 50 |
-
@property
|
| 51 |
-
def valid_item_names(self):
|
| 52 |
-
return self._test_item_names
|
| 53 |
-
|
| 54 |
-
@property
|
| 55 |
-
def test_item_names(self):
|
| 56 |
-
return self._test_item_names
|
| 57 |
-
|
| 58 |
-
def load_meta_data(self):
|
| 59 |
-
self.items = File2Batch.file2temporary_dict()
|
| 60 |
-
|
| 61 |
-
def _phone_encoder(self):
|
| 62 |
-
from preprocessing.hubertinfer import Hubertencoder
|
| 63 |
-
return Hubertencoder(hparams['hubert_path'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocessing/__pycache__/SVCpre.cpython-38.pyc
DELETED
|
Binary file (3.19 kB)
|
|
|
preprocessing/__pycache__/base_binarizer.cpython-38.pyc
DELETED
|
Binary file (7.99 kB)
|
|
|
preprocessing/__pycache__/data_gen_utils.cpython-38.pyc
DELETED
|
Binary file (11.7 kB)
|
|
|
preprocessing/__pycache__/hubertinfer.cpython-38.pyc
DELETED
|
Binary file (1.63 kB)
|
|
|
preprocessing/__pycache__/process_pipeline.cpython-38.pyc
DELETED
|
Binary file (5.3 kB)
|
|
|
preprocessing/base_binarizer.py
DELETED
|
@@ -1,237 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from webbrowser import get
|
| 3 |
-
os.environ["OMP_NUM_THREADS"] = "1"
|
| 4 |
-
import yaml
|
| 5 |
-
from utils.multiprocess_utils import chunked_multiprocess_run
|
| 6 |
-
import random
|
| 7 |
-
import json
|
| 8 |
-
# from resemblyzer import VoiceEncoder
|
| 9 |
-
from tqdm import tqdm
|
| 10 |
-
from preprocessing.data_gen_utils import get_mel2ph, get_pitch_parselmouth, build_phone_encoder,get_pitch_crepe
|
| 11 |
-
from utils.hparams import set_hparams, hparams
|
| 12 |
-
import numpy as np
|
| 13 |
-
from utils.indexed_datasets import IndexedDatasetBuilder
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
class BinarizationError(Exception):
|
| 17 |
-
pass
|
| 18 |
-
|
| 19 |
-
BASE_ITEM_ATTRIBUTES = ['txt', 'ph', 'wav_fn', 'tg_fn', 'spk_id']
|
| 20 |
-
|
| 21 |
-
class BaseBinarizer:
|
| 22 |
-
'''
|
| 23 |
-
Base class for data processing.
|
| 24 |
-
1. *process* and *process_data_split*:
|
| 25 |
-
process entire data, generate the train-test split (support parallel processing);
|
| 26 |
-
2. *process_item*:
|
| 27 |
-
process singe piece of data;
|
| 28 |
-
3. *get_pitch*:
|
| 29 |
-
infer the pitch using some algorithm;
|
| 30 |
-
4. *get_align*:
|
| 31 |
-
get the alignment using 'mel2ph' format (see https://arxiv.org/abs/1905.09263).
|
| 32 |
-
5. phoneme encoder, voice encoder, etc.
|
| 33 |
-
|
| 34 |
-
Subclasses should define:
|
| 35 |
-
1. *load_metadata*:
|
| 36 |
-
how to read multiple datasets from files;
|
| 37 |
-
2. *train_item_names*, *valid_item_names*, *test_item_names*:
|
| 38 |
-
how to split the dataset;
|
| 39 |
-
3. load_ph_set:
|
| 40 |
-
the phoneme set.
|
| 41 |
-
'''
|
| 42 |
-
def __init__(self, item_attributes=BASE_ITEM_ATTRIBUTES):
|
| 43 |
-
self.binarization_args = hparams['binarization_args']
|
| 44 |
-
#self.pre_align_args = hparams['pre_align_args']
|
| 45 |
-
|
| 46 |
-
self.items = {}
|
| 47 |
-
# every item in self.items has some attributes
|
| 48 |
-
self.item_attributes = item_attributes
|
| 49 |
-
|
| 50 |
-
self.load_meta_data()
|
| 51 |
-
# check program correctness 检查itemdict的key只能在给定的列表中取值
|
| 52 |
-
assert all([attr in self.item_attributes for attr in list(self.items.values())[0].keys()])
|
| 53 |
-
self.item_names = sorted(list(self.items.keys()))
|
| 54 |
-
|
| 55 |
-
if self.binarization_args['shuffle']:
|
| 56 |
-
random.seed(1234)
|
| 57 |
-
random.shuffle(self.item_names)
|
| 58 |
-
|
| 59 |
-
# set default get_pitch algorithm
|
| 60 |
-
if hparams['use_crepe']:
|
| 61 |
-
self.get_pitch_algorithm = get_pitch_crepe
|
| 62 |
-
else:
|
| 63 |
-
self.get_pitch_algorithm = get_pitch_parselmouth
|
| 64 |
-
|
| 65 |
-
def load_meta_data(self):
|
| 66 |
-
raise NotImplementedError
|
| 67 |
-
|
| 68 |
-
@property
|
| 69 |
-
def train_item_names(self):
|
| 70 |
-
raise NotImplementedError
|
| 71 |
-
|
| 72 |
-
@property
|
| 73 |
-
def valid_item_names(self):
|
| 74 |
-
raise NotImplementedError
|
| 75 |
-
|
| 76 |
-
@property
|
| 77 |
-
def test_item_names(self):
|
| 78 |
-
raise NotImplementedError
|
| 79 |
-
|
| 80 |
-
def build_spk_map(self):
|
| 81 |
-
spk_map = set()
|
| 82 |
-
for item_name in self.item_names:
|
| 83 |
-
spk_name = self.items[item_name]['spk_id']
|
| 84 |
-
spk_map.add(spk_name)
|
| 85 |
-
spk_map = {x: i for i, x in enumerate(sorted(list(spk_map)))}
|
| 86 |
-
assert len(spk_map) == 0 or len(spk_map) <= hparams['num_spk'], len(spk_map)
|
| 87 |
-
return spk_map
|
| 88 |
-
|
| 89 |
-
def item_name2spk_id(self, item_name):
|
| 90 |
-
return self.spk_map[self.items[item_name]['spk_id']]
|
| 91 |
-
|
| 92 |
-
def _phone_encoder(self):
|
| 93 |
-
'''
|
| 94 |
-
use hubert encoder
|
| 95 |
-
'''
|
| 96 |
-
raise NotImplementedError
|
| 97 |
-
'''
|
| 98 |
-
create 'phone_set.json' file if it doesn't exist
|
| 99 |
-
'''
|
| 100 |
-
ph_set_fn = f"{hparams['binary_data_dir']}/phone_set.json"
|
| 101 |
-
ph_set = []
|
| 102 |
-
if hparams['reset_phone_dict'] or not os.path.exists(ph_set_fn):
|
| 103 |
-
self.load_ph_set(ph_set)
|
| 104 |
-
ph_set = sorted(set(ph_set))
|
| 105 |
-
json.dump(ph_set, open(ph_set_fn, 'w', encoding='utf-8'))
|
| 106 |
-
print("| Build phone set: ", ph_set)
|
| 107 |
-
else:
|
| 108 |
-
ph_set = json.load(open(ph_set_fn, 'r', encoding='utf-8'))
|
| 109 |
-
print("| Load phone set: ", ph_set)
|
| 110 |
-
return build_phone_encoder(hparams['binary_data_dir'])
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def load_ph_set(self, ph_set):
|
| 114 |
-
raise NotImplementedError
|
| 115 |
-
|
| 116 |
-
def meta_data_iterator(self, prefix):
|
| 117 |
-
if prefix == 'valid':
|
| 118 |
-
item_names = self.valid_item_names
|
| 119 |
-
elif prefix == 'test':
|
| 120 |
-
item_names = self.test_item_names
|
| 121 |
-
else:
|
| 122 |
-
item_names = self.train_item_names
|
| 123 |
-
for item_name in item_names:
|
| 124 |
-
meta_data = self.items[item_name]
|
| 125 |
-
yield item_name, meta_data
|
| 126 |
-
|
| 127 |
-
def process(self):
|
| 128 |
-
os.makedirs(hparams['binary_data_dir'], exist_ok=True)
|
| 129 |
-
self.spk_map = self.build_spk_map()
|
| 130 |
-
print("| spk_map: ", self.spk_map)
|
| 131 |
-
spk_map_fn = f"{hparams['binary_data_dir']}/spk_map.json"
|
| 132 |
-
json.dump(self.spk_map, open(spk_map_fn, 'w', encoding='utf-8'))
|
| 133 |
-
|
| 134 |
-
self.phone_encoder =self._phone_encoder()
|
| 135 |
-
self.process_data_split('valid')
|
| 136 |
-
self.process_data_split('test')
|
| 137 |
-
self.process_data_split('train')
|
| 138 |
-
|
| 139 |
-
def process_data_split(self, prefix):
|
| 140 |
-
data_dir = hparams['binary_data_dir']
|
| 141 |
-
args = []
|
| 142 |
-
builder = IndexedDatasetBuilder(f'{data_dir}/{prefix}')
|
| 143 |
-
lengths = []
|
| 144 |
-
f0s = []
|
| 145 |
-
total_sec = 0
|
| 146 |
-
# if self.binarization_args['with_spk_embed']:
|
| 147 |
-
# voice_encoder = VoiceEncoder().cuda()
|
| 148 |
-
|
| 149 |
-
for item_name, meta_data in self.meta_data_iterator(prefix):
|
| 150 |
-
args.append([item_name, meta_data, self.binarization_args])
|
| 151 |
-
spec_min=[]
|
| 152 |
-
spec_max=[]
|
| 153 |
-
# code for single cpu processing
|
| 154 |
-
for i in tqdm(reversed(range(len(args))), total=len(args)):
|
| 155 |
-
a = args[i]
|
| 156 |
-
item = self.process_item(*a)
|
| 157 |
-
if item is None:
|
| 158 |
-
continue
|
| 159 |
-
spec_min.append(item['spec_min'])
|
| 160 |
-
spec_max.append(item['spec_max'])
|
| 161 |
-
# item['spk_embe'] = voice_encoder.embed_utterance(item['wav']) \
|
| 162 |
-
# if self.binardization_args['with_spk_embed'] else None
|
| 163 |
-
if not self.binarization_args['with_wav'] and 'wav' in item:
|
| 164 |
-
if hparams['debug']:
|
| 165 |
-
print("del wav")
|
| 166 |
-
del item['wav']
|
| 167 |
-
if(hparams['debug']):
|
| 168 |
-
print(item)
|
| 169 |
-
builder.add_item(item)
|
| 170 |
-
lengths.append(item['len'])
|
| 171 |
-
total_sec += item['sec']
|
| 172 |
-
# if item.get('f0') is not None:
|
| 173 |
-
# f0s.append(item['f0'])
|
| 174 |
-
if prefix=='train':
|
| 175 |
-
spec_max=np.max(spec_max,0)
|
| 176 |
-
spec_min=np.min(spec_min,0)
|
| 177 |
-
print(spec_max.shape)
|
| 178 |
-
with open(hparams['config_path'], encoding='utf-8') as f:
|
| 179 |
-
_hparams=yaml.safe_load(f)
|
| 180 |
-
_hparams['spec_max']=spec_max.tolist()
|
| 181 |
-
_hparams['spec_min']=spec_min.tolist()
|
| 182 |
-
with open(hparams['config_path'], 'w', encoding='utf-8') as f:
|
| 183 |
-
yaml.safe_dump(_hparams,f)
|
| 184 |
-
builder.finalize()
|
| 185 |
-
np.save(f'{data_dir}/{prefix}_lengths.npy', lengths)
|
| 186 |
-
if len(f0s) > 0:
|
| 187 |
-
f0s = np.concatenate(f0s, 0)
|
| 188 |
-
f0s = f0s[f0s != 0]
|
| 189 |
-
np.save(f'{data_dir}/{prefix}_f0s_mean_std.npy', [np.mean(f0s).item(), np.std(f0s).item()])
|
| 190 |
-
print(f"| {prefix} total duration: {total_sec:.3f}s")
|
| 191 |
-
|
| 192 |
-
def process_item(self, item_name, meta_data, binarization_args):
|
| 193 |
-
from preprocessing.process_pipeline import File2Batch
|
| 194 |
-
return File2Batch.temporary_dict2processed_input(item_name, meta_data, self.phone_encoder, binarization_args)
|
| 195 |
-
|
| 196 |
-
def get_align(self, meta_data, mel, phone_encoded, res):
|
| 197 |
-
raise NotImplementedError
|
| 198 |
-
|
| 199 |
-
def get_align_from_textgrid(self, meta_data, mel, phone_encoded, res):
|
| 200 |
-
'''
|
| 201 |
-
NOTE: this part of script is *isolated* from other scripts, which means
|
| 202 |
-
it may not be compatible with the current version.
|
| 203 |
-
'''
|
| 204 |
-
return
|
| 205 |
-
tg_fn, ph = meta_data['tg_fn'], meta_data['ph']
|
| 206 |
-
if tg_fn is not None and os.path.exists(tg_fn):
|
| 207 |
-
mel2ph, dur = get_mel2ph(tg_fn, ph, mel, hparams)
|
| 208 |
-
else:
|
| 209 |
-
raise BinarizationError(f"Align not found")
|
| 210 |
-
if mel2ph.max() - 1 >= len(phone_encoded):
|
| 211 |
-
raise BinarizationError(
|
| 212 |
-
f"Align does not match: mel2ph.max() - 1: {mel2ph.max() - 1}, len(phone_encoded): {len(phone_encoded)}")
|
| 213 |
-
res['mel2ph'] = mel2ph
|
| 214 |
-
res['dur'] = dur
|
| 215 |
-
|
| 216 |
-
def get_f0cwt(self, f0, res):
|
| 217 |
-
'''
|
| 218 |
-
NOTE: this part of script is *isolated* from other scripts, which means
|
| 219 |
-
it may not be compatible with the current version.
|
| 220 |
-
'''
|
| 221 |
-
return
|
| 222 |
-
from utils.cwt import get_cont_lf0, get_lf0_cwt
|
| 223 |
-
uv, cont_lf0_lpf = get_cont_lf0(f0)
|
| 224 |
-
logf0s_mean_org, logf0s_std_org = np.mean(cont_lf0_lpf), np.std(cont_lf0_lpf)
|
| 225 |
-
cont_lf0_lpf_norm = (cont_lf0_lpf - logf0s_mean_org) / logf0s_std_org
|
| 226 |
-
Wavelet_lf0, scales = get_lf0_cwt(cont_lf0_lpf_norm)
|
| 227 |
-
if np.any(np.isnan(Wavelet_lf0)):
|
| 228 |
-
raise BinarizationError("NaN CWT")
|
| 229 |
-
res['cwt_spec'] = Wavelet_lf0
|
| 230 |
-
res['cwt_scales'] = scales
|
| 231 |
-
res['f0_mean'] = logf0s_mean_org
|
| 232 |
-
res['f0_std'] = logf0s_std_org
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
if __name__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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocessing/binarize.py
DELETED
|
@@ -1,20 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
|
| 3 |
-
os.environ["OMP_NUM_THREADS"] = "1"
|
| 4 |
-
|
| 5 |
-
import importlib
|
| 6 |
-
from utils.hparams import set_hparams, hparams
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def binarize():
|
| 10 |
-
binarizer_cls = hparams.get("binarizer_cls", 'basics.base_binarizer.BaseBinarizer')
|
| 11 |
-
pkg = ".".join(binarizer_cls.split(".")[:-1])
|
| 12 |
-
cls_name = binarizer_cls.split(".")[-1]
|
| 13 |
-
binarizer_cls = getattr(importlib.import_module(pkg), cls_name)
|
| 14 |
-
print("| Binarizer: ", binarizer_cls)
|
| 15 |
-
binarizer_cls().process()
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
if __name__ == '__main__':
|
| 19 |
-
set_hparams()
|
| 20 |
-
binarize()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocessing/data_gen_utils.py
DELETED
|
@@ -1,426 +0,0 @@
|
|
| 1 |
-
from io import BytesIO
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
import struct
|
| 6 |
-
import warnings
|
| 7 |
-
from collections import OrderedDict
|
| 8 |
-
|
| 9 |
-
import librosa
|
| 10 |
-
import numpy as np
|
| 11 |
-
import parselmouth
|
| 12 |
-
import pyloudnorm as pyln
|
| 13 |
-
import resampy
|
| 14 |
-
import torch
|
| 15 |
-
import torchcrepe
|
| 16 |
-
import webrtcvad
|
| 17 |
-
from scipy.ndimage.morphology import binary_dilation
|
| 18 |
-
from skimage.transform import resize
|
| 19 |
-
import pyworld as world
|
| 20 |
-
|
| 21 |
-
from utils import audio
|
| 22 |
-
from utils.pitch_utils import f0_to_coarse
|
| 23 |
-
from utils.text_encoder import TokenTextEncoder
|
| 24 |
-
|
| 25 |
-
warnings.filterwarnings("ignore")
|
| 26 |
-
PUNCS = '!,.?;:'
|
| 27 |
-
|
| 28 |
-
int16_max = (2 ** 15) - 1
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def trim_long_silences(path, sr=None, return_raw_wav=False, norm=True, vad_max_silence_length=12):
|
| 32 |
-
"""
|
| 33 |
-
Ensures that segments without voice in the waveform remain no longer than a
|
| 34 |
-
threshold determined by the VAD parameters in params.py.
|
| 35 |
-
:param wav: the raw waveform as a numpy array of floats
|
| 36 |
-
:param vad_max_silence_length: Maximum number of consecutive silent frames a segment can have.
|
| 37 |
-
:return: the same waveform with silences trimmed away (length <= original wav length)
|
| 38 |
-
"""
|
| 39 |
-
|
| 40 |
-
## Voice Activation Detection
|
| 41 |
-
# Window size of the VAD. Must be either 10, 20 or 30 milliseconds.
|
| 42 |
-
# This sets the granularity of the VAD. Should not need to be changed.
|
| 43 |
-
sampling_rate = 16000
|
| 44 |
-
wav_raw, sr = librosa.core.load(path, sr=sr)
|
| 45 |
-
|
| 46 |
-
if norm:
|
| 47 |
-
meter = pyln.Meter(sr) # create BS.1770 meter
|
| 48 |
-
loudness = meter.integrated_loudness(wav_raw)
|
| 49 |
-
wav_raw = pyln.normalize.loudness(wav_raw, loudness, -20.0)
|
| 50 |
-
if np.abs(wav_raw).max() > 1.0:
|
| 51 |
-
wav_raw = wav_raw / np.abs(wav_raw).max()
|
| 52 |
-
|
| 53 |
-
wav = librosa.resample(wav_raw, sr, sampling_rate, res_type='kaiser_best')
|
| 54 |
-
|
| 55 |
-
vad_window_length = 30 # In milliseconds
|
| 56 |
-
# Number of frames to average together when performing the moving average smoothing.
|
| 57 |
-
# The larger this value, the larger the VAD variations must be to not get smoothed out.
|
| 58 |
-
vad_moving_average_width = 8
|
| 59 |
-
|
| 60 |
-
# Compute the voice detection window size
|
| 61 |
-
samples_per_window = (vad_window_length * sampling_rate) // 1000
|
| 62 |
-
|
| 63 |
-
# Trim the end of the audio to have a multiple of the window size
|
| 64 |
-
wav = wav[:len(wav) - (len(wav) % samples_per_window)]
|
| 65 |
-
|
| 66 |
-
# Convert the float waveform to 16-bit mono PCM
|
| 67 |
-
pcm_wave = struct.pack("%dh" % len(wav), *(np.round(wav * int16_max)).astype(np.int16))
|
| 68 |
-
|
| 69 |
-
# Perform voice activation detection
|
| 70 |
-
voice_flags = []
|
| 71 |
-
vad = webrtcvad.Vad(mode=3)
|
| 72 |
-
for window_start in range(0, len(wav), samples_per_window):
|
| 73 |
-
window_end = window_start + samples_per_window
|
| 74 |
-
voice_flags.append(vad.is_speech(pcm_wave[window_start * 2:window_end * 2],
|
| 75 |
-
sample_rate=sampling_rate))
|
| 76 |
-
voice_flags = np.array(voice_flags)
|
| 77 |
-
|
| 78 |
-
# Smooth the voice detection with a moving average
|
| 79 |
-
def moving_average(array, width):
|
| 80 |
-
array_padded = np.concatenate((np.zeros((width - 1) // 2), array, np.zeros(width // 2)))
|
| 81 |
-
ret = np.cumsum(array_padded, dtype=float)
|
| 82 |
-
ret[width:] = ret[width:] - ret[:-width]
|
| 83 |
-
return ret[width - 1:] / width
|
| 84 |
-
|
| 85 |
-
audio_mask = moving_average(voice_flags, vad_moving_average_width)
|
| 86 |
-
audio_mask = np.round(audio_mask).astype(np.bool)
|
| 87 |
-
|
| 88 |
-
# Dilate the voiced regions
|
| 89 |
-
audio_mask = binary_dilation(audio_mask, np.ones(vad_max_silence_length + 1))
|
| 90 |
-
audio_mask = np.repeat(audio_mask, samples_per_window)
|
| 91 |
-
audio_mask = resize(audio_mask, (len(wav_raw),)) > 0
|
| 92 |
-
if return_raw_wav:
|
| 93 |
-
return wav_raw, audio_mask, sr
|
| 94 |
-
return wav_raw[audio_mask], audio_mask, sr
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def process_utterance(wav_path,
|
| 98 |
-
fft_size=1024,
|
| 99 |
-
hop_size=256,
|
| 100 |
-
win_length=1024,
|
| 101 |
-
window="hann",
|
| 102 |
-
num_mels=80,
|
| 103 |
-
fmin=80,
|
| 104 |
-
fmax=7600,
|
| 105 |
-
eps=1e-6,
|
| 106 |
-
sample_rate=22050,
|
| 107 |
-
loud_norm=False,
|
| 108 |
-
min_level_db=-100,
|
| 109 |
-
return_linear=False,
|
| 110 |
-
trim_long_sil=False, vocoder='pwg'):
|
| 111 |
-
if isinstance(wav_path, str) or isinstance(wav_path, BytesIO):
|
| 112 |
-
if trim_long_sil:
|
| 113 |
-
wav, _, _ = trim_long_silences(wav_path, sample_rate)
|
| 114 |
-
else:
|
| 115 |
-
wav, _ = librosa.core.load(wav_path, sr=sample_rate)
|
| 116 |
-
else:
|
| 117 |
-
wav = wav_path
|
| 118 |
-
if loud_norm:
|
| 119 |
-
meter = pyln.Meter(sample_rate) # create BS.1770 meter
|
| 120 |
-
loudness = meter.integrated_loudness(wav)
|
| 121 |
-
wav = pyln.normalize.loudness(wav, loudness, -22.0)
|
| 122 |
-
if np.abs(wav).max() > 1:
|
| 123 |
-
wav = wav / np.abs(wav).max()
|
| 124 |
-
|
| 125 |
-
# get amplitude spectrogram
|
| 126 |
-
x_stft = librosa.stft(wav, n_fft=fft_size, hop_length=hop_size,
|
| 127 |
-
win_length=win_length, window=window, pad_mode="constant")
|
| 128 |
-
spc = np.abs(x_stft) # (n_bins, T)
|
| 129 |
-
|
| 130 |
-
# get mel basis
|
| 131 |
-
fmin = 0 if fmin == -1 else fmin
|
| 132 |
-
fmax = sample_rate / 2 if fmax == -1 else fmax
|
| 133 |
-
mel_basis = librosa.filters.mel(sample_rate, fft_size, num_mels, fmin, fmax)
|
| 134 |
-
mel = mel_basis @ spc
|
| 135 |
-
|
| 136 |
-
if vocoder == 'pwg':
|
| 137 |
-
mel = np.log10(np.maximum(eps, mel)) # (n_mel_bins, T)
|
| 138 |
-
else:
|
| 139 |
-
assert False, f'"{vocoder}" is not in ["pwg"].'
|
| 140 |
-
|
| 141 |
-
l_pad, r_pad = audio.librosa_pad_lr(wav, fft_size, hop_size, 1)
|
| 142 |
-
wav = np.pad(wav, (l_pad, r_pad), mode='constant', constant_values=0.0)
|
| 143 |
-
wav = wav[:mel.shape[1] * hop_size]
|
| 144 |
-
|
| 145 |
-
if not return_linear:
|
| 146 |
-
return wav, mel
|
| 147 |
-
else:
|
| 148 |
-
spc = audio.amp_to_db(spc)
|
| 149 |
-
spc = audio.normalize(spc, {'min_level_db': min_level_db})
|
| 150 |
-
return wav, mel, spc
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
def get_pitch_parselmouth(wav_data, mel, hparams):
|
| 154 |
-
"""
|
| 155 |
-
|
| 156 |
-
:param wav_data: [T]
|
| 157 |
-
:param mel: [T, 80]
|
| 158 |
-
:param hparams:
|
| 159 |
-
:return:
|
| 160 |
-
"""
|
| 161 |
-
# time_step = hparams['hop_size'] / hparams['audio_sample_rate']
|
| 162 |
-
# f0_min = hparams['f0_min']
|
| 163 |
-
# f0_max = hparams['f0_max']
|
| 164 |
-
|
| 165 |
-
# if hparams['hop_size'] == 128:
|
| 166 |
-
# pad_size = 4
|
| 167 |
-
# elif hparams['hop_size'] == 256:
|
| 168 |
-
# pad_size = 2
|
| 169 |
-
# else:
|
| 170 |
-
# assert False
|
| 171 |
-
|
| 172 |
-
# f0 = parselmouth.Sound(wav_data, hparams['audio_sample_rate']).to_pitch_ac(
|
| 173 |
-
# time_step=time_step, voicing_threshold=0.6,
|
| 174 |
-
# pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
|
| 175 |
-
# lpad = pad_size * 2
|
| 176 |
-
# rpad = len(mel) - len(f0) - lpad
|
| 177 |
-
# f0 = np.pad(f0, [[lpad, rpad]], mode='constant')
|
| 178 |
-
# # mel and f0 are extracted by 2 different libraries. we should force them to have the same length.
|
| 179 |
-
# # Attention: we find that new version of some libraries could cause ``rpad'' to be a negetive value...
|
| 180 |
-
# # Just to be sure, we recommend users to set up the same environments as them in requirements_auto.txt (by Anaconda)
|
| 181 |
-
# delta_l = len(mel) - len(f0)
|
| 182 |
-
# assert np.abs(delta_l) <= 8
|
| 183 |
-
# if delta_l > 0:
|
| 184 |
-
# f0 = np.concatenate([f0, [f0[-1]] * delta_l], 0)
|
| 185 |
-
# f0 = f0[:len(mel)]
|
| 186 |
-
# pad_size=(int(len(wav_data) // hparams['hop_size']) - len(f0) + 1) // 2
|
| 187 |
-
# f0 = np.pad(f0,[[pad_size,len(mel) - len(f0) - pad_size]], mode='constant')
|
| 188 |
-
# pitch_coarse = f0_to_coarse(f0, hparams)
|
| 189 |
-
# return f0, pitch_coarse
|
| 190 |
-
|
| 191 |
-
# Bye bye Parselmouth !
|
| 192 |
-
return get_pitch_world(wav_data, mel, hparams)
|
| 193 |
-
|
| 194 |
-
def get_pitch_world(wav_data, mel, hparams):
|
| 195 |
-
"""
|
| 196 |
-
|
| 197 |
-
:param wav_data: [T]
|
| 198 |
-
:param mel: [T, 80]
|
| 199 |
-
:param hparams:
|
| 200 |
-
:return:
|
| 201 |
-
"""
|
| 202 |
-
time_step = 1000 * hparams['hop_size'] / hparams['audio_sample_rate']
|
| 203 |
-
f0_min = hparams['f0_min']
|
| 204 |
-
f0_max = hparams['f0_max']
|
| 205 |
-
|
| 206 |
-
# Here's to hoping it uses numpy stuff !
|
| 207 |
-
f0, _ = world.harvest(wav_data.astype(np.double), hparams['audio_sample_rate'], f0_min, f0_max, time_step)
|
| 208 |
-
|
| 209 |
-
# Change padding
|
| 210 |
-
len_diff = len(mel) - len(f0)
|
| 211 |
-
if len_diff > 0:
|
| 212 |
-
pad_len = (len_diff + 1) // 2
|
| 213 |
-
f0 = np.pad(f0, [[pad_len, len_diff - pad_len]])
|
| 214 |
-
else:
|
| 215 |
-
pad_len = (1 - len_diff) // 2
|
| 216 |
-
rpad = pad_len + len_diff
|
| 217 |
-
if rpad != 0:
|
| 218 |
-
f0 = f0[pad_len:rpad]
|
| 219 |
-
f0 = f0[pad_len:]
|
| 220 |
-
pitch_coarse = f0_to_coarse(f0, hparams)
|
| 221 |
-
return f0, pitch_coarse
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
def get_pitch_crepe(wav_data, mel, hparams, threshold=0.05):
|
| 225 |
-
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 226 |
-
device = torch.device("cuda")
|
| 227 |
-
# crepe只支持16khz采样率,需要重采样
|
| 228 |
-
wav16k = resampy.resample(wav_data, hparams['audio_sample_rate'], 16000)
|
| 229 |
-
wav16k_torch = torch.FloatTensor(wav16k).unsqueeze(0).to(device)
|
| 230 |
-
|
| 231 |
-
# 频率范围
|
| 232 |
-
f0_min = hparams['f0_min']
|
| 233 |
-
f0_max = hparams['f0_max']
|
| 234 |
-
|
| 235 |
-
# 重采样后按照hopsize=80,也就是5ms一帧分析f0
|
| 236 |
-
f0, pd = torchcrepe.predict(wav16k_torch, 16000, 80, f0_min, f0_max, pad=True, model='full', batch_size=1024,
|
| 237 |
-
device=device, return_periodicity=True)
|
| 238 |
-
|
| 239 |
-
# 滤波,去掉静音,设置uv阈值,参考原仓库readme
|
| 240 |
-
pd = torchcrepe.filter.median(pd, 3)
|
| 241 |
-
pd = torchcrepe.threshold.Silence(-60.)(pd, wav16k_torch, 16000, 80)
|
| 242 |
-
f0 = torchcrepe.threshold.At(threshold)(f0, pd)
|
| 243 |
-
f0 = torchcrepe.filter.mean(f0, 3)
|
| 244 |
-
|
| 245 |
-
# 将nan频率(uv部分)转换为0频率
|
| 246 |
-
f0 = torch.where(torch.isnan(f0), torch.full_like(f0, 0), f0)
|
| 247 |
-
|
| 248 |
-
'''
|
| 249 |
-
np.savetxt('问棋-crepe.csv',np.array([0.005*np.arange(len(f0[0])),f0[0].cpu().numpy()]).transpose(),delimiter=',')
|
| 250 |
-
'''
|
| 251 |
-
|
| 252 |
-
# 去掉0频率,并线性插值
|
| 253 |
-
nzindex = torch.nonzero(f0[0]).squeeze()
|
| 254 |
-
f0 = torch.index_select(f0[0], dim=0, index=nzindex).cpu().numpy()
|
| 255 |
-
time_org = 0.005 * nzindex.cpu().numpy()
|
| 256 |
-
time_frame = np.arange(len(mel)) * hparams['hop_size'] / hparams['audio_sample_rate']
|
| 257 |
-
if f0.shape[0] == 0:
|
| 258 |
-
f0 = torch.FloatTensor(time_frame.shape[0]).fill_(0)
|
| 259 |
-
print('f0 all zero!')
|
| 260 |
-
else:
|
| 261 |
-
f0 = np.interp(time_frame, time_org, f0, left=f0[0], right=f0[-1])
|
| 262 |
-
pitch_coarse = f0_to_coarse(f0, hparams)
|
| 263 |
-
return f0, pitch_coarse
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
def remove_empty_lines(text):
|
| 267 |
-
"""remove empty lines"""
|
| 268 |
-
assert (len(text) > 0)
|
| 269 |
-
assert (isinstance(text, list))
|
| 270 |
-
text = [t.strip() for t in text]
|
| 271 |
-
if "" in text:
|
| 272 |
-
text.remove("")
|
| 273 |
-
return text
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
class TextGrid(object):
|
| 277 |
-
def __init__(self, text):
|
| 278 |
-
text = remove_empty_lines(text)
|
| 279 |
-
self.text = text
|
| 280 |
-
self.line_count = 0
|
| 281 |
-
self._get_type()
|
| 282 |
-
self._get_time_intval()
|
| 283 |
-
self._get_size()
|
| 284 |
-
self.tier_list = []
|
| 285 |
-
self._get_item_list()
|
| 286 |
-
|
| 287 |
-
def _extract_pattern(self, pattern, inc):
|
| 288 |
-
"""
|
| 289 |
-
Parameters
|
| 290 |
-
----------
|
| 291 |
-
pattern : regex to extract pattern
|
| 292 |
-
inc : increment of line count after extraction
|
| 293 |
-
Returns
|
| 294 |
-
-------
|
| 295 |
-
group : extracted info
|
| 296 |
-
"""
|
| 297 |
-
try:
|
| 298 |
-
group = re.match(pattern, self.text[self.line_count]).group(1)
|
| 299 |
-
self.line_count += inc
|
| 300 |
-
except AttributeError:
|
| 301 |
-
raise ValueError("File format error at line %d:%s" % (self.line_count, self.text[self.line_count]))
|
| 302 |
-
return group
|
| 303 |
-
|
| 304 |
-
def _get_type(self):
|
| 305 |
-
self.file_type = self._extract_pattern(r"File type = \"(.*)\"", 2)
|
| 306 |
-
|
| 307 |
-
def _get_time_intval(self):
|
| 308 |
-
self.xmin = self._extract_pattern(r"xmin = (.*)", 1)
|
| 309 |
-
self.xmax = self._extract_pattern(r"xmax = (.*)", 2)
|
| 310 |
-
|
| 311 |
-
def _get_size(self):
|
| 312 |
-
self.size = int(self._extract_pattern(r"size = (.*)", 2))
|
| 313 |
-
|
| 314 |
-
def _get_item_list(self):
|
| 315 |
-
"""Only supports IntervalTier currently"""
|
| 316 |
-
for itemIdx in range(1, self.size + 1):
|
| 317 |
-
tier = OrderedDict()
|
| 318 |
-
item_list = []
|
| 319 |
-
tier_idx = self._extract_pattern(r"item \[(.*)\]:", 1)
|
| 320 |
-
tier_class = self._extract_pattern(r"class = \"(.*)\"", 1)
|
| 321 |
-
if tier_class != "IntervalTier":
|
| 322 |
-
raise NotImplementedError("Only IntervalTier class is supported currently")
|
| 323 |
-
tier_name = self._extract_pattern(r"name = \"(.*)\"", 1)
|
| 324 |
-
tier_xmin = self._extract_pattern(r"xmin = (.*)", 1)
|
| 325 |
-
tier_xmax = self._extract_pattern(r"xmax = (.*)", 1)
|
| 326 |
-
tier_size = self._extract_pattern(r"intervals: size = (.*)", 1)
|
| 327 |
-
for i in range(int(tier_size)):
|
| 328 |
-
item = OrderedDict()
|
| 329 |
-
item["idx"] = self._extract_pattern(r"intervals \[(.*)\]", 1)
|
| 330 |
-
item["xmin"] = self._extract_pattern(r"xmin = (.*)", 1)
|
| 331 |
-
item["xmax"] = self._extract_pattern(r"xmax = (.*)", 1)
|
| 332 |
-
item["text"] = self._extract_pattern(r"text = \"(.*)\"", 1)
|
| 333 |
-
item_list.append(item)
|
| 334 |
-
tier["idx"] = tier_idx
|
| 335 |
-
tier["class"] = tier_class
|
| 336 |
-
tier["name"] = tier_name
|
| 337 |
-
tier["xmin"] = tier_xmin
|
| 338 |
-
tier["xmax"] = tier_xmax
|
| 339 |
-
tier["size"] = tier_size
|
| 340 |
-
tier["items"] = item_list
|
| 341 |
-
self.tier_list.append(tier)
|
| 342 |
-
|
| 343 |
-
def toJson(self):
|
| 344 |
-
_json = OrderedDict()
|
| 345 |
-
_json["file_type"] = self.file_type
|
| 346 |
-
_json["xmin"] = self.xmin
|
| 347 |
-
_json["xmax"] = self.xmax
|
| 348 |
-
_json["size"] = self.size
|
| 349 |
-
_json["tiers"] = self.tier_list
|
| 350 |
-
return json.dumps(_json, ensure_ascii=False, indent=2)
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
def get_mel2ph(tg_fn, ph, mel, hparams):
|
| 354 |
-
ph_list = ph.split(" ")
|
| 355 |
-
with open(tg_fn, "r", encoding='utf-8') as f:
|
| 356 |
-
tg = f.readlines()
|
| 357 |
-
tg = remove_empty_lines(tg)
|
| 358 |
-
tg = TextGrid(tg)
|
| 359 |
-
tg = json.loads(tg.toJson())
|
| 360 |
-
split = np.ones(len(ph_list) + 1, np.float) * -1
|
| 361 |
-
tg_idx = 0
|
| 362 |
-
ph_idx = 0
|
| 363 |
-
tg_align = [x for x in tg['tiers'][-1]['items']]
|
| 364 |
-
tg_align_ = []
|
| 365 |
-
for x in tg_align:
|
| 366 |
-
x['xmin'] = float(x['xmin'])
|
| 367 |
-
x['xmax'] = float(x['xmax'])
|
| 368 |
-
if x['text'] in ['sil', 'sp', '', 'SIL', 'PUNC']:
|
| 369 |
-
x['text'] = ''
|
| 370 |
-
if len(tg_align_) > 0 and tg_align_[-1]['text'] == '':
|
| 371 |
-
tg_align_[-1]['xmax'] = x['xmax']
|
| 372 |
-
continue
|
| 373 |
-
tg_align_.append(x)
|
| 374 |
-
tg_align = tg_align_
|
| 375 |
-
tg_len = len([x for x in tg_align if x['text'] != ''])
|
| 376 |
-
ph_len = len([x for x in ph_list if not is_sil_phoneme(x)])
|
| 377 |
-
assert tg_len == ph_len, (tg_len, ph_len, tg_align, ph_list, tg_fn)
|
| 378 |
-
while tg_idx < len(tg_align) or ph_idx < len(ph_list):
|
| 379 |
-
if tg_idx == len(tg_align) and is_sil_phoneme(ph_list[ph_idx]):
|
| 380 |
-
split[ph_idx] = 1e8
|
| 381 |
-
ph_idx += 1
|
| 382 |
-
continue
|
| 383 |
-
x = tg_align[tg_idx]
|
| 384 |
-
if x['text'] == '' and ph_idx == len(ph_list):
|
| 385 |
-
tg_idx += 1
|
| 386 |
-
continue
|
| 387 |
-
assert ph_idx < len(ph_list), (tg_len, ph_len, tg_align, ph_list, tg_fn)
|
| 388 |
-
ph = ph_list[ph_idx]
|
| 389 |
-
if x['text'] == '' and not is_sil_phoneme(ph):
|
| 390 |
-
assert False, (ph_list, tg_align)
|
| 391 |
-
if x['text'] != '' and is_sil_phoneme(ph):
|
| 392 |
-
ph_idx += 1
|
| 393 |
-
else:
|
| 394 |
-
assert (x['text'] == '' and is_sil_phoneme(ph)) \
|
| 395 |
-
or x['text'].lower() == ph.lower() \
|
| 396 |
-
or x['text'].lower() == 'sil', (x['text'], ph)
|
| 397 |
-
split[ph_idx] = x['xmin']
|
| 398 |
-
if ph_idx > 0 and split[ph_idx - 1] == -1 and is_sil_phoneme(ph_list[ph_idx - 1]):
|
| 399 |
-
split[ph_idx - 1] = split[ph_idx]
|
| 400 |
-
ph_idx += 1
|
| 401 |
-
tg_idx += 1
|
| 402 |
-
assert tg_idx == len(tg_align), (tg_idx, [x['text'] for x in tg_align])
|
| 403 |
-
assert ph_idx >= len(ph_list) - 1, (ph_idx, ph_list, len(ph_list), [x['text'] for x in tg_align], tg_fn)
|
| 404 |
-
mel2ph = np.zeros([mel.shape[0]], np.int)
|
| 405 |
-
split[0] = 0
|
| 406 |
-
split[-1] = 1e8
|
| 407 |
-
for i in range(len(split) - 1):
|
| 408 |
-
assert split[i] != -1 and split[i] <= split[i + 1], (split[:-1],)
|
| 409 |
-
split = [int(s * hparams['audio_sample_rate'] / hparams['hop_size'] + 0.5) for s in split]
|
| 410 |
-
for ph_idx in range(len(ph_list)):
|
| 411 |
-
mel2ph[split[ph_idx]:split[ph_idx + 1]] = ph_idx + 1
|
| 412 |
-
mel2ph_torch = torch.from_numpy(mel2ph)
|
| 413 |
-
T_t = len(ph_list)
|
| 414 |
-
dur = mel2ph_torch.new_zeros([T_t + 1]).scatter_add(0, mel2ph_torch, torch.ones_like(mel2ph_torch))
|
| 415 |
-
dur = dur[1:].numpy()
|
| 416 |
-
return mel2ph, dur
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
def build_phone_encoder(data_dir):
|
| 420 |
-
phone_list_file = os.path.join(data_dir, 'phone_set.json')
|
| 421 |
-
phone_list = json.load(open(phone_list_file, encoding='utf-8'))
|
| 422 |
-
return TokenTextEncoder(None, vocab_list=phone_list, replace_oov=',')
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
def is_sil_phoneme(p):
|
| 426 |
-
return not p[0].isalpha()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocessing/hubertinfer.py
DELETED
|
@@ -1,42 +0,0 @@
|
|
| 1 |
-
import os.path
|
| 2 |
-
from io import BytesIO
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
|
| 5 |
-
import numpy as np
|
| 6 |
-
import torch
|
| 7 |
-
|
| 8 |
-
from network.hubert.hubert_model import hubert_soft, get_units
|
| 9 |
-
from network.hubert.vec_model import load_model, get_vec_units
|
| 10 |
-
from utils.hparams import hparams
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class Hubertencoder():
|
| 14 |
-
def __init__(self, pt_path=f'.checkpoints/hubert/hubert_soft.pt'):
|
| 15 |
-
if not 'use_vec' in hparams.keys():
|
| 16 |
-
hparams['use_vec'] = False
|
| 17 |
-
if hparams['use_vec']:
|
| 18 |
-
pt_path = f".checkpoints/vec/checkpoint_best_legacy_500.pt"
|
| 19 |
-
self.dev = torch.device("cuda")
|
| 20 |
-
self.hbt_model = load_model(pt_path)
|
| 21 |
-
else:
|
| 22 |
-
pt_path = list(Path(pt_path).parent.rglob('*.pt'))[0]
|
| 23 |
-
if 'hubert_gpu' in hparams.keys():
|
| 24 |
-
self.use_gpu = hparams['hubert_gpu']
|
| 25 |
-
else:
|
| 26 |
-
self.use_gpu = True
|
| 27 |
-
self.dev = torch.device("cuda" if self.use_gpu and torch.cuda.is_available() else "cpu")
|
| 28 |
-
self.hbt_model = hubert_soft(str(pt_path)).to(self.dev)
|
| 29 |
-
|
| 30 |
-
def encode(self, wav_path):
|
| 31 |
-
if isinstance(wav_path, BytesIO):
|
| 32 |
-
npy_path = ""
|
| 33 |
-
wav_path.seek(0)
|
| 34 |
-
else:
|
| 35 |
-
npy_path = Path(wav_path).with_suffix('.npy')
|
| 36 |
-
if os.path.exists(npy_path):
|
| 37 |
-
units = np.load(str(npy_path))
|
| 38 |
-
elif hparams['use_vec']:
|
| 39 |
-
units = get_vec_units(self.hbt_model, wav_path, self.dev).cpu().numpy()[0]
|
| 40 |
-
else:
|
| 41 |
-
units = get_units(self.hbt_model, wav_path, self.dev).cpu().numpy()[0]
|
| 42 |
-
return units # [T,256]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocessing/process_pipeline.py
DELETED
|
@@ -1,199 +0,0 @@
|
|
| 1 |
-
'''
|
| 2 |
-
file -> temporary_dict -> processed_input -> batch
|
| 3 |
-
'''
|
| 4 |
-
from utils.hparams import hparams
|
| 5 |
-
from network.vocoders.base_vocoder import VOCODERS
|
| 6 |
-
import numpy as np
|
| 7 |
-
import traceback
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
from .data_gen_utils import get_pitch_parselmouth,get_pitch_crepe
|
| 10 |
-
from .base_binarizer import BinarizationError
|
| 11 |
-
import torch
|
| 12 |
-
import utils
|
| 13 |
-
|
| 14 |
-
class File2Batch:
|
| 15 |
-
'''
|
| 16 |
-
pipeline: file -> temporary_dict -> processed_input -> batch
|
| 17 |
-
'''
|
| 18 |
-
|
| 19 |
-
@staticmethod
|
| 20 |
-
def file2temporary_dict():
|
| 21 |
-
'''
|
| 22 |
-
read from file, store data in temporary dicts
|
| 23 |
-
'''
|
| 24 |
-
raw_data_dir = Path(hparams['raw_data_dir'])
|
| 25 |
-
# meta_midi = json.load(open(os.path.join(raw_data_dir, 'meta.json'))) # [list of dict]
|
| 26 |
-
|
| 27 |
-
# if hparams['perform_enhance'] and not hparams['infer']:
|
| 28 |
-
# vocoder=get_vocoder_cls(hparams)()
|
| 29 |
-
# raw_files = list(raw_data_dir.rglob(f"*.wav"))
|
| 30 |
-
# dic=[]
|
| 31 |
-
# time_step = hparams['hop_size'] / hparams['audio_sample_rate']
|
| 32 |
-
# f0_min = hparams['f0_min']
|
| 33 |
-
# f0_max = hparams['f0_max']
|
| 34 |
-
# for file in raw_files:
|
| 35 |
-
# y, sr = librosa.load(file, sr=hparams['audio_sample_rate'])
|
| 36 |
-
# f0 = parselmouth.Sound(y, hparams['audio_sample_rate']).to_pitch_ac(
|
| 37 |
-
# time_step=time_step , voicing_threshold=0.6,
|
| 38 |
-
# pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
|
| 39 |
-
# f0_mean=np.mean(f0[f0>0])
|
| 40 |
-
# dic.append(f0_mean)
|
| 41 |
-
# for idx in np.where(dic>np.percentile(dic, 80))[0]:
|
| 42 |
-
# file=raw_files[idx]
|
| 43 |
-
# wav,mel=vocoder.wav2spec(str(file))
|
| 44 |
-
# f0,_=get_pitch_parselmouth(wav,mel,hparams)
|
| 45 |
-
# f0[f0>0]=f0[f0>0]*(2**(2/12))
|
| 46 |
-
# wav_pred=vocoder.spec2wav(torch.FloatTensor(mel),f0=torch.FloatTensor(f0))
|
| 47 |
-
# sf.write(file.with_name(file.name[:-4]+'_high.wav'), wav_pred, 24000, 'PCM_16')
|
| 48 |
-
utterance_labels =[]
|
| 49 |
-
utterance_labels.extend(list(raw_data_dir.rglob(f"*.wav")))
|
| 50 |
-
utterance_labels.extend(list(raw_data_dir.rglob(f"*.ogg")))
|
| 51 |
-
#open(os.path.join(raw_data_dir, 'transcriptions.txt'), encoding='utf-8').readlines()
|
| 52 |
-
|
| 53 |
-
all_temp_dict = {}
|
| 54 |
-
for utterance_label in utterance_labels:
|
| 55 |
-
#song_info = utterance_label.split('|')
|
| 56 |
-
item_name =str(utterance_label)#raw_item_name = song_info[0]
|
| 57 |
-
# print(item_name)
|
| 58 |
-
temp_dict = {}
|
| 59 |
-
temp_dict['wav_fn'] =str(utterance_label)#f'{raw_data_dir}/wavs/{item_name}.wav'
|
| 60 |
-
# temp_dict['txt'] = song_info[1]
|
| 61 |
-
|
| 62 |
-
# temp_dict['ph'] = song_info[2]
|
| 63 |
-
# # self.item2wdb[item_name] = list(np.nonzero([1 if x in ALL_YUNMU + ['AP', 'SP'] else 0 for x in song_info[2].split()])[0])
|
| 64 |
-
# temp_dict['word_boundary'] = np.array([1 if x in ALL_YUNMU + ['AP', 'SP'] else 0 for x in song_info[2].split()])
|
| 65 |
-
# temp_dict['ph_durs'] = [float(x) for x in song_info[5].split(" ")]
|
| 66 |
-
|
| 67 |
-
# temp_dict['pitch_midi'] = np.array([note_to_midi(x.split("/")[0]) if x != 'rest' else 0
|
| 68 |
-
# for x in song_info[3].split(" ")])
|
| 69 |
-
# temp_dict['midi_dur'] = np.array([float(x) for x in song_info[4].split(" ")])
|
| 70 |
-
# temp_dict['is_slur'] = np.array([int(x) for x in song_info[6].split(" ")])
|
| 71 |
-
temp_dict['spk_id'] = hparams['speaker_id']
|
| 72 |
-
# assert temp_dict['pitch_midi'].shape == temp_dict['midi_dur'].shape == temp_dict['is_slur'].shape, \
|
| 73 |
-
# (temp_dict['pitch_midi'].shape, temp_dict['midi_dur'].shape, temp_dict['is_slur'].shape)
|
| 74 |
-
|
| 75 |
-
all_temp_dict[item_name] = temp_dict
|
| 76 |
-
|
| 77 |
-
return all_temp_dict
|
| 78 |
-
|
| 79 |
-
@staticmethod
|
| 80 |
-
def temporary_dict2processed_input(item_name, temp_dict, encoder, binarization_args):
|
| 81 |
-
'''
|
| 82 |
-
process data in temporary_dicts
|
| 83 |
-
'''
|
| 84 |
-
def get_pitch(wav, mel):
|
| 85 |
-
# get ground truth f0 by self.get_pitch_algorithm
|
| 86 |
-
if hparams['use_crepe']:
|
| 87 |
-
gt_f0, gt_pitch_coarse = get_pitch_crepe(wav, mel, hparams)
|
| 88 |
-
else:
|
| 89 |
-
gt_f0, gt_pitch_coarse = get_pitch_parselmouth(wav, mel, hparams)
|
| 90 |
-
if sum(gt_f0) == 0:
|
| 91 |
-
raise BinarizationError("Empty **gt** f0")
|
| 92 |
-
processed_input['f0'] = gt_f0
|
| 93 |
-
processed_input['pitch'] = gt_pitch_coarse
|
| 94 |
-
|
| 95 |
-
def get_align(meta_data, mel, phone_encoded, hop_size=hparams['hop_size'], audio_sample_rate=hparams['audio_sample_rate']):
|
| 96 |
-
mel2ph = np.zeros([mel.shape[0]], int)
|
| 97 |
-
start_frame=0
|
| 98 |
-
ph_durs = mel.shape[0]/phone_encoded.shape[0]
|
| 99 |
-
if hparams['debug']:
|
| 100 |
-
print(mel.shape,phone_encoded.shape,mel.shape[0]/phone_encoded.shape[0])
|
| 101 |
-
for i_ph in range(phone_encoded.shape[0]):
|
| 102 |
-
|
| 103 |
-
end_frame = int(i_ph*ph_durs +ph_durs+ 0.5)
|
| 104 |
-
mel2ph[start_frame:end_frame+1] = i_ph + 1
|
| 105 |
-
start_frame = end_frame+1
|
| 106 |
-
|
| 107 |
-
processed_input['mel2ph'] = mel2ph
|
| 108 |
-
|
| 109 |
-
if hparams['vocoder'] in VOCODERS:
|
| 110 |
-
wav, mel = VOCODERS[hparams['vocoder']].wav2spec(temp_dict['wav_fn'])
|
| 111 |
-
else:
|
| 112 |
-
wav, mel = VOCODERS[hparams['vocoder'].split('.')[-1]].wav2spec(temp_dict['wav_fn'])
|
| 113 |
-
processed_input = {
|
| 114 |
-
'item_name': item_name, 'mel': mel, 'wav': wav,
|
| 115 |
-
'sec': len(wav) / hparams['audio_sample_rate'], 'len': mel.shape[0]
|
| 116 |
-
}
|
| 117 |
-
processed_input = {**temp_dict, **processed_input} # merge two dicts
|
| 118 |
-
processed_input['spec_min']=np.min(mel,axis=0)
|
| 119 |
-
processed_input['spec_max']=np.max(mel,axis=0)
|
| 120 |
-
#(processed_input['spec_min'].shape)
|
| 121 |
-
try:
|
| 122 |
-
if binarization_args['with_f0']:
|
| 123 |
-
get_pitch(wav, mel)
|
| 124 |
-
if binarization_args['with_hubert']:
|
| 125 |
-
try:
|
| 126 |
-
hubert_encoded = processed_input['hubert'] = encoder.encode(temp_dict['wav_fn'])
|
| 127 |
-
except:
|
| 128 |
-
traceback.print_exc()
|
| 129 |
-
raise Exception(f"hubert encode error")
|
| 130 |
-
if binarization_args['with_align']:
|
| 131 |
-
get_align(temp_dict, mel, hubert_encoded)
|
| 132 |
-
except Exception as e:
|
| 133 |
-
print(f"| Skip item ({e}). item_name: {item_name}, wav_fn: {temp_dict['wav_fn']}")
|
| 134 |
-
return None
|
| 135 |
-
return processed_input
|
| 136 |
-
|
| 137 |
-
@staticmethod
|
| 138 |
-
def processed_input2batch(samples):
|
| 139 |
-
'''
|
| 140 |
-
Args:
|
| 141 |
-
samples: one batch of processed_input
|
| 142 |
-
NOTE:
|
| 143 |
-
the batch size is controlled by hparams['max_sentences']
|
| 144 |
-
'''
|
| 145 |
-
if len(samples) == 0:
|
| 146 |
-
return {}
|
| 147 |
-
id = torch.LongTensor([s['id'] for s in samples])
|
| 148 |
-
item_names = [s['item_name'] for s in samples]
|
| 149 |
-
#text = [s['text'] for s in samples]
|
| 150 |
-
#txt_tokens = utils.collate_1d([s['txt_token'] for s in samples], 0)
|
| 151 |
-
hubert = utils.collate_2d([s['hubert'] for s in samples], 0.0)
|
| 152 |
-
f0 = utils.collate_1d([s['f0'] for s in samples], 0.0)
|
| 153 |
-
pitch = utils.collate_1d([s['pitch'] for s in samples])
|
| 154 |
-
uv = utils.collate_1d([s['uv'] for s in samples])
|
| 155 |
-
energy = utils.collate_1d([s['energy'] for s in samples], 0.0)
|
| 156 |
-
mel2ph = utils.collate_1d([s['mel2ph'] for s in samples], 0.0) \
|
| 157 |
-
if samples[0]['mel2ph'] is not None else None
|
| 158 |
-
mels = utils.collate_2d([s['mel'] for s in samples], 0.0)
|
| 159 |
-
#txt_lengths = torch.LongTensor([s['txt_token'].numel() for s in samples])
|
| 160 |
-
hubert_lengths = torch.LongTensor([s['hubert'].shape[0] for s in samples])
|
| 161 |
-
mel_lengths = torch.LongTensor([s['mel'].shape[0] for s in samples])
|
| 162 |
-
|
| 163 |
-
batch = {
|
| 164 |
-
'id': id,
|
| 165 |
-
'item_name': item_names,
|
| 166 |
-
'nsamples': len(samples),
|
| 167 |
-
# 'text': text,
|
| 168 |
-
# 'txt_tokens': txt_tokens,
|
| 169 |
-
# 'txt_lengths': txt_lengths,
|
| 170 |
-
'hubert':hubert,
|
| 171 |
-
'mels': mels,
|
| 172 |
-
'mel_lengths': mel_lengths,
|
| 173 |
-
'mel2ph': mel2ph,
|
| 174 |
-
'energy': energy,
|
| 175 |
-
'pitch': pitch,
|
| 176 |
-
'f0': f0,
|
| 177 |
-
'uv': uv,
|
| 178 |
-
}
|
| 179 |
-
#========not used=================
|
| 180 |
-
# if hparams['use_spk_embed']:
|
| 181 |
-
# spk_embed = torch.stack([s['spk_embed'] for s in samples])
|
| 182 |
-
# batch['spk_embed'] = spk_embed
|
| 183 |
-
# if hparams['use_spk_id']:
|
| 184 |
-
# spk_ids = torch.LongTensor([s['spk_id'] for s in samples])
|
| 185 |
-
# batch['spk_ids'] = spk_ids
|
| 186 |
-
# if hparams['pitch_type'] == 'cwt':
|
| 187 |
-
# cwt_spec = utils.collate_2d([s['cwt_spec'] for s in samples])
|
| 188 |
-
# f0_mean = torch.Tensor([s['f0_mean'] for s in samples])
|
| 189 |
-
# f0_std = torch.Tensor([s['f0_std'] for s in samples])
|
| 190 |
-
# batch.update({'cwt_spec': cwt_spec, 'f0_mean': f0_mean, 'f0_std': f0_std})
|
| 191 |
-
# elif hparams['pitch_type'] == 'ph':
|
| 192 |
-
# batch['f0'] = utils.collate_1d([s['f0_ph'] for s in samples])
|
| 193 |
-
|
| 194 |
-
# batch['pitch_midi'] = utils.collate_1d([s['pitch_midi'] for s in samples], 0)
|
| 195 |
-
# batch['midi_dur'] = utils.collate_1d([s['midi_dur'] for s in samples], 0)
|
| 196 |
-
# batch['is_slur'] = utils.collate_1d([s['is_slur'] for s in samples], 0)
|
| 197 |
-
# batch['word_boundary'] = utils.collate_1d([s['word_boundary'] for s in samples], 0)
|
| 198 |
-
|
| 199 |
-
return batch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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