forked from lhotse-speech/lhotse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_serialization.py
518 lines (458 loc) · 15.8 KB
/
test_serialization.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import os
from tempfile import NamedTemporaryFile
import pytest
from lhotse import (
AudioSource,
CutSet,
Features,
FeatureSet,
MonoCut,
MultiCut,
Recording,
RecordingSet,
SupervisionSegment,
SupervisionSet,
load_manifest,
store_manifest,
)
from lhotse.lazy import LazyJsonlIterator
from lhotse.serialization import SequentialJsonlWriter, load_manifest_lazy, open_best
from lhotse.supervision import AlignmentItem
from lhotse.testing.dummies import DummyManifest
from lhotse.utils import fastcopy
from lhotse.utils import nullcontext as does_not_raise
@pytest.mark.parametrize(
["path", "exception_expectation"],
[
("test/fixtures/audio.json", does_not_raise()),
("test/fixtures/supervision.json", does_not_raise()),
("test/fixtures/dummy_feats/feature_manifest.json", does_not_raise()),
("test/fixtures/libri/cuts.json", does_not_raise()),
("test/fixtures/libri/cuts_multi.json", does_not_raise()),
("test/fixtures/feature_config.yml", pytest.raises(ValueError)),
("no/such/path.xd", pytest.raises(ValueError)),
],
)
def test_load_any_lhotse_manifest(path, exception_expectation):
with exception_expectation:
load_manifest(path)
@pytest.mark.parametrize(
["path", "exception_expectation"],
[
("test/fixtures/audio.json", does_not_raise()),
("test/fixtures/supervision.json", does_not_raise()),
("test/fixtures/dummy_feats/feature_manifest.json", does_not_raise()),
("test/fixtures/libri/cuts.json", does_not_raise()),
("test/fixtures/libri/cuts_multi.json", does_not_raise()),
("test/fixtures/feature_config.yml", pytest.raises(ValueError)),
("no/such/path.xd", pytest.raises(ValueError)),
],
)
def test_load_any_lhotse_manifest_lazy(path, exception_expectation):
with exception_expectation:
me = load_manifest(path)
# some temporary files are needed to convert JSON to JSONL
with NamedTemporaryFile(suffix=".jsonl.gz") as f:
me.to_file(f.name)
f.flush()
ml = load_manifest_lazy(f.name)
assert list(me) == list(ml) # equal under iteration
@pytest.fixture
def recording_set():
return RecordingSet.from_recordings(
[
Recording(
id="x",
sources=[
AudioSource(
type="file", channels=[0], source="text/fixtures/mono_c0.wav"
),
AudioSource(
type="command",
channels=[1],
source="cat text/fixtures/mono_c1.wav",
),
],
sampling_rate=8000,
num_samples=4000,
duration=0.5,
)
]
)
@pytest.fixture
def supervision_set():
return SupervisionSet.from_segments(
[
SupervisionSegment(
id="segment-1",
recording_id="recording-1",
channel=0,
start=0.1,
duration=0.3,
text="transcript of the first segment",
language="english",
speaker="Norman Dyhrentfurth",
gender="male",
alignment={
"word": [
AlignmentItem(symbol="transcript", start=0.1, duration=0.08),
AlignmentItem(symbol="of", start=0.18, duration=0.02),
AlignmentItem(symbol="the", start=0.2, duration=0.03),
AlignmentItem(symbol="first", start=0.23, duration=0.07),
AlignmentItem(symbol="segment", start=0.3, duration=0.1),
]
},
)
]
)
@pytest.fixture
def feature_set():
return FeatureSet(
features=[
Features(
recording_id="irrelevant",
channels=0,
start=0.0,
duration=20.0,
type="fbank",
num_frames=2000,
num_features=20,
frame_shift=0.01,
sampling_rate=16000,
storage_type="lilcom",
storage_path="/irrelevant/",
storage_key="path.llc",
)
]
)
@pytest.fixture
def cut_set():
cut = MonoCut(
id="cut-1",
start=0.0,
duration=10.0,
channel=0,
features=Features(
type="fbank",
num_frames=100,
num_features=40,
frame_shift=0.01,
sampling_rate=16000,
start=0.0,
duration=10.0,
storage_type="lilcom",
storage_path="irrelevant",
storage_key="irrelevant",
),
recording=Recording(
id="rec-1",
sampling_rate=16000,
num_samples=160000,
duration=10.0,
sources=[AudioSource(type="file", channels=[0], source="irrelevant")],
),
supervisions=[
SupervisionSegment(
id="sup-1", recording_id="irrelevant", start=0.5, duration=6.0
),
SupervisionSegment(
id="sup-2", recording_id="irrelevant", start=7.0, duration=2.0
),
],
)
multi_cut = MultiCut(
id="cut-2",
start=0.0,
duration=10.0,
channel=0,
recording=Recording(
id="rec-2",
sampling_rate=16000,
num_samples=160000,
duration=10.0,
channel_ids=[0, 1],
sources=[AudioSource(type="file", channels=[0, 1], source="irrelevant")],
),
supervisions=[
SupervisionSegment(
id="sup-3", recording_id="irrelevant", start=0.5, duration=6.0
),
SupervisionSegment(
id="sup-4", recording_id="irrelevant", start=7.0, duration=2.0
),
],
)
return CutSet.from_cuts(
[
cut,
fastcopy(cut, id="cut-nosup", supervisions=[]),
fastcopy(cut, id="cut-norec", recording=None),
fastcopy(cut, id="cut-nofeat", features=None),
cut.pad(duration=30.0, direction="left"),
cut.pad(duration=30.0, direction="right"),
cut.pad(duration=30.0, direction="both"),
cut.mix(cut, offset_other_by=5.0, snr=8),
multi_cut,
]
)
@pytest.mark.parametrize(
["format", "compressed"],
[
("yaml", False),
("yaml", True),
("json", False),
("json", True),
("jsonl", False),
("jsonl", True),
],
)
def test_feature_set_serialization(feature_set, format, compressed):
with NamedTemporaryFile(suffix=".gz" if compressed else "") as f:
if format == "jsonl":
feature_set.to_jsonl(f.name)
feature_set_deserialized = FeatureSet.from_jsonl(f.name)
if format == "json":
feature_set.to_json(f.name)
feature_set_deserialized = FeatureSet.from_json(f.name)
if format == "yaml":
feature_set.to_yaml(f.name)
feature_set_deserialized = FeatureSet.from_yaml(f.name)
assert feature_set_deserialized == feature_set
@pytest.mark.parametrize(
["format", "compressed"],
[
("yaml", False),
("yaml", True),
("json", False),
("json", True),
("jsonl", False),
("jsonl", True),
],
)
def test_serialization(recording_set, format, compressed):
with NamedTemporaryFile(suffix=".gz" if compressed else "") as f:
if format == "jsonl":
recording_set.to_jsonl(f.name)
deserialized = RecordingSet.from_jsonl(f.name)
if format == "yaml":
recording_set.to_yaml(f.name)
deserialized = RecordingSet.from_yaml(f.name)
if format == "json":
recording_set.to_json(f.name)
deserialized = RecordingSet.from_json(f.name)
assert deserialized == recording_set
@pytest.mark.parametrize(
["format", "compressed"],
[
("yaml", False),
("yaml", True),
("json", False),
("json", True),
("jsonl", False),
("jsonl", True),
],
)
def test_supervision_set_serialization(supervision_set, format, compressed):
with NamedTemporaryFile(suffix=".gz" if compressed else "") as f:
if format == "yaml":
supervision_set.to_yaml(f.name)
restored = supervision_set.from_yaml(f.name)
if format == "json":
supervision_set.to_json(f.name)
restored = supervision_set.from_json(f.name)
if format == "jsonl":
supervision_set.to_jsonl(f.name)
restored = supervision_set.from_jsonl(f.name)
assert supervision_set == restored
@pytest.mark.parametrize(
["format", "compressed"],
[
("yaml", False),
("yaml", True),
("json", False),
("json", True),
("jsonl", False),
("jsonl", True),
],
)
def test_cut_set_serialization(cut_set, format, compressed):
with NamedTemporaryFile(suffix=".gz" if compressed else "") as f:
if format == "yaml":
cut_set.to_yaml(f.name)
restored = CutSet.from_yaml(f.name)
if format == "json":
cut_set.to_json(f.name)
restored = CutSet.from_json(f.name)
if format == "jsonl":
cut_set.to_jsonl(f.name)
restored = CutSet.from_jsonl(f.name)
assert cut_set == restored
@pytest.fixture
def manifests(recording_set, supervision_set, feature_set, cut_set):
return {
"recording_set": recording_set,
"supervision_set": supervision_set,
"feature_set": feature_set,
"cut_set": cut_set,
}
@pytest.mark.parametrize(
"manifest_type", ["recording_set", "supervision_set", "feature_set", "cut_set"]
)
@pytest.mark.parametrize(
["format", "compressed"],
[
("yaml", False),
("yaml", True),
("json", False),
("json", True),
("jsonl", False),
("jsonl", True),
],
)
def test_generic_serialization_classmethod(
manifests, manifest_type, format, compressed
):
manifest = manifests[manifest_type]
with NamedTemporaryFile(suffix="." + format + (".gz" if compressed else "")) as f:
manifest.to_file(f.name)
restored = type(manifest).from_file(f.name).to_eager()
assert manifest == restored
@pytest.mark.parametrize(
"manifest_type", ["recording_set", "supervision_set", "feature_set", "cut_set"]
)
@pytest.mark.parametrize(
["format", "compressed"],
[
("yaml", False),
("yaml", True),
("json", False),
("json", True),
("jsonl", False),
("jsonl", True),
],
)
def test_generic_serialization(manifests, manifest_type, format, compressed):
manifest = manifests[manifest_type]
with NamedTemporaryFile(suffix="." + format + (".gz" if compressed else "")) as f:
store_manifest(manifest, f.name)
restored = load_manifest(f.name)
assert manifest == restored
@pytest.mark.parametrize(
"manifest_type", ["recording_set", "supervision_set", "cut_set", "feature_set"]
)
@pytest.mark.parametrize(
["format", "compressed"],
[
("jsonl", False),
("jsonl", True),
],
)
def test_sequential_jsonl_writer(manifests, manifest_type, format, compressed):
manifest = manifests[manifest_type]
with NamedTemporaryFile(
suffix="." + format + (".gz" if compressed else "")
) as jsonl_f:
with manifest.open_writer(jsonl_f.name) as writer:
for item in manifest:
writer.write(item)
restored = writer.open_manifest()
# Same manifest type
assert type(manifest) == type(restored)
# Equal under iteration
assert list(manifest) == list(restored)
def test_sequential_jsonl_writer_with_dict_input():
data = [{"key": "value", "other_key": "other_value"}, {"key": "value2"}]
with NamedTemporaryFile(suffix=".jsonl") as jsonl_f:
with SequentialJsonlWriter(jsonl_f.name) as writer:
for item in data:
writer.write(item)
restored = list(LazyJsonlIterator(jsonl_f.name))
assert len(restored) == 2
assert data[0] == restored[0]
assert data[1] == restored[1]
@pytest.mark.parametrize(
"manifest_type", ["recording_set", "supervision_set", "cut_set", "feature_set"]
)
def test_in_memory_writer(manifests, manifest_type):
manifest = manifests[manifest_type]
with manifest.open_writer(None) as writer:
for item in manifest:
writer.write(item)
restored = writer.open_manifest()
assert manifest == restored
@pytest.mark.parametrize("overwrite", [True, False])
def test_sequential_jsonl_writer_overwrite(overwrite):
cuts = DummyManifest(CutSet, begin_id=0, end_id=100)
half = cuts.split(num_splits=2)[0]
with NamedTemporaryFile(suffix=".jsonl") as jsonl_f:
# Store the first half
half.to_file(jsonl_f.name)
# Open sequential writer
with CutSet.open_writer(jsonl_f.name, overwrite=overwrite) as writer:
if overwrite:
assert all(not writer.contains(id_) for id_ in half.ids)
else:
assert all(writer.contains(id_) for id_ in half.ids)
@pytest.mark.parametrize(
"manifest_type", ["recording_set", "supervision_set", "cut_set", "feature_set"]
)
def test_manifest_is_lazy(manifests, manifest_type):
# Eager manifest is not lazy
eager = manifests[manifest_type]
cls = type(eager)
assert not eager.is_lazy
# Save the manifest to JSONL and open it lazily
with NamedTemporaryFile(suffix=".jsonl") as f, cls.open_writer(f.name) as writer:
for item in eager:
writer.write(item)
f.flush()
lazy = writer.open_manifest()
# Lazy manifest is lazy
assert lazy.is_lazy
# Concatenation of eager + eager manifests is eager
eager_eager_cat = eager + eager
assert eager_eager_cat.is_lazy
# Concatenation of lazy + eager manifests is lazy
lazy_eager_cat = lazy + eager
assert lazy_eager_cat.is_lazy
# Concatenation of eager + lazy manifests is lazy
eager_lazy_cat = eager + lazy
assert eager_lazy_cat.is_lazy
# Concatenation of eager + lazy manifests is lazy
lazy_lazy_cat = eager + lazy
assert lazy_lazy_cat.is_lazy
# Muxing of eager + eager manifests is lazy
eager_eager_mux = cls.mux(eager, eager)
assert eager_eager_mux.is_lazy
# Muxing of lazy + eager manifests is lazy
lazy_eager_mux = cls.mux(lazy, eager)
assert lazy_eager_mux.is_lazy
# Muxing of eager + lazy manifests is lazy
eager_lazy_mux = cls.mux(eager, lazy)
assert eager_lazy_mux.is_lazy
# Muxing of eager + lazy manifests is lazy
lazy_lazy_mux = cls.mux(lazy, lazy)
assert lazy_lazy_mux.is_lazy
@pytest.mark.skipif(os.name == "nt", reason="This test cannot be run on Windows.")
def test_open_pipe(tmp_path):
data = "text"
with open_best(f"pipe:gzip -c > {tmp_path}/text.gz", mode="w") as f:
print(data, file=f)
with open_best(f"pipe:gunzip -c {tmp_path}/text.gz", mode="r") as f:
data_read = f.read().strip()
assert data_read == data
@pytest.mark.skipif(os.name == "nt", reason="This test cannot be run on Windows.")
def test_open_pipe_iter(tmp_path):
lines = [
"line0",
"line1",
"line2",
]
with open_best(f"pipe:gzip -c > {tmp_path}/text.gz", mode="w") as f:
for l in lines:
print(l, file=f)
lines_read = []
with open_best(f"pipe:gunzip -c {tmp_path}/text.gz", mode="r") as f:
for l in f:
lines_read.append(l.strip())
assert lines_read == lines