'''1file -> temporary_dict -> processed_input -> batch2'''3from utils.hparams import hparams4from network.vocoders.base_vocoder import VOCODERS5import numpy as np6import traceback7from pathlib import Path8from .data_gen_utils import get_pitch_parselmouth,get_pitch_crepe9from .base_binarizer import BinarizationError10import torch11import utils1213class File2Batch:14'''15pipeline: file -> temporary_dict -> processed_input -> batch16'''1718@staticmethod19def file2temporary_dict():20'''21read from file, store data in temporary dicts22'''23raw_data_dir = Path(hparams['raw_data_dir'])24# meta_midi = json.load(open(os.path.join(raw_data_dir, 'meta.json'))) # [list of dict]2526# if hparams['perform_enhance'] and not hparams['infer']:27# vocoder=get_vocoder_cls(hparams)()28# raw_files = list(raw_data_dir.rglob(f"*.wav"))29# dic=[]30# time_step = hparams['hop_size'] / hparams['audio_sample_rate']31# f0_min = hparams['f0_min']32# f0_max = hparams['f0_max']33# for file in raw_files:34# y, sr = librosa.load(file, sr=hparams['audio_sample_rate'])35# f0 = parselmouth.Sound(y, hparams['audio_sample_rate']).to_pitch_ac(36# time_step=time_step , voicing_threshold=0.6,37# pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']38# f0_mean=np.mean(f0[f0>0])39# dic.append(f0_mean)40# for idx in np.where(dic>np.percentile(dic, 80))[0]:41# file=raw_files[idx]42# wav,mel=vocoder.wav2spec(str(file))43# f0,_=get_pitch_parselmouth(wav,mel,hparams)44# f0[f0>0]=f0[f0>0]*(2**(2/12))45# wav_pred=vocoder.spec2wav(torch.FloatTensor(mel),f0=torch.FloatTensor(f0))46# sf.write(file.with_name(file.name[:-4]+'_high.wav'), wav_pred, 24000, 'PCM_16')47utterance_labels =[]48utterance_labels.extend(list(raw_data_dir.rglob(f"*.wav")))49utterance_labels.extend(list(raw_data_dir.rglob(f"*.ogg")))50#open(os.path.join(raw_data_dir, 'transcriptions.txt'), encoding='utf-8').readlines()5152all_temp_dict = {}53for utterance_label in utterance_labels:54#song_info = utterance_label.split('|')55item_name =str(utterance_label)#raw_item_name = song_info[0]56# print(item_name)57temp_dict = {}58temp_dict['wav_fn'] =str(utterance_label)#f'{raw_data_dir}/wavs/{item_name}.wav'59# temp_dict['txt'] = song_info[1]6061# temp_dict['ph'] = song_info[2]62# # 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])63# temp_dict['word_boundary'] = np.array([1 if x in ALL_YUNMU + ['AP', 'SP'] else 0 for x in song_info[2].split()])64# temp_dict['ph_durs'] = [float(x) for x in song_info[5].split(" ")]6566# temp_dict['pitch_midi'] = np.array([note_to_midi(x.split("/")[0]) if x != 'rest' else 067# for x in song_info[3].split(" ")])68# temp_dict['midi_dur'] = np.array([float(x) for x in song_info[4].split(" ")])69# temp_dict['is_slur'] = np.array([int(x) for x in song_info[6].split(" ")])70temp_dict['spk_id'] = hparams['speaker_id']71# assert temp_dict['pitch_midi'].shape == temp_dict['midi_dur'].shape == temp_dict['is_slur'].shape, \72# (temp_dict['pitch_midi'].shape, temp_dict['midi_dur'].shape, temp_dict['is_slur'].shape)7374all_temp_dict[item_name] = temp_dict7576return all_temp_dict7778@staticmethod79def temporary_dict2processed_input(item_name, temp_dict, encoder, binarization_args):80'''81process data in temporary_dicts82'''83def get_pitch(wav, mel):84# get ground truth f0 by self.get_pitch_algorithm85if hparams['use_crepe']:86gt_f0, gt_pitch_coarse = get_pitch_crepe(wav, mel, hparams)87else:88gt_f0, gt_pitch_coarse = get_pitch_parselmouth(wav, mel, hparams)89if sum(gt_f0) == 0:90raise BinarizationError("Empty **gt** f0")91processed_input['f0'] = gt_f092processed_input['pitch'] = gt_pitch_coarse9394def get_align(meta_data, mel, phone_encoded, hop_size=hparams['hop_size'], audio_sample_rate=hparams['audio_sample_rate']):95mel2ph = np.zeros([mel.shape[0]], int)96start_frame=097ph_durs = mel.shape[0]/phone_encoded.shape[0]98if hparams['debug']:99print(mel.shape,phone_encoded.shape,mel.shape[0]/phone_encoded.shape[0])100for i_ph in range(phone_encoded.shape[0]):101102end_frame = int(i_ph*ph_durs +ph_durs+ 0.5)103mel2ph[start_frame:end_frame+1] = i_ph + 1104start_frame = end_frame+1105106processed_input['mel2ph'] = mel2ph107108if hparams['vocoder'] in VOCODERS:109wav, mel = VOCODERS[hparams['vocoder']].wav2spec(temp_dict['wav_fn'])110else:111wav, mel = VOCODERS[hparams['vocoder'].split('.')[-1]].wav2spec(temp_dict['wav_fn'])112processed_input = {113'item_name': item_name, 'mel': mel, 'wav': wav,114'sec': len(wav) / hparams['audio_sample_rate'], 'len': mel.shape[0]115}116processed_input = {**temp_dict, **processed_input} # merge two dicts117processed_input['spec_min']=np.min(mel,axis=0)118processed_input['spec_max']=np.max(mel,axis=0)119#(processed_input['spec_min'].shape)120try:121if binarization_args['with_f0']:122get_pitch(wav, mel)123if binarization_args['with_hubert']:124try:125hubert_encoded = processed_input['hubert'] = encoder.encode(temp_dict['wav_fn'])126except:127traceback.print_exc()128raise Exception(f"hubert encode error")129if binarization_args['with_align']:130get_align(temp_dict, mel, hubert_encoded)131except Exception as e:132print(f"| Skip item ({e}). item_name: {item_name}, wav_fn: {temp_dict['wav_fn']}")133return None134return processed_input135136@staticmethod137def processed_input2batch(samples):138'''139Args:140samples: one batch of processed_input141NOTE:142the batch size is controlled by hparams['max_sentences']143'''144if len(samples) == 0:145return {}146id = torch.LongTensor([s['id'] for s in samples])147item_names = [s['item_name'] for s in samples]148#text = [s['text'] for s in samples]149#txt_tokens = utils.collate_1d([s['txt_token'] for s in samples], 0)150hubert = utils.collate_2d([s['hubert'] for s in samples], 0.0)151f0 = utils.collate_1d([s['f0'] for s in samples], 0.0)152pitch = utils.collate_1d([s['pitch'] for s in samples])153uv = utils.collate_1d([s['uv'] for s in samples])154energy = utils.collate_1d([s['energy'] for s in samples], 0.0)155mel2ph = utils.collate_1d([s['mel2ph'] for s in samples], 0.0) \156if samples[0]['mel2ph'] is not None else None157mels = utils.collate_2d([s['mel'] for s in samples], 0.0)158#txt_lengths = torch.LongTensor([s['txt_token'].numel() for s in samples])159hubert_lengths = torch.LongTensor([s['hubert'].shape[0] for s in samples])160mel_lengths = torch.LongTensor([s['mel'].shape[0] for s in samples])161162batch = {163'id': id,164'item_name': item_names,165'nsamples': len(samples),166# 'text': text,167# 'txt_tokens': txt_tokens,168# 'txt_lengths': txt_lengths,169'hubert':hubert,170'mels': mels,171'mel_lengths': mel_lengths,172'mel2ph': mel2ph,173'energy': energy,174'pitch': pitch,175'f0': f0,176'uv': uv,177}178#========not used=================179# if hparams['use_spk_embed']:180# spk_embed = torch.stack([s['spk_embed'] for s in samples])181# batch['spk_embed'] = spk_embed182# if hparams['use_spk_id']:183# spk_ids = torch.LongTensor([s['spk_id'] for s in samples])184# batch['spk_ids'] = spk_ids185# if hparams['pitch_type'] == 'cwt':186# cwt_spec = utils.collate_2d([s['cwt_spec'] for s in samples])187# f0_mean = torch.Tensor([s['f0_mean'] for s in samples])188# f0_std = torch.Tensor([s['f0_std'] for s in samples])189# batch.update({'cwt_spec': cwt_spec, 'f0_mean': f0_mean, 'f0_std': f0_std})190# elif hparams['pitch_type'] == 'ph':191# batch['f0'] = utils.collate_1d([s['f0_ph'] for s in samples])192193# batch['pitch_midi'] = utils.collate_1d([s['pitch_midi'] for s in samples], 0)194# batch['midi_dur'] = utils.collate_1d([s['midi_dur'] for s in samples], 0)195# batch['is_slur'] = utils.collate_1d([s['is_slur'] for s in samples], 0)196# batch['word_boundary'] = utils.collate_1d([s['word_boundary'] for s in samples], 0)197198return batch199200