File size: 5,844 Bytes
e678f88 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | from pathlib import Path
import json
import os
from tqdm import tqdm
import random
import argparse
import yaml
import numpy as np
import pickle
def parse_speaker(path, method):
# parse the hubert code path
if type(path) == str:
path = Path(path)
if method == "_":
return path.name.split("_")[0]
elif method == "single":
return "A"
else:
raise NotImplementedError()
def adjust_duration(total_codes, durations):
"""
Adjusts the durations list so that the sum of its elements equals the provided total_codes.
If the adjustment is not possible or the difference is greater than 2, returns None.
Args:
total_codes (int): The desired sum of the durations list.
durations (list[int]): The list of durations to be adjusted.
Returns:
list[int] or None: The adjusted list of durations or None if adjustment is not possible.
"""
total_duration = sum(durations)
difference = total_duration - total_codes
if difference == 0:
return durations
if abs(difference) > 2:
print("Unable to adjust durations. The difference is greater than 2.")
return None
if difference < 0:
durations[-1] += abs(difference)
return durations
if difference > 0:
remaining = difference
idxs_by_size = sorted(range(len(durations)), key=lambda i: -durations[i])
for i in idxs_by_size:
if remaining == 0:
break
take = min(remaining, durations[i] - 1) if durations[i] > 1 else 0
durations[i] -= take
remaining -= take
if remaining == 0:
return durations
print("Unable to adjust durations: no element/combo could absorb the difference.")
return None
class Preprocessor:
# take as input the list of hubert dictionaries and extract durations
# we write two files: train.txt and val.txt
# each file is a similar list of dictionaries with keys as follows:
# audio: path to original wav
# hubert: space separated string of hubert tokens
# speaker: speaker id
def __init__(self, config):
self.config = config
self.root_dir = Path(config["path"]["root_path"])
self.hubert_path = config["path"]["hubert_path"]
self.speaker_method = config["preprocess"]["speaker"]
self.val_size = config["preprocess"]["val_size"]
self.alignment_dir = Path(config["path"]["alignment_path"])
def build_from_path(self):
print("Processing data...")
with open(self.hubert_path) as f:
hubert_lines = f.readlines()
speaker_set = set()
random.shuffle(hubert_lines)
processed_lines = list()
skipped_lines = 0
# load all characters found in the dataset
with open(self.alignment_dir / "symbols.pkl", "rb") as f:
symbols = pickle.load(f)
for l in tqdm(hubert_lines):
# load dict containing audio path, hubert units and total duration
data_dict = json.loads(l.strip().replace("'", '"'))
# get basename
basename = Path(data_dict["audio"]).stem
# get speaker
speaker = parse_speaker(data_dict["audio"], method=self.speaker_method)
speaker_set.add(speaker)
data_dict['speaker'] = speaker
# get tokens obtained from DFA training
if not os.path.exists(self.alignment_dir / "{}/tokens/{}.npy".format(speaker,basename)):
continue
tokens = np.load(self.alignment_dir / "{}/tokens/{}.npy".format(speaker,basename))
# get characters from tokens. replace ' ' with 'sil' character
characters = ['sil' if symbols[i-1] == ' ' else symbols[i-1] for i in tokens]
# get durations obtained from DFA training
if not os.path.exists(self.alignment_dir / "{}/outputs/durations/{}.npy".format(speaker,basename)):
continue
durations = np.load(self.alignment_dir / "{}/outputs/durations/{}.npy".format(speaker,basename))
# adjust durations with HuBERT units
durations = adjust_duration(len(data_dict['hubert'].split()), durations)
if durations is None:
skipped_lines+=1
continue
assert sum(durations) == len(data_dict['hubert'].split()), f"{sum(durations)}, {len(data_dict['hubert'].split())}"
data_dict['characters'] = " ".join(characters)
data_dict['duration'] = " ".join([str(i) for i in durations])
processed_lines.append(data_dict)
print("Total skipped lines: ", skipped_lines)
if not os.path.exists(self.root_dir):
os.makedirs(self.root_dir)
# save speakers dictionary
with open(self.root_dir / "speakers.json", 'w') as f:
speaker_dict = {s:i for i,s in enumerate(speaker_set)}
print("saving speakers.json")
json.dump(speaker_dict, f)
with open(self.root_dir / "train.txt", 'w') as f:
for line in processed_lines[self.val_size:]:
f.write(str(line) + "\n")
with open(self.root_dir / "val.txt", 'w') as f:
for line in processed_lines[:self.val_size]:
f.write(str(line) + "\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("config", type=str, default="utils/TTE/TTE_config.yaml", help="path to config.yaml")
args = parser.parse_args()
config = yaml.load(open(args.config, "r"), Loader=yaml.FullLoader)
Prep = Preprocessor(config)
Prep.build_from_path() |