2021-07-06 17:11:35 +00:00
|
|
|
import os
|
2021-12-03 05:43:07 +00:00
|
|
|
import os
|
2021-07-06 17:11:35 +00:00
|
|
|
import random
|
2021-12-29 21:44:32 +00:00
|
|
|
import sys
|
2021-08-11 19:34:31 +00:00
|
|
|
|
2021-07-06 17:11:35 +00:00
|
|
|
import torch
|
2021-08-12 21:44:55 +00:00
|
|
|
import torch.nn.functional as F
|
2021-12-03 05:43:07 +00:00
|
|
|
import torch.utils.data
|
2021-10-31 21:01:38 +00:00
|
|
|
import torchaudio
|
2021-07-28 02:33:30 +00:00
|
|
|
from tqdm import tqdm
|
2021-07-06 17:11:35 +00:00
|
|
|
|
2021-12-29 21:44:32 +00:00
|
|
|
from data.audio.unsupervised_audio_dataset import load_audio, load_similar_clips
|
2021-12-03 05:43:07 +00:00
|
|
|
from models.tacotron2.taco_utils import load_filepaths_and_text
|
2021-12-25 22:21:01 +00:00
|
|
|
from models.tacotron2.text import text_to_sequence, sequence_to_text
|
2021-07-28 02:33:30 +00:00
|
|
|
from utils.util import opt_get
|
2021-07-06 17:11:35 +00:00
|
|
|
|
|
|
|
|
2022-01-17 04:10:46 +00:00
|
|
|
def load_tsv(filename):
|
|
|
|
with open(filename, encoding='utf-8') as f:
|
|
|
|
components = [line.strip().split('\t') for line in f]
|
|
|
|
base = os.path.dirname(filename)
|
|
|
|
filepaths_and_text = [[os.path.join(base, f'{component[1]}'), component[0]] for component in components]
|
|
|
|
return filepaths_and_text
|
|
|
|
|
|
|
|
|
|
|
|
def load_tsv_aligned_codes(filename):
|
|
|
|
with open(filename, encoding='utf-8') as f:
|
|
|
|
components = [line.strip().split('\t') for line in f]
|
|
|
|
base = os.path.dirname(filename)
|
|
|
|
def convert_string_list_to_tensor(strlist):
|
|
|
|
if strlist.startswith('['):
|
|
|
|
strlist = strlist[1:]
|
|
|
|
if strlist.endswith(']'):
|
|
|
|
strlist = strlist[:-1]
|
|
|
|
as_ints = [int(s) for s in strlist.split(', ')]
|
|
|
|
return torch.tensor(as_ints)
|
|
|
|
filepaths_and_text = [[os.path.join(base, f'{component[1]}'), component[0], convert_string_list_to_tensor(component[2])] for component in components]
|
|
|
|
return filepaths_and_text
|
|
|
|
|
|
|
|
|
|
|
|
def load_mozilla_cv(filename):
|
|
|
|
with open(filename, encoding='utf-8') as f:
|
|
|
|
components = [line.strip().split('\t') for line in f][1:] # First line is the header
|
|
|
|
base = os.path.dirname(filename)
|
|
|
|
filepaths_and_text = [[os.path.join(base, f'clips/{component[1]}'), component[2]] for component in components]
|
|
|
|
return filepaths_and_text
|
|
|
|
|
|
|
|
|
|
|
|
def load_voxpopuli(filename):
|
|
|
|
with open(filename, encoding='utf-8') as f:
|
|
|
|
lines = [line.strip().split('\t') for line in f][1:] # First line is the header
|
|
|
|
base = os.path.dirname(filename)
|
|
|
|
filepaths_and_text = []
|
|
|
|
for line in lines:
|
|
|
|
if len(line) == 0:
|
|
|
|
continue
|
|
|
|
file, raw_text, norm_text, speaker_id, split, gender = line
|
|
|
|
year = file[:4]
|
|
|
|
filepaths_and_text.append([os.path.join(base, year, f'{file}.ogg.wav'), raw_text])
|
|
|
|
return filepaths_and_text
|
2021-08-16 23:13:40 +00:00
|
|
|
|
|
|
|
|
2021-12-25 22:21:01 +00:00
|
|
|
class CharacterTokenizer:
|
|
|
|
def encode(self, txt):
|
2021-12-30 20:41:24 +00:00
|
|
|
return text_to_sequence(txt, ['english_cleaners'])
|
2021-12-25 22:21:01 +00:00
|
|
|
|
|
|
|
def decode(self, seq):
|
|
|
|
return sequence_to_text(seq)
|
|
|
|
|
|
|
|
|
2021-10-31 21:01:38 +00:00
|
|
|
class TextWavLoader(torch.utils.data.Dataset):
|
2021-07-06 17:11:35 +00:00
|
|
|
def __init__(self, hparams):
|
2022-01-17 04:10:46 +00:00
|
|
|
self.path = hparams['path']
|
|
|
|
if not isinstance(self.path, list):
|
|
|
|
self.path = [self.path]
|
2021-08-14 22:04:05 +00:00
|
|
|
|
2022-01-17 04:10:46 +00:00
|
|
|
fetcher_mode = opt_get(hparams, ['fetcher_mode'], 'lj')
|
|
|
|
if not isinstance(fetcher_mode, list):
|
|
|
|
fetcher_mode = [fetcher_mode]
|
|
|
|
assert len(self.path) == len(fetcher_mode)
|
2021-08-14 22:04:05 +00:00
|
|
|
|
2021-12-03 05:14:44 +00:00
|
|
|
self.load_conditioning = opt_get(hparams, ['load_conditioning'], False)
|
2021-12-29 21:44:32 +00:00
|
|
|
self.conditioning_candidates = opt_get(hparams, ['num_conditioning_candidates'], 1)
|
2021-12-03 05:14:44 +00:00
|
|
|
self.conditioning_length = opt_get(hparams, ['conditioning_length'], 44100)
|
2021-12-23 23:12:16 +00:00
|
|
|
self.debug_failures = opt_get(hparams, ['debug_loading_failures'], False)
|
2022-01-16 00:38:26 +00:00
|
|
|
self.load_aligned_codes = opt_get(hparams, ['load_aligned_codes'], False)
|
|
|
|
self.aligned_codes_to_audio_ratio = opt_get(hparams, ['aligned_codes_ratio'], 443)
|
2022-01-17 04:10:46 +00:00
|
|
|
self.audiopaths_and_text = []
|
|
|
|
for p, fm in zip(self.path, fetcher_mode):
|
|
|
|
if fm == 'lj' or fm == 'libritts':
|
|
|
|
fetcher_fn = load_filepaths_and_text
|
|
|
|
elif fm == 'tsv':
|
|
|
|
fetcher_fn = load_tsv_aligned_codes if self.load_aligned_codes else load_tsv
|
|
|
|
elif fm == 'mozilla_cv':
|
|
|
|
assert not self.load_conditioning # Conditioning inputs are incompatible with mozilla_cv
|
|
|
|
fetcher_fn = load_mozilla_cv
|
|
|
|
elif fm == 'voxpopuli':
|
|
|
|
assert not self.load_conditioning # Conditioning inputs are incompatible with voxpopuli
|
|
|
|
fetcher_fn = load_voxpopuli
|
|
|
|
else:
|
|
|
|
raise NotImplementedError()
|
|
|
|
self.audiopaths_and_text.extend(fetcher_fn(p))
|
2021-07-06 17:11:35 +00:00
|
|
|
self.text_cleaners = hparams.text_cleaners
|
2021-10-31 21:01:38 +00:00
|
|
|
self.sample_rate = hparams.sample_rate
|
2022-01-17 04:10:46 +00:00
|
|
|
random.seed(hparams.seed)
|
|
|
|
random.shuffle(self.audiopaths_and_text)
|
2021-10-31 21:01:38 +00:00
|
|
|
self.max_wav_len = opt_get(hparams, ['max_wav_length'], None)
|
2022-01-16 00:38:26 +00:00
|
|
|
if self.max_wav_len is not None:
|
2022-01-16 22:17:17 +00:00
|
|
|
self.max_aligned_codes = self.max_wav_len // self.aligned_codes_to_audio_ratio
|
2021-08-12 21:44:55 +00:00
|
|
|
self.max_text_len = opt_get(hparams, ['max_text_length'], None)
|
2022-01-06 17:29:39 +00:00
|
|
|
assert self.max_wav_len is not None and self.max_text_len is not None
|
2021-12-25 22:28:59 +00:00
|
|
|
self.use_bpe_tokenizer = opt_get(hparams, ['use_bpe_tokenizer'], True)
|
|
|
|
if self.use_bpe_tokenizer:
|
2021-12-30 20:41:24 +00:00
|
|
|
from data.audio.voice_tokenizer import VoiceBpeTokenizer
|
|
|
|
self.tokenizer = VoiceBpeTokenizer(opt_get(hparams, ['tokenizer_vocab'], '../experiments/bpe_lowercase_asr_256.json'))
|
2021-12-25 22:21:01 +00:00
|
|
|
else:
|
|
|
|
self.tokenizer = CharacterTokenizer()
|
2022-01-06 18:15:16 +00:00
|
|
|
self.skipped_items = 0 # records how many items are skipped when accessing an index.
|
2021-07-06 17:11:35 +00:00
|
|
|
|
2021-10-31 21:01:38 +00:00
|
|
|
def get_wav_text_pair(self, audiopath_and_text):
|
2021-07-06 17:11:35 +00:00
|
|
|
# separate filename and text
|
|
|
|
audiopath, text = audiopath_and_text[0], audiopath_and_text[1]
|
2021-08-14 20:37:17 +00:00
|
|
|
text_seq = self.get_text(text)
|
2021-10-31 21:01:38 +00:00
|
|
|
wav = load_audio(audiopath, self.sample_rate)
|
|
|
|
return (text_seq, wav, text, audiopath_and_text[0])
|
2021-07-06 17:11:35 +00:00
|
|
|
|
|
|
|
def get_text(self, text):
|
2021-12-30 20:41:24 +00:00
|
|
|
tokens = self.tokenizer.encode(text)
|
2021-12-22 22:06:14 +00:00
|
|
|
tokens = torch.IntTensor(tokens)
|
2021-12-25 22:28:59 +00:00
|
|
|
if self.use_bpe_tokenizer:
|
|
|
|
# Assert if any UNK,start tokens encountered.
|
|
|
|
assert not torch.any(tokens == 1)
|
|
|
|
# The stop token should always be sacred.
|
2021-12-22 22:06:14 +00:00
|
|
|
assert not torch.any(tokens == 0)
|
|
|
|
return tokens
|
2021-07-06 17:11:35 +00:00
|
|
|
|
|
|
|
def __getitem__(self, index):
|
2022-01-06 18:15:16 +00:00
|
|
|
self.skipped_items += 1
|
2021-12-03 05:43:07 +00:00
|
|
|
try:
|
2022-01-17 04:10:46 +00:00
|
|
|
tseq, wav, text, path = self.get_wav_text_pair(self.audiopaths_and_text[index])
|
2022-01-16 00:38:26 +00:00
|
|
|
if text is None or len(text.strip()) == 0:
|
|
|
|
raise ValueError
|
2022-01-17 04:10:46 +00:00
|
|
|
cond, cond_is_self = load_similar_clips(self.audiopaths_and_text[index][0], self.conditioning_length, self.sample_rate,
|
2022-01-06 22:24:37 +00:00
|
|
|
n=self.conditioning_candidates) if self.load_conditioning else (None, False)
|
2021-12-03 05:43:07 +00:00
|
|
|
except:
|
2022-01-06 18:15:16 +00:00
|
|
|
if self.skipped_items > 100:
|
|
|
|
raise # Rethrow if we have nested too far.
|
2021-12-23 23:12:16 +00:00
|
|
|
if self.debug_failures:
|
2022-01-17 04:10:46 +00:00
|
|
|
print(f"error loading {self.audiopaths_and_text[index][0]} {sys.exc_info()}")
|
2021-12-29 21:44:32 +00:00
|
|
|
return self[(index+1) % len(self)]
|
2022-01-16 00:38:26 +00:00
|
|
|
|
|
|
|
if self.load_aligned_codes:
|
2022-01-17 04:10:46 +00:00
|
|
|
aligned_codes = self.audiopaths_and_text[index][2]
|
2022-01-16 00:38:26 +00:00
|
|
|
|
2022-01-06 18:15:16 +00:00
|
|
|
actually_skipped_items = self.skipped_items
|
|
|
|
self.skipped_items = 0
|
2021-10-31 21:01:38 +00:00
|
|
|
if wav is None or \
|
|
|
|
(self.max_wav_len is not None and wav.shape[-1] > self.max_wav_len) or \
|
2021-08-14 20:37:17 +00:00
|
|
|
(self.max_text_len is not None and tseq.shape[0] > self.max_text_len):
|
2021-10-31 21:01:38 +00:00
|
|
|
# Basically, this audio file is nonexistent or too long to be supported by the dataset.
|
2021-08-11 22:17:03 +00:00
|
|
|
# It's hard to handle this situation properly. Best bet is to return the a random valid token and skew the dataset somewhat as a result.
|
2022-01-01 07:16:30 +00:00
|
|
|
if self.debug_failures:
|
|
|
|
print(f"error loading {path}: ranges are out of bounds; {wav.shape[-1]}, {tseq.shape[0]}")
|
2021-08-12 21:22:34 +00:00
|
|
|
rv = random.randint(0,len(self)-1)
|
2021-08-11 22:17:03 +00:00
|
|
|
return self[rv]
|
2021-10-31 21:01:38 +00:00
|
|
|
orig_output = wav.shape[-1]
|
2021-08-14 20:37:17 +00:00
|
|
|
orig_text_len = tseq.shape[0]
|
2022-01-06 17:29:39 +00:00
|
|
|
if wav.shape[-1] != self.max_wav_len:
|
|
|
|
wav = F.pad(wav, (0, self.max_wav_len - wav.shape[-1]))
|
2022-01-16 00:38:26 +00:00
|
|
|
if self.load_aligned_codes:
|
|
|
|
# These codes are aligned to audio inputs, so make sure to pad them as well.
|
|
|
|
aligned_codes = F.pad(aligned_codes, (0, self.max_aligned_codes-aligned_codes.shape[0]))
|
2022-01-06 17:29:39 +00:00
|
|
|
if tseq.shape[0] != self.max_text_len:
|
|
|
|
tseq = F.pad(tseq, (0, self.max_text_len - tseq.shape[0]))
|
2021-12-03 05:14:44 +00:00
|
|
|
res = {
|
2022-01-06 17:29:39 +00:00
|
|
|
'real_text': text,
|
|
|
|
'padded_text': tseq,
|
|
|
|
'text_lengths': torch.tensor(orig_text_len, dtype=torch.long),
|
|
|
|
'wav': wav,
|
|
|
|
'wav_lengths': torch.tensor(orig_output, dtype=torch.long),
|
2022-01-06 18:15:16 +00:00
|
|
|
'filenames': path,
|
|
|
|
'skipped_items': actually_skipped_items,
|
2021-07-09 04:13:44 +00:00
|
|
|
}
|
2022-01-06 17:29:39 +00:00
|
|
|
if self.load_conditioning:
|
|
|
|
res['conditioning'] = cond
|
2022-01-06 18:15:16 +00:00
|
|
|
res['conditioning_contains_self'] = cond_is_self
|
2022-01-16 00:38:26 +00:00
|
|
|
if self.load_aligned_codes:
|
|
|
|
res['aligned_codes'] = aligned_codes
|
2021-12-03 05:14:44 +00:00
|
|
|
return res
|
2021-07-06 17:11:35 +00:00
|
|
|
|
2022-01-06 17:29:39 +00:00
|
|
|
def __len__(self):
|
2022-01-17 04:10:46 +00:00
|
|
|
return len(self.audiopaths_and_text)
|
2022-01-06 17:29:39 +00:00
|
|
|
|
2021-07-06 17:11:35 +00:00
|
|
|
|
2022-01-06 19:38:20 +00:00
|
|
|
class PairedVoiceDebugger:
|
|
|
|
def __init__(self):
|
|
|
|
self.total_items = 0
|
|
|
|
self.loaded_items = 0
|
|
|
|
self.self_conditioning_items = 0
|
|
|
|
|
|
|
|
def get_state(self):
|
|
|
|
return {'total_items': self.total_items,
|
|
|
|
'loaded_items': self.loaded_items,
|
|
|
|
'self_conditioning_items': self.self_conditioning_items}
|
|
|
|
|
|
|
|
def load_state(self, state):
|
|
|
|
if isinstance(state, dict):
|
|
|
|
self.total_items = opt_get(state, ['total_items'], 0)
|
|
|
|
self.loaded_items = opt_get(state, ['loaded_items'], 0)
|
|
|
|
self.self_conditioning_items = opt_get(state, ['self_conditioning_items'], 0)
|
|
|
|
|
|
|
|
def update(self, batch):
|
|
|
|
self.total_items += batch['wav'].shape[0]
|
|
|
|
self.loaded_items += batch['skipped_items'].sum().item()
|
|
|
|
if 'conditioning' in batch.keys():
|
|
|
|
self.self_conditioning_items += batch['conditioning_contains_self'].sum().item()
|
|
|
|
|
|
|
|
def get_debugging_map(self):
|
|
|
|
return {
|
|
|
|
'total_samples_loaded': self.total_items,
|
|
|
|
'percent_skipped_samples': (self.loaded_items - self.total_items) / self.loaded_items,
|
|
|
|
'percent_conditioning_is_self': self.self_conditioning_items / self.loaded_items,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2021-07-06 17:11:35 +00:00
|
|
|
if __name__ == '__main__':
|
2022-01-17 04:10:46 +00:00
|
|
|
batch_sz = 8
|
2021-07-06 17:11:35 +00:00
|
|
|
params = {
|
2021-12-22 21:03:18 +00:00
|
|
|
'mode': 'paired_voice_audio',
|
2022-01-17 04:10:46 +00:00
|
|
|
'path': ['Y:\\clips\\books1\\transcribed-w2v.tsv'],
|
|
|
|
'fetcher_mode': ['tsv'],
|
2021-07-26 22:27:31 +00:00
|
|
|
'phase': 'train',
|
2021-12-03 05:14:44 +00:00
|
|
|
'n_workers': 0,
|
2021-10-31 21:01:38 +00:00
|
|
|
'batch_size': batch_sz,
|
2021-12-17 06:28:44 +00:00
|
|
|
'max_wav_length': 255995,
|
2021-11-21 04:33:49 +00:00
|
|
|
'max_text_length': 200,
|
2021-10-31 21:01:38 +00:00
|
|
|
'sample_rate': 22050,
|
2022-01-17 04:10:46 +00:00
|
|
|
'load_conditioning': True,
|
2021-12-29 21:44:32 +00:00
|
|
|
'num_conditioning_candidates': 2,
|
|
|
|
'conditioning_length': 44000,
|
2021-12-30 20:41:24 +00:00
|
|
|
'use_bpe_tokenizer': True,
|
2022-01-17 04:10:46 +00:00
|
|
|
'load_aligned_codes': True,
|
2021-07-06 17:11:35 +00:00
|
|
|
}
|
2021-07-26 22:27:31 +00:00
|
|
|
from data import create_dataset, create_dataloader
|
|
|
|
|
2022-01-05 22:47:22 +00:00
|
|
|
def save(b, i, ib, key, c=None):
|
|
|
|
if c is not None:
|
|
|
|
torchaudio.save(f'{i}_clip_{ib}_{key}_{c}.wav', b[key][ib][c], 22050)
|
|
|
|
else:
|
|
|
|
torchaudio.save(f'{i}_clip_{ib}_{key}.wav', b[key][ib], 22050)
|
|
|
|
|
2021-07-26 22:27:31 +00:00
|
|
|
ds, c = create_dataset(params, return_collate=True)
|
|
|
|
dl = create_dataloader(ds, params, collate_fn=c)
|
2021-07-20 14:36:46 +00:00
|
|
|
i = 0
|
2021-08-06 18:03:46 +00:00
|
|
|
m = None
|
2021-12-03 05:14:44 +00:00
|
|
|
for i, b in tqdm(enumerate(dl)):
|
|
|
|
for ib in range(batch_sz):
|
2022-01-05 22:47:22 +00:00
|
|
|
print(f'{i} {ib} {b["real_text"][ib]}')
|
2022-01-17 04:10:46 +00:00
|
|
|
save(b, i, ib, 'wav')
|
|
|
|
if i > 5:
|
|
|
|
break
|
2021-12-29 21:44:32 +00:00
|
|
|
|