RaphaelOlivier commited on
Commit
ddf469d
1 Parent(s): be94471

Upload librispeech_asr_adversarial.py

Browse files
Files changed (1) hide show
  1. librispeech_asr_adversarial.py +139 -0
librispeech_asr_adversarial.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Lint as: python3
17
+ """Adversarial examples based on the Librispeech automatic speech recognition dataset."""
18
+
19
+ from __future__ import absolute_import, division, print_function
20
+
21
+ import glob
22
+ import os
23
+
24
+ import datasets
25
+
26
+
27
+ # TODO: change
28
+ _CITATION = """\
29
+ @inproceedings{panayotov2015librispeech,
30
+ title={Librispeech: an ASR corpus based on public domain audio books},
31
+ author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev},
32
+ booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2015 IEEE International Conference on},
33
+ pages={5206--5210},
34
+ year={2015},
35
+ organization={IEEE}
36
+ }
37
+ """
38
+
39
+ # TODO: change
40
+ _DESCRIPTION = """\
41
+ LibriSpeech is a corpus of approximately 1000 hours of read English speech with sampling rate of 16 kHz,
42
+ prepared by Vassil Panayotov with the assistance of Daniel Povey. The data is derived from read
43
+ audiobooks from the LibriVox project, and has been carefully segmented and aligned.
44
+ Note that in order to limit the required storage for preparing this dataset, the audio
45
+ is stored in the .flac format and is not converted to a float32 array. To convert, the audio
46
+ file to a float32 array, please make use of the `.map()` function as follows:
47
+ ```python
48
+ import soundfile as sf
49
+ def map_to_array(batch):
50
+ speech_array, _ = sf.read(batch["file"])
51
+ batch["speech"] = speech_array
52
+ return batch
53
+ dataset = dataset.map(map_to_array, remove_columns=["file"])
54
+ ```
55
+ """
56
+ # TODO: change
57
+ _DL_URL = "https://drive.google.com/file/d/1oaBhaHlY4TD2JcvenR-6OZNIsyPG8OGN/view?usp=sharing"
58
+
59
+
60
+ class LibrispeechASRConfig(datasets.BuilderConfig):
61
+ """BuilderConfig for LibriSpeechASR."""
62
+
63
+ def __init__(self, **kwargs):
64
+ """
65
+ Args:
66
+ data_dir: `string`, the path to the folder containing the files in the
67
+ downloaded .tar
68
+ citation: `string`, citation for the data set
69
+ url: `string`, url for information about the data set
70
+ **kwargs: keyword arguments forwarded to super.
71
+ """
72
+ super(LibrispeechASRConfig, self).__init__(
73
+ version=datasets.Version("2.1.0", ""), **kwargs)
74
+
75
+
76
+ class LibrispeechASR(datasets.GeneratorBasedBuilder):
77
+ """Librispeech dataset."""
78
+
79
+ BUILDER_CONFIGS = [
80
+ LibrispeechASRConfig(name="adv", description="'Adversarial' speech."),
81
+ ]
82
+
83
+ def _info(self):
84
+ return datasets.DatasetInfo(
85
+ description=_DESCRIPTION,
86
+ features=datasets.Features(
87
+ {
88
+ "file": datasets.Value("string"),
89
+ "audio": datasets.features.Audio(sampling_rate=16_000),
90
+ "text": datasets.Value("string"),
91
+ "id": datasets.Value("string"),
92
+ }
93
+ ),
94
+ supervised_keys=("speech", "text"),
95
+ homepage=_DL_URL,
96
+ citation=_CITATION,
97
+ )
98
+
99
+ def _split_generators(self, dl_manager):
100
+ archive_path = dl_manager.download_and_extract(
101
+ _DL_URL)
102
+ return [
103
+ datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={
104
+ "archive_path": archive_path["dev"], "split_name": f"dev_{self.config.name}"}),
105
+ ]
106
+
107
+ def _generate_examples(self, archive_path, split_name):
108
+ """Generate examples from a Librispeech archive_path."""
109
+ transcripts_glob = os.path.join(archive_path, "**/*.txt")
110
+ if split_name.endswith("adv-txt"):
111
+ split_folder = split_name[:-7]
112
+ use_adv_transcript = True
113
+ else:
114
+ assert split_name.endswith("nat-txt")
115
+ split_folder = split_name[:-7]
116
+ use_adv_transcript = False
117
+
118
+ for transcript_file in glob.glob(transcripts_glob):
119
+ path = os.path.dirname(transcript_file)
120
+ audio_path = os.path.join(path, split_folder)
121
+ with open(os.path.join(path, transcript_file)) as f:
122
+ for line in f:
123
+ line = line.strip()
124
+ key, og_transcript, adv_transcript = line.split(",", 2)
125
+ transcript = adv_transcript if use_adv_transcript else og_transcript
126
+ suffix = "adv" if use_adv_transcript else "nat"
127
+ audio_file = f"{key}_{suffix}.wav"
128
+ speaker_id, chapter_id = [int(el)
129
+ for el in key.split("-")[:2]]
130
+ split_key = key+"_"+suffix+"_"+split_name
131
+ example = {
132
+ "id": split_key,
133
+ "speaker_id": speaker_id,
134
+ "chapter_id": chapter_id,
135
+ "file": os.path.join(audio_path, audio_file),
136
+ "audio": os.path.join(audio_path, audio_file),
137
+ "text": transcript,
138
+ }
139
+ yield split_key, example