forked from speechbrain/speechbrain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswitchboard_prepare.py
1261 lines (1071 loc) · 41.9 KB
/
switchboard_prepare.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
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
"""
This script prepares the data of the switchboard-1 release 2 corpus (LDC97S62).
Optionally, the Fisher corpus transcripts (LDC2004T19 and LDC2005T19) can be added to
the CSVs for Tokenizer and LM training.
The test set is based on the eval2000/Hub 5 data (LDC2002S09/LDC2002T43).
The datasets can be obtained from:
- Switchboard: https://catalog.ldc.upenn.edu/LDC97S62
- Fisher part 1: https://catalog.ldc.upenn.edu/LDC2004T19
- Fisher part 2: https://catalog.ldc.upenn.edu/LDC2005T19
The test data is available at:
- Speech data: https://catalog.ldc.upenn.edu/LDC2002S09
- Transcripts: https://catalog.ldc.upenn.edu/LDC2002T43
Author
------
Dominik Wagner 2022
"""
import csv
import os
import re
from collections import defaultdict
from speechbrain.dataio.dataio import merge_csvs
from speechbrain.utils.data_utils import download_file, get_all_files
from speechbrain.utils.logger import get_logger
logger = get_logger(__name__)
SAMPLERATE = 8000
def prepare_switchboard(
data_folder,
save_folder,
splits=None,
split_ratio=None,
merge_lst=None,
merge_name=None,
skip_prep=False,
add_fisher_corpus=False,
max_utt=300,
):
"""
Main function for Switchboard data preparation.
Arguments
---------
data_folder : str
Path to the folder where the Switchboard (and Fisher) datasets are stored.
Note that the Fisher data must be stored (or at least symlinked)
to the same location.
save_folder : str
The directory to store the outputs generated by this script.
splits : list
A list of data splits you want to obtain from the Switchboard dataset.
This would be usually ["train", "dev"] since the "test" set is generated
separately using the Hub5/eval2000 portion of the Switchboard corpus.
The default split is into a ["train", "dev"] portion based on
the split_ratio argument.
split_ratio : list
List containing the portions you want to allocate to
each of your data splits e.g. [90, 10]. The default is [90, 10].
merge_lst : list
This allows you to merge some (or all) of the data splits you specified
(e.g. ["train", "dev"]) into a single file. The default is [], i.e. no merging.
merge_name : str
Name of the merged csv file.
skip_prep : bool
If True, data preparation is skipped.
add_fisher_corpus : bool
If True, a separate csv file called "train_lm.csv" will be created containing
the Switchboard training data and the Fisher corpus transcripts.
The "train_lm.csv" file can be used instead of the regular "train.csv" file
for LM and Tokenizer training.
Note that this requires the Fisher corpus (part 1 and part 2)
to be downloaded in your data_folder location.
max_utt : int
Remove excess utterances once they appear more than a specified
number of times with the same transcription, in a data set.
This is useful for removing utterances like "uh-huh" from training.
Returns
-------
None
Example
-------
>>> data_folder = "/nfs/data/ldc"
>>> save_folder = "swbd_data"
>>> splits = ["train", "dev"]
>>> split_ratio = [90, 10]
>>> prepare_switchboard(data_folder, save_folder, splits, split_ratio, add_fisher_corpus=True)
"""
if merge_lst is None:
merge_lst = []
if split_ratio is None:
split_ratio = [90, 10]
if splits is None:
splits = ["train", "dev"]
if skip_prep:
logger.info("Data preparation skipped manually via hparams")
return
filenames = []
for split in splits:
filenames.append(os.path.join(save_folder, str(split + ".csv")))
if add_fisher_corpus:
filenames.append(os.path.join(save_folder, "train_lm.csv"))
filenames.append(os.path.join(save_folder, "test.csv"))
if skip(*filenames):
logger.info("Preparation completed in previous run, skipping.")
return
swbd_train_lines = swbd1_data_prep(
data_folder,
save_folder,
splits,
split_ratio,
add_fisher_corpus=add_fisher_corpus,
max_utt=max_utt,
)
# Merging csv file if needed
maybe_merge_files(merge_name, merge_lst)
# Prepare eval2000 testset
eval2000_data_prep(data_folder, save_folder)
if add_fisher_corpus:
fisher_lines = fisher_data_prep(data_folder, save_folder)
# fisher_lines already contains a header, so we don't need to add one here
combined_lines = fisher_lines + swbd_train_lines
csv_file = os.path.join(save_folder, "train_lm.csv")
# We set max_utt to a large number, so all utterances will be included in train_lm.csv
# Note that the Kaldi recipe also doesn't care about a maximum utterance number in the
# LM training corpus.
write_csv(csv_file, combined_lines, utt_id_idx=1, max_utt=999999999)
logger.info("Switchboard data preparation finished.")
def write_csv(csv_file, csv_lines, utt_id_idx=0, max_utt=300):
"""
Write utterances to a .csv file.
Arguments
---------
csv_file : str
Full path of the file to save
csv_lines : list
A list of lists containing the data to write to the .csv file.
utt_id_idx : int
Element in the list representing a line that marks the utterance id.
This is necessary to keep track of duplicate utterances.
max_utt : int
Maximum number of duplicate utterances to be written.
Once max_utt is exceeded, any lines containing the same
utterance will not be written to the .csv file
"""
# Keep track of the number of times each utterance appears
utt2count = defaultdict(int)
with open(csv_file, mode="w") as csv_f:
csv_writer = csv.writer(
csv_f, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL
)
for line in csv_lines:
current_utt = line[utt_id_idx]
# Avoid that the same utterance becomes part of the dataset too often
if utt2count[current_utt] < max_utt:
csv_writer.writerow(line)
utt2count[current_utt] += 1
def maybe_merge_files(merge_name, merge_lst: list):
"""
Merge multiple .csv files and store the combined data in a new file.
Arguments
---------
merge_name : str
New name to save the combined files under.
merge_lst : list
List of data splits to be merged.
"""
if len(merge_lst) > 1:
if merge_name is not None and len(merge_name) > 0:
merge_files = [data_split + ".csv" for data_split in merge_lst]
merge_csvs(
data_folder=save_folder,
csv_lst=merge_files,
merged_csv=merge_name,
)
else:
logger.warning(
"No name for merged .csv supplied. "
"You can pass a name for the merged .csv files "
"via the merge_name parameter. Not combining any .csv files!"
)
def check_data_folder(root_folder):
"""
Check if all directories exist to prepare the Switchboard dataset.
Arguments
---------
root_folder : str
Root directory, where the Switchboard data is located.
Expects the following subdirectories to exist:
"docs", "swb1_d1", "swb1_d2", "swb1_d3", "swb1_d4"
"""
for sub_folder in ["docs", "swb1_d1", "swb1_d2", "swb1_d3", "swb1_d4"]:
swbd_folder = os.path.join(root_folder, sub_folder)
if not os.path.exists(swbd_folder):
err_msg = f"The folder {swbd_folder} does not exist (it is expected in the Switchboard dataset)"
raise OSError(err_msg)
def download_transcripts(target_folder):
"""
Download and unpack Switchboard transcripts from OpenSLR.
Arguments
---------
target_folder : str
Desired location to store the transcripts.
"""
transcription_dir = os.path.join(target_folder, "swb_ms98_transcriptions")
if not os.path.exists(transcription_dir):
logger.info(
f"Download transcriptions and store them in {target_folder}"
)
download_source = "http://www.openslr.org/resources/5/switchboard_word_alignments.tar.gz"
download_target = os.path.join(
target_folder, "switchboard_word_alignments.tar.gz"
)
download_file(download_source, download_target, unpack=True)
else:
logger.info(
f"Skipping download of transcriptions because {target_folder} already exists."
)
def skip(*filenames):
"""
Detects if the Switchboard data preparation has already been done.
Arguments
---------
*filenames : tuple
List of paths to check for existence.
Returns
-------
bool
if True, the preparation phase can be skipped.
if False, preparation must be done.
"""
for filename in filenames:
if not os.path.isfile(filename):
return False
return True
def filter_text(
transcription: str, dataset="train", acronyms=None, acronyms_noi=None
):
"""
This function takes a string representing a sentence in one
of the datasets and cleans it using various regular expressions.
The types of regular expressions applied depend on the dataset.
Arguments
---------
transcription : str
A transcribed sentence
dataset : str
Either "train", "eval2000", or "fisher" depending on the type
of data you want to clean.
acronyms : dict
Dictionary mapping acronyms to Fisher convention (only relevant for swbd1 training data)
acronyms_noi : dict
Dictionary mapping acronyms to Fisher convention without I (only relevant for swbd1 training data)
Returns
-------
A string containing the cleaned sentence.
"""
dataset = dataset.strip().lower()
if dataset == "train":
# This is similar to what swbd1_data_prep.sh and swbd1_map_words.pl does.
transcription = re.sub(
r"\[SILENCE\]", "", transcription, flags=re.IGNORECASE
)
transcription = re.sub(r"<.*?>", "", transcription)
transcription = match_swbd1(transcription.strip())
transcription = re.sub(r"\s\s+", " ", transcription)
# Convert acronyms to Fisher convention
if len(transcription) > 0:
transcription = map_acronyms(acronyms, acronyms_noi, transcription)
# Split acronyms written as u._c._l._a._ into single characters (e.g. u c l a)
transcription = remove_acronym_symbols(transcription)
transcription = transcription.upper().strip()
elif dataset in ["eval2000", "hub5", "test"]:
# This is similar to what eval2000_data_prep.sh does.
transcription = match_eval2000(transcription.strip())
elif dataset == "fisher":
# This is similar to what fisher_data_prep.sh does.
transcription = match_fisher(transcription.strip())
else:
raise NameError(f"Invalid dataset descriptor '{dataset}' supplied.")
# Remove redundant whitespaces
transcription = re.sub(r"\s\s+", " ", transcription)
return transcription.strip()
# cspell:ignore WOLMANIZED
def match_swbd1(text):
"""
Clean transcripts in the Switchboard-1 training data.
The transformations we do are:
- remove laughter markings, e.g. [LAUGHTER-STORY] -> STORY
- Remove partial-words, e.g. -[40]1K becomes -1K and -[AN]Y IY becomes -Y
Also, curly braces, which appear to be used for "nonstandard"
words or non-words, are removed, e.g. {WOLMANIZED} -> WOLMANIZED
This is similar to Kaldi's swbd1_map_words.pl.
Arguments
---------
text : str
Input text from the Switchboard-1 training data.
Returns
-------
A string containing the cleaned sentence.
"""
tokens = text.split()
parsed_tokens = []
# cspell:disable
for token in tokens:
# e.g. [LAUGHTER-STORY] -> STORY; elem 1 and 3 relate to preserving trailing "-"
m = re.match(r"(|-)^\[LAUGHTER-(.+)\](|-)$", token, flags=re.IGNORECASE)
token = "".join(m.group(1, 2, 3)) if m else token
# e.g. [IT'N/ISN'T] -> IT'N
# Note: 1st part may include partial-word stuff, which we process further below,
# e.g. [LEM[GUINI]-/LINGUINI]
m = re.match(r"^\[(.+)/.+\](|-)$", token)
token = "".join(m.group(1, 2)) if m else token
# e.g. -[AN]Y -> -Y
m = re.match(r"^(|-)\[[^][]+\](.+)$", token)
token = "-" + m.group(2) if m else token
# e.g. AB[SOLUTE]- -> AB-;
m = re.match(r"^(.+)\[[^][]+\](|-)$", token)
token = "".join(m.group(1, 2)) if m else token
# e.g. EX[SPECIALLY]-/ESPECIALLY] -> EX
m = re.match(r"([^][]+)\[.+\]$", token)
token = m.group(1) if m else token
# e.g. {YUPPIEDOM} -> YUPPIEDOM
m = re.match(r"^\{(.+)\}$", token)
token = m.group(1) if m else token
# e.g. AMMU[N]IT- -> AMMU-IT
m = re.match(r"(\w+)\[([^][])+\](\w+)", token)
token = m.group(1) + "-" + m.group(3) if m else token
# e.g. THEM_1 -> THEM
token = re.sub(r"_\d+$", "", token)
parsed_tokens.append(token)
return " ".join(parsed_tokens)
# cspell:enable
def match_eval2000(text):
"""
Clean transcripts in the 2000 Hub5 english evaluation test (LDC2002S09 LDC2002T43)
See:
http://www.ldc.upenn.edu/Catalog/catalogEntry.jsp?catalogId=LDC2002S09
http://www.ldc.upenn.edu/Catalog/CatalogEntry.jsp?catalogId=LDC2002T43
This is similar to eval2000_data_prep.sh
Arguments
---------
text : str
Input text from the eval2000 test data.
Returns
-------
A string containing the cleaned sentence.
"""
cleaned_text = ""
# Remove utterance when it's just optional nonwords
text = text.strip().upper()
for nw in ["UM-HUM", "UMM", "UH-HUH", "MHM", "UH-OH"]:
text = text.replace(nw, "")
if "IGNORE_TIME_SEGMENT_" not in text:
# Remove <B_ASIDE> and <E_ASIDE>.
cleaned_text = re.sub(r"<.*?>", "", text)
# Remove everything that is declared optional e.g. (%HESITATION) or (WE-)
cleaned_text = re.sub(r"[\(\[].*?[\)\]]", "", cleaned_text)
else:
logger.debug(f"Ignoring eval2000 segment: {text}")
return cleaned_text
def match_fisher(text):
"""
Clean transcripts in the Fisher corpus.
This is similar to fisher_data_prep.sh
Arguments
---------
text : str
Input text from the Fisher data.
Returns
-------
A string containing the cleaned sentence.
"""
cleaned_text = ""
# Remove utterance when it's just optional nonwords
text = text.strip().upper()
for nw in ["UM-HUM", "UMM", "UH-HUH", "MHM", "UH-OH"]:
text = text.replace(nw, "")
if "((" not in text:
cleaned_text = re.sub(
r"\[laugh\]", "[laughter]", text, flags=re.IGNORECASE
)
cleaned_text = re.sub(
r"\[sigh\]", "[noise]", cleaned_text, flags=re.IGNORECASE
)
cleaned_text = re.sub(
r"\[cough\]", "[noise]", cleaned_text, flags=re.IGNORECASE
)
cleaned_text = re.sub(
r"\[sigh\]", "[noise]", cleaned_text, flags=re.IGNORECASE
)
cleaned_text = re.sub(
r"\[mn\]", "[noise]", cleaned_text, flags=re.IGNORECASE
)
cleaned_text = re.sub(
r"\[breath\]", "[noise]", cleaned_text, flags=re.IGNORECASE
)
cleaned_text = re.sub(
r"\[lipsmack\]", "[noise]", cleaned_text, flags=re.IGNORECASE
)
return cleaned_text
def remove_acronym_symbols(text):
"""
Remove symbols according to the Fisher acronym convention.
This splits acronyms written as u._c._l._a._ into single characters (e.g. u c l a)
Arguments
---------
text : str
Input text
Returns
-------
A string containing the cleaned text.
"""
cleaned_text = re.sub(r"\._", " ", text)
cleaned_text = re.sub(r"\.", "", cleaned_text)
cleaned_text = re.sub(r"them_1", "them", cleaned_text, flags=re.IGNORECASE)
return cleaned_text
def prepare_lexicon(lexicon_file, output_file):
"""
Prepare the swbd1 lexicon for further processing.
The lexicon is used to find acronyms and to convert them into Fisher convention.
Arguments
---------
lexicon_file : str
Path to the sw-ms98-dict.text file in the Switchboard corpus
output_file : str
Path to store the cleaned lexicon at
Returns
-------
A list containing the cleaned lexicon entries
"""
lexicon = []
lex_out = open(output_file, "w")
with open(lexicon_file) as lf:
# Skip first row
next(lf)
for line in lf:
# Skip header
if line.startswith("#"):
continue
parsed_line = match_swbd1(line.strip())
if len(parsed_line) > 0:
lexicon.append(parsed_line)
lex_out.write(f"{parsed_line}\n")
return lexicon
def make_acronym_map(save_folder, lexicon_file, acronym_map_file):
"""
Create mappings that can be used to convert acronyms in the Switchboard corpus
into acronyms using the Fisher corpus convention.
Examples we want to convert:
IBM to i._b._m.
BBC to b._b._c.
BBCs to b._b._c.s
This is what Kaldi's format_acronyms_dict.py does.
Arguments
---------
save_folder : str
Folder to store the acronym map on disk
lexicon_file : str
Path to the sw-ms98-dict.text file
acronym_map_file : str
File to store the acronym map in
Returns
-------
Two dictionaries mapping from swbd acronyms to acronyms according to the Fisher corpus convention.
The first dict contains all entries, the other has the letter I removed.
"""
# Taken from https://github.com/kaldi-asr/kaldi/blob/master/egs/swbd/s5c/local/MSU_single_letter.txt
msu_single_letter = [
"A ey",
"B b iy",
"C s iy",
"D d iy",
"E iy",
"F eh f",
"G jh iy",
"H ey ch",
"I ay",
"J jh ey",
"K k ey",
"L eh l",
"M eh m",
"N eh n",
"O ow",
"P p iy",
"Q k y uw",
"R aa r",
"S eh s",
"T t iy",
"U y uw",
"V v iy",
"W d ah b ax l y uw",
"X eh k s",
"Y w ay",
"Z z iy",
]
fin_lex = (
prepare_lexicon(lexicon_file, os.path.join(save_folder, "lexicon.txt"))
+ msu_single_letter
)
logger.info(
f"Prepared Swbd1 + MSU single letter lexicon with {len(fin_lex)} entries"
)
fout_map = open(acronym_map_file, "w")
# Initialise single letter dictionary
dict_letter = {}
for single_letter_lex in msu_single_letter:
items = single_letter_lex.split()
dict_letter[items[0]] = single_letter_lex[len(items[0]) + 1 :].strip()
for lex in fin_lex:
items = lex.split()
word = items[0]
lexicon = lex[len(items[0]) + 1 :].strip()
# find acronyms from words with only letters and '
pre_match = re.match(r"^[A-Za-z]+$|^[A-Za-z]+\'s$|^[A-Za-z]+s$", word)
if pre_match:
# find if words in the form of xxx's is acronym
if word[-2:] == "'s" and (lexicon[-1] == "s" or lexicon[-1] == "z"):
actual_word = word[:-2]
actual_lexicon = lexicon[:-2]
acronym_lexicon = ""
for w in actual_word:
acronym_lexicon = (
acronym_lexicon + dict_letter[w.upper()] + " "
)
if acronym_lexicon.strip() == actual_lexicon:
acronym_mapped = ""
acronym_mapped_back = ""
for w in actual_word[:-1]:
acronym_mapped = acronym_mapped + w.lower() + "._"
acronym_mapped_back = (
acronym_mapped_back + w.lower() + " "
)
acronym_mapped = (
acronym_mapped + actual_word[-1].lower() + ".'s"
)
acronym_mapped_back = (
acronym_mapped_back + actual_word[-1].lower() + "'s"
)
fout_map.write(
word
+ "\t"
+ acronym_mapped
+ "\t"
+ acronym_mapped_back
+ "\n"
)
# find if words in the form of xxxs is acronym # cspell:ignore xxxs
elif word[-1] == "s" and (lexicon[-1] == "s" or lexicon[-1] == "z"):
actual_word = word[:-1]
actual_lexicon = lexicon[:-2]
acronym_lexicon = ""
for w in actual_word:
acronym_lexicon = (
acronym_lexicon + dict_letter[w.upper()] + " "
)
if acronym_lexicon.strip() == actual_lexicon:
acronym_mapped = ""
acronym_mapped_back = ""
for w in actual_word[:-1]:
acronym_mapped = acronym_mapped + w.lower() + "._"
acronym_mapped_back = (
acronym_mapped_back + w.lower() + " "
)
acronym_mapped = (
acronym_mapped + actual_word[-1].lower() + ".s"
)
acronym_mapped_back = (
acronym_mapped_back + actual_word[-1].lower() + "'s"
)
fout_map.write(
word
+ "\t"
+ acronym_mapped
+ "\t"
+ acronym_mapped_back
+ "\n"
)
# find if words in the form of xxx (not ended with 's or s) is acronym
elif word.find("'") == -1 and word[-1] != "s":
acronym_lexicon = ""
for w in word:
acronym_lexicon = (
acronym_lexicon + dict_letter[w.upper()] + " "
)
if acronym_lexicon.strip() == lexicon:
acronym_mapped = ""
acronym_mapped_back = ""
for w in word[:-1]:
acronym_mapped = acronym_mapped + w.lower() + "._"
acronym_mapped_back = (
acronym_mapped_back + w.lower() + " "
)
acronym_mapped = acronym_mapped + word[-1].lower() + "."
acronym_mapped_back = acronym_mapped_back + word[-1].lower()
fout_map.write(
word
+ "\t"
+ acronym_mapped
+ "\t"
+ acronym_mapped_back
+ "\n"
)
fout_map.close()
# Load acronym map for further processing
fin_map = open(acronym_map_file, "r")
dict_acronym = {}
dict_acronym_noi = {} # Mapping of acronyms without I, i
for pair in fin_map:
items = pair.split("\t")
dict_acronym[items[0]] = items[1]
dict_acronym_noi[items[0]] = items[1]
fin_map.close()
del dict_acronym_noi["I"]
del dict_acronym_noi["i"]
return dict_acronym, dict_acronym_noi
def map_acronyms(dict_acronym, dict_acronym_noi, transcription):
"""
Transform acronyms in Switchboard transcripts into Fisher corpus convention.
Examples we want to convert:
IBM to i._b._m.
BBC to b._b._c.
BBCs to b._b._c.s
This is what Kaldi's map_acronyms_transcripts.py does.
Arguments
---------
dict_acronym : dict
Mapping from swbd acronyms to acronyms according to the Fisher corpus convention
dict_acronym_noi : dict
Mapping from swbd acronyms to acronyms according to the Fisher corpus convention with the letter I removed
transcription : str
A sentence in the Switchboard transcripts
Returns
-------
The original sentence but with acronyms according to the Fisher convention
"""
items = transcription.split()
utt_length = len(items)
# First pass mapping to map I as part of acronym
for i in range(utt_length):
if items[i] == "I":
x = 0
while i - 1 - x >= 0 and re.match(r"^[A-Z]$", items[i - 1 - x]):
x += 1
y = 0
while i + 1 + y < utt_length and re.match(
r"^[A-Z]$", items[i + 1 + y]
):
y += 1
if x + y > 0:
for bias in range(-x, y + 1):
items[i + bias] = dict_acronym[items[i + bias]]
# Second pass mapping (not mapping 'i' and 'I')
for i in range(len(items)):
if items[i] in dict_acronym_noi.keys():
items[i] = dict_acronym_noi[items[i]]
sentence = " ".join(items[1:])
return items[0] + " " + sentence
def make_name_to_disk_dict(mapping_table: str):
"""
The Switchboard data is spread across 4 DVDs
represented by directories ("swb1_d1", "swb1_d2" and so on).
This function creates a lookup dictionary to map a given filename to the
disk it was stored on.
This information is useful to assemble the absolute path to the sph audio
files.
Arguments
---------
mapping_table : str
String representing the path to the mapping table file "swb1_all.dvd.tbl"
provided along with the rest of the Switchboard data.
Returns
-------
name2disk : dict
A dictionary that maps from sph filename (key) to disk-id (value)
"""
name2disk = {}
with open(mapping_table) as mt:
for line in mt:
split = line.split()
name = split[1].strip()
name2disk[name] = split[0].strip()
return name2disk
def swbd1_data_prep(
data_folder,
save_folder,
splits,
split_ratio,
add_fisher_corpus=False,
max_utt=9999999999,
):
"""
Prepare the Switchboard Phase 1 training data (LDC97S62).
Arguments
---------
data_folder : str
Path to the data. Expects the LDC97S62 directory to be located there.
save_folder : str
Path where the file output will be stored
splits : list
A list of data splits you want to obtain from the Switchboard dataset (usually ["train", "dev"])
split_ratio : list
List containing the portions you want to allocate to each of your data splits e.g. [90, 10]
add_fisher_corpus : bool
If True, a separate csv file called "train_lm.csv" will be created which contains
the Switchboard training data and the Fisher corpus transcripts.
max_utt : int
Exclude utterances once they appear more than a specified number of times
Returns
-------
A list containing the prepared data for further processing
"""
logger.info("Starting data preparation for main Switchboard corpus")
train_data_folder = os.path.join(data_folder, "LDC97S62")
check_data_folder(train_data_folder)
if not os.path.exists(save_folder):
os.makedirs(save_folder)
download_transcripts(save_folder)
# Make a mapping from Switchboard acronyms to Fisher convention
logger.info("Preparing acronym mappings")
lexicon_input_file = os.path.join(
save_folder, "swb_ms98_transcriptions", "sw-ms98-dict.text"
)
acronym_map_output_file = os.path.join(save_folder, "acronyms.map")
dict_acronym, dict_acronym_noi = make_acronym_map(
save_folder, lexicon_input_file, acronym_map_output_file
)
assert len(splits) == len(split_ratio)
if sum(split_ratio) != 100 and sum(split_ratio) != 1:
error_msg = (
"Implausible split ratios! Make sure they equal to 1 (or 100)."
)
raise ValueError(error_msg)
if sum(split_ratio) == 100:
split_ratio = [i / 100 for i in split_ratio]
# collect all files containing transcriptions
transcript_files = get_all_files(
os.path.join(save_folder, "swb_ms98_transcriptions"),
match_and=["trans.text"],
)
split_lens = [int(i * len(transcript_files)) for i in split_ratio]
name2disk = make_name_to_disk_dict(
os.path.join(train_data_folder, "docs/swb1_all.dvd.tbl")
)
logger.info(
f"Made name2disk mapping dict containing {len(name2disk)} conversations."
)
start = 0
stop = 0
# We save all lines from the swbd train split, in case we want to combine them
# with the Fisher corpus for LM and Tokenizer training later
swbd_train_lines = []
for i, split in enumerate(splits):
stop += split_lens[i]
transcript_files_split = transcript_files[start:stop]
logger.info(
f"Preparing data for {split} split. "
f"Split will contain {len(transcript_files_split)} "
f"conversations separated by channel."
)
start += split_lens[i]
csv_lines = [
[
"ID",
"duration",
"start",
"stop",
"channel",
"wav",
"words",
"spk_id",
]
]
# Open each transcription file and extract information
for filename in transcript_files_split:
with open(filename) as file:
for line in file:
str_split = line.split()
id = str_split[0].strip()
channel = id.split("-")[0][-1]
wav_name = id.split("-")[0][:6] + ".sph"
spk_id = wav_name.replace(".sph", channel)
wav_name = wav_name.replace(wav_name[0:2], "sw0")
disk = name2disk[wav_name]
wav_path = os.path.join(
train_data_folder, disk, "data", wav_name
)
# We want the segment start and end times in samples,
# so we can slice the segment from the tensor
seg_start = int(float(str_split[1].strip()) * SAMPLERATE)
seg_end = int(float(str_split[2].strip()) * SAMPLERATE)
audio_duration = (seg_end - seg_start) / SAMPLERATE
transcription = " ".join(str_split[3:])
cleaned_transcription = filter_text(
transcription,
dataset="train",
acronyms=dict_acronym,
acronyms_noi=dict_acronym_noi,
)
# Skip empty transcriptions
if len(cleaned_transcription) > 0:
csv_lines.append(
[
id,
audio_duration,
seg_start,
seg_end,
channel,
wav_path,
cleaned_transcription,
spk_id,
]
)
# We store the lines from the first split
# (assuming this is the training data) in a separate list
# so we can easily merge it with the Fisher data later
if add_fisher_corpus and i == 0:
swbd_train_lines.append([id, cleaned_transcription])
# Setting path for the csv file
csv_file = os.path.join(save_folder, str(split + ".csv"))
logger.info(f"Creating csv file {csv_file}")
write_csv(csv_file, csv_lines, utt_id_idx=6, max_utt=max_utt)
return swbd_train_lines
def eval2000_data_prep(data_folder: str, save_folder: str):
"""
Prepare the eval2000/Hub5 English data (LDC2002S09 and LDC2002T43).
The data serves as the test set and is separated into
the full dataset (test.csv), the Switchboard portion
of the dataset (test_swbd.csv) and the Callhome portion
of the dataset (test_callhome.csv).
Arguments
---------
data_folder : str
Path to the folder where the eval2000/Hub5 English data is located.
save_folder : str
The directory to store the csv files at.
"""
logger.info(
"Begin preparing the eval2000 Hub5 English test set and transcripts (LDC2002S09 and LDC2002T43)"
)
audio_folder = os.path.join(data_folder, "LDC2002S09/hub5e_00/english")
transcription_file = os.path.join(
data_folder,
"LDC2002T43/2000_hub5_eng_eval_tr/reference/hub5e00.english.000405.stm",
)
for d in [audio_folder, transcription_file]:
if not os.path.exists(d):
err_msg = f"The folder {d} does not exist (it is expected to prepare the eval2000/hub5 test set)"
raise OSError(err_msg)
csv_lines_callhome = [
["ID", "duration", "start", "stop", "channel", "wav", "words", "spk_id"]
]
csv_lines_swbd = [
["ID", "duration", "start", "stop", "channel", "wav", "words", "spk_id"]
]