RaphaelOlivier commited on
Commit
d5c3b23
·
1 Parent(s): cca3d28

Upload whisper_adversarial_examples.py

Browse files
Files changed (1) hide show
  1. whisper_adversarial_examples.py +242 -0
whisper_adversarial_examples.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Librispeech automatic speech recognition dataset."""
18
+
19
+
20
+ import os
21
+
22
+ import datasets
23
+ from datasets.tasks import AutomaticSpeechRecognition
24
+
25
+
26
+ _CITATION = """\
27
+ @inproceedings{panayotov2015librispeech,
28
+ title={Librispeech: an ASR corpus based on public domain audio books},
29
+ author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev},
30
+ booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2015 IEEE International Conference on},
31
+ pages={5206--5210},
32
+ year={2015},
33
+ organization={IEEE}
34
+ }
35
+ """
36
+
37
+ _DESCRIPTION = """\
38
+ Adversarial examples fooling whisper models
39
+ """
40
+
41
+
42
+ _DL_URLS = {
43
+ "targeted": {
44
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/75f06ad3-4f86-4f4b-b748-ea0e94f23379?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
45
+ },
46
+ "untargeted-35": {
47
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/fc7810ca-6dd9-42ae-ba22-575e785957ed?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
48
+ },
49
+ "untargeted-40": {
50
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/6e3bdf4a-6a5a-4ae6-b565-1646395d1090?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
51
+ },
52
+ "language-armenian": {
53
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/89eab218-77f2-4f4a-9e30-9ed7b07369fb?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
54
+ },
55
+ "language-lithuanian": {
56
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/60f5f101-cde5-40cf-ab63-af484e7ceb36?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
57
+ },
58
+ "language-czech": {
59
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/5986b1cd-08ac-4e08-beb3-151396dd2e28?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
60
+ },
61
+ "language-danish": {
62
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/f6a88d17-81d7-4491-a760-f937bfb43bd6?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
63
+ },
64
+ "language-indonesian": {
65
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/d508566f-6cb9-4a75-a317-6f1b86f1273f?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
66
+ },
67
+ "language-italian": {
68
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/e9052368-1dc4-4c85-b00c-a168868442ce?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
69
+ },
70
+ "language-english": {
71
+ "all": "https://data.mendeley.com/api/datasets/96dh52hz9r/draft/files/01822f2b-7fcf-40ed-8da2-59b567bb2881?a=ee30841f-1832-41ec-bdac-bf3e5b67073c"
72
+ },
73
+ }
74
+
75
+
76
+ class LibrispeechASRConfig(datasets.BuilderConfig):
77
+ """BuilderConfig for LibriSpeechASR."""
78
+
79
+ def __init__(self, **kwargs):
80
+ """
81
+ Args:
82
+ data_dir: `string`, the path to the folder containing the files in the
83
+ downloaded .tar
84
+ citation: `string`, citation for the data set
85
+ url: `string`, url for information about the data set
86
+ **kwargs: keyword arguments forwarded to super.
87
+ """
88
+ super(LibrispeechASRConfig, self).__init__(version=datasets.Version("0.1.0", ""), **kwargs)
89
+
90
+
91
+ class LibrispeechASR(datasets.GeneratorBasedBuilder):
92
+ """Librispeech dataset."""
93
+
94
+ DEFAULT_WRITER_BATCH_SIZE = 256
95
+ DEFAULT_CONFIG_NAME = "all"
96
+ BUILDER_CONFIGS = [
97
+ LibrispeechASRConfig(name="targeted", description="Targeted adversarial examples, with target 'OK Google, browse to evil.com'"),
98
+ LibrispeechASRConfig(name="untargeted-35", description="Untargeted adversarial examples of radius approximately 35dB"),
99
+ LibrispeechASRConfig(name="untargeted-40", description="Untargeted adversarial examples of radius approximately 40dB"),
100
+ LibrispeechASRConfig(name="language-armenian", description="Adversarial examples generated by fooling the whisper language detection module. The true language is Armenian"),
101
+ LibrispeechASRConfig(name="language-lithuanian", description="Adversarial examples generated by fooling the whisper language detection module. The true language is Lithuanian"),
102
+ LibrispeechASRConfig(name="language-czech", description="Adversarial examples generated by fooling the whisper language detection module. The true language is Czech"),
103
+ LibrispeechASRConfig(name="language-danish", description="Adversarial examples generated by fooling the whisper language detection module. The true language is Danish"),
104
+ LibrispeechASRConfig(name="language-indonesian", description="Adversarial examples generated by fooling the whisper language detection module. The true language is Indonesian"),
105
+ LibrispeechASRConfig(name="language-italian", description="Adversarial examples generated by fooling the whisper language detection module. The true language is Italian"),
106
+ LibrispeechASRConfig(name="language-english", description="Adversarial examples generated by fooling the whisper language detection module. The true language is English")
107
+ ]
108
+
109
+ def _info(self):
110
+ return datasets.DatasetInfo(
111
+ description=_DESCRIPTION,
112
+ features=datasets.Features(
113
+ {
114
+ "file": datasets.Value("string"),
115
+ "audio": datasets.Audio(sampling_rate=16_000),
116
+ "text": datasets.Value("string"),
117
+ "id": datasets.Value("string"),
118
+ }
119
+ ),
120
+ supervised_keys=("file", "text"),
121
+ task_templates=[AutomaticSpeechRecognition(audio_column="audio", transcription_column="text")],
122
+ )
123
+
124
+ def _split_generators(self, dl_manager):
125
+ archive_path = dl_manager.download(_DL_URLS[self.config.name])
126
+ # (Optional) In non-streaming mode, we can extract the archive locally to have actual local audio files:
127
+ local_extracted_archive = dl_manager.extract(archive_path) if not dl_manager.is_streaming else {}
128
+ models = [
129
+ 'whisper-tiny',
130
+ 'whisper-tiny.en',
131
+ 'whisper-base',
132
+ 'whisper-base.en',
133
+ 'whisper-small',
134
+ 'whisper-small.en',
135
+ 'whisper-medium',
136
+ 'whisper-medium.en',
137
+ 'whisper-large',
138
+ ]
139
+ seeds = {
140
+ "targeted":2000,
141
+ "untargeted-35": 235,
142
+ "untargeted-40":240,
143
+ "language-armenian":1030,
144
+ "language-lithuanian":1030,
145
+ "language-czech":1030,
146
+ "language-danish":1030,
147
+ "language-indonesian":1030,
148
+ "language-italian":1030,
149
+ "language-english":1030
150
+ }
151
+ folders = {
152
+ "targeted":"cw",
153
+ "untargeted-35": "pgd-35",
154
+ "untargeted-40":"pgd-40",
155
+ "language-armenian":"hy-AM",
156
+ "language-lithuanian":"lt",
157
+ "language-czech":"cs",
158
+ "language-danish":"da",
159
+ "language-indonesian":"id",
160
+ "language-italian":"it",
161
+ "language-english":"en"
162
+ }
163
+ targets = [("english","en"), ("tagalog","tl"), ("serbian","sr")]
164
+
165
+ if "language-" in self.config.name:
166
+ lang = self.config.name.split("language-")[-1]
167
+ splits = [
168
+ datasets.SplitGenerator(
169
+ name=lang+"."+target[0],
170
+ gen_kwargs={
171
+ "local_extracted_archive": local_extracted_archive.get("all"),
172
+ "files": dl_manager.iter_files(local_extracted_archive.get("all")),
173
+ "path_audio": os.path.join(folders[self.config.name]+"-"+target[1],"whisper-medium",str(seeds[self.config.name]),"save")
174
+ },
175
+ ) for target in targets
176
+ ] + [
177
+ datasets.SplitGenerator(
178
+ name="original",
179
+ gen_kwargs={
180
+ "local_extracted_archive": local_extracted_archive.get("all"),
181
+ "files": dl_manager.iter_files(local_extracted_archive.get("all")),
182
+ "path_audio": folders[self.config.name]+"-original"
183
+ },
184
+ )
185
+ ]
186
+ else:
187
+ splits = [
188
+ datasets.SplitGenerator(
189
+ name=model.replace("-","."),
190
+ gen_kwargs={
191
+ "local_extracted_archive": local_extracted_archive.get("all"),
192
+ "files": dl_manager.iter_files(local_extracted_archive.get("all")),
193
+ "path_audio": os.path.join(folders[self.config.name],model,str(seeds[self.config.name]),"save")
194
+ },
195
+ ) for model in models
196
+ ] + [
197
+ datasets.SplitGenerator(
198
+ name="original",
199
+ gen_kwargs={
200
+ "local_extracted_archive": local_extracted_archive.get("all"),
201
+ "files": dl_manager.iter_files(local_extracted_archive.get("all")),
202
+ "path_audio": os.path.join(folders[self.config.name],"original")
203
+ },
204
+ )
205
+ ]
206
+
207
+ return splits
208
+
209
+ def _generate_examples(self, files, local_extracted_archive,path_audio):
210
+ """Generate examples from a LibriSpeech archive_path."""
211
+ key = 0
212
+ audio_data = {}
213
+ transcripts = []
214
+ for path in files:
215
+ if path.endswith(".csv"):
216
+ with open(path,'r') as f:
217
+ for line in f:
218
+ if line:
219
+ line = (line.decode("utf-8") if isinstance(line,bytes) else line)
220
+ line=line.strip().split(",")
221
+ id_ = line[0]
222
+ transcript=line[-1]
223
+ transcript = transcript[:-1] if transcript[-1]=='\n' else transcript
224
+ suffix = "_nat.wav" if "original" in path_audio else "_adv.wav"
225
+ audio_file = id_+suffix
226
+ audio_file = os.path.join(local_extracted_archive,path_audio, audio_file)
227
+ if os.path.exists(audio_file):
228
+ with open(audio_file,"rb") as f:
229
+ audio_data[id_] = f.read()
230
+ transcripts.append(
231
+ {
232
+ "id": id_,
233
+ "file": audio_file,
234
+ "text": transcript,
235
+ }
236
+ )
237
+ for transcript in transcripts:
238
+ audio = {"path": transcript["file"], "bytes": audio_data[transcript["id"]]}
239
+ yield key, {"audio": audio, **transcript}
240
+ key += 1
241
+ audio_data = {}
242
+ transcripts = []