spapi commited on
Commit
e5933f1
·
verified ·
1 Parent(s): d2b34bb

Add segment-ytc.py script

Browse files
Files changed (1) hide show
  1. scripts/segment-ytc.py +337 -0
scripts/segment-ytc.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from dataclasses import dataclass
3
+ from multiprocessing import cpu_count
4
+ from pathlib import Path
5
+ import numpy as np
6
+ import torch
7
+ import yaml
8
+ from torch.utils.data import DataLoader
9
+ from tqdm import tqdm
10
+ from constants import HIDDEN_SIZE, TARGET_SAMPLE_RATE
11
+ from data import FixedSegmentationDatasetNoTarget, segm_collate_fn
12
+ from eval import infer
13
+ from models import SegmentationFrameClassifer, prepare_wav2vec
14
+ import os
15
+
16
+ @dataclass
17
+ class Segment:
18
+ start: float
19
+ end: float
20
+ probs: np.array
21
+ decimal: int = 4
22
+
23
+ @property
24
+ def duration(self):
25
+ return float(round((self.end - self.start) / TARGET_SAMPLE_RATE, self.decimal))
26
+
27
+ @property
28
+ def offset(self):
29
+ return float(round(self.start / TARGET_SAMPLE_RATE, self.decimal))
30
+
31
+ @property
32
+ def offset_plus_duration(self):
33
+ return round(self.offset + self.duration, self.decimal)
34
+
35
+
36
+ def trim(sgm: Segment, threshold: float) -> Segment:
37
+ """reduces the segment to between the first and last points that are above the threshold
38
+
39
+ Args:
40
+ sgm (Segment): a segment
41
+ threshold (float): probability threshold
42
+
43
+ Returns:
44
+ Segment: new reduced segment
45
+ """
46
+ included_indices = np.where(sgm.probs >= threshold)[0]
47
+
48
+ # return empty segment
49
+ if not len(included_indices):
50
+ return Segment(sgm.start, sgm.start, np.empty([0]))
51
+
52
+ i = included_indices[0]
53
+ j = included_indices[-1] + 1
54
+
55
+ sgm = Segment(sgm.start + i, sgm.start + j, sgm.probs[i:j])
56
+
57
+ return sgm
58
+
59
+
60
+ def split_and_trim(
61
+ sgm: Segment, split_idx: int, threshold: float
62
+ ) -> tuple[Segment, Segment]:
63
+ """splits the input segment at the split_idx and then trims and returns the two resulting segments
64
+
65
+ Args:
66
+ sgm (Segment): input segment
67
+ split_idx (int): index to split the input segment
68
+ threshold (float): probability threshold
69
+
70
+ Returns:
71
+ tuple[Segment, Segment]: the two resulting segments
72
+ """
73
+
74
+ probs_a = sgm.probs[:split_idx]
75
+ sgm_a = Segment(sgm.start, sgm.start + len(probs_a), probs_a)
76
+
77
+ probs_b = sgm.probs[split_idx + 1 :]
78
+ sgm_b = Segment(sgm_a.end + 1, sgm.end, probs_b)
79
+
80
+ sgm_a = trim(sgm_a, threshold)
81
+ sgm_b = trim(sgm_b, threshold)
82
+
83
+ return sgm_a, sgm_b
84
+
85
+
86
+ def pdac(
87
+ probs: np.array,
88
+ max_segment_length: float,
89
+ min_segment_length: float,
90
+ threshold: float,
91
+ not_strict: bool
92
+ ) -> list[Segment]:
93
+ """applies the probabilistic Divide-and-Conquer algorithm to split an audio
94
+ into segments satisfying the max-segment-length and min-segment-length conditions
95
+
96
+ Args:
97
+ probs (np.array): the binary frame-level probabilities
98
+ output by the segmentation-frame-classifier
99
+ max_segment_length (float): the maximum length of a segment
100
+ min_segment_length (float): the minimum length of a segment
101
+ threshold (float): probability threshold
102
+ not_strict (bool): whether segments longer than max are allowed
103
+
104
+ Returns:
105
+ list[Segment]: resulting segmentation
106
+ """
107
+
108
+ segments = []
109
+ sgm = Segment(0, len(probs), probs)
110
+ sgm = trim(sgm, threshold)
111
+
112
+ def recusrive_split(sgm):
113
+ if sgm.duration < max_segment_length:
114
+ segments.append(sgm)
115
+ else:
116
+ j = 0
117
+ sorted_indices = np.argsort(sgm.probs)
118
+ while j < len(sorted_indices):
119
+ split_idx = sorted_indices[j]
120
+ split_prob = sgm.probs[split_idx]
121
+ if not_strict and split_prob > threshold:
122
+ segments.append(sgm)
123
+ break
124
+
125
+ sgm_a, sgm_b = split_and_trim(sgm, split_idx, threshold)
126
+ if (
127
+ sgm_a.duration > min_segment_length
128
+ and sgm_b.duration > min_segment_length
129
+ ):
130
+ recusrive_split(sgm_a)
131
+ recusrive_split(sgm_b)
132
+ break
133
+ j += 1
134
+ else:
135
+ if not_strict:
136
+ segments.append(sgm)
137
+ else:
138
+ if sgm_a.duration > min_segment_length:
139
+ recusrive_split(sgm_a)
140
+ if sgm_b.duration > min_segment_length:
141
+ recusrive_split(sgm_b)
142
+
143
+ recusrive_split(sgm)
144
+
145
+ return segments
146
+
147
+
148
+ def update_yaml_content(
149
+ yaml_content: list[dict], segments: list[Segment], wav_name: str
150
+ ) -> list[dict]:
151
+ """extends the yaml content with the segmentation of this wav file
152
+
153
+ Args:
154
+ yaml_content (list[dict]): segmentation in yaml format
155
+ segments (list[Segment]): resulting segmentation from pdac
156
+ wav_name (str): name of the wav file
157
+
158
+ Returns:
159
+ list[dict]: extended segmentation in yaml format
160
+ """
161
+ for sgm in segments:
162
+ yaml_content.append(
163
+ {
164
+ "duration": sgm.duration,
165
+ "offset": sgm.offset,
166
+ "rW": 0,
167
+ "uW": 0,
168
+ "speaker_id": "NA",
169
+ "wav": wav_name,
170
+ }
171
+ )
172
+ return yaml_content
173
+
174
+
175
+ def segment(args):
176
+
177
+ device = (
178
+ torch.device(f"cuda:0")
179
+ if torch.cuda.device_count() > 0
180
+ else torch.device("cpu")
181
+ )
182
+
183
+ checkpoint = torch.load(args.path_to_checkpoint, map_location=device)
184
+
185
+ # init wav2vec 2.0
186
+ wav2vec_model = prepare_wav2vec(
187
+ checkpoint["args"].model_name,
188
+ checkpoint["args"].wav2vec_keep_layers,
189
+ device,
190
+ )
191
+ # init segmentation frame classifier
192
+ sfc_model = SegmentationFrameClassifer(
193
+ d_model=HIDDEN_SIZE,
194
+ n_transformer_layers=checkpoint["args"].classifier_n_transformer_layers,
195
+ ).to(device)
196
+ sfc_model.load_state_dict(checkpoint["state_dict"])
197
+ sfc_model.eval()
198
+
199
+ yaml_content = []
200
+ with open(args.wavs, 'r') as file:
201
+ wav_paths = [x.strip() for x in file.readlines()]
202
+ #for wav_path in sorted(list(Path(args.path_to_wavs).glob("*.wav"))):
203
+ for wav_path in wav_paths:
204
+
205
+ # initialize a dataset for the fixed segmentation
206
+ dataset = FixedSegmentationDatasetNoTarget(wav_path, args.inference_segment_length, args.inference_times)
207
+ sgm_frame_probs = None
208
+
209
+ for inference_iteration in range(args.inference_times):
210
+
211
+ # create a dataloader for this fixed-length segmentation of the wav file
212
+ dataset.fixed_length_segmentation(inference_iteration)
213
+ dataloader = DataLoader(
214
+ dataset,
215
+ batch_size=args.inference_batch_size,
216
+ num_workers=min(cpu_count() // 2, 4),
217
+ shuffle=False,
218
+ drop_last=False,
219
+ collate_fn=segm_collate_fn,
220
+ )
221
+
222
+ # get frame segmentation frame probabilities in the output space
223
+ probs, _ = infer(
224
+ wav2vec_model,
225
+ sfc_model,
226
+ dataloader,
227
+ device,
228
+ )
229
+ if sgm_frame_probs is None:
230
+ sgm_frame_probs = probs.copy()
231
+ else:
232
+ sgm_frame_probs += probs
233
+
234
+ sgm_frame_probs /= args.inference_times
235
+
236
+ segments = pdac(
237
+ sgm_frame_probs,
238
+ args.dac_max_segment_length,
239
+ args.dac_min_segment_length,
240
+ args.dac_threshold,
241
+ args.not_strict
242
+ )
243
+ wav_path_name = os.path.basename(wav_path)
244
+ for sgm in segments:
245
+ print(f"Segmentation:{wav_path_name}\t{sgm.offset}\t{sgm.duration}")
246
+ yaml_content = update_yaml_content(yaml_content, segments, wav_path_name)
247
+
248
+ path_to_segmentation_yaml = Path(args.path_to_segmentation_yaml)
249
+ path_to_segmentation_yaml.parent.mkdir(parents=True, exist_ok=True)
250
+ with open(path_to_segmentation_yaml, "w") as f:
251
+ yaml.dump(yaml_content, f, default_flow_style=True)
252
+
253
+ print(
254
+ f"Saved SHAS segmentation with max={args.dac_max_segment_length} & "
255
+ f"min={args.dac_min_segment_length} at {path_to_segmentation_yaml}"
256
+ )
257
+
258
+
259
+ if __name__ == "__main__":
260
+
261
+ parser = argparse.ArgumentParser()
262
+ parser.add_argument(
263
+ "--path_to_segmentation_yaml",
264
+ "-yaml",
265
+ type=str,
266
+ required=True,
267
+ help="absolute path to the yaml file to save the generated segmentation",
268
+ )
269
+ parser.add_argument(
270
+ "--path_to_checkpoint",
271
+ "-ckpt",
272
+ type=str,
273
+ required=True,
274
+ help="absolute path to the audio-frame-classifier checkpoint",
275
+ )
276
+ parser.add_argument(
277
+ "-wavs",
278
+ type=str,
279
+ help="absolute path to the directory of the wav audios to be segmented",
280
+ )
281
+ parser.add_argument(
282
+ "--inference_batch_size",
283
+ "-bs",
284
+ type=int,
285
+ default=12,
286
+ help="batch size (in examples) of inference with the audio-frame-classifier",
287
+ )
288
+ parser.add_argument(
289
+ "--inference_segment_length",
290
+ "-len",
291
+ type=int,
292
+ default=20,
293
+ help="segment length (in seconds) of fixed-length segmentation during inference"
294
+ "with audio-frame-classifier",
295
+ )
296
+ parser.add_argument(
297
+ "--inference_times",
298
+ "-n",
299
+ type=int,
300
+ default=1,
301
+ help="how many times to apply inference on different fixed-length segmentations"
302
+ "of each wav",
303
+ )
304
+ parser.add_argument(
305
+ "--dac_max_segment_length",
306
+ "-max",
307
+ type=float,
308
+ default=20.0,
309
+ help="the segmentation algorithm splits until all segments are below this value"
310
+ "(in seconds)",
311
+ )
312
+ parser.add_argument(
313
+ "--dac_min_segment_length",
314
+ "-min",
315
+ type=float,
316
+ default=0.2,
317
+ help="a split by the algorithm is carried out only if the resulting two segments"
318
+ "are above this value (in seconds)",
319
+ )
320
+ parser.add_argument(
321
+ "--dac_threshold",
322
+ "-thr",
323
+ type=float,
324
+ default=0.5,
325
+ help="after each split by the algorithm, the resulting segments are trimmed to"
326
+ "the first and last points that corresponds to a probability above this value",
327
+ )
328
+ parser.add_argument(
329
+ "--not_strict",
330
+ action="store_true",
331
+ help="whether segments longer than max are allowed."
332
+ "If this argument is used, respecting the classification threshold conditions (p > thr)"
333
+ "is more important than the length conditions (len < max)."
334
+ )
335
+ args = parser.parse_args()
336
+
337
+ segment(args)