-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathdataio.py
More file actions
1417 lines (1220 loc) · 41.7 KB
/
dataio.py
File metadata and controls
1417 lines (1220 loc) · 41.7 KB
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Data reading and writing.
Authors
* Mirco Ravanelli 2020
* Aku Rouhe 2020
* Ju-Chieh Chou 2020
* Samuele Cornell 2020
* Abdel HEBA 2020
* Gaëlle Laperrière 2021
* Sahar Ghannay 2021
* Sylvain de Langen 2022
* Adel Moumen 2025
"""
import csv
import hashlib
import json
import os
import pickle
import re
import time
from io import BytesIO
from typing import Union
import numpy as np
import torch
from speechbrain.dataio import audio_io
from speechbrain.utils.logger import get_logger
from speechbrain.utils.torch_audio_backend import (
check_torchaudio_backend,
validate_backend,
)
check_torchaudio_backend()
logger = get_logger(__name__)
def load_data_json(json_path, replacements=None):
"""Loads JSON and recursively formats string values.
Arguments
---------
json_path : str
Path to CSV file.
replacements : dict
(Optional dict), e.g., {"data_folder": "/home/speechbrain/data"}.
This is used to recursively format all string values in the data.
Returns
-------
dict
JSON data with replacements applied.
Example
-------
>>> json_spec = '''{
... "ex1": {"files": ["{ROOT}/mic1/ex1.wav", "{ROOT}/mic2/ex1.wav"], "id": 1},
... "ex2": {"files": [{"spk1": "{ROOT}/ex2.wav"}, {"spk2": "{ROOT}/ex2.wav"}], "id": 2}
... }
... '''
>>> tmpfile = getfixture("tmpdir") / "test.json"
>>> with open(tmpfile, "w", encoding="utf-8") as fo:
... _ = fo.write(json_spec)
>>> data = load_data_json(tmpfile, {"ROOT": "/home"})
>>> data["ex1"]["files"][0]
'/home/mic1/ex1.wav'
>>> data["ex2"]["files"][1]["spk2"]
'/home/ex2.wav'
"""
if replacements is None:
replacements = {}
with open(json_path, encoding="utf-8") as f:
out_json = json.load(f)
_recursive_format(out_json, replacements)
return out_json
def _recursive_format(data, replacements):
# Data: dict or list, replacements : dict
# Replaces string keys in replacements by their values
# at all levels of data (in str values)
# Works in-place.
if isinstance(data, dict):
for key, item in data.items():
if isinstance(item, dict) or isinstance(item, list):
_recursive_format(item, replacements)
elif isinstance(item, str):
data[key] = item.format_map(replacements)
# If not dict, list or str, do nothing
if isinstance(data, list):
for i, item in enumerate(data):
if isinstance(item, dict) or isinstance(item, list):
_recursive_format(item, replacements)
elif isinstance(item, str):
data[i] = item.format_map(replacements)
# If not dict, list or str, do nothing
def load_data_csv(csv_path, replacements=None):
"""Loads CSV and formats string values.
Uses the SpeechBrain legacy CSV data format, where the CSV must have an
'ID' field.
If there is a field called duration, it is interpreted as a float.
The rest of the fields are left as they are (legacy _format and _opts fields
are not used to load the data in any special way).
Bash-like string replacements with $to_replace are supported.
Arguments
---------
csv_path : str
Path to CSV file.
replacements : dict
(Optional dict), e.g., {"data_folder": "/home/speechbrain/data"}
This is used to recursively format all string values in the data.
Returns
-------
dict
CSV data with replacements applied.
Example
-------
>>> csv_spec = '''ID,duration,wav_path
... utt1,1.45,$data_folder/utt1.wav
... utt2,2.0,$data_folder/utt2.wav
... '''
>>> tmpfile = getfixture("tmpdir") / "test.csv"
>>> with open(tmpfile, "w", encoding="utf-8") as fo:
... _ = fo.write(csv_spec)
>>> data = load_data_csv(tmpfile, {"data_folder": "/home"})
>>> data["utt1"]["wav_path"]
'/home/utt1.wav'
"""
if replacements is None:
replacements = {}
with open(csv_path, newline="", encoding="utf-8") as csvfile:
result = {}
reader = csv.DictReader(csvfile, skipinitialspace=True)
variable_finder = re.compile(r"\$([\w.]+)")
for row in reader:
# ID:
try:
data_id = row["ID"]
del row["ID"] # This is used as a key in result, instead.
except KeyError:
raise KeyError(
"CSV has to have an 'ID' field, with unique ids"
" for all data points"
)
if data_id in result:
raise ValueError(f"Duplicate id: {data_id}")
# Replacements:
for key, value in row.items():
try:
row[key] = variable_finder.sub(
lambda match: str(replacements[match[1]]), value
)
except KeyError:
raise KeyError(
f"The item {value} requires replacements "
"which were not supplied."
)
# Duration:
if "duration" in row:
row["duration"] = float(row["duration"])
result[data_id] = row
return result
def read_audio_info(path, backend=None) -> "audio_io.AudioInfo":
"""Retrieves audio metadata from a file path. Uses audio_io.info which is
based on soundfile.
Note that this may cause full file traversal in certain cases!
Arguments
---------
path : str
Path to the audio file to examine.
backend : str, optional
Audio backend to use for loading the audio file. This parameter is
kept for compatibility but is currently ignored (soundfile is always used).
Returns
-------
audio_io.AudioInfo
Audio metadata with fields: sample_rate, num_frames, channels, etc.
NOTE
----
Some codecs, such as MP3, require full file traversal for accurate length
information to be retrieved.
In these cases, you may as well read the entire audio file to avoid doubling
the processing time.
"""
if backend is not None:
validate_backend(backend)
# Use audio_io.info which is based on soundfile
info = audio_io.info(path)
# Soundfile generally provides reliable frame counts, but if for some
# reason num_frames is 0, we can fall back to loading the file
if info.num_frames == 0:
channels_data, sample_rate = audio_io.load(path)
info.num_frames = channels_data.size(-1) # frames dimension
info.sample_rate = sample_rate
return info
def read_audio(waveforms_obj, backend=None):
"""General audio loading, based on a custom notation.
Expected use case is in conjunction with Datasets
specified by JSON.
The parameter may just be a path to a file:
`read_audio("/path/to/wav1.wav")`
Alternatively, you can specify more options in a dict, e.g.:
```
# load a file from sample 8000 through 15999
read_audio({"file": "/path/to/wav2.wav", "start": 8000, "stop": 16000})
```
Which codecs are supported depends on the soundfile library.
Refer to `audio_io.load` documentation for further details.
Arguments
---------
waveforms_obj : str, dict
Path to audio or dict with the desired configuration.
Keys for the dict variant:
- `"file"` (str): Path to the audio file.
- `"start"` (int, optional): The first sample to load.
If unspecified, load from the very first frame.
- `"stop"` (int, optional): The last sample to load (exclusive).
If unspecified or equal to start, load from `start` to the end.
Will not fail if `stop` is past the sample count of the file and will
return less frames.
backend : str, optional
Audio backend to use for loading the audio file. Must be one of
'ffmpeg', 'sox', 'soundfile' or None. If None, uses torchaudio's default backend.
Returns
-------
torch.Tensor
1-channel: audio tensor with shape: `(samples, )`.
>=2-channels: audio tensor with shape: `(samples, channels)`.
Raises
------
ValueError
If the `backend` is not one of the allowed values.
Must be one of [None, 'ffmpeg', 'sox', 'soundfile'].
Example
-------
>>> dummywav = torch.rand(16000)
>>> import os
>>> tmpfile = str(getfixture("tmpdir") / "wave.wav")
>>> write_audio(tmpfile, dummywav, 16000)
>>> asr_example = {"wav": tmpfile, "spk_id": "foo", "words": "foo bar"}
>>> loaded = read_audio(asr_example["wav"])
>>> loaded.allclose(
... dummywav.squeeze(0), atol=1e-4
... ) # replace with eq with sox_io backend
True
"""
validate_backend(backend)
# Case 1: Directly a file path (str) or file-like object or raw bytes.
# If a file-like object, ensure the pointer is at the beginning.
if hasattr(waveforms_obj, "seek"):
waveforms_obj.seek(0)
if isinstance(waveforms_obj, (str, BytesIO, bytes)):
# If raw bytes, wrap them in a BytesIO.
if isinstance(waveforms_obj, bytes):
waveforms_obj = BytesIO(waveforms_obj)
waveforms_obj.seek(0)
audio, _ = audio_io.load(waveforms_obj)
# Case 2: A dict with more options. Only works with file paths.
else:
path = waveforms_obj["file"]
start = waveforms_obj.get("start", 0)
# To match past SB behavior, `start == stop` or omitted `stop` means to
# load all frames from `start` to the file end.
stop = waveforms_obj.get("stop", start)
if start < 0:
raise ValueError(
f"Invalid sample range (start < 0): {start}..{stop}!"
)
if stop < start:
# Could occur if the user tried one of two things:
# - specify a negative value as an attempt to index from the end;
# - specify -1 as an attempt to load up to the last sample.
raise ValueError(
f"Invalid sample range (stop < start): {start}..{stop}!\n"
'Hint: Omit "stop" if you want to read to the end of file.'
)
# Requested to load until a specific frame?
if start != stop:
num_frames = stop - start
audio, fs = audio_io.load(
path, num_frames=num_frames, frame_offset=start
)
else:
# Load to the end.
audio, fs = audio_io.load(path, frame_offset=start)
audio = audio.transpose(0, 1)
return audio.squeeze(1)
def read_audio_multichannel(waveforms_obj, backend=None):
"""General audio loading, based on a custom notation.
Expected use case is in conjunction with Datasets
specified by JSON.
The custom notation:
The annotation can be just a path to a file:
"/path/to/wav1.wav"
Multiple (possibly multi-channel) files can be specified, as long as they
have the same length:
{"files": [
"/path/to/wav1.wav",
"/path/to/wav2.wav"
]
}
Or you can specify a single file more succinctly:
{"files": "/path/to/wav2.wav"}
Offset number samples and stop number samples also can be specified to read
only a segment within the files.
{"files": [
"/path/to/wav1.wav",
"/path/to/wav2.wav"
]
"start": 8000
"stop": 16000
}
Arguments
---------
waveforms_obj : str, dict
Audio reading annotation, see above for format.
backend : str, optional
Audio backend to use for loading the audio file. Must be one of
'ffmpeg', 'sox', 'soundfile' or None. If None, uses torchaudio's default backend.
Raises
------
ValueError
If the `backend` is not one of the allowed values.
Must be one of [None, 'ffmpeg', 'sox', 'soundfile'].
Returns
-------
torch.Tensor
Audio tensor with shape: (samples, ).
Example
-------
>>> dummywav = torch.rand(16000, 2)
>>> import os
>>> tmpfile = str(getfixture("tmpdir") / "wave.wav")
>>> write_audio(tmpfile, dummywav, 16000)
>>> asr_example = {"wav": tmpfile, "spk_id": "foo", "words": "foo bar"}
>>> loaded = read_audio(asr_example["wav"])
>>> loaded.allclose(
... dummywav.squeeze(0), atol=1e-4
... ) # replace with eq with sox_io backend
True
"""
validate_backend(backend)
# Case 1: Directly a file path (str) or file-like object or raw bytes.
# If a file-like object, ensure the pointer is at the beginning.
if hasattr(waveforms_obj, "seek"):
waveforms_obj.seek(0)
if isinstance(waveforms_obj, (str, BytesIO, bytes)):
# If raw bytes, wrap them in a BytesIO.
if isinstance(waveforms_obj, bytes):
waveforms_obj = BytesIO(waveforms_obj)
waveforms_obj.seek(0)
audio, _ = audio_io.load(waveforms_obj)
return audio.transpose(0, 1)
# Case 2: A dict with more options. Only works with file paths.
files = waveforms_obj["files"]
if not isinstance(files, list):
files = [files]
waveforms = []
start = waveforms_obj.get("start", 0)
# Default stop to start -> if not specified, num_frames becomes 0,
# which is the torchaudio default
stop = waveforms_obj.get("stop", start - 1)
num_frames = stop - start
for f in files:
audio, fs = audio_io.load(f, num_frames=num_frames, frame_offset=start)
waveforms.append(audio)
out = torch.cat(waveforms, 0)
return out.transpose(0, 1)
def write_audio(filepath, audio, samplerate):
"""Write audio on disk. It is basically a wrapper to support saving
audio signals in the speechbrain format (audio, channels).
Arguments
---------
filepath: path
Path where to save the audio file.
audio : torch.Tensor
Audio file in the expected speechbrain format (signal, channels).
samplerate: int
Sample rate (e.g., 16000).
Example
-------
>>> import os
>>> tmpfile = str(getfixture("tmpdir") / "wave.wav")
>>> dummywav = torch.rand(16000, 2)
>>> write_audio(tmpfile, dummywav, 16000)
>>> loaded = read_audio(tmpfile)
>>> loaded.allclose(
... dummywav, atol=1e-4
... ) # replace with eq with sox_io backend
True
"""
if len(audio.shape) == 2:
audio = audio.transpose(0, 1)
elif len(audio.shape) == 1:
audio = audio.unsqueeze(0)
audio_io.save(filepath, audio, samplerate)
def load_pickle(pickle_path):
"""Utility function for loading .pkl pickle files.
Arguments
---------
pickle_path : str
Path to pickle file.
Returns
-------
out : object
Python object loaded from pickle.
"""
with open(pickle_path, "rb") as f:
out = pickle.load(f)
return out
def to_floatTensor(x: Union[list, tuple, np.ndarray]):
"""
Arguments
---------
x : (list, tuple, np.ndarray)
Input data to be converted to torch float.
Returns
-------
tensor : torch.Tensor
Data now in torch.tensor float datatype.
"""
if isinstance(x, torch.Tensor):
return x.float()
if isinstance(x, np.ndarray):
return torch.from_numpy(x).float()
else:
return torch.tensor(x, dtype=torch.float)
def to_doubleTensor(x: Union[list, tuple, np.ndarray]):
"""
Arguments
---------
x : (list, tuple, np.ndarray)
Input data to be converted to torch double.
Returns
-------
tensor : torch.Tensor
Data now in torch.tensor double datatype.
"""
if isinstance(x, torch.Tensor):
return x.double()
if isinstance(x, np.ndarray):
return torch.from_numpy(x).double()
else:
return torch.tensor(x, dtype=torch.double)
def to_longTensor(x: Union[list, tuple, np.ndarray]):
"""
Arguments
---------
x : (list, tuple, np.ndarray)
Input data to be converted to torch long.
Returns
-------
tensor : torch.Tensor
Data now in torch.tensor long datatype.
"""
if isinstance(x, torch.Tensor):
return x.long()
if isinstance(x, np.ndarray):
return torch.from_numpy(x).long()
else:
return torch.tensor(x, dtype=torch.long)
def convert_index_to_lab(batch, ind2lab):
"""Convert a batch of integer IDs to string labels.
Arguments
---------
batch : list
List of lists, a batch of sequences.
ind2lab : dict
Mapping from integer IDs to labels.
Returns
-------
list
List of lists, same size as batch, with labels from ind2lab.
Example
-------
>>> ind2lab = {1: "h", 2: "e", 3: "l", 4: "o"}
>>> out = convert_index_to_lab([[4, 1], [1, 2, 3, 3, 4]], ind2lab)
>>> for seq in out:
... print("".join(seq))
oh
hello
"""
return [[ind2lab[int(index)] for index in seq] for seq in batch]
def relative_time_to_absolute(batch, relative_lens, rate):
"""Converts SpeechBrain style relative length to the absolute duration.
Operates on batch level.
Arguments
---------
batch : torch.Tensor
Sequences to determine the duration for.
relative_lens : torch.Tensor
The relative length of each sequence in batch. The longest sequence in
the batch needs to have relative length 1.0.
rate : float
The rate at which sequence elements occur in real-world time. Sample
rate, if batch is raw wavs (recommended) or 1/frame_shift if batch is
features. This has to have 1/s as the unit.
Returns
-------
torch.Tensor
Duration of each sequence in seconds.
Example
-------
>>> batch = torch.ones(2, 16000)
>>> relative_lens = torch.tensor([3.0 / 4.0, 1.0])
>>> rate = 16000
>>> print(relative_time_to_absolute(batch, relative_lens, rate))
tensor([0.7500, 1.0000])
"""
max_len = batch.shape[1]
durations = torch.round(relative_lens * max_len) / rate
return durations
class IterativeCSVWriter:
"""Write CSV files a line at a time.
Arguments
---------
outstream : file-object
A writeable stream
data_fields : list
List of the optional keys to write. Each key will be expanded to the
SpeechBrain format, producing three fields: key, key_format, key_opts.
defaults : dict
Mapping from CSV key to corresponding default value.
Example
-------
>>> import io
>>> f = io.StringIO()
>>> writer = IterativeCSVWriter(f, ["phn"])
>>> print(f.getvalue())
ID,duration,phn,phn_format,phn_opts
>>> writer.write("UTT1", 2.5, "sil hh ee ll ll oo sil", "string", "")
>>> print(f.getvalue())
ID,duration,phn,phn_format,phn_opts
UTT1,2.5,sil hh ee ll ll oo sil,string,
>>> writer.write(
... ID="UTT2", phn="sil ww oo rr ll dd sil", phn_format="string"
... )
>>> print(f.getvalue())
ID,duration,phn,phn_format,phn_opts
UTT1,2.5,sil hh ee ll ll oo sil,string,
UTT2,,sil ww oo rr ll dd sil,string,
>>> writer.set_default("phn_format", "string")
>>> writer.write_batch(ID=["UTT3", "UTT4"], phn=["ff oo oo", "bb aa rr"])
>>> print(f.getvalue())
ID,duration,phn,phn_format,phn_opts
UTT1,2.5,sil hh ee ll ll oo sil,string,
UTT2,,sil ww oo rr ll dd sil,string,
UTT3,,ff oo oo,string,
UTT4,,bb aa rr,string,
"""
def __init__(self, outstream, data_fields, defaults=None):
if defaults is None:
defaults = {}
self._outstream = outstream
self.fields = ["ID", "duration"] + self._expand_data_fields(data_fields)
self.defaults = defaults
self._outstream.write(",".join(self.fields))
def set_default(self, field, value):
"""Sets a default value for the given CSV field.
Arguments
---------
field : str
A field in the CSV.
value : str
The default value.
"""
if field not in self.fields:
raise ValueError(f"{field} is not a field in this CSV!")
self.defaults[field] = value
def write(self, *args, **kwargs):
"""Writes one data line into the CSV.
Arguments
---------
*args : tuple
Supply every field with a value in positional form OR.
**kwargs : dict
Supply certain fields by key. The ID field is mandatory for all
lines, but others can be left empty.
"""
if args:
if len(args) != len(self.fields):
raise ValueError("Need consistent fields")
to_write = [str(arg) for arg in args]
if kwargs:
raise ValueError(
"Use either positional fields or named fields, "
"but not both."
)
else:
if kwargs:
if "ID" not in kwargs:
raise ValueError("I'll need to see some ID")
full_vals = self.defaults.copy()
full_vals.update(kwargs)
to_write = [
str(full_vals.get(field, "")) for field in self.fields
]
else:
raise ValueError(
"Use either positional fields or named fields."
)
self._outstream.write("\n")
self._outstream.write(",".join(to_write))
def write_batch(self, *args, **kwargs):
"""Writes a batch of lines into the CSV.
Here each argument should be a list with the same length.
Arguments
---------
*args : tuple
Supply every field with a value in positional form OR.
**kwargs : dict
Supply certain fields by key. The ID field is mandatory for all
lines, but others can be left empty.
"""
if args and kwargs:
raise ValueError(
"Use either positional fields or named fields, but not both."
)
if args:
if len(args) != len(self.fields):
raise ValueError("Need consistent fields")
for arg_row in zip(*args):
self.write(*arg_row)
if kwargs:
if "ID" not in kwargs:
raise ValueError("I'll need to see some ID")
keys = kwargs.keys()
for value_row in zip(*kwargs.values()):
kwarg_row = dict(zip(keys, value_row))
self.write(**kwarg_row)
@staticmethod
def _expand_data_fields(data_fields):
expanded = []
for data_field in data_fields:
expanded.append(data_field)
expanded.append(data_field + "_format")
expanded.append(data_field + "_opts")
return expanded
def write_txt_file(data, filename, sampling_rate=None):
"""Write data in text format.
Arguments
---------
data : str, list, torch.Tensor, numpy.ndarray
The data to write in the text file.
filename : str
Path to file where to write the data.
sampling_rate : None
Not used, just here for interface compatibility.
Example
-------
>>> tmpdir = getfixture("tmpdir")
>>> signal = torch.tensor([1, 2, 3, 4])
>>> write_txt_file(signal, tmpdir / "example.txt")
"""
del sampling_rate # Not used.
# Check if the path of filename exists
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w", encoding="utf-8") as fout:
if isinstance(data, torch.Tensor):
data = data.tolist()
if isinstance(data, np.ndarray):
data = data.tolist()
if isinstance(data, list):
for line in data:
print(line, file=fout)
if isinstance(data, str):
print(data, file=fout)
def write_stdout(data, filename=None, sampling_rate=None):
"""Write data to standard output.
Arguments
---------
data : str, list, torch.Tensor, numpy.ndarray
The data to write in the text file.
filename : None
Not used, just here for compatibility.
sampling_rate : None
Not used, just here for compatibility.
Example
-------
>>> tmpdir = getfixture("tmpdir")
>>> signal = torch.tensor([[1, 2, 3, 4]])
>>> write_stdout(signal, tmpdir / "example.txt")
[1, 2, 3, 4]
"""
# Managing Torch.Tensor
if isinstance(data, torch.Tensor):
data = data.tolist()
# Managing np.ndarray
if isinstance(data, np.ndarray):
data = data.tolist()
if isinstance(data, list):
for line in data:
print(line)
if isinstance(data, str):
print(data)
def length_to_mask(length, max_len=None, dtype=None, device=None):
"""Creates a binary mask for each sequence.
Reference: https://discuss.pytorch.org/t/how-to-generate-variable-length-mask/23397/3
Arguments
---------
length : torch.LongTensor
Containing the length of each sequence in the batch. Must be 1D.
max_len : int
Max length for the mask, also the size of the second dimension.
dtype : torch.dtype, default: None
The dtype of the generated mask.
device: torch.device, default: None
The device to put the mask variable.
Returns
-------
mask : tensor
The binary mask.
Example
-------
>>> length = torch.Tensor([1, 2, 3])
>>> mask = length_to_mask(length)
>>> mask
tensor([[1., 0., 0.],
[1., 1., 0.],
[1., 1., 1.]])
"""
assert len(length.shape) == 1
if max_len is None:
max_len = length.max().long().item() # using arange to generate mask
mask = torch.arange(
max_len, device=length.device, dtype=length.dtype
).expand(len(length), max_len) < length.unsqueeze(1)
if dtype is None:
dtype = length.dtype
if device is None:
device = length.device
mask = torch.as_tensor(mask, dtype=dtype, device=device)
return mask
def read_kaldi_lab(kaldi_ali, kaldi_lab_opts):
"""Read labels in kaldi format.
Uses kaldi IO.
Arguments
---------
kaldi_ali : str
Path to directory where kaldi alignments are stored.
kaldi_lab_opts : str
A string that contains the options for reading the kaldi alignments.
Returns
-------
lab : dict
A dictionary containing the labels.
Note
----
This depends on kaldi-io-for-python. Install it separately.
See: https://github.com/vesis84/kaldi-io-for-python
Example
-------
This example requires kaldi files.
```
lab_folder = "/home/kaldi/egs/TIMIT/s5/exp/dnn4_pretrain-dbn_dnn_ali"
read_kaldi_lab(lab_folder, "ali-to-pdf")
```
"""
# EXTRA TOOLS
try:
import kaldi_io
except ImportError:
raise ImportError("Could not import kaldi_io. Install it to use this.")
# Reading the Kaldi labels
lab = {
k: v
for k, v in kaldi_io.read_vec_int_ark(
"gunzip -c "
+ kaldi_ali
+ "/ali*.gz | "
+ kaldi_lab_opts
+ " "
+ kaldi_ali
+ "/final.mdl ark:- ark:-|"
)
}
return lab
def get_md5(file):
"""Get the md5 checksum of an input file.
Arguments
---------
file : str
Path to file for which compute the checksum.
Returns
-------
md5
Checksum for the given filepath.
Example
-------
>>> get_md5("tests/samples/single-mic/example1.wav")
'c482d0081ca35302d30d12f1136c34e5'
"""
# Lets read stuff in 64kb chunks!
BUF_SIZE = 65536
md5 = hashlib.md5()
# Computing md5
with open(file, "rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
md5.update(data)
return md5.hexdigest()
def save_md5(files, out_file):
"""Saves the md5 of a list of input files as a pickled dict into a file.
Arguments
---------
files : list
List of input files from which we will compute the md5.
out_file : str
The path where to store the output pkl file.
Example
-------
>>> files = ["tests/samples/single-mic/example1.wav"]
>>> tmpdir = getfixture("tmpdir")
>>> save_md5(files, tmpdir / "md5.pkl")
"""
# Initialization of the dictionary
md5_dict = {}
# Computing md5 for all the files in the list
for file in files:
md5_dict[file] = get_md5(file)
# Saving dictionary in pkl format
save_pkl(md5_dict, out_file)
def save_pkl(obj, file):
"""Save an object in pkl format.
Arguments
---------
obj : object
Object to save in pkl format
file : str
Path to the output file
Example
-------
>>> tmpfile = getfixture("tmpdir") / "example.pkl"
>>> save_pkl([1, 2, 3, 4, 5], tmpfile)
>>> load_pkl(tmpfile)
[1, 2, 3, 4, 5]
"""
with open(file, "wb") as f:
pickle.dump(obj, f)
def load_pkl(file):
"""Loads a pkl file.
For an example, see `save_pkl`.
Arguments
---------
file : str
Path to the input pkl file.
Returns
-------
The loaded object.
"""
# Deals with the situation where two processes are trying
# to access the same label dictionary by creating a lock
count = 100
while count > 0:
if os.path.isfile(file + ".lock"):
time.sleep(1)
count -= 1