upload p3
Browse filesFiles changed (18)
- checkpoints/FastDiff/config.yamlAdded+149
- checkpoints/FastDiff/model_ckpt_steps_500000.ckptAdded+3
- checkpoints/ProDiff/config.yamlAdded+205
- checkpoints/ProDiff/model_ckpt_steps_200000.ckptAdded+3
- checkpoints/ProDiff_Teacher/config.yamlAdded+205
- checkpoints/ProDiff_Teacher/model_ckpt_steps_188000.ckptAdded+3
- data_gen/tts/base_binarizer.pyAdded+224
- data_gen/tts/base_preprocess.pyAdded+245
- data_gen/tts/bin/binarize.pyAdded+20
- data_gen/tts/bin/pre_align.pyAdded+20
- data_gen/tts/bin/train_mfa_align.pyAdded+15
- data_gen/tts/data_gen_utils.pyAdded+352
- data_gen/tts/txt_processors/__init__.pyAdded+1
- data_gen/tts/txt_processors/base_text_processor.pyAdded+47
- data_gen/tts/txt_processors/en.pyAdded+77
- data_gen/tts/wav_processors/__init__.pyAdded+2
- data_gen/tts/wav_processors/base_processor.pyAdded+25
- data_gen/tts/wav_processors/common_processors.pyAdded+86
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149N: ''T: 1000accumulate_grad_batches: 1amp: falseaudio_channels: 1audio_num_mel_bins: 80audio_sample_rate: 22050aux_context_window: 0beta_0: 1.0e-06beta_T: 0.01binarization_args: reset_phone_dict: true reset_word_dict: true shuffle: false trim_eos_bos: false with_align: false with_f0: false with_f0cwt: false with_linear: false with_spk_embed: false with_spk_id: true with_txt: false with_wav: true with_word: falsebinarizer_cls: data_gen.tts.vocoder_binarizer.VocoderBinarizerbinary_data_dir: data/binary/LJSpeechcheck_val_every_n_epoch: 10clip_grad_norm: 1clip_grad_value: 0cond_channels: 80debug: falsedec_ffn_kernel_size: 9dec_layers: 4dict_dir: ''diffusion_step_embed_dim_in: 128diffusion_step_embed_dim_mid: 512diffusion_step_embed_dim_out: 512disc_start_steps: 40000discriminator_grad_norm: 1dropout: 0.0ds_workers: 1enc_ffn_kernel_size: 9enc_layers: 4endless_ds: trueeval_max_batches: -1ffn_act: geluffn_padding: SAMEfft_size: 1024fmax: 7600fmin: 80frames_multiple: 1gen_dir_name: ''generator_grad_norm: 10griffin_lim_iters: 60hidden_size: 256hop_size: 256infer: falseinner_channels: 32kpnet_conv_size: 3kpnet_hidden_channels: 64load_ckpt: ''loud_norm: falselr: 2e-4lvc_kernel_size: 3lvc_layers_each_block: 4max_epochs: 1000max_frames: 1548max_input_tokens: 1550max_samples: 25600max_sentences: 20max_tokens: 30000max_updates: 1000000max_valid_sentences: 1max_valid_tokens: 60000mel_loss: l1mel_vmax: 1.5mel_vmin: -6mfa_version: 2min_frames: 0min_level_db: -100noise_schedule: ''num_ckpt_keep: 3num_heads: 2num_mels: 80num_sanity_val_steps: -1num_spk: 400num_test_samples: 0num_valid_plots: 10optimizer_adam_beta1: 0.9optimizer_adam_beta2: 0.98out_wav_norm: falsepitch_extractor: parselmouthpre_align_args: allow_no_txt: false denoise: false nsample_per_mfa_group: 1000 sox_resample: false sox_to_wav: false trim_sil: false txt_processor: en use_tone: truepre_align_cls: egs.datasets.audio.pre_align.PreAlignprint_nan_grads: falseprocessed_data_dir: data/processed/LJSpeechprofile_infer: falseraw_data_dir: data/raw/LJSpeech-1.1ref_level_db: 20rename_tmux: trueresume_from_checkpoint: 0save_best: truesave_codes: []save_f0: falsesave_gt: truescheduler: rsqrtseed: 1234sort_by_len: truetask_cls: modules.FastDiff.task.FastDiff.FastDiffTasktb_log_interval: 100test_ids: []test_input_dir: ''test_mel_dir: ''test_num: 100test_set_name: testtrain_set_name: traintrain_sets: ''upsample_ratios:- 8- 8- 4use_pitch_embed: falseuse_spk_embed: falseuse_spk_id: falseuse_split_spk_id: falseuse_wav: trueuse_weight_norm: trueuse_word_input: falseval_check_interval: 2000valid_infer_interval: 10000valid_monitor_key: val_lossvalid_monitor_mode: minvalid_set_name: validvocoder_denoise_c: 0.0warmup_updates: 8000weight_decay: 0win_length: nullwin_size: 1024window: hannword_size: 30000work_dir: checkpoints/FastDiff123version https://git-lfs.github.com/spec/v1oid sha256:ee7b6022e525c71a6025b41eeeafff9d6186b52cba76b580d6986bc8674902f3size 183951271123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205accumulate_grad_batches: 1amp: falseaudio_num_mel_bins: 80audio_sample_rate: 22050base_config:- ./base.yamlbinarization_args: reset_phone_dict: true reset_word_dict: true shuffle: false trim_eos_bos: false trim_sil: false with_align: true with_f0: true with_f0cwt: false with_linear: false with_spk_embed: false with_spk_id: true with_txt: true with_wav: false with_word: truebinarizer_cls: data_gen.tts.base_binarizer.BaseBinarizerbinary_data_dir: data/binary/LJSpeechcheck_val_every_n_epoch: 10clip_grad_norm: 1clip_grad_value: 0conv_use_pos: falsecwt_add_f0_loss: falsecwt_hidden_size: 128cwt_layers: 2cwt_loss: l1cwt_std_scale: 0.8debug: falsedec_dilations:- 1- 1- 1- 1dec_ffn_kernel_size: 9dec_inp_add_noise: falsedec_kernel_size: 5dec_layers: 4dec_num_heads: 2decoder_rnn_dim: 0decoder_type: fftdict_dir: ''diff_decoder_type: wavenetdiff_loss_type: l1dilation_cycle_length: 1dropout: 0.1ds_workers: 2dur_enc_hidden_stride_kernel:- 0,2,3- 0,2,3- 0,1,3dur_loss: msedur_predictor_kernel: 3dur_predictor_layers: 2enc_dec_norm: lnenc_dilations:- 1- 1- 1- 1enc_ffn_kernel_size: 9enc_kernel_size: 5enc_layers: 4encoder_K: 8encoder_type: fftendless_ds: trueffn_act: geluffn_hidden_size: 1024ffn_padding: SAMEfft_size: 1024fmax: 7600fmin: 80frames_multiple: 1gen_dir_name: ''gen_tgt_spk_id: -1griffin_lim_iters: 60hidden_size: 256hop_size: 256infer: falsekeep_bins: 80lambda_commit: 0.25lambda_energy: 0.1lambda_f0: 1.0lambda_ph_dur: 0.1lambda_sent_dur: 1.0lambda_uv: 1.0lambda_word_dur: 1.0layers_in_block: 2load_ckpt: ''loud_norm: falselr: 1.0max_beta: 0.06max_epochs: 1000max_frames: 1548max_input_tokens: 1550max_sentences: 48max_tokens: 32000max_updates: 200000max_valid_sentences: 1max_valid_tokens: 60000mel_loss: ssim:0.5|l1:0.5mel_vmax: 1.5mel_vmin: -6min_frames: 0min_level_db: -100num_ckpt_keep: 3num_heads: 2num_sanity_val_steps: -1num_spk: 400num_test_samples: 0num_valid_plots: 10optimizer_adam_beta1: 0.9optimizer_adam_beta2: 0.98out_wav_norm: falsepitch_ar: falsepitch_embed_type: 0pitch_enc_hidden_stride_kernel:- 0,2,5- 0,2,5- 0,2,5pitch_extractor: parselmouthpitch_loss: l1pitch_norm: standardpitch_ssim_win: 11pitch_type: framepre_align_args: allow_no_txt: false denoise: false sox_resample: false sox_to_wav: false trim_sil: false txt_processor: en use_tone: truepre_align_cls: ''predictor_dropout: 0.5predictor_grad: 0.1predictor_hidden: -1predictor_kernel: 5predictor_layers: 2pretrain_fs_ckpt: ''print_nan_grads: falseprocessed_data_dir: data/processed/LJSpeechprofile_infer: falseraw_data_dir: data/raw/LJSpeechref_hidden_stride_kernel:- 0,3,5- 0,3,5- 0,2,5- 0,2,5- 0,2,5ref_level_db: 20ref_norm_layer: bnrename_tmux: trueresidual_channels: 256residual_layers: 20resume_from_checkpoint: 0save_best: truesave_codes: []save_f0: falsesave_gt: trueschedule_type: vpsdescheduler: rsqrtseed: 1234sil_add_noise: falsesort_by_len: truespec_max: []spec_min: []task_cls: modules.ProDiff.task.ProDiff_task.ProDiff_Tasktb_log_interval: 100teacher_ckpt: checkpoints/ProDiff_Teacher/model_ckpt_steps_188000.ckpttest_ids: []test_input_dir: ''test_num: 100test_set_name: testtimesteps: 4train_set_name: traintrain_sets: ''use_cond_disc: trueuse_energy_embed: trueuse_gt_dur: trueuse_gt_f0: trueuse_pitch_embed: trueuse_pos_embed: trueuse_ref_enc: falseuse_spk_embed: falseuse_spk_id: trueuse_split_spk_id: falseuse_uv: trueuse_var_enc: falseval_check_interval: 2000valid_infer_interval: 10000valid_monitor_key: val_lossvalid_monitor_mode: minvalid_set_name: validvar_enc_vq_codes: 64vocoder_denoise_c: 0.0warmup_updates: 2000weight_decay: 0win_size: 1024word_size: 30000work_dir: checkpoints/ProDiff123version https://git-lfs.github.com/spec/v1oid sha256:8cc8aad355c297b010e2c362341f736b3477744af76e02f6c9965409a7e9113asize 349055740123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205accumulate_grad_batches: 1amp: falseaudio_num_mel_bins: 80audio_sample_rate: 22050base_config:- ./base.yamlbinarization_args: reset_phone_dict: true reset_word_dict: true shuffle: false trim_eos_bos: false trim_sil: false with_align: true with_f0: true with_f0cwt: false with_linear: false with_spk_embed: false with_spk_id: true with_txt: true with_wav: false with_word: truebinarizer_cls: data_gen.tts.base_binarizer.BaseBinarizerbinary_data_dir: data/binary/LJSpeechcheck_val_every_n_epoch: 10clip_grad_norm: 1clip_grad_value: 0conv_use_pos: falsecwt_add_f0_loss: falsecwt_hidden_size: 128cwt_layers: 2cwt_loss: l1cwt_std_scale: 0.8debug: falsedec_dilations:- 1- 1- 1- 1dec_ffn_kernel_size: 9dec_inp_add_noise: falsedec_kernel_size: 5dec_layers: 4dec_num_heads: 2decoder_rnn_dim: 0decoder_type: fftdict_dir: ''diff_decoder_type: wavenetdiff_loss_type: l1dilation_cycle_length: 1dropout: 0.1ds_workers: 2dur_enc_hidden_stride_kernel:- 0,2,3- 0,2,3- 0,1,3dur_loss: msedur_predictor_kernel: 3dur_predictor_layers: 2enc_dec_norm: lnenc_dilations:- 1- 1- 1- 1enc_ffn_kernel_size: 9enc_kernel_size: 5enc_layers: 4encoder_K: 8encoder_type: fftendless_ds: trueffn_act: geluffn_hidden_size: 1024ffn_padding: SAMEfft_size: 1024fmax: 7600fmin: 80frames_multiple: 1gen_dir_name: ''gen_tgt_spk_id: -1griffin_lim_iters: 60hidden_size: 256hop_size: 256infer: falsekeep_bins: 80lambda_commit: 0.25lambda_energy: 0.1lambda_f0: 1.0lambda_ph_dur: 0.1lambda_sent_dur: 1.0lambda_uv: 1.0lambda_word_dur: 1.0layers_in_block: 2load_ckpt: ''loud_norm: falselr: 1.0max_beta: 0.06max_epochs: 1000max_frames: 1548max_input_tokens: 1550max_sentences: 48max_tokens: 32000max_updates: 200000max_valid_sentences: 1max_valid_tokens: 60000mel_loss: ssim:0.5|l1:0.5mel_vmax: 1.5mel_vmin: -6min_frames: 0min_level_db: -100num_ckpt_keep: 3num_heads: 2num_sanity_val_steps: -1num_spk: 400num_test_samples: 20num_valid_plots: 10optimizer_adam_beta1: 0.9optimizer_adam_beta2: 0.98out_wav_norm: falsepitch_ar: falsepitch_embed_type: 0pitch_enc_hidden_stride_kernel:- 0,2,5- 0,2,5- 0,2,5pitch_extractor: parselmouthpitch_loss: l1pitch_norm: standardpitch_ssim_win: 11pitch_type: framepre_align_args: allow_no_txt: false denoise: false sox_resample: false sox_to_wav: false trim_sil: false txt_processor: en use_tone: truepre_align_cls: egs.datasets.audio.lj.pre_align.LJPreAlignpredictor_dropout: 0.5predictor_grad: 0.1predictor_hidden: -1predictor_kernel: 5predictor_layers: 2pretrain_fs_ckpt: ''print_nan_grads: falseprocessed_data_dir: data/processed/LJSpeechprofile_infer: falseraw_data_dir: data/raw/LJSpeechref_hidden_stride_kernel:- 0,3,5- 0,3,5- 0,2,5- 0,2,5- 0,2,5ref_level_db: 20ref_norm_layer: bnrename_tmux: trueresidual_channels: 256residual_layers: 20resume_from_checkpoint: 0save_best: truesave_codes: []save_f0: falsesave_gt: trueschedule_type: vpsdescheduler: rsqrtseed: 1234sil_add_noise: falsesort_by_len: truespec_max: []spec_min: []task_cls: modules.ProDiff.task.ProDiff_teacher_task.ProDiff_teacher_Tasktb_log_interval: 100test_ids: []test_input_dir: ''test_num: 100test_set_name: testtimescale: 1timesteps: 4train_set_name: traintrain_sets: ''use_cond_disc: trueuse_energy_embed: trueuse_gt_dur: trueuse_gt_f0: trueuse_pitch_embed: trueuse_pos_embed: trueuse_ref_enc: falseuse_spk_embed: falseuse_spk_id: trueuse_split_spk_id: falseuse_uv: trueuse_var_enc: falseval_check_interval: 2000valid_infer_interval: 10000valid_monitor_key: val_lossvalid_monitor_mode: minvalid_set_name: validvar_enc_vq_codes: 64vocoder_denoise_c: 0.0warmup_updates: 2000weight_decay: 0win_size: 1024word_size: 30000work_dir: checkpoints/ProDiff_Teacher1123version https://git-lfs.github.com/spec/v1oid sha256:5d3d02a215431c69dd54c1413b9a02cdc32795e2039ad9be857b12e85c470eeasize 342252871123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224import osos.environ["OMP_NUM_THREADS"] = "1"
from utils.multiprocess_utils import chunked_multiprocess_runimport randomimport tracebackimport jsonfrom resemblyzer import VoiceEncoderfrom tqdm import tqdmfrom data_gen.tts.data_gen_utils import get_mel2ph, get_pitch, build_phone_encoderfrom utils.hparams import set_hparams, hparamsimport numpy as npfrom utils.indexed_datasets import IndexedDatasetBuilderfrom vocoders.base_vocoder import VOCODERSimport pandas as pd
class BinarizationError(Exception): pass
class BaseBinarizer: def __init__(self, processed_data_dir=None): if processed_data_dir is None: processed_data_dir = hparams['processed_data_dir'] self.processed_data_dirs = processed_data_dir.split(",") self.binarization_args = hparams['binarization_args'] self.pre_align_args = hparams['pre_align_args'] self.forced_align = self.pre_align_args['forced_align'] tg_dir = None if self.forced_align == 'mfa': tg_dir = 'mfa_outputs' if self.forced_align == 'kaldi': tg_dir = 'kaldi_outputs' self.item2txt = {} self.item2ph = {} self.item2wavfn = {} self.item2tgfn = {} self.item2spk = {} for ds_id, processed_data_dir in enumerate(self.processed_data_dirs): self.meta_df = pd.read_csv(f"{processed_data_dir}/metadata_phone.csv", dtype=str) for r_idx, r in self.meta_df.iterrows(): item_name = raw_item_name = r['item_name'] if len(self.processed_data_dirs) > 1: item_name = f'ds{ds_id}_{item_name}' self.item2txt[item_name] = r['txt'] self.item2ph[item_name] = r['ph'] self.item2wavfn[item_name] = os.path.join(hparams['raw_data_dir'], 'wavs', os.path.basename(r['wav_fn']).split('_')[1]) self.item2spk[item_name] = r.get('spk', 'SPK1') if len(self.processed_data_dirs) > 1: self.item2spk[item_name] = f"ds{ds_id}_{self.item2spk[item_name]}" if tg_dir is not None: self.item2tgfn[item_name] = f"{processed_data_dir}/{tg_dir}/{raw_item_name}.TextGrid" self.item_names = sorted(list(self.item2txt.keys())) if self.binarization_args['shuffle']: random.seed(1234) random.shuffle(self.item_names)
@property def train_item_names(self): return self.item_names[hparams['test_num']+hparams['valid_num']:]
@property def valid_item_names(self): return self.item_names[0: hparams['test_num']+hparams['valid_num']] #
@property def test_item_names(self): return self.item_names[0: hparams['test_num']] # Audios for MOS testing are in 'test_ids'
def build_spk_map(self): spk_map = set() for item_name in self.item_names: spk_name = self.item2spk[item_name] spk_map.add(spk_name) spk_map = {x: i for i, x in enumerate(sorted(list(spk_map)))} assert len(spk_map) == 0 or len(spk_map) <= hparams['num_spk'], len(spk_map) return spk_map
def item_name2spk_id(self, item_name): return self.spk_map[self.item2spk[item_name]]
def _phone_encoder(self): ph_set_fn = f"{hparams['binary_data_dir']}/phone_set.json" ph_set = [] if hparams['reset_phone_dict'] or not os.path.exists(ph_set_fn): for processed_data_dir in self.processed_data_dirs: ph_set += [x.split(' ')[0] for x in open(f'{processed_data_dir}/dict.txt').readlines()] ph_set = sorted(set(ph_set)) json.dump(ph_set, open(ph_set_fn, 'w')) else: ph_set = json.load(open(ph_set_fn, 'r')) print("| phone set: ", ph_set) return build_phone_encoder(hparams['binary_data_dir'])
def meta_data(self, prefix): if prefix == 'valid': item_names = self.valid_item_names elif prefix == 'test': item_names = self.test_item_names else: item_names = self.train_item_names for item_name in item_names: ph = self.item2ph[item_name] txt = self.item2txt[item_name] tg_fn = self.item2tgfn.get(item_name) wav_fn = self.item2wavfn[item_name] spk_id = self.item_name2spk_id(item_name) yield item_name, ph, txt, tg_fn, wav_fn, spk_id
def process(self): os.makedirs(hparams['binary_data_dir'], exist_ok=True) self.spk_map = self.build_spk_map() print("| spk_map: ", self.spk_map) spk_map_fn = f"{hparams['binary_data_dir']}/spk_map.json" json.dump(self.spk_map, open(spk_map_fn, 'w'))
self.phone_encoder = self._phone_encoder() self.process_data('valid') self.process_data('test') self.process_data('train')
def process_data(self, prefix): data_dir = hparams['binary_data_dir'] args = [] builder = IndexedDatasetBuilder(f'{data_dir}/{prefix}') lengths = [] f0s = [] total_sec = 0 if self.binarization_args['with_spk_embed']: voice_encoder = VoiceEncoder().cuda()
meta_data = list(self.meta_data(prefix)) for m in meta_data: args.append(list(m) + [self.phone_encoder, self.binarization_args]) num_workers = int(os.getenv('N_PROC', os.cpu_count() // 3)) for f_id, (_, item) in enumerate( zip(tqdm(meta_data), chunked_multiprocess_run(self.process_item, args, num_workers=num_workers))): if item is None: continue item['spk_embed'] = voice_encoder.embed_utterance(item['wav']) \ if self.binarization_args['with_spk_embed'] else None if not self.binarization_args['with_wav'] and 'wav' in item: print("del wav") del item['wav'] builder.add_item(item) lengths.append(item['len']) total_sec += item['sec'] if item.get('f0') is not None: f0s.append(item['f0']) builder.finalize() np.save(f'{data_dir}/{prefix}_lengths.npy', lengths) if len(f0s) > 0: f0s = np.concatenate(f0s, 0) f0s = f0s[f0s != 0] np.save(f'{data_dir}/{prefix}_f0s_mean_std.npy', [np.mean(f0s).item(), np.std(f0s).item()]) print(f"| {prefix} total duration: {total_sec:.3f}s")
@classmethod def process_item(cls, item_name, ph, txt, tg_fn, wav_fn, spk_id, encoder, binarization_args): if hparams['vocoder'] in VOCODERS: wav, mel = VOCODERS[hparams['vocoder']].wav2spec(wav_fn) else: wav, mel = VOCODERS[hparams['vocoder'].split('.')[-1]].wav2spec(wav_fn) res = { 'item_name': item_name, 'txt': txt, 'ph': ph, 'mel': mel, 'wav': wav, 'wav_fn': wav_fn, 'sec': len(wav) / hparams['audio_sample_rate'], 'len': mel.shape[0], 'spk_id': spk_id } try: if binarization_args['with_f0']: cls.get_pitch(wav, mel, res) if binarization_args['with_f0cwt']: cls.get_f0cwt(res['f0'], res) if binarization_args['with_txt']: try: phone_encoded = res['phone'] = encoder.encode(ph) except: traceback.print_exc() raise BinarizationError(f"Empty phoneme") if binarization_args['with_align']: cls.get_align(tg_fn, ph, mel, phone_encoded, res) except BinarizationError as e: print(f"| Skip item ({e}). item_name: {item_name}, wav_fn: {wav_fn}") return None return res
@staticmethod def get_align(tg_fn, ph, mel, phone_encoded, res): if tg_fn is not None and os.path.exists(tg_fn): mel2ph, dur = get_mel2ph(tg_fn, ph, mel, hparams) else: raise BinarizationError(f"Align not found") if mel2ph.max() - 1 >= len(phone_encoded): raise BinarizationError( f"Align does not match: mel2ph.max() - 1: {mel2ph.max() - 1}, len(phone_encoded): {len(phone_encoded)}") res['mel2ph'] = mel2ph res['dur'] = dur
@staticmethod def get_pitch(wav, mel, res): f0, pitch_coarse = get_pitch(wav, mel, hparams) if sum(f0) == 0: raise BinarizationError("Empty f0") res['f0'] = f0 res['pitch'] = pitch_coarse
@staticmethod def get_f0cwt(f0, res): from utils.cwt import get_cont_lf0, get_lf0_cwt uv, cont_lf0_lpf = get_cont_lf0(f0) logf0s_mean_org, logf0s_std_org = np.mean(cont_lf0_lpf), np.std(cont_lf0_lpf) cont_lf0_lpf_norm = (cont_lf0_lpf - logf0s_mean_org) / logf0s_std_org Wavelet_lf0, scales = get_lf0_cwt(cont_lf0_lpf_norm) if np.any(np.isnan(Wavelet_lf0)): raise BinarizationError("NaN CWT") res['cwt_spec'] = Wavelet_lf0 res['cwt_scales'] = scales res['f0_mean'] = logf0s_mean_org res['f0_std'] = logf0s_std_org
if __name__ == "__main__": set_hparams() BaseBinarizer().process()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245import jsonimport osimport randomimport reimport tracebackfrom collections import Counterfrom functools import partial
import librosafrom tqdm import tqdmfrom data_gen.tts.txt_processors.base_text_processor import get_txt_processor_clsfrom data_gen.tts.wav_processors.base_processor import get_wav_processor_clsfrom utils.hparams import hparamsfrom utils.multiprocess_utils import multiprocess_run_tqdmfrom utils.os_utils import link_file, move_file, remove_filefrom data_gen.tts.data_gen_utils import is_sil_phoneme, build_token_encoder
class BasePreprocessor: def __init__(self): self.preprocess_args = hparams['preprocess_args'] txt_processor = self.preprocess_args['txt_processor'] self.txt_processor = get_txt_processor_cls(txt_processor) self.raw_data_dir = hparams['raw_data_dir'] self.processed_dir = hparams['processed_data_dir'] self.spk_map_fn = f"{self.processed_dir}/spk_map.json"
def meta_data(self): """ :return: {'item_name': Str, 'wav_fn': Str, 'txt': Str, 'spk_name': Str, 'txt_loader': None or Func} """ raise NotImplementedError
def process(self): processed_dir = self.processed_dir wav_processed_tmp_dir = f'{processed_dir}/processed_tmp' remove_file(wav_processed_tmp_dir) os.makedirs(wav_processed_tmp_dir, exist_ok=True) wav_processed_dir = f'{processed_dir}/{self.wav_processed_dirname}' remove_file(wav_processed_dir) os.makedirs(wav_processed_dir, exist_ok=True)
meta_data = list(tqdm(self.meta_data(), desc='Load meta data')) item_names = [d['item_name'] for d in meta_data] assert len(item_names) == len(set(item_names)), 'Key `item_name` should be Unique.'
# preprocess data phone_list = [] word_list = [] spk_names = set() process_item = partial(self.preprocess_first_pass, txt_processor=self.txt_processor, wav_processed_dir=wav_processed_dir, wav_processed_tmp=wav_processed_tmp_dir, preprocess_args=self.preprocess_args) items = [] args = [{ 'item_name': item_raw['item_name'], 'txt_raw': item_raw['txt'], 'wav_fn': item_raw['wav_fn'], 'txt_loader': item_raw.get('txt_loader'), 'others': item_raw.get('others', None) } for item_raw in meta_data] for item_, (item_id, item) in zip(meta_data, multiprocess_run_tqdm(process_item, args, desc='Preprocess')): if item is not None: item_.update(item) item = item_ if 'txt_loader' in item: del item['txt_loader'] item['id'] = item_id item['spk_name'] = item.get('spk_name', '<SINGLE_SPK>') item['others'] = item.get('others', None) phone_list += item['ph'].split(" ") word_list += item['word'].split(" ") spk_names.add(item['spk_name']) items.append(item)
# add encoded tokens ph_encoder, word_encoder = self._phone_encoder(phone_list), self._word_encoder(word_list) spk_map = self.build_spk_map(spk_names) args = [{ 'ph': item['ph'], 'word': item['word'], 'spk_name': item['spk_name'], 'word_encoder': word_encoder, 'ph_encoder': ph_encoder, 'spk_map': spk_map } for item in items] for idx, item_new_kv in multiprocess_run_tqdm(self.preprocess_second_pass, args, desc='Add encoded tokens'): items[idx].update(item_new_kv)
# build mfa data if self.preprocess_args['use_mfa']: mfa_dict = set() mfa_input_dir = f'{processed_dir}/mfa_inputs' remove_file(mfa_input_dir) # group MFA inputs for better parallelism mfa_groups = [i // self.preprocess_args['nsample_per_mfa_group'] for i in range(len(items))] if self.preprocess_args['mfa_group_shuffle']: random.seed(hparams['seed']) random.shuffle(mfa_groups) args = [{ 'item': item, 'mfa_input_dir': mfa_input_dir, 'mfa_group': mfa_group, 'wav_processed_tmp': wav_processed_tmp_dir, 'preprocess_args': self.preprocess_args } for item, mfa_group in zip(items, mfa_groups)] for i, (ph_gb_word_nosil, new_wav_align_fn) in multiprocess_run_tqdm( self.build_mfa_inputs, args, desc='Build MFA data'): items[i]['wav_align_fn'] = new_wav_align_fn for w in ph_gb_word_nosil.split(" "): mfa_dict.add(f"{w} {w.replace('_', ' ')}") mfa_dict = sorted(mfa_dict) with open(f'{processed_dir}/mfa_dict.txt', 'w') as f: f.writelines([f'{l}\n' for l in mfa_dict]) with open(f"{processed_dir}/{self.meta_csv_filename}.json", 'w') as f: f.write(re.sub(r'\n\s+([\d+\]])', r'\1', json.dumps(items, ensure_ascii=False, sort_keys=False, indent=1))) remove_file(wav_processed_tmp_dir)
@classmethod def preprocess_first_pass(cls, item_name, txt_raw, txt_processor, wav_fn, wav_processed_dir, wav_processed_tmp, preprocess_args, txt_loader=None, others=None): try: if txt_loader is not None: txt_raw = txt_loader(txt_raw) ph, txt, word, ph2word, ph_gb_word = cls.txt_to_ph(txt_processor, txt_raw, preprocess_args) wav_fn, wav_align_fn = cls.process_wav( item_name, wav_fn, hparams['processed_data_dir'], wav_processed_tmp, preprocess_args)
# wav for binarization ext = os.path.splitext(wav_fn)[1] os.makedirs(wav_processed_dir, exist_ok=True) new_wav_fn = f"{wav_processed_dir}/{item_name}{ext}" move_link_func = move_file if os.path.dirname(wav_fn) == wav_processed_tmp else link_file move_link_func(wav_fn, new_wav_fn) return { 'txt': txt, 'txt_raw': txt_raw, 'ph': ph, 'word': word, 'ph2word': ph2word, 'ph_gb_word': ph_gb_word, 'wav_fn': new_wav_fn, 'wav_align_fn': wav_align_fn, 'others': others } except: traceback.print_exc() print(f"| Error is caught. item_name: {item_name}.") return None
@staticmethod def txt_to_ph(txt_processor, txt_raw, preprocess_args): txt_struct, txt = txt_processor.process(txt_raw, preprocess_args) ph = [p for w in txt_struct for p in w[1]] return " ".join(ph), txt
@staticmethod def process_wav(item_name, wav_fn, processed_dir, wav_processed_tmp, preprocess_args): processors = [get_wav_processor_cls(v) for v in preprocess_args['wav_processors']] processors = [k() for k in processors if k is not None] if len(processors) >= 1: sr_file = librosa.core.get_samplerate(wav_fn) output_fn_for_align = None ext = os.path.splitext(wav_fn)[1] input_fn = f"{wav_processed_tmp}/{item_name}{ext}" link_file(wav_fn, input_fn) for p in processors: outputs = p.process(input_fn, sr_file, wav_processed_tmp, processed_dir, item_name, preprocess_args) if len(outputs) == 3: input_fn, sr, output_fn_for_align = outputs else: input_fn, sr = outputs return input_fn, output_fn_for_align else: return wav_fn, wav_fn
def _phone_encoder(self, ph_set): ph_set_fn = f"{self.processed_dir}/phone_set.json" if self.preprocess_args['reset_phone_dict'] or not os.path.exists(ph_set_fn): ph_set = sorted(set(ph_set)) json.dump(ph_set, open(ph_set_fn, 'w'), ensure_ascii=False) print("| Build phone set: ", ph_set) else: ph_set = json.load(open(ph_set_fn, 'r')) print("| Load phone set: ", ph_set) return build_token_encoder(ph_set_fn)
def _word_encoder(self, word_set): word_set_fn = f"{self.processed_dir}/word_set.json" if self.preprocess_args['reset_word_dict']: word_set = Counter(word_set) total_words = sum(word_set.values()) word_set = word_set.most_common(hparams['word_dict_size']) num_unk_words = total_words - sum([x[1] for x in word_set]) word_set = ['<BOS>', '<EOS>'] + [x[0] for x in word_set] word_set = sorted(set(word_set)) json.dump(word_set, open(word_set_fn, 'w'), ensure_ascii=False) print(f"| Build word set. Size: {len(word_set)}, #total words: {total_words}," f" #unk_words: {num_unk_words}, word_set[:10]:, {word_set[:10]}.") else: word_set = json.load(open(word_set_fn, 'r')) print("| Load word set. Size: ", len(word_set), word_set[:10]) return build_token_encoder(word_set_fn)
@classmethod def preprocess_second_pass(cls, word, ph, spk_name, word_encoder, ph_encoder, spk_map): word_token = word_encoder.encode(word) ph_token = ph_encoder.encode(ph) spk_id = spk_map[spk_name] return {'word_token': word_token, 'ph_token': ph_token, 'spk_id': spk_id}
def build_spk_map(self, spk_names): spk_map = {x: i for i, x in enumerate(sorted(list(spk_names)))} assert len(spk_map) == 0 or len(spk_map) <= hparams['num_spk'], len(spk_map) print(f"| Number of spks: {len(spk_map)}, spk_map: {spk_map}") json.dump(spk_map, open(self.spk_map_fn, 'w'), ensure_ascii=False) return spk_map
@classmethod def build_mfa_inputs(cls, item, mfa_input_dir, mfa_group, wav_processed_tmp, preprocess_args): item_name = item['item_name'] wav_align_fn = item['wav_align_fn'] ph_gb_word = item['ph_gb_word'] ext = os.path.splitext(wav_align_fn)[1] mfa_input_group_dir = f'{mfa_input_dir}/{mfa_group}' os.makedirs(mfa_input_group_dir, exist_ok=True) new_wav_align_fn = f"{mfa_input_group_dir}/{item_name}{ext}" move_link_func = move_file if os.path.dirname(wav_align_fn) == wav_processed_tmp else link_file move_link_func(wav_align_fn, new_wav_align_fn) ph_gb_word_nosil = " ".join(["_".join([p for p in w.split("_") if not is_sil_phoneme(p)]) for w in ph_gb_word.split(" ") if not is_sil_phoneme(w)]) with open(f'{mfa_input_group_dir}/{item_name}.lab', 'w') as f_txt: f_txt.write(ph_gb_word_nosil) return ph_gb_word_nosil, new_wav_align_fn
def load_spk_map(self, base_dir): spk_map_fn = f"{base_dir}/spk_map.json" spk_map = json.load(open(spk_map_fn, 'r')) return spk_map
def load_dict(self, base_dir): ph_encoder = build_token_encoder(f'{base_dir}/phone_set.json') return ph_encoder
@property def meta_csv_filename(self): return 'metadata'
@property def wav_processed_dirname(self): return 'wav_processed'1234567891011121314151617181920import os
os.environ["OMP_NUM_THREADS"] = "1"
import importlibfrom utils.hparams import set_hparams, hparams
def binarize(): binarizer_cls = hparams.get("binarizer_cls", 'data_gen.tts.base_binarizer.BaseBinarizer') pkg = ".".join(binarizer_cls.split(".")[:-1]) cls_name = binarizer_cls.split(".")[-1] binarizer_cls = getattr(importlib.import_module(pkg), cls_name) print("| Binarizer: ", binarizer_cls) binarizer_cls().process()
if __name__ == '__main__': set_hparams() binarize()1234567891011121314151617181920import os
os.environ["OMP_NUM_THREADS"] = "1"
import importlibfrom utils.hparams import set_hparams, hparams
def pre_align(): assert hparams['pre_align_cls'] != ''
pkg = ".".join(hparams["pre_align_cls"].split(".")[:-1]) cls_name = hparams["pre_align_cls"].split(".")[-1] process_cls = getattr(importlib.import_module(pkg), cls_name) process_cls().process()
if __name__ == '__main__': set_hparams() pre_align()123456789101112131415import subprocessfrom utils.hparams import hparams, set_hparamsimport os
def train_mfa_align(): CORPUS = hparams['processed_data_dir'].split("/")[-1] print(f"| Run MFA for {CORPUS}.") NUM_JOB = int(os.getenv('N_PROC', os.cpu_count())) subprocess.check_call(f'CORPUS={CORPUS} NUM_JOB={NUM_JOB} bash usr/run_mfa_train_align.sh', shell=True)
if __name__ == '__main__': set_hparams(print_hparams=False) train_mfa_align()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352import warnings
warnings.filterwarnings("ignore")
# import parselmouthimport osimport torchfrom skimage.transform import resizefrom utils.text_encoder import TokenTextEncoderfrom utils.pitch_utils import f0_to_coarseimport structimport webrtcvadfrom scipy.ndimage.morphology import binary_dilationimport librosaimport numpy as npfrom utils import audioimport pyloudnorm as pylnimport reimport jsonfrom collections import OrderedDict
PUNCS = '!,.?;:'
int16_max = (2 ** 15) - 1
def trim_long_silences(path, sr=None, return_raw_wav=False, norm=True, vad_max_silence_length=12): """ Ensures that segments without voice in the waveform remain no longer than a threshold determined by the VAD parameters in params.py. :param wav: the raw waveform as a numpy array of floats :param vad_max_silence_length: Maximum number of consecutive silent frames a segment can have. :return: the same waveform with silences trimmed away (length <= original wav length) """
## Voice Activation Detection # Window size of the VAD. Must be either 10, 20 or 30 milliseconds. # This sets the granularity of the VAD. Should not need to be changed. sampling_rate = 16000 wav_raw, sr = librosa.core.load(path, sr=sr)
if norm: meter = pyln.Meter(sr) # create BS.1770 meter loudness = meter.integrated_loudness(wav_raw) wav_raw = pyln.normalize.loudness(wav_raw, loudness, -20.0) if np.abs(wav_raw).max() > 1.0: wav_raw = wav_raw / np.abs(wav_raw).max()
wav = librosa.resample(wav_raw, sr, sampling_rate, res_type='kaiser_best')
vad_window_length = 30 # In milliseconds # Number of frames to average together when performing the moving average smoothing. # The larger this value, the larger the VAD variations must be to not get smoothed out. vad_moving_average_width = 8
# Compute the voice detection window size samples_per_window = (vad_window_length * sampling_rate) // 1000
# Trim the end of the audio to have a multiple of the window size wav = wav[:len(wav) - (len(wav) % samples_per_window)]
# Convert the float waveform to 16-bit mono PCM pcm_wave = struct.pack("%dh" % len(wav), *(np.round(wav * int16_max)).astype(np.int16))
# Perform voice activation detection voice_flags = [] vad = webrtcvad.Vad(mode=3) for window_start in range(0, len(wav), samples_per_window): window_end = window_start + samples_per_window voice_flags.append(vad.is_speech(pcm_wave[window_start * 2:window_end * 2], sample_rate=sampling_rate)) voice_flags = np.array(voice_flags)
# Smooth the voice detection with a moving average def moving_average(array, width): array_padded = np.concatenate((np.zeros((width - 1) // 2), array, np.zeros(width // 2))) ret = np.cumsum(array_padded, dtype=float) ret[width:] = ret[width:] - ret[:-width] return ret[width - 1:] / width
audio_mask = moving_average(voice_flags, vad_moving_average_width) audio_mask = np.round(audio_mask).astype(np.bool)
# Dilate the voiced regions audio_mask = binary_dilation(audio_mask, np.ones(vad_max_silence_length + 1)) audio_mask = np.repeat(audio_mask, samples_per_window) audio_mask = resize(audio_mask, (len(wav_raw),)) > 0 if return_raw_wav: return wav_raw, audio_mask, sr return wav_raw[audio_mask], audio_mask, sr
def process_utterance(wav_path, fft_size=1024, hop_size=256, win_length=1024, window="hann", num_mels=80, fmin=80, fmax=7600, eps=1e-6, sample_rate=22050, loud_norm=False, min_level_db=-100, return_linear=False, trim_long_sil=False, vocoder='pwg'): if isinstance(wav_path, str): if trim_long_sil: wav, _, _ = trim_long_silences(wav_path, sample_rate) else: wav, _ = librosa.core.load(wav_path, sr=sample_rate) else: wav = wav_path
if loud_norm: meter = pyln.Meter(sample_rate) # create BS.1770 meter loudness = meter.integrated_loudness(wav) wav = pyln.normalize.loudness(wav, loudness, -22.0) if np.abs(wav).max() > 1: wav = wav / np.abs(wav).max()
# get amplitude spectrogram x_stft = librosa.stft(wav, n_fft=fft_size, hop_length=hop_size, win_length=win_length, window=window, pad_mode="constant") spc = np.abs(x_stft) # (n_bins, T)
# get mel basis fmin = 0 if fmin == -1 else fmin fmax = sample_rate / 2 if fmax == -1 else fmax mel_basis = librosa.filters.mel(sample_rate, fft_size, num_mels, fmin, fmax) mel = mel_basis @ spc
if vocoder == 'pwg': mel = np.log10(np.maximum(eps, mel)) # (n_mel_bins, T) else: assert False, f'"{vocoder}" is not in ["pwg"].'
l_pad, r_pad = audio.librosa_pad_lr(wav, fft_size, hop_size, 1) wav = np.pad(wav, (l_pad, r_pad), mode='constant', constant_values=0.0) wav = wav[:mel.shape[1] * hop_size]
if not return_linear: return wav, mel else: spc = audio.amp_to_db(spc) spc = audio.normalize(spc, {'min_level_db': min_level_db}) return wav, mel, spc
def get_pitch(wav_data, mel, hparams): """
:param wav_data: [T] :param mel: [T, 80] :param hparams: :return: """ time_step = hparams['hop_size'] / hparams['audio_sample_rate'] * 1000 f0_min = 80 f0_max = 750
if hparams['hop_size'] == 128: pad_size = 4 elif hparams['hop_size'] == 256: pad_size = 2 else: assert False
f0 = parselmouth.Sound(wav_data, hparams['audio_sample_rate']).to_pitch_ac( time_step=time_step / 1000, voicing_threshold=0.6, pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency'] lpad = pad_size * 2 rpad = len(mel) - len(f0) - lpad f0 = np.pad(f0, [[lpad, rpad]], mode='constant') # mel and f0 are extracted by 2 different libraries. we should force them to have the same length. # Attention: we find that new version of some libraries could cause ``rpad'' to be a negetive value... # Just to be sure, we recommend users to set up the same environments as them in requirements_auto.txt (by Anaconda) delta_l = len(mel) - len(f0) assert np.abs(delta_l) <= 8 if delta_l > 0: f0 = np.concatenate([f0, [f0[-1]] * delta_l], 0) f0 = f0[:len(mel)] pitch_coarse = f0_to_coarse(f0) return f0, pitch_coarse
def remove_empty_lines(text): """remove empty lines""" assert (len(text) > 0) assert (isinstance(text, list)) text = [t.strip() for t in text] if "" in text: text.remove("") return text
class TextGrid(object): def __init__(self, text): text = remove_empty_lines(text) self.text = text self.line_count = 0 self._get_type() self._get_time_intval() self._get_size() self.tier_list = [] self._get_item_list()
def _extract_pattern(self, pattern, inc): """ Parameters ---------- pattern : regex to extract pattern inc : increment of line count after extraction Returns ------- group : extracted info """ try: group = re.match(pattern, self.text[self.line_count]).group(1) self.line_count += inc except AttributeError: raise ValueError("File format error at line %d:%s" % (self.line_count, self.text[self.line_count])) return group
def _get_type(self): self.file_type = self._extract_pattern(r"File type = \"(.*)\"", 2)
def _get_time_intval(self): self.xmin = self._extract_pattern(r"xmin = (.*)", 1) self.xmax = self._extract_pattern(r"xmax = (.*)", 2)
def _get_size(self): self.size = int(self._extract_pattern(r"size = (.*)", 2))
def _get_item_list(self): """Only supports IntervalTier currently""" for itemIdx in range(1, self.size + 1): tier = OrderedDict() item_list = [] tier_idx = self._extract_pattern(r"item \[(.*)\]:", 1) tier_class = self._extract_pattern(r"class = \"(.*)\"", 1) if tier_class != "IntervalTier": raise NotImplementedError("Only IntervalTier class is supported currently") tier_name = self._extract_pattern(r"name = \"(.*)\"", 1) tier_xmin = self._extract_pattern(r"xmin = (.*)", 1) tier_xmax = self._extract_pattern(r"xmax = (.*)", 1) tier_size = self._extract_pattern(r"intervals: size = (.*)", 1) for i in range(int(tier_size)): item = OrderedDict() item["idx"] = self._extract_pattern(r"intervals \[(.*)\]", 1) item["xmin"] = self._extract_pattern(r"xmin = (.*)", 1) item["xmax"] = self._extract_pattern(r"xmax = (.*)", 1) item["text"] = self._extract_pattern(r"text = \"(.*)\"", 1) item_list.append(item) tier["idx"] = tier_idx tier["class"] = tier_class tier["name"] = tier_name tier["xmin"] = tier_xmin tier["xmax"] = tier_xmax tier["size"] = tier_size tier["items"] = item_list self.tier_list.append(tier)
def toJson(self): _json = OrderedDict() _json["file_type"] = self.file_type _json["xmin"] = self.xmin _json["xmax"] = self.xmax _json["size"] = self.size _json["tiers"] = self.tier_list return json.dumps(_json, ensure_ascii=False, indent=2)
def get_mel2ph(tg_fn, ph, mel, hparams): ph_list = ph.split(" ") with open(tg_fn, "r") as f: tg = f.readlines() tg = remove_empty_lines(tg) tg = TextGrid(tg) tg = json.loads(tg.toJson()) split = np.ones(len(ph_list) + 1, np.float) * -1 tg_idx = 0 ph_idx = 0 tg_align = [x for x in tg['tiers'][-1]['items']] tg_align_ = [] for x in tg_align: x['xmin'] = float(x['xmin']) x['xmax'] = float(x['xmax']) if x['text'] in ['sil', 'sp', '', 'SIL', 'PUNC']: x['text'] = '' if len(tg_align_) > 0 and tg_align_[-1]['text'] == '': tg_align_[-1]['xmax'] = x['xmax'] continue tg_align_.append(x) tg_align = tg_align_ tg_len = len([x for x in tg_align if x['text'] != '']) ph_len = len([x for x in ph_list if not is_sil_phoneme(x)]) assert tg_len == ph_len, (tg_len, ph_len, tg_align, ph_list, tg_fn) while tg_idx < len(tg_align) or ph_idx < len(ph_list): if tg_idx == len(tg_align) and is_sil_phoneme(ph_list[ph_idx]): split[ph_idx] = 1e8 ph_idx += 1 continue x = tg_align[tg_idx] if x['text'] == '' and ph_idx == len(ph_list): tg_idx += 1 continue assert ph_idx < len(ph_list), (tg_len, ph_len, tg_align, ph_list, tg_fn) ph = ph_list[ph_idx] if x['text'] == '' and not is_sil_phoneme(ph): assert False, (ph_list, tg_align) if x['text'] != '' and is_sil_phoneme(ph): ph_idx += 1 else: assert (x['text'] == '' and is_sil_phoneme(ph)) \ or x['text'].lower() == ph.lower() \ or x['text'].lower() == 'sil', (x['text'], ph) split[ph_idx] = x['xmin'] if ph_idx > 0 and split[ph_idx - 1] == -1 and is_sil_phoneme(ph_list[ph_idx - 1]): split[ph_idx - 1] = split[ph_idx] ph_idx += 1 tg_idx += 1 assert tg_idx == len(tg_align), (tg_idx, [x['text'] for x in tg_align]) assert ph_idx >= len(ph_list) - 1, (ph_idx, ph_list, len(ph_list), [x['text'] for x in tg_align], tg_fn) mel2ph = np.zeros([mel.shape[0]], np.int) split[0] = 0 split[-1] = 1e8 for i in range(len(split) - 1): assert split[i] != -1 and split[i] <= split[i + 1], (split[:-1],) split = [int(s * hparams['audio_sample_rate'] / hparams['hop_size'] + 0.5) for s in split] for ph_idx in range(len(ph_list)): mel2ph[split[ph_idx]:split[ph_idx + 1]] = ph_idx + 1 mel2ph_torch = torch.from_numpy(mel2ph) T_t = len(ph_list) dur = mel2ph_torch.new_zeros([T_t + 1]).scatter_add(0, mel2ph_torch, torch.ones_like(mel2ph_torch)) dur = dur[1:].numpy() return mel2ph, dur
def build_phone_encoder(data_dir): phone_list_file = os.path.join(data_dir, 'phone_set.json') phone_list = json.load(open(phone_list_file)) return TokenTextEncoder(None, vocab_list=phone_list, replace_oov=',')
def is_sil_phoneme(p): return not p[0].isalpha()
def build_token_encoder(token_list_file): token_list = json.load(open(token_list_file)) return TokenTextEncoder(None, vocab_list=token_list, replace_oov='<UNK>')1from . import en1234567891011121314151617181920212223242526272829303132333435363738394041424344454647from data_gen.tts.data_gen_utils import is_sil_phoneme
REGISTERED_TEXT_PROCESSORS = {}
def register_txt_processors(name): def _f(cls): REGISTERED_TEXT_PROCESSORS[name] = cls return cls
return _f
def get_txt_processor_cls(name): return REGISTERED_TEXT_PROCESSORS.get(name, None)
class BaseTxtProcessor: @staticmethod def sp_phonemes(): return ['|']
@classmethod def process(cls, txt, preprocess_args): raise NotImplementedError
@classmethod def postprocess(cls, txt_struct, preprocess_args): # remove sil phoneme in head and tail while len(txt_struct) > 0 and is_sil_phoneme(txt_struct[0][0]): txt_struct = txt_struct[1:] while len(txt_struct) > 0 and is_sil_phoneme(txt_struct[-1][0]): txt_struct = txt_struct[:-1] if preprocess_args['with_phsep']: txt_struct = cls.add_bdr(txt_struct) if preprocess_args['add_eos_bos']: txt_struct = [["<BOS>", ["<BOS>"]]] + txt_struct + [["<EOS>", ["<EOS>"]]] return txt_struct
@classmethod def add_bdr(cls, txt_struct): txt_struct_ = [] for i, ts in enumerate(txt_struct): txt_struct_.append(ts) if i != len(txt_struct) - 1 and \ not is_sil_phoneme(txt_struct[i][0]) and not is_sil_phoneme(txt_struct[i + 1][0]): txt_struct_.append(['|', ['|']]) return txt_struct_1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import reimport unicodedata
from g2p_en import G2pfrom g2p_en.expand import normalize_numbersfrom nltk import pos_tagfrom nltk.tokenize import TweetTokenizer
from data_gen.tts.txt_processors.base_text_processor import BaseTxtProcessor, register_txt_processorsfrom data_gen.tts.data_gen_utils import is_sil_phoneme, PUNCS
class EnG2p(G2p): word_tokenize = TweetTokenizer().tokenize
def __call__(self, text): # preprocessing words = EnG2p.word_tokenize(text) tokens = pos_tag(words) # tuples of (word, tag)
# steps prons = [] for word, pos in tokens: if re.search("[a-z]", word) is None: pron = [word]
elif word in self.homograph2features: # Check homograph pron1, pron2, pos1 = self.homograph2features[word] if pos.startswith(pos1): pron = pron1 else: pron = pron2 elif word in self.cmu: # lookup CMU dict pron = self.cmu[word][0] else: # predict for oov pron = self.predict(word)
prons.extend(pron) prons.extend([" "])
return prons[:-1]
@register_txt_processors('en')class TxtProcessor(BaseTxtProcessor): g2p = EnG2p()
@staticmethod def preprocess_text(text): text = normalize_numbers(text) text = ''.join(char for char in unicodedata.normalize('NFD', text) if unicodedata.category(char) != 'Mn') # Strip accents text = text.lower() text = re.sub("[\'\"()]+", "", text) text = re.sub("[-]+", " ", text) text = re.sub(f"[^ a-z{PUNCS}]", "", text) text = re.sub(f" ?([{PUNCS}]) ?", r"\1", text) # !! -> ! text = re.sub(f"([{PUNCS}])+", r"\1", text) # !! -> ! text = text.replace("i.e.", "that is") text = text.replace("i.e.", "that is") text = text.replace("etc.", "etc") text = re.sub(f"([{PUNCS}])", r" \1 ", text) text = re.sub(rf"\s+", r" ", text) return text
@classmethod def process(cls, txt, preprocess_args): txt = cls.preprocess_text(txt).strip() phs = cls.g2p(txt) txt_struct = [[w, []] for w in txt.split(" ")] i_word = 0 for p in phs: if p == ' ': i_word += 1 else: txt_struct[i_word][1].append(p) txt_struct = cls.postprocess(txt_struct, preprocess_args) return txt_struct, txt12from . import base_processorfrom . import common_processors12345678910111213141516171819202122232425REGISTERED_WAV_PROCESSORS = {}
def register_wav_processors(name): def _f(cls): REGISTERED_WAV_PROCESSORS[name] = cls return cls
return _f
def get_wav_processor_cls(name): return REGISTERED_WAV_PROCESSORS.get(name, None)
class BaseWavProcessor: @property def name(self): raise NotImplementedError
def output_fn(self, input_fn): return f'{input_fn[:-4]}_{self.name}.wav'
def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args): raise NotImplementedError1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import osimport subprocessimport librosaimport numpy as npfrom data_gen.tts.wav_processors.base_processor import BaseWavProcessor, register_wav_processorsfrom data_gen.tts.data_gen_utils import trim_long_silencesfrom utils.audio import save_wavfrom utils.rnnoise import rnnoisefrom utils.hparams import hparams
@register_wav_processors(name='sox_to_wav')class ConvertToWavProcessor(BaseWavProcessor): @property def name(self): return 'ToWav'
def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args): if input_fn[-4:] == '.wav': return input_fn, sr else: output_fn = self.output_fn(input_fn) subprocess.check_call(f'sox -v 0.95 "{input_fn}" -t wav "{output_fn}"', shell=True) return output_fn, sr
@register_wav_processors(name='sox_resample')class ResampleProcessor(BaseWavProcessor): @property def name(self): return 'Resample'
def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args): output_fn = self.output_fn(input_fn) sr_file = librosa.core.get_samplerate(input_fn) if sr != sr_file: subprocess.check_call(f'sox -v 0.95 "{input_fn}" -r{sr} "{output_fn}"', shell=True) y, _ = librosa.core.load(input_fn, sr=sr) y, _ = librosa.effects.trim(y) save_wav(y, output_fn, sr) return output_fn, sr else: return input_fn, sr
@register_wav_processors(name='trim_sil')class TrimSILProcessor(BaseWavProcessor): @property def name(self): return 'TrimSIL'
def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args): output_fn = self.output_fn(input_fn) y, _ = librosa.core.load(input_fn, sr=sr) y, _ = librosa.effects.trim(y) save_wav(y, output_fn, sr) return output_fn
@register_wav_processors(name='trim_all_sil')class TrimAllSILProcessor(BaseWavProcessor): @property def name(self): return 'TrimSIL'
def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args): output_fn = self.output_fn(input_fn) y, audio_mask, _ = trim_long_silences( input_fn, vad_max_silence_length=preprocess_args.get('vad_max_silence_length', 12)) save_wav(y, output_fn, sr) if preprocess_args['save_sil_mask']: os.makedirs(f'{processed_dir}/sil_mask', exist_ok=True) np.save(f'{processed_dir}/sil_mask/{item_name}.npy', audio_mask) return output_fn, sr
@register_wav_processors(name='denoise')class DenoiseProcessor(BaseWavProcessor): @property def name(self): return 'Denoise'
def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args): output_fn = self.output_fn(input_fn) rnnoise(input_fn, output_fn, out_sample_rate=sr) return output_fn, srcheckpoints/FastDiff/config.yamlAdded+149
checkpoints/FastDiff/model_ckpt_steps_500000.ckptAdded+3
checkpoints/ProDiff/config.yamlAdded+205
checkpoints/ProDiff/model_ckpt_steps_200000.ckptAdded+3
checkpoints/ProDiff_Teacher/config.yamlAdded+205
checkpoints/ProDiff_Teacher/model_ckpt_steps_188000.ckptAdded+3
data_gen/tts/base_binarizer.pyAdded+224
data_gen/tts/base_preprocess.pyAdded+245
data_gen/tts/bin/binarize.pyAdded+20
data_gen/tts/bin/pre_align.pyAdded+20
data_gen/tts/bin/train_mfa_align.pyAdded+15
data_gen/tts/data_gen_utils.pyAdded+352
data_gen/tts/txt_processors/__init__.pyAdded+1
data_gen/tts/txt_processors/base_text_processor.pyAdded+47
data_gen/tts/txt_processors/en.pyAdded+77
data_gen/tts/wav_processors/__init__.pyAdded+2
data_gen/tts/wav_processors/base_processor.pyAdded+25
data_gen/tts/wav_processors/common_processors.pyAdded+86