-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalign_and_segment_multi.py
222 lines (188 loc) · 7.88 KB
/
align_and_segment_multi.py
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import os
import torch
import torchaudio
import sox
import json
import random
import argparse
from text_normalization import text_normalize
from align_utils import (
get_uroman_tokens,
time_to_frame,
load_model_dict,
merge_repeats,
get_spans,
)
import torchaudio.functional as F
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
SAMPLING_FREQ = 16000
EMISSION_INTERVAL = 30
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def generate_emissions(model, audio_file):
waveform, _ = torchaudio.load(audio_file) # waveform: channels X T
waveform = waveform.to(DEVICE)
total_duration = sox.file_info.duration(audio_file)
audio_sf = sox.file_info.sample_rate(audio_file)
assert audio_sf == SAMPLING_FREQ
emissions_arr = []
with torch.inference_mode():
i = 0
while i < total_duration:
segment_start_time, segment_end_time = (i, i + EMISSION_INTERVAL)
context = EMISSION_INTERVAL * 0.1
input_start_time = max(segment_start_time - context, 0)
input_end_time = min(segment_end_time + context, total_duration)
waveform_split = waveform[
:,
int(SAMPLING_FREQ * input_start_time) : int(
SAMPLING_FREQ * (input_end_time)
),
]
model_outs, _ = model(waveform_split)
emissions_ = model_outs[0]
emission_start_frame = time_to_frame(segment_start_time)
emission_end_frame = time_to_frame(segment_end_time)
offset = time_to_frame(input_start_time)
emissions_ = emissions_[
emission_start_frame - offset : emission_end_frame - offset, :
]
emissions_arr.append(emissions_)
i += EMISSION_INTERVAL
emissions = torch.cat(emissions_arr, dim=0).squeeze().detach()
emissions = torch.log_softmax(emissions, dim=-1).detach()
emissions = emissions.clone().detach()
stride = float(waveform.size(1) * 1000 / emissions.size(0) / SAMPLING_FREQ)
return emissions, stride
def get_alignments(
audio_file,
tokens,
model,
dictionary,
use_star,
):
# Generate emissions
emissions, stride = generate_emissions(model, audio_file)
T, N = emissions.size()
if use_star:
emissions = torch.cat([emissions, torch.zeros(T, 1).to(DEVICE)], dim=1)
# Force Alignment
if tokens:
token_indices = [dictionary[c] for c in " ".join(tokens).split(" ") if c in dictionary]
else:
print(f"Empty transcript!!!!! for audio file {audio_file}")
token_indices = []
blank = dictionary["<blank>"]
targets = torch.tensor(token_indices, dtype=torch.int32).to(DEVICE)
input_lengths = torch.tensor(emissions.shape[0])
target_lengths = torch.tensor(targets.shape[0])
path, _ = F.forced_align(
emissions, targets, input_lengths, target_lengths, blank=blank
)
path = path.to("cpu").tolist()
segments = merge_repeats(path, {v: k for k, v in dictionary.items()})
return segments, stride
def do_batch(model, dictionary, align_data, lang, use_star=True, cut=False, uroman_path="uroman/bin"):
for index, ele in enumerate(align_data):
transcripts, audio_filepath, outdir = ele['transcripts'], ele['audio_file'], ele['outdir']
print(f"{index} / {len(align_data)} processing {audio_filepath} start.")
os.makedirs(outdir, exist_ok=True)
manifest_file = f"{outdir}/manifest.json"
if os.path.exists(manifest_file):
print(f"{manifest_file} already existed. skip it...")
continue
norm_transcripts = [text_normalize(line.strip(), lang) for line in transcripts]
tokens = get_uroman_tokens(norm_transcripts, uroman_path, lang)
if use_star:
if "<star>" not in dictionary:
dictionary["<star>"] = len(dictionary)
stars = ["<star>"] * len(tokens)
tokens = [i for pair in zip(tokens, stars) for i in pair]
tokens = ["<star>"] + tokens
transcripts = [i for pair in zip(transcripts, stars) for i in pair]
transcripts = ["<star>"] + transcripts
norm_transcripts = [i for pair in zip(norm_transcripts, stars) for i in pair]
norm_transcripts = ["<star>"] + norm_transcripts
segments, stride = get_alignments(
audio_filepath,
tokens,
model,
dictionary,
use_star,
)
# Get spans of each line in input text file
spans = get_spans(tokens, segments)
with open(manifest_file, "w") as f:
for i, t in enumerate(transcripts):
span = spans[i]
if transcripts[i] == "<star>":
continue
seg_start_idx = span[0].start
seg_end_idx = span[-1].end
audio_start_sec = seg_start_idx * stride / 1000
audio_end_sec = seg_end_idx * stride / 1000
sample = {
"audio_start_sec": audio_start_sec,
"audio_end_sec": audio_end_sec,
"duration": audio_end_sec - audio_start_sec,
"text": t,
"normalized_text":norm_transcripts[i],
"uroman_tokens": tokens[i],
}
if cut:
output_file = f"{outdir}/segment{i}.flac"
tfm = sox.Transformer()
tfm.trim(audio_start_sec , audio_end_sec)
tfm.build_file(audio_filepath, output_file)
sample["audio_filepath"] = str(output_file)
f.write(json.dumps(sample, ensure_ascii=False) + "\n")
print(f"{index} / {len(align_data)} processing {manifest_file} done.")
def main(args):
model, dictionary = load_model_dict()
model = model.to(DEVICE)
print("model has been loaded.")
cons = open(args.info_filepath).readlines()
align_data_list = []
for line in cons:
# <audio-name>\t<audio-path>\t<segmented-text1>\t...\t<segmented-textn>
name, wavp, *transcripts = line.strip().split("\t")
align_data_list.append(
{
"audio_file": wavp,
"transcripts": transcripts,
"outdir": os.path.join(args.outdir, name)
}
)
random.shuffle(align_data_list)
align_data_list = align_data_list
num_threads = args.num_threads
num_batch = len(align_data_list) // num_threads + 1
batches = [ align_data_list[index*num_batch:(index+1)*num_batch] for index in range(num_threads)]
tasks = []
with ThreadPoolExecutor(max_workers=num_threads) as t:
for batch in batches:
task = t.submit(do_batch, model, dictionary, batch, args.lang, args.use_star, args.cut)
tasks.append(task)
wait(tasks, return_when=ALL_COMPLETED)
print("done")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Align and segment long audio files")
parser.add_argument(
"-i", "--info_filepath", type=str, help="Path to information for waited segmented files."
)
parser.add_argument(
"-l", "--lang", type=str, default="eng", help="ISO code of the language"
)
parser.add_argument(
"-s", "--use_star", type=bool, default=True, help="Use star at the start of transcript",
)
parser.add_argument(
"-o", "--outdir", type=str, help="Output directory to store segmented results, maybe the segmented files.",
)
parser.add_argument(
"-c", "--cut", type=bool, default=False, help="Whether cut the long audio to small pieces according to the alignment results.",
)
parser.add_argument(
"-t", "--num_threads", type=int, default=25, help="number of threads to do the alignment.",
)
args = parser.parse_args()
main(args)