versae commited on
Commit
c7f7d90
1 Parent(s): 6e82d48

NB-Wav2Vec2-1B-Bokmaal-v2

Browse files
.gitattributes CHANGED
@@ -2,13 +2,11 @@
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
  *.npy filter=lfs diff=lfs merge=lfs -text
@@ -22,14 +20,19 @@
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
  *.wasm filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
5
  *.ftz filter=lfs diff=lfs merge=lfs -text
6
  *.gz filter=lfs diff=lfs merge=lfs -text
7
  *.h5 filter=lfs diff=lfs merge=lfs -text
8
  *.joblib filter=lfs diff=lfs merge=lfs -text
9
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
10
  *.model filter=lfs diff=lfs merge=lfs -text
11
  *.msgpack filter=lfs diff=lfs merge=lfs -text
12
  *.npy filter=lfs diff=lfs merge=lfs -text
 
20
  *.pt filter=lfs diff=lfs merge=lfs -text
21
  *.pth filter=lfs diff=lfs merge=lfs -text
22
  *.rar filter=lfs diff=lfs merge=lfs -text
 
23
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
25
  *.tflite filter=lfs diff=lfs merge=lfs -text
26
  *.tgz filter=lfs diff=lfs merge=lfs -text
27
  *.wasm filter=lfs diff=lfs merge=lfs -text
28
  *.xz filter=lfs diff=lfs merge=lfs -text
29
  *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
31
  *tfevents* filter=lfs diff=lfs merge=lfs -text
32
+ wandb/run-20220829_122920-1y92iq2k/run-1y92iq2k.wandb filter=lfs diff=lfs merge=lfs -text
33
+ wandb/run-20220829_122920-1y92iq2k/logs/debug-internal.log filter=lfs diff=lfs merge=lfs -text
34
+ wandb/run-20220829_122920-1y92iq2k/files/output.log filter=lfs diff=lfs merge=lfs -text
35
+ *.wandb filter=lfs diff=lfs merge=lfs -text
36
+ wandb/run-20220919_091325-3hu9r4oi/logs/debug-internal.log filter=lfs diff=lfs merge=lfs -text
37
+ wandb/run-20220919_091325-3hu9r4oi/files/output.log filter=lfs diff=lfs merge=lfs -text
38
+ language_model/unigrams.txt filter=lfs diff=lfs merge=lfs -text
add_kenlm.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from transformers import AutoProcessor
3
+ from transformers import Wav2Vec2ProcessorWithLM
4
+ from pyctcdecode import build_ctcdecoder
5
+
6
+
7
+ def main(args):
8
+ processor = AutoProcessor.from_pretrained(args.model_name_or_path)
9
+ vocab_dict = processor.tokenizer.get_vocab()
10
+ sorted_vocab_dict = {
11
+ k.lower(): v for k, v in sorted(vocab_dict.items(), key=lambda item: item[1])
12
+ }
13
+ decoder = build_ctcdecoder(
14
+ labels=list(sorted_vocab_dict.keys()),
15
+ kenlm_model_path=args.kenlm_model_path,
16
+ )
17
+ processor_with_lm = Wav2Vec2ProcessorWithLM(
18
+ feature_extractor=processor.feature_extractor,
19
+ tokenizer=processor.tokenizer,
20
+ decoder=decoder,
21
+ )
22
+ processor_with_lm.save_pretrained(args.model_name_or_path)
23
+ print(
24
+ f"Run: ~/bin/build_binary language_model/*.arpa language_model/5gram.bin -T $(pwd) && rm language_model/*.arpa")
25
+
26
+
27
+ def parse_args():
28
+ parser = argparse.ArgumentParser()
29
+ parser.add_argument('--model_name_or_path', default="./", help='Model name or path. Defaults to ./')
30
+ parser.add_argument('--kenlm_model_path', required=True, help='Path to KenLM arpa file.')
31
+ args = parser.parse_args()
32
+ return args
33
+
34
+
35
+ if __name__ == "__main__":
36
+ main(parse_args())
37
+
added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"<s>": 39, "</s>": 40}
alphabet.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"labels": [" ", "(", ")", "0", "3", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u00e5", "\u00e6", "\u00f8", "\u2047", "", "<s>", "</s>"], "is_bpe": false}
cardinal_numbers.py ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ """From https://github.com/peresolb/number-conversion/"""
5
+ import sys
6
+ import os
7
+ import nltk
8
+
9
+
10
+ # Dict for basic primitive numbers: 1-10
11
+ b = {
12
+ 1: "én",
13
+ 2: "to",
14
+ 3: "tre",
15
+ 4: "fire",
16
+ 5: "fem",
17
+ 6: "seks",
18
+ 7: "sju",
19
+ 8: "åtte",
20
+ 9: "ni",
21
+ 10: "ti",
22
+ }
23
+ b_nn = {
24
+ 1: "ein",
25
+ 2: "to",
26
+ 3: "tre",
27
+ 4: "fire",
28
+ 5: "fem",
29
+ 6: "seks",
30
+ 7: "sju",
31
+ 8: "åtte",
32
+ 9: "ni",
33
+ 10: "ti",
34
+ }
35
+
36
+ # Dict for teen primitive numbers: 11-19
37
+ t = {
38
+ 11: "elleve",
39
+ 12: "tolv",
40
+ 13: "tretten",
41
+ 14: "fjorten",
42
+ 15: "femten",
43
+ 16: "seksten",
44
+ 17: "sytten",
45
+ 18: "atten",
46
+ 19: "nitten",
47
+ }
48
+
49
+
50
+ # Dict for two digit primitive numbers: 20-90
51
+ do = {
52
+ 20: "tjue",
53
+ 30: "tretti",
54
+ 40: "førti",
55
+ 50: "femti",
56
+ 60: "seksti",
57
+ 70: "sytti",
58
+ 80: "åtti",
59
+ 90: "nitti",
60
+ }
61
+
62
+
63
+ # Dict for the 3 digit primitive number: 100
64
+ doo = {100: "hundre"}
65
+
66
+
67
+ # Dict for the 4 digit primitive number: 1000
68
+ dooo = {1000: "tusen"}
69
+
70
+
71
+ # Reverser function for primitive number dicts
72
+ def _revdict(numberdict):
73
+ newdict = {}
74
+ for k, v in numberdict.items():
75
+ newdict[v] = k
76
+ return newdict
77
+
78
+
79
+ # The reverse of the primitive number dicts, where strings are keys and integers are values,
80
+ # are name of original dict underscore 'r'
81
+ b_r, b_nn_r, t_r, do_r, doo_r, dooo_r = (
82
+ _revdict(b),
83
+ _revdict(b_nn),
84
+ _revdict(t),
85
+ _revdict(do),
86
+ _revdict(doo),
87
+ _revdict(dooo),
88
+ )
89
+
90
+
91
+ def _oneten(nr, reverse=False, nn=False):
92
+ """Function taking an int from 1-10 and returning the corresponding word,
93
+ or, if reverse=True, taking a numberword from 1-10 and returning the digit"""
94
+ if reverse == False:
95
+ if not type(nr) is int:
96
+ return None
97
+ if nr <= 10:
98
+ if nn == False:
99
+ return b[nr]
100
+ else:
101
+ return b_nn[nr]
102
+ else:
103
+ if not type(nr) is str:
104
+ return None
105
+ if nn == False:
106
+ if nr in b_r.keys():
107
+ return b_r[nr]
108
+ else:
109
+ if nr in b_nn_r.keys():
110
+ return b_nn_r[nr]
111
+
112
+
113
+ def _onedig(nr, reverse=False, nn=False):
114
+ if reverse == False:
115
+ if not _oneten(nr) == "ti":
116
+ if nn == False:
117
+ return _oneten(nr)
118
+ else:
119
+ return _oneten(nr, nn=True)
120
+ if reverse == True:
121
+ if not _oneten(nr, reverse=True) == 10:
122
+ if nn == False:
123
+ return _oneten(nr, reverse=True)
124
+ else:
125
+ return _oneten(nr, reverse=True, nn=True)
126
+
127
+
128
+ def _teen(nr, reverse=False):
129
+ """Function taking a primitive two-digit int in the teen range and returning the
130
+ corresponding word, or, if reverse=True, the corresponding number word"""
131
+ if reverse == False:
132
+ if not type(nr) is int:
133
+ return None
134
+ if nr in t.keys():
135
+ return t[nr]
136
+ else:
137
+ if not type(nr) is str:
138
+ return None
139
+ if nr in t_r.keys():
140
+ return t_r[nr]
141
+
142
+
143
+ def _twodig(nr, reverse=False):
144
+ """Function taking a primitive two-digit int in the range 20-90 and returning
145
+ the corresponding word, or, if reverse=True, the corresponding number word"""
146
+ if reverse == False:
147
+ if not type(nr) is int:
148
+ return None
149
+ if nr in do.keys():
150
+ return do[nr]
151
+ else:
152
+ if not type(nr) is str:
153
+ return None
154
+ if nr in do_r.keys():
155
+ return do_r[nr]
156
+
157
+
158
+ def _numparser(numword, nn=False):
159
+ """Parse word to see if they start with a wd in firstnumwords.
160
+ If yes, return firstnumword and second part"""
161
+ if not type(numword) is str:
162
+ return None
163
+ firstpart = ""
164
+ scndpart = ""
165
+ firstnumwords = list(do_r.keys())
166
+ for s in firstnumwords:
167
+ if numword.startswith(s):
168
+ slength = len(s)
169
+ firstpart = s
170
+ scndpart = numword[slength:]
171
+ if nn == False:
172
+ if (
173
+ scndpart in b_r.keys() and b_r[scndpart] < 10
174
+ ): # Only return if second part is dig below 10
175
+ return (firstpart, scndpart)
176
+ else:
177
+ if (
178
+ scndpart in b_nn_r.keys() and b_nn_r[scndpart] < 10
179
+ ): # Only return if second part is dig below 10
180
+ return (firstpart, scndpart)
181
+
182
+
183
+ def _one_to_nineteen(nr, reverse=False, nn=False):
184
+ """Function taking a primitive two-digit int in the range 1-19
185
+ and returning the corresponding word, or, if reverse=True, the corresponding number word"""
186
+ if reverse == False:
187
+ if not type(nr) is int:
188
+ return None
189
+ if nr < 11:
190
+ if nn == False:
191
+ return _oneten(nr)
192
+ else:
193
+ return _oneten(nr, nn=True)
194
+ elif nr < 20:
195
+ return _teen(nr)
196
+ else:
197
+ if not type(nr) is str:
198
+ return None
199
+ if nn == False:
200
+ if type(_oneten(nr, reverse=True)) is int:
201
+ return _oneten(nr, reverse=True)
202
+ elif type(_teen(nr, reverse=True)):
203
+ return _teen(nr, reverse=True)
204
+ else:
205
+ if type(_oneten(nr, reverse=True, nn=True)) is int:
206
+ return _oneten(nr, reverse=True, nn=True)
207
+ elif type(_teen(nr, reverse=True)):
208
+ return _teen(nr, reverse=True)
209
+
210
+
211
+ def _one_to_nn(nr, reverse=False, nn=False):
212
+ """Function taking an int in the range 1-99 and returning the corresponding word. Reverse as before"""
213
+ if reverse == False:
214
+ if not type(nr) is int:
215
+ return None
216
+ if nr > 0:
217
+ if nr < 20:
218
+ if nn == False:
219
+ return _one_to_nineteen(nr)
220
+ else:
221
+ return _one_to_nineteen(nr, nn=True)
222
+ elif nr < 100:
223
+ if nr in do.keys():
224
+ return _twodig(nr)
225
+ else:
226
+ nrstring = str(nr)
227
+ frstdig = int(nrstring[0]) * 10
228
+ scndig = int(nrstring[1])
229
+ frstwd = _twodig(frstdig)
230
+ if nn == False:
231
+ scnwd = _onedig(scndig)
232
+ else:
233
+ scnwd = _onedig(scndig, nn=True)
234
+ nrwd = frstwd + scnwd
235
+ return nrwd
236
+ else:
237
+ if not type(nr) is str:
238
+ return None
239
+ if nn == False:
240
+ if type(_one_to_nineteen(nr, reverse=True)) is int:
241
+ return _one_to_nineteen(nr, reverse=True)
242
+ elif type(_twodig(nr, reverse=True)) is int:
243
+ return _twodig(nr, reverse=True)
244
+ else:
245
+ if _numparser(nr) == None:
246
+ return None
247
+ parsed = _numparser(nr)
248
+ first = _twodig(parsed[0], reverse=True)
249
+ second = _one_to_nineteen(parsed[1], reverse=True)
250
+ return first + second
251
+ else:
252
+ if type(_one_to_nineteen(nr, reverse=True, nn=True)) is int:
253
+ return _one_to_nineteen(nr, reverse=True, nn=True)
254
+ elif type(_twodig(nr, reverse=True)) is int:
255
+ return _twodig(nr, reverse=True)
256
+ else:
257
+ if _numparser(nr, nn=True) == None:
258
+ return None
259
+ parsed = _numparser(nr, nn=True)
260
+ first = _twodig(parsed[0], reverse=True)
261
+ second = _one_to_nineteen(parsed[1], reverse=True, nn=True)
262
+ return first + second
263
+
264
+
265
+ def _one_to_nnn(nr, reverse=False, nn=False):
266
+ """Function taking an int in the range 1-999 and returning the corresponding word. Reverse as before"""
267
+ if reverse == False:
268
+ if not type(nr) is int:
269
+ return None
270
+ if nr == 0:
271
+ return None
272
+ if nr < 100: # 1-99
273
+ if nn == False:
274
+ return _one_to_nn(nr)
275
+ else:
276
+ return _one_to_nn(nr, nn=True)
277
+ elif nr < 1000:
278
+ if nr == 100: # 100
279
+ return doo[100]
280
+ else:
281
+ nrstring = str(nr) # 435 181
282
+ frstdig = int(nrstring[0]) # 4 1
283
+ scndig = int(nrstring[1]) # 3 8
284
+ thrdig = int(nrstring[2]) # 5 1
285
+ scthdig = int(nrstring[1:]) # 35 81
286
+ if nn == False:
287
+ frstwd = _onedig(frstdig) # fire
288
+ else:
289
+ frstwd = _onedig(frstdig, nn=True)
290
+ nrwd = ""
291
+ if scndig == 0: # 405 or 400
292
+ if thrdig == 0: # 400
293
+ nrwd = "%s %s" % (frstwd, doo[100]) # fire hundre
294
+ else: # 405
295
+ if nn == False:
296
+ thrdwd = _one_to_nn(thrdig) # fem
297
+ else:
298
+ thrdwd = _one_to_nn(thrdig, nn=True)
299
+ if frstdig != 1:
300
+ nrwd = "%s %s og %s" % (
301
+ frstwd,
302
+ doo[100],
303
+ thrdwd,
304
+ ) # fire hundre og fem
305
+ else:
306
+ nrwd = "%s og %s" % (doo[100], thrdwd) # hundre og fem
307
+ else: # 435
308
+ scthwd = ""
309
+ if nn == False:
310
+ scthwd = _one_to_nn(scthdig) # trettifem
311
+ else:
312
+ scthwd = _one_to_nn(scthdig, nn=True)
313
+ if frstdig != 1:
314
+ nrwd = "%s %s og %s" % (frstwd, doo[100], scthwd)
315
+ else:
316
+ nrwd = "%s og %s" % (doo[100], scthwd) # hundre og trettifem
317
+ return nrwd
318
+ else:
319
+ if not type(nr) is str:
320
+ return None
321
+ if type(doo_r.get(nr, None)) is int: # hundre - 100
322
+ return doo_r[nr]
323
+ elif (
324
+ len(nr.split(" ")) == 1
325
+ and type(_one_to_nn(nr, reverse=True)) is int
326
+ and nn == False
327
+ ):
328
+ return _one_to_nn(nr, reverse=True) # 44
329
+ elif (
330
+ len(nr.split(" ")) == 1
331
+ and type(_one_to_nn(nr, reverse=True, nn=True)) is int
332
+ and nn == True
333
+ ):
334
+ return _one_to_nn(nr, reverse=True, nn=True) # 44
335
+ elif len(nr.split(" ")) == 2: # to hundre
336
+ splitwords = nr.split(" ")
337
+ if nn == False and nr == "ett hundre":
338
+ return 100
339
+ elif nn == True and nr == "eitt hundre":
340
+ return 100
341
+ elif (
342
+ type(_one_to_nn(splitwords[0], reverse=True)) is int
343
+ and splitwords[1] == "hundre"
344
+ ):
345
+ return _one_to_nn(splitwords[0], reverse=True) * 100
346
+ elif len(nr.split(" ")) == 3: # hundre og tre
347
+ splitwords = nr.split(" ")
348
+ if splitwords[0] == "hundre" and splitwords[1] == "og":
349
+ if nn == False:
350
+ if type(_one_to_nn(splitwords[2], reverse=True)) is int:
351
+ return 100 + _one_to_nn(splitwords[2], reverse=True)
352
+ else:
353
+ if type(_one_to_nn(splitwords[2], reverse=True, nn=True)) is int:
354
+ return 100 + _one_to_nn(splitwords[2], reverse=True, nn=True)
355
+ else:
356
+ return None
357
+ elif len(nr.split(" ")) == 4: # ett hundre og trettifire, fire hundre og åtte
358
+ splitwords = nr.split(" ")
359
+ if nn == False:
360
+ if (
361
+ splitwords[0] == "ett"
362
+ and splitwords[1] == "hundre"
363
+ and splitwords[2] == "og"
364
+ and type(_one_to_nn(splitwords[3], reverse=True)) is int
365
+ ): # ett hundre og trettifire
366
+ return 100 + _one_to_nn(splitwords[3], reverse=True)
367
+ elif (
368
+ type(_one_to_nn(splitwords[0], reverse=True)) is int
369
+ and _one_to_nn(splitwords[0], reverse=True) < 10
370
+ and splitwords[1] == "hundre"
371
+ and splitwords[2] == "og"
372
+ and type(_one_to_nn(splitwords[3], reverse=True)) is int
373
+ ): # fire hundre og trettifire
374
+ hundreds = _one_to_nn(splitwords[0], reverse=True) * 100
375
+ tens = _one_to_nn(splitwords[3], reverse=True)
376
+ return hundreds + tens
377
+ else:
378
+ return None
379
+ else:
380
+ if (
381
+ splitwords[0] == "eitt"
382
+ and splitwords[1] == "hundre"
383
+ and splitwords[2] == "og"
384
+ and type(_one_to_nn(splitwords[3], reverse=True, nn=True)) is int
385
+ ): # eit hundre og trettifire
386
+ return 100 + _one_to_nn(splitwords[3], reverse=True, nn=True)
387
+ elif (
388
+ type(_one_to_nn(splitwords[0], reverse=True, nn=True)) is int
389
+ and _one_to_nn(splitwords[0], reverse=True, nn=True) < 10
390
+ and splitwords[1] == "hundre"
391
+ and splitwords[2] == "og"
392
+ and type(_one_to_nn(splitwords[3], reverse=True, nn=True)) is int
393
+ ): # fire hundre og trettifire
394
+ hundreds = _one_to_nn(splitwords[0], reverse=True, nn=True) * 100
395
+ tens = _one_to_nn(splitwords[3], reverse=True, nn=True)
396
+ return hundreds + tens
397
+ else:
398
+ return None
399
+
400
+
401
+ def _high_hundred(nr, nn=False):
402
+ """In Norwegian, as in English, it is possible to express the numbers 1100-1999 with hundreds,
403
+ e.g. "tolv hundre og nittiåtte", /twelve hundred and ninety-eight/. We want to be able to convert
404
+ these to integers. However, we don't need to produce them, so this algoritm only goes from strings to integers"""
405
+ if not type(nr) is str:
406
+ return None
407
+ if len(nr.split(" ")) > 1:
408
+ frstwd = nr.split(" ")[0]
409
+ if not type(_teen(frstwd, reverse=True)) is int:
410
+ return None
411
+ frstdig = _teen(frstwd, reverse=True)
412
+ if len(nr.split(" ")) == 2 and nr.split(" ")[1] == "hundre": # femten hundre
413
+ return frstdig * 100
414
+ elif (
415
+ len(nr.split(" ")) == 4
416
+ and nr.split(" ")[1] == "hundre"
417
+ and nr.split(" ")[2] == "og"
418
+ ):
419
+ if (
420
+ nn == False and type(_one_to_nn(nr.split(" ")[3], reverse=True)) is int
421
+ ): # femten hundre og førtito
422
+ lastdigs = _one_to_nn(nr.split(" ")[3], reverse=True)
423
+ return (frstdig * 100) + lastdigs
424
+ elif (
425
+ nn == True
426
+ and type(_one_to_nn(nr.split(" ")[3], reverse=True, nn=True)) is int
427
+ ): # femten hundre og førtito
428
+ lastdigs = _one_to_nn(nr.split(" ")[3], reverse=True, nn=True)
429
+ return (frstdig * 100) + lastdigs
430
+
431
+
432
+ def _one_to_nnnnnn(nr, reverse=False, nn=False):
433
+ """Function taking an int in the range 1-999999 and returning the corresponding word. Reverse as before"""
434
+ if reverse == False:
435
+ if not type(nr) is int:
436
+ return None
437
+ if nr == 0:
438
+ return None
439
+ if nr < 1000: # 1-999
440
+ if nn == False:
441
+ return _one_to_nnn(nr)
442
+ else:
443
+ return _one_to_nnn(nr, nn=True)
444
+ elif nr < 1000000: # 1000-999999
445
+ if nr == 1000: # 1000
446
+ if nn == False:
447
+ return "ett tusen"
448
+ else:
449
+ return "eitt tusen"
450
+ else:
451
+ nrstring = str(nr) # Starting with last three digits. e.g. 23[456]
452
+ ultdig = int(nrstring[-1]) # 6
453
+ penultdig = int(nrstring[-2]) # 5
454
+ antepenultdig = int(nrstring[-3]) # 4
455
+ ult_and_penultdig = int(nrstring[-2:]) # 56
456
+ ult_penult_antepenultdig = int(nrstring[-3:]) # 456
457
+ tailstring = ""
458
+ if antepenultdig == 0: # 012, 002, 000
459
+ if penultdig == 0: # 000, 002
460
+ if ultdig == 0: # 000
461
+ tailstring = "tusen"
462
+ else: # 002
463
+ if nn == False:
464
+ ultstring = _one_to_nnn(ultdig)
465
+ tailstring = "tusen og %s" % ultstring # tusen og to
466
+ else:
467
+ ultstring = _one_to_nnn(ultdig, nn=True)
468
+ tailstring = "tusen og %s" % ultstring # tusen og to
469
+ else: # 012
470
+ if nn == False:
471
+ ult_and_penultstring = _one_to_nnn(ult_and_penultdig)
472
+ tailstring = (
473
+ "tusen og %s" % ult_and_penultstring
474
+ ) # tusen og tolv
475
+ else:
476
+ ult_and_penultstring = _one_to_nnn(
477
+ ult_and_penultdig, nn=True
478
+ )
479
+ tailstring = (
480
+ "tusen og %s" % ult_and_penultstring
481
+ ) # tusen og tolv
482
+ else: # 456
483
+ if nn == False:
484
+ ult_penult_antepenultstring = _one_to_nnn(
485
+ ult_penult_antepenultdig
486
+ )
487
+ if str(ult_penult_antepenultdig)[0] == "1":
488
+ tailstring = (
489
+ "tusen ett %s" % ult_penult_antepenultstring
490
+ ) # tusen ett hundre
491
+ else:
492
+ tailstring = (
493
+ "tusen %s" % ult_penult_antepenultstring
494
+ ) # tusen fire hundre og femtiseks
495
+ else:
496
+ ult_penult_antepenultstring = _one_to_nnn(
497
+ ult_penult_antepenultdig, nn=True
498
+ )
499
+ if str(ult_penult_antepenultdig)[0] == "1":
500
+ tailstring = (
501
+ "tusen eitt %s" % ult_penult_antepenultstring
502
+ ) # tusen ett hundre
503
+ else:
504
+ tailstring = (
505
+ "tusen %s" % ult_penult_antepenultstring
506
+ ) # tusen fire hundre og femtiseks
507
+ startdigs = int(
508
+ nrstring[:-3]
509
+ ) # startstring can consist of the 1, 2 or 3 first digits
510
+ startstring = ""
511
+ if startdigs == 1: # 1001 starts with "ett"
512
+ if nn == False:
513
+ startstring = "ett"
514
+ else:
515
+ startstring = "eitt"
516
+ elif startdigs > 99 and startdigs < 200: # 155555 starts with ett
517
+ if nn == False:
518
+ startnumstring = _one_to_nnn(startdigs)
519
+ startstring = "ett %s" % startnumstring
520
+ else:
521
+ startnumstring = _one_to_nnn(startdigs, nn=True)
522
+ startstring = "eitt %s" % startnumstring
523
+ else: # the remaining numbers are purely compositional
524
+ if nn == False:
525
+ startstring = _one_to_nnn(startdigs)
526
+ else:
527
+ startstring = _one_to_nnn(startdigs, nn=True)
528
+ numstring = "%s %s" % (startstring, tailstring)
529
+ return numstring
530
+ else:
531
+ if not type(nr) is str:
532
+ return None
533
+ if type(_one_to_nnn(nr, reverse=True)) is int and nn == False:
534
+ return _one_to_nnn(nr, reverse=True) # 444
535
+ elif type(_one_to_nnn(nr, reverse=True, nn=True)) is int and nn == True:
536
+ return _one_to_nnn(nr, reverse=True, nn=True) # 444
537
+ elif nr == "tusen": # tusen - 1000
538
+ return 1000
539
+ elif (
540
+ len(nr.split(" ")) > 1 and nr.split(" ")[-1] == "tusen"
541
+ ): # ett tusen, ett hundre tusen etc.
542
+ wdlist = nr.split(" ")
543
+ firstphrase = " ".join(wdlist[:-1])
544
+ if type(_one_to_nnn(firstphrase, reverse=True)) is int and nn == False:
545
+ firstdig = _one_to_nnn(firstphrase, reverse=True)
546
+ return firstdig * 1000
547
+ elif (
548
+ type(_one_to_nnn(firstphrase, reverse=True, nn=True)) is int
549
+ and nn == True
550
+ ):
551
+ firstdig = _one_to_nnn(firstphrase, reverse=True, nn=True)
552
+ return firstdig * 1000
553
+ elif (
554
+ len(nr.split(" ")) == 2 and nr.split(" ")[0] == "ett" and nn == False
555
+ ): # ett tusen
556
+ return 1000
557
+ elif len(nr.split(" ")) == 2 and nr.split(" ")[0] == "eitt" and nn == True:
558
+ return 1000
559
+ else: # misspellings should not result in return value
560
+ return None
561
+ else:
562
+ if len(nr.split(" ")) > 1: # all other numbers should contain spaces
563
+ numwordlist = nr.split(" ")
564
+ if (
565
+ "tusen" in numwordlist
566
+ ): # Find last part of numphrase, which starts with "tusen"
567
+ tusenind = numwordlist.index("tusen") # find index of "tusen"
568
+ lastwords = numwordlist[tusenind:] # words from 'tusen'
569
+ firstwords = numwordlist[:tusenind] # words until 'tusen'
570
+ lastdigs = 0
571
+ if len(lastwords) == 3:
572
+ if lastwords[1] == "og": # 'tusen og fire' 'tusen og førtifire'
573
+ lastword = lastwords[-1]
574
+ if nn == False:
575
+ lastdigs = _one_to_nnn(lastword, reverse=True)
576
+ elif nn == True:
577
+ lastdigs = _one_to_nnn(lastword, reverse=True, nn=True)
578
+ elif (
579
+ nn == False
580
+ and type(_one_to_nnn(" ".join(lastwords[1:]), reverse=True))
581
+ is int
582
+ and lastwords[2] == "hundre"
583
+ ): # tusen to hundre
584
+ hundredphrase = " ".join(lastwords[1:])
585
+ lastdigs = _one_to_nnn(hundredphrase, reverse=True)
586
+ elif (
587
+ nn == True
588
+ and type(
589
+ _one_to_nnn(
590
+ " ".join(lastwords[1:]), reverse=True, nn=True
591
+ )
592
+ )
593
+ is int
594
+ and lastwords[2] == "hundre"
595
+ ): # tusen to hundre
596
+ hundredphrase = " ".join(lastwords[1:])
597
+ lastdigs = _one_to_nnn(hundredphrase, reverse=True, nn=True)
598
+ else: # misspellings should not result in return value
599
+ return None
600
+ elif (
601
+ len(lastwords) == 5 and lastwords[2] == "hundre"
602
+ ): # 'tusen fire hundre og fem'
603
+ hundredphrase = " ".join(lastwords[1:])
604
+ if nn == False:
605
+ lastdigs = _one_to_nnn(hundredphrase, reverse=True)
606
+ else:
607
+ lastdigs = _one_to_nnn(hundredphrase, reverse=True, nn=True)
608
+ else: # misspellings should not result in return value
609
+ return None
610
+ firstdigs = 0
611
+ firstphrase = " ".join(firstwords)
612
+ if len(firstwords) == 0: # as in 'tusen og tretti'
613
+ firstdigs = 1000
614
+ elif (
615
+ len(firstwords) == 1 and firstwords[0] == "ett" and nn == False
616
+ ):
617
+ firstdigs = 1000
618
+ elif (
619
+ len(firstwords) == 1 and firstwords[0] == "eitt" and nn == True
620
+ ):
621
+ firstdigs = 1000
622
+ elif (
623
+ type(_one_to_nnn(firstphrase, reverse=True)) is int
624
+ and nn == False
625
+ ):
626
+ firstdigs = _one_to_nnn(firstphrase, reverse=True) * 1000
627
+ elif (
628
+ type(_one_to_nnn(firstphrase, reverse=True, nn=True)) is int
629
+ and nn == True
630
+ ):
631
+ firstdigs = (
632
+ _one_to_nnn(firstphrase, reverse=True, nn=True) * 1000
633
+ )
634
+ else: # misspellings should not result in return value
635
+ return None
636
+ if type(firstdigs) is int and type(lastdigs) is int:
637
+ return firstdigs + lastdigs
638
+
639
+
640
+ def convert_nums(nr, reverse=False, nn=False):
641
+ """Functions for converting numbers. Only works for numbers in range 0-999999 for now"""
642
+ if reverse == False:
643
+ if type(nr) is int:
644
+ returnstring = ""
645
+ if nr == 0:
646
+ returnstring = "null"
647
+ elif nr < 1000000:
648
+ if nn == False:
649
+ returnstring = _one_to_nnnnnn(nr)
650
+ else:
651
+ returnstring = _one_to_nnnnnn(nr, nn=True)
652
+ else:
653
+ return None
654
+ return returnstring
655
+ else:
656
+ if type(nr) is str:
657
+ returnint = 0
658
+ if nr == "null":
659
+ returnint = 0
660
+ elif nn == False and type(_one_to_nnnnnn(nr, reverse=True)) is int:
661
+ returnint = _one_to_nnnnnn(nr, reverse=True)
662
+ elif nn == True and type(_one_to_nnnnnn(nr, reverse=True, nn=True)) is int:
663
+ returnint = _one_to_nnnnnn(nr, reverse=True, nn=True)
664
+ elif nn == False and type(_high_hundred(nr)) is int:
665
+ returnint = _high_hundred(nr)
666
+ elif nn == True and type(_high_hundred(nr, nn=True)) is int:
667
+ returnint = _high_hundred(nr, nn=True)
668
+ else:
669
+ return None
670
+ return returnint
671
+
672
+
673
+ if __name__ == "__main__":
674
+ # testing
675
+ mydigit = 243564
676
+ mynumstring = "hundre og atten tusen fire hundre og trettién"
677
+ mydigit_nn = 34381
678
+ mynumstring_nn = "tre hundre og førtiein"
679
+
680
+ print(
681
+ "Digit conversion bm: %s\nString conversion bm: %s"
682
+ % (convert_nums(mydigit), convert_nums(mynumstring, reverse=True))
683
+ )
684
+ print(
685
+ "Digit conversion nn: %s\nString conversion nn: %s"
686
+ % (
687
+ convert_nums(mydigit_nn, nn=True),
688
+ convert_nums(mynumstring_nn, nn=True, reverse=True),
689
+ )
690
+ )
config.json ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "facebook/wav2vec2-xls-r-1b",
3
+ "activation_dropout": 0.055,
4
+ "adapter_kernel_size": 3,
5
+ "adapter_stride": 2,
6
+ "add_adapter": false,
7
+ "apply_spec_augment": true,
8
+ "architectures": [
9
+ "Wav2Vec2ForCTC"
10
+ ],
11
+ "attention_dropout": 0.094,
12
+ "bos_token_id": 1,
13
+ "classifier_proj_size": 256,
14
+ "codevector_dim": 1024,
15
+ "contrastive_logits_temperature": 0.1,
16
+ "conv_bias": true,
17
+ "conv_dim": [
18
+ 512,
19
+ 512,
20
+ 512,
21
+ 512,
22
+ 512,
23
+ 512,
24
+ 512
25
+ ],
26
+ "conv_kernel": [
27
+ 10,
28
+ 3,
29
+ 3,
30
+ 3,
31
+ 3,
32
+ 2,
33
+ 2
34
+ ],
35
+ "conv_stride": [
36
+ 5,
37
+ 2,
38
+ 2,
39
+ 2,
40
+ 2,
41
+ 2,
42
+ 2
43
+ ],
44
+ "ctc_loss_reduction": "mean",
45
+ "ctc_zero_infinity": true,
46
+ "diversity_loss_weight": 0.1,
47
+ "do_stable_layer_norm": true,
48
+ "eos_token_id": 2,
49
+ "feat_extract_activation": "gelu",
50
+ "feat_extract_dropout": 0.0,
51
+ "feat_extract_norm": "layer",
52
+ "feat_proj_dropout": 0.04,
53
+ "feat_quantizer_dropout": 0.0,
54
+ "final_dropout": 0.0,
55
+ "hidden_act": "gelu",
56
+ "hidden_dropout": 0.047,
57
+ "hidden_size": 1280,
58
+ "initializer_range": 0.02,
59
+ "intermediate_size": 5120,
60
+ "layer_norm_eps": 1e-05,
61
+ "layerdrop": 0.041,
62
+ "mask_feature_length": 64,
63
+ "mask_feature_min_masks": 0,
64
+ "mask_feature_prob": 0.25,
65
+ "mask_time_length": 10,
66
+ "mask_time_min_masks": 2,
67
+ "mask_time_prob": 0.082,
68
+ "model_type": "wav2vec2",
69
+ "num_adapter_layers": 3,
70
+ "num_attention_heads": 16,
71
+ "num_codevector_groups": 2,
72
+ "num_codevectors_per_group": 320,
73
+ "num_conv_pos_embedding_groups": 16,
74
+ "num_conv_pos_embeddings": 128,
75
+ "num_feat_extract_layers": 7,
76
+ "num_hidden_layers": 48,
77
+ "num_negatives": 100,
78
+ "output_hidden_size": 1280,
79
+ "pad_token_id": 38,
80
+ "proj_codevector_dim": 1024,
81
+ "tdnn_dilation": [
82
+ 1,
83
+ 2,
84
+ 3,
85
+ 1,
86
+ 1
87
+ ],
88
+ "tdnn_dim": [
89
+ 512,
90
+ 512,
91
+ 512,
92
+ 512,
93
+ 1500
94
+ ],
95
+ "tdnn_kernel": [
96
+ 5,
97
+ 3,
98
+ 3,
99
+ 1,
100
+ 1
101
+ ],
102
+ "torch_dtype": "float32",
103
+ "transformers_version": "4.18.0",
104
+ "use_weighted_layer_sum": false,
105
+ "vocab_size": 41,
106
+ "xvector_output_dim": 512
107
+ }
eval.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ from typing import Dict
5
+
6
+ import torch
7
+ from datasets import Audio, Dataset, load_dataset, load_metric
8
+ from num2words import num2words as n2w
9
+ from slugify import slugify
10
+
11
+ from transformers import AutoFeatureExtractor, AutoModelForCTC, pipeline, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM, Wav2Vec2FeatureExtractor
12
+ # from pyctcdecode import BeamSearchDecoderCTC
13
+
14
+ from cardinal_numbers import convert_nums
15
+
16
+
17
+ def log_results(result: Dataset, args: Dict[str, str]):
18
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
19
+
20
+ log_outputs = args.log_outputs
21
+ lm = "withLM" if args.use_lm else "noLM"
22
+ model_id = args.model_id.replace("/", "_").replace(".", "")
23
+ if args.filter:
24
+ extra_args = [args.config, slugify(args.filter), args.split, lm]
25
+ else:
26
+ extra_args = [args.config, args.split, lm]
27
+ dataset_id = "_".join([model_id] + args.dataset.split("/") + extra_args)
28
+
29
+ # load metric
30
+ wer = load_metric("wer")
31
+ cer = load_metric("cer")
32
+
33
+ # compute metrics
34
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
35
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
36
+
37
+ # print & log results
38
+ result_str = f"{dataset_id}\nWER: {wer_result}\nCER: {cer_result}"
39
+ print(result_str)
40
+
41
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
42
+ f.write(result_str)
43
+ with open(f"{dataset_id}_eval_results.tsv", "w") as f:
44
+ f.write("\t".join([args.model_id, args.dataset, args.config, args.filter, args.split, str(lm), str(wer_result), str(cer_result)]))
45
+
46
+ # log all results in text file. Possibly interesting for analysis
47
+ if log_outputs is not None:
48
+ pred_file = f"log_{dataset_id}_predictions.txt"
49
+ target_file = f"log_{dataset_id}_targets.txt"
50
+
51
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
52
+ # mapping function to write output
53
+ def write_to_file(batch, i):
54
+ p.write(f"{i}" + "\n")
55
+ p.write(batch["prediction"] + "\n")
56
+ t.write(f"{i}" + "\n")
57
+ t.write(batch["target"] + "\n")
58
+
59
+ result.map(write_to_file, with_indices=True)
60
+
61
+
62
+ def normalize_text(original_text: str, dataset: str) -> str:
63
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
64
+
65
+ text = original_text.lower()
66
+ if dataset.lower().endswith("fleurs"):
67
+ replacements = (
68
+ (r"\be\.kr", "etter kristus fødsel"),
69
+ (r"\bf\.kr", "før kristi fødsel"),
70
+ (r"\bca[.]?\b", "circa"),
71
+ (r"(\d)\s*km/t", r"\1 kilometer i timen"),
72
+ (r"(\d)\s*km", r"\1 kilometer"),
73
+ (r"(\d)\s*cm", r"\1 centimeter"),
74
+ (r"(\d)\s*mm", r"\1 millimeter"),
75
+ (r"kl\.", "klokka"),
76
+ (r"f\.eks", "for eksempel"),
77
+ )
78
+ for abrev, expasion in replacements:
79
+ text = re.sub(abrev, expasion, text)
80
+ text = re.sub(r'(\d+)[-–](\d+)', r'\1 til \2', text) # 1-89, 70-90
81
+ text = re.sub(r'(\d{2}):00', r'\1', text) # 21:00
82
+ text = re.sub(r"(\d{2}):0(\d{1})", r"\1 null \2", text) # 17:03
83
+ text = re.sub(r"(\d{1,2}):(\d{1,2})", r"\1 \2", text) # 17:23 (time), 4:3 (aspect ratios)
84
+ text = re.sub(r"(1[1-9])00", r"\1 hundre", text) # 1800, 1900
85
+ text = re.sub(r"(1[1-9])0([1-9])", r"\1 null \2 ", text) # 1901, 1909
86
+ text = re.sub(r"(1[1-9])([1-9]\d)", r"\1 \2 ", text) # 1911, 1987
87
+ text = re.sub(r"(20)0([1-9])", r"\1 null \2 ", text) # 2009
88
+ text = re.sub(r"(20)(\d{2})", r"\1 \2 ", text) # 2009
89
+ text = re.sub(r"(\d{1,3})[.](\d{1,2})", r"\1 dot \2 ", text) # 802.11n, 2.5ghz (in English)
90
+ text = re.sub(r"(\d{1,2})[ .](\d{3})", r"\1\2", text) # 10 000, 32.000
91
+ text = re.sub(r'(\w+)-(\w+)', r'\1 \2', text) # n-standard
92
+ # text = re.compile(r"-?0?[1-9][\d.]*").sub(lambda x: n2w(x.group(0), lang="no"), text.replace(".", ""))
93
+ text = re.compile(r"-?0?[1-9][\d.]*").sub(lambda x: convert_nums(int(x.group(0)), nn=True), text.replace(".", ""))
94
+
95
+
96
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
97
+ text = re.sub(chars_to_ignore_regex, "", text) + " "
98
+
99
+ if dataset.lower().endswith("nst"):
100
+ text = text.lower()
101
+ text = text.replace("(...vær stille under dette opptaket...)", "")
102
+ text = re.sub('[áàâ]', 'a', text)
103
+ text = re.sub('[ä]', 'æ', text)
104
+ text = re.sub('[éèëê]', 'e', text)
105
+ text = re.sub('[íìïî]', 'i', text)
106
+ text = re.sub('[óòöô]', 'o', text)
107
+ text = re.sub('[ö]', 'ø', text)
108
+ text = re.sub('[ç]', 'c', text)
109
+ text = re.sub('[úùüû]', 'u', text)
110
+ # text = re.sub('\\(?=(Punktum|Komma|Utropstegn|Spørsmålstegn))', ' ', text)
111
+ text = re.sub('\s+', ' ', text)
112
+ elif dataset.lower().endswith("npsc"):
113
+ text = re.sub('[áàâ]', 'a', text)
114
+ text = re.sub('[ä]', 'æ', text)
115
+ text = re.sub('[éèëê]', 'e', text)
116
+ text = re.sub('[íìïî]', 'i', text)
117
+ text = re.sub('[óòöô]', 'o', text)
118
+ text = re.sub('[ö]', 'ø', text)
119
+ text = re.sub('[ç]', 'c', text)
120
+ text = re.sub('[úùüû]', 'u', text)
121
+ text = re.sub('\s+', ' ', text)
122
+ elif dataset.lower().endswith("fleurs"):
123
+ text = re.sub('[áàâ]', 'a', text)
124
+ text = re.sub('[ä]', 'æ', text)
125
+ text = re.sub('[éèëê]', 'e', text)
126
+ text = re.sub('[íìïî]', 'i', text)
127
+ text = re.sub('[óòöô]', 'o', text)
128
+ text = re.sub('[ö]', 'ø', text)
129
+ text = re.sub('[ç]', 'c', text)
130
+ text = re.sub('[úùüû]', 'u', text)
131
+ text = re.sub('[«»]', '', text)
132
+ text = re.sub('\s+', ' ', text)
133
+ text = re.sub('<ee>', 'eee', text)
134
+ text = re.sub('<qq>', 'qqq', text)
135
+ text = re.sub('<mm>', 'mmm', text)
136
+ text = re.sub('<inaudible>', 'xxx', text)
137
+
138
+ # # In addition, we can normalize the target text, e.g. removing new lines characters etc...
139
+ # # note that order is important here!
140
+ # token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
141
+
142
+ # for t in token_sequences_to_ignore:
143
+ # text = " ".join(text.split(t))
144
+
145
+ return text
146
+
147
+
148
+ def main(args):
149
+ # load dataset
150
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
151
+ if args.filter:
152
+ attribute, value = list(map(str.strip, args.filter.split(":")))
153
+ dataset = dataset.filter(
154
+ lambda x: x[attribute] == value,
155
+ desc=f"Filtering on {args.filter}",
156
+ )
157
+ # for testing: only process the first two examples as a test
158
+ # dataset = dataset.select(range(10))
159
+
160
+ # load processor
161
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
162
+ sampling_rate = feature_extractor.sampling_rate
163
+
164
+ # resample audio
165
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
166
+
167
+ # load eval pipeline
168
+ if args.device is None:
169
+ args.device = 0 if torch.cuda.is_available() else -1
170
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
171
+
172
+ model_instance = AutoModelForCTC.from_pretrained(args.model_id)
173
+ if args.use_lm:
174
+ processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
175
+ decoder = processor.decoder
176
+ else:
177
+ processor = Wav2Vec2Processor.from_pretrained(args.model_id)
178
+ decoder = None
179
+ asr = pipeline(
180
+ "automatic-speech-recognition",
181
+ model=model_instance,
182
+ tokenizer=processor.tokenizer,
183
+ feature_extractor=processor.feature_extractor,
184
+ decoder=decoder,
185
+ device=args.device
186
+ )
187
+
188
+ # feature_extractor_dict, _ = Wav2Vec2FeatureExtractor.get_feature_extractor_dict(args.model_id)
189
+ # feature_extractor_dict["processor_class"] = "Wav2Vec2Processor" if not args.use_lm else "Wav2Vec2ProcessorWithLM"
190
+ # feature_extractor = Wav2Vec2FeatureExtractor.from_dict(feature_extractor_dict)
191
+
192
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id, feature_extractor=feature_extractor, device=args.device, decoder=BeamSearchDecoderCTC.load_from_dir("./"))
193
+
194
+ # map function to decode audio
195
+ def map_to_pred(batch):
196
+ prediction = asr(
197
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
198
+ )
199
+
200
+ batch["prediction"] = prediction["text"]
201
+ batch["target"] = normalize_text(batch[args.text_column], args.dataset)
202
+ return batch
203
+
204
+ # run inference on all examples
205
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
206
+
207
+ # compute and log_results
208
+ # do not change function below
209
+ log_results(result, args)
210
+
211
+
212
+ if __name__ == "__main__":
213
+ parser = argparse.ArgumentParser()
214
+
215
+ parser.add_argument(
216
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
217
+ )
218
+ parser.add_argument(
219
+ "--dataset",
220
+ type=str,
221
+ required=True,
222
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
223
+ )
224
+ parser.add_argument(
225
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
226
+ )
227
+ parser.add_argument(
228
+ "--filter", type=str, default="", help="Simple filter on attributes. *E.g.* `region_of_youth:Troms` would pnly keep those samplesfor which the condition is met"
229
+ )
230
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
231
+ parser.add_argument(
232
+ "--text_column", type=str, default="text", help="Column name containing the transcription."
233
+ )
234
+ parser.add_argument(
235
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
236
+ )
237
+ parser.add_argument(
238
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
239
+ )
240
+ parser.add_argument(
241
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
242
+ )
243
+ parser.add_argument(
244
+ "--device",
245
+ type=int,
246
+ default=None,
247
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
248
+ )
249
+ parser.add_argument(
250
+ "--use_lm", action="store_true", help="If defined, use included language model as the decoder."
251
+ )
252
+ args = parser.parse_args()
253
+
254
+ main(args)
language_model/5gram.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b41c24c63f2f0585bea83666369593f3b3e6d047f327a90f36ebca2c35ef0ff
3
+ size 4243671427
language_model/attrs.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"alpha": 0.5, "beta": 1.5, "unk_score_offset": -10.0, "score_boundary": true}
language_model/unigrams.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac3e71ca49838ca355df6fdcb8d89344a5a9bf9e1a76587cdf5df1367c19b9a9
3
+ size 16759269
preprocessor_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
4
+ "feature_size": 1,
5
+ "padding_side": "right",
6
+ "padding_value": 0,
7
+ "processor_class": "Wav2Vec2ProcessorWithLM",
8
+ "return_attention_mask": true,
9
+ "sampling_rate": 16000
10
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0de5c9ba91acd5844605a71e621f73b3dd9f9acbfb283d3d835b44a491b189b6
3
+ size 3850475057
run.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ WANDB_ENTITY=NbAiLab WANDB_PROJECT=wav2vec2 python run_speech_recognition_ctc.py \
2
+ --model_name_or_path="facebook/wav2vec2-xls-r-1b" \
3
+ --hub_model_id="NbAiLab/wav2vec2-1b-npsc-nst" \
4
+ --output_dir="./" \
5
+ --num_train_epochs="40" \
6
+ --per_device_train_batch_size="12" \
7
+ --per_device_eval_batch_size="12" \
8
+ --gradient_accumulation_steps="2" \
9
+ --learning_rate="2e-5" \
10
+ --warmup_steps="2000" \
11
+ --length_column_name="input_length" \
12
+ --evaluation_strategy="steps" \
13
+ --text_column_name="text" \
14
+ --save_steps="500" \
15
+ --eval_steps="500" \
16
+ --logging_steps="100" \
17
+ --layerdrop="0.041" \
18
+ --attention_dropout="0.094" \
19
+ --activation_dropout="0.055" \
20
+ --hidden_dropout="0.047" \
21
+ --save_total_limit="3" \
22
+ --freeze_feature_encoder \
23
+ --feat_proj_dropout="0.04" \
24
+ --mask_time_prob="0.082" \
25
+ --mask_time_length="10" \
26
+ --mask_feature_prob="0.25" \
27
+ --mask_feature_length="64" \
28
+ --gradient_checkpointing \
29
+ --min_duration_in_seconds="0.5" \
30
+ --max_duration_in_seconds="30.0" \
31
+ --use_auth_token \
32
+ --seed="42" \
33
+ --fp16 \
34
+ --group_by_length \
35
+ --do_train --do_eval \
36
+ --push_to_hub \
37
+ --preprocessing_num_workers="32" \
38
+ --ctc_zero_infinity
run_speech_recognition_ctc.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+
16
+ """ Fine-tuning a 🤗 Transformers CTC model for automatic speech recognition"""
17
+
18
+ import functools
19
+ import json
20
+ import logging
21
+ import os
22
+ import re
23
+ import sys
24
+ import warnings
25
+ from dataclasses import dataclass, field
26
+ from typing import Dict, List, Optional, Union
27
+
28
+ import datasets
29
+ import numpy as np
30
+ import torch
31
+ from datasets import DatasetDict, load_dataset, load_metric
32
+
33
+ import transformers
34
+ from transformers import (
35
+ AutoConfig,
36
+ AutoFeatureExtractor,
37
+ AutoModelForCTC,
38
+ AutoProcessor,
39
+ AutoTokenizer,
40
+ HfArgumentParser,
41
+ Trainer,
42
+ TrainingArguments,
43
+ Wav2Vec2Processor,
44
+ set_seed,
45
+ )
46
+ from transformers.trainer_utils import get_last_checkpoint, is_main_process
47
+ from transformers.utils import check_min_version
48
+ from transformers.utils.versions import require_version
49
+
50
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
51
+ check_min_version("4.16.0.dev0")
52
+
53
+ require_version("datasets>=1.13.3", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+
58
+ def list_field(default=None, metadata=None):
59
+ return field(default_factory=lambda: default, metadata=metadata)
60
+
61
+
62
+ @dataclass
63
+ class ModelArguments:
64
+ """
65
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
66
+ """
67
+
68
+ model_name_or_path: str = field(
69
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
70
+ )
71
+ tokenizer_name_or_path: Optional[str] = field(
72
+ default=None,
73
+ metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
74
+ )
75
+ cache_dir: Optional[str] = field(
76
+ default=None,
77
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
78
+ )
79
+ freeze_feature_encoder: bool = field(
80
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
81
+ )
82
+ attention_dropout: float = field(
83
+ default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
84
+ )
85
+ activation_dropout: float = field(
86
+ default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
87
+ )
88
+ feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
89
+ hidden_dropout: float = field(
90
+ default=0.0,
91
+ metadata={
92
+ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
93
+ },
94
+ )
95
+ final_dropout: float = field(
96
+ default=0.0,
97
+ metadata={"help": "The dropout probability for the final projection layer."},
98
+ )
99
+ mask_time_prob: float = field(
100
+ default=0.05,
101
+ metadata={
102
+ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector"
103
+ "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
104
+ "vectors will be masked along the time axis."
105
+ },
106
+ )
107
+ mask_time_length: int = field(
108
+ default=10,
109
+ metadata={"help": "Length of vector span to mask along the time axis."},
110
+ )
111
+ mask_feature_prob: float = field(
112
+ default=0.0,
113
+ metadata={
114
+ "help": "Probability of each feature vector along the feature axis to be chosen as the start of the vector"
115
+ "span to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature bins will be masked along the time axis."
116
+ },
117
+ )
118
+ mask_feature_length: int = field(
119
+ default=10,
120
+ metadata={"help": "Length of vector span to mask along the feature axis."},
121
+ )
122
+ layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
123
+ ctc_loss_reduction: Optional[str] = field(
124
+ default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
125
+ )
126
+ ctc_zero_infinity: Optional[bool] = field(
127
+ default=False, metadata={"help": "If True, will try yo aboud the CTC loss goinf to infinity."}
128
+ )
129
+
130
+
131
+ @dataclass
132
+ class DataTrainingArguments:
133
+ """
134
+ Arguments pertaining to what data we are going to input our model for training and eval.
135
+
136
+ Using `HfArgumentParser` we can turn this class
137
+ into argparse arguments to be able to specify them on
138
+ the command line.
139
+ """
140
+
141
+ # dataset_name: str = field(
142
+ # metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
143
+ # )
144
+ # dataset_config_name: str = field(
145
+ # default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
146
+ # )
147
+ train_split_name: str = field(
148
+ default="train",
149
+ metadata={
150
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
151
+ },
152
+ )
153
+ eval_split_name: str = field(
154
+ default="test",
155
+ metadata={
156
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
157
+ },
158
+ )
159
+ audio_column_name: str = field(
160
+ default="audio",
161
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
162
+ )
163
+ text_column_name: str = field(
164
+ default="text",
165
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
166
+ )
167
+ overwrite_cache: bool = field(
168
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
169
+ )
170
+ preprocessing_num_workers: Optional[int] = field(
171
+ default=None,
172
+ metadata={"help": "The number of processes to use for the preprocessing."},
173
+ )
174
+ max_train_samples: Optional[int] = field(
175
+ default=None,
176
+ metadata={
177
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
178
+ "value if set."
179
+ },
180
+ )
181
+ max_eval_samples: Optional[int] = field(
182
+ default=None,
183
+ metadata={
184
+ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
185
+ "value if set."
186
+ },
187
+ )
188
+ chars_to_ignore: Optional[List[str]] = list_field(
189
+ default=None,
190
+ metadata={"help": "A list of characters to remove from the transcripts."},
191
+ )
192
+ eval_metrics: List[str] = list_field(
193
+ default=["wer"],
194
+ metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
195
+ )
196
+ max_duration_in_seconds: float = field(
197
+ default=20.0,
198
+ metadata={
199
+ "help": "Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`"
200
+ },
201
+ )
202
+ min_duration_in_seconds: float = field(
203
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
204
+ )
205
+ preprocessing_only: bool = field(
206
+ default=False,
207
+ metadata={
208
+ "help": "Whether to only do data preprocessing and skip training. "
209
+ "This is especially useful when data preprocessing errors out in distributed training due to timeout. "
210
+ "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` "
211
+ "so that the cached datasets can consequently be loaded in distributed training"
212
+ },
213
+ )
214
+ use_auth_token: bool = field(
215
+ default=False,
216
+ metadata={
217
+ "help": "If :obj:`True`, will use the token generated when running"
218
+ ":obj:`transformers-cli login` as HTTP bearer authorization for remote files."
219
+ },
220
+ )
221
+ unk_token: str = field(
222
+ default="[UNK]",
223
+ metadata={"help": "The unk token for the tokenizer"},
224
+ )
225
+ pad_token: str = field(
226
+ default="[PAD]",
227
+ metadata={"help": "The padding token for the tokenizer"},
228
+ )
229
+ word_delimiter_token: str = field(
230
+ default="|",
231
+ metadata={"help": "The word delimiter token for the tokenizer"},
232
+ )
233
+ phoneme_language: Optional[str] = field(
234
+ default=None,
235
+ metadata={
236
+ "help": "The target language that should be used be"
237
+ " passed to the tokenizer for tokenization. Note that"
238
+ " this is only relevant if the model classifies the"
239
+ " input audio to a sequence of phoneme sequences."
240
+ },
241
+ )
242
+
243
+
244
+ @dataclass
245
+ class DataCollatorCTCWithPadding:
246
+ """
247
+ Data collator that will dynamically pad the inputs received.
248
+ Args:
249
+ processor (:class:`~transformers.AutoProcessor`)
250
+ The processor used for proccessing the data.
251
+ padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
252
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
253
+ among:
254
+ * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
255
+ sequence if provided).
256
+ * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
257
+ maximum acceptable input length for the model if that argument is not provided.
258
+ * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
259
+ different lengths).
260
+ max_length (:obj:`int`, `optional`):
261
+ Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
262
+ max_length_labels (:obj:`int`, `optional`):
263
+ Maximum length of the ``labels`` returned list and optionally padding length (see above).
264
+ pad_to_multiple_of (:obj:`int`, `optional`):
265
+ If set will pad the sequence to a multiple of the provided value.
266
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
267
+ 7.5 (Volta).
268
+ """
269
+
270
+ processor: AutoProcessor
271
+ padding: Union[bool, str] = "longest"
272
+ pad_to_multiple_of: Optional[int] = None
273
+ pad_to_multiple_of_labels: Optional[int] = None
274
+
275
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
276
+ # split inputs and labels since they have to be of different lenghts and need
277
+ # different padding methods
278
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
279
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
280
+
281
+ batch = self.processor.pad(
282
+ input_features,
283
+ padding=self.padding,
284
+ pad_to_multiple_of=self.pad_to_multiple_of,
285
+ return_tensors="pt",
286
+ )
287
+
288
+ with self.processor.as_target_processor():
289
+ labels_batch = self.processor.pad(
290
+ label_features,
291
+ padding=self.padding,
292
+ pad_to_multiple_of=self.pad_to_multiple_of_labels,
293
+ return_tensors="pt",
294
+ )
295
+
296
+ # replace padding with -100 to ignore loss correctly
297
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
298
+
299
+ batch["labels"] = labels
300
+
301
+ return batch
302
+
303
+
304
+ def create_vocabulary_from_data(
305
+ datasets: DatasetDict,
306
+ word_delimiter_token: Optional[str] = None,
307
+ unk_token: Optional[str] = None,
308
+ pad_token: Optional[str] = None,
309
+ ):
310
+ # Given training and test labels create vocabulary
311
+ alphabet = set()
312
+
313
+ def extract_all_chars(batch):
314
+ all_text = " ".join(batch["target_text"])
315
+ alphabet.update(all_text)
316
+
317
+ datasets.map(
318
+ extract_all_chars,
319
+ batched=True,
320
+ batch_size=-1,
321
+ keep_in_memory=True,
322
+ remove_columns=datasets["train"].column_names,
323
+ )
324
+
325
+ # # take union of all unique characters in each dataset
326
+ # vocab_set = functools.reduce(
327
+ # lambda vocab_1, vocab_2: {"vocab": list(set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]))}, vocabs.values()
328
+ # )["vocab"][0]
329
+
330
+ vocab_dict = {v: k for k, v in enumerate(sorted(list(alphabet)))}
331
+
332
+ # replace white space with delimiter token
333
+ if word_delimiter_token is not None:
334
+ vocab_dict[word_delimiter_token] = vocab_dict[" "]
335
+ del vocab_dict[" "]
336
+
337
+ # add unk and pad token
338
+ if unk_token is not None:
339
+ vocab_dict[unk_token] = len(vocab_dict)
340
+
341
+ if pad_token is not None:
342
+ vocab_dict[pad_token] = len(vocab_dict)
343
+
344
+ return vocab_dict
345
+
346
+
347
+ def make_dataset(seed=42):
348
+ # Pre-processing dataset
349
+ import re
350
+
351
+ def map_nst(entry):
352
+ text = entry["text"].lower()
353
+ text = text.replace("(...Vær stille under dette opptaket...)", "")
354
+ text = re.sub('[áàâ]', 'a', text)
355
+ text = re.sub('[ä]', 'æ', text)
356
+ text = re.sub('[éèëê]', 'e', text)
357
+ text = re.sub('[íìïî]', 'i', text)
358
+ text = re.sub('[óòöô]', 'o', text)
359
+ text = re.sub('[ö]', 'ø', text)
360
+ text = re.sub('[ç]', 'c', text)
361
+ text = re.sub('[úùüû]', 'u', text)
362
+ # text = re.sub('\\(?=(Punktum|Komma|Utropstegn|Spørsmålstegn))', ' ', text)
363
+ text = re.sub('\s+', ' ', text)
364
+ return {"text": text}
365
+
366
+ def filter_nst(entry):
367
+ if not ((len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)):
368
+ return False # Too short
369
+ if re.match(entry["type"], "pIW|CA"):
370
+ return False # Spelling out words
371
+ return True
372
+
373
+ def filter_npsc(entry):
374
+ # False if there are digits in the text
375
+ if not ((len(entry["text"]) <= len(entry["audio"]["array"]) // 320) and (len(entry["text"].strip()) >= 3)):
376
+ return False # Too short
377
+ if re.search("\d", entry["text"]):
378
+ return False
379
+ return True
380
+
381
+ def map_npsc(entry):
382
+ batch = {"text": entry["text"].lower()}
383
+ batch["text"] = re.sub('[áàâ]', 'a', batch["text"])
384
+ batch["text"] = re.sub('[ä]', 'æ', batch["text"])
385
+ batch["text"] = re.sub('[éèëê]', 'e', batch["text"])
386
+ batch["text"] = re.sub('[íìïî]', 'i', batch["text"])
387
+ batch["text"] = re.sub('[óòöô]', 'o', batch["text"])
388
+ batch["text"] = re.sub('[ö]', 'ø', batch["text"])
389
+ batch["text"] = re.sub('[ç]', 'c', batch["text"])
390
+ batch["text"] = re.sub('[úùüû]', 'u', batch["text"])
391
+ batch["text"] = re.sub('\s', ' ', batch["text"])
392
+ batch["text"] = re.sub('<ee>', 'eee', batch["text"])
393
+ batch["text"] = re.sub('<qq>', 'qqq', batch["text"])
394
+ batch["text"] = re.sub('<mm>', 'mmm', batch["text"])
395
+ batch["text"] = re.sub('<inaudible>', 'xxx', batch["text"])
396
+ # batch["text"] = re.sub('<inaudible>', '?', batch["text"])
397
+ if "<" in batch["text"]:
398
+ raise ValueError(batch["text"])
399
+ return batch
400
+
401
+ nst = datasets.load_dataset("NbAiLab/NST", "no-close")
402
+ npsc = datasets.load_dataset("NbAiLab/NPSC", "16K_mp3")
403
+ # TODO NST_hesitate
404
+
405
+ split = len(npsc["train"]) / (len(npsc["train"]) + len(npsc["validation"])) # Use same train/val ratio as NPSC
406
+ nst_train = nst["train"].train_test_split(train_size=split, seed=seed)
407
+ nst["train"] = nst_train["train"]
408
+ nst["validation"] = nst_train["test"]
409
+
410
+ nst = nst.filter(filter_nst).map(map_nst).shuffle(seed=seed)
411
+ npsc = npsc.filter(filter_npsc).map(map_npsc).shuffle(seed=seed)
412
+
413
+ npsc_base = npsc.remove_columns([col for col in npsc["train"].column_names if col not in ["text", "audio"]])
414
+ nst_base = nst.remove_columns([col for col in nst["train"].column_names if col not in ["text", "audio"]])
415
+
416
+ combined = {}
417
+ for split in "train", "validation", "test":
418
+ probs = np.array([len(nst_base[split]), len(npsc_base[split])]) # Weight by number of examples
419
+ probs = (probs / probs.sum()).tolist()
420
+ comb = datasets.interleave_datasets([nst_base[split], npsc_base[split]], probabilities=probs, seed=seed)
421
+ combined[split] = comb
422
+
423
+ return datasets.DatasetDict(**combined)
424
+
425
+
426
+ def main():
427
+ # See all possible arguments in src/transformers/training_args.py
428
+ # or by passing the --help flag to this script.
429
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
430
+
431
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
432
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
433
+ # If we pass only one argument to the script and it's the path to a json file,
434
+ # let's parse it to get our arguments.
435
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
436
+ else:
437
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
438
+
439
+ # Detecting last checkpoint.
440
+ last_checkpoint = None
441
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
442
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
443
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
444
+ raise ValueError(
445
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
446
+ "Use --overwrite_output_dir to overcome."
447
+ )
448
+ elif last_checkpoint is not None:
449
+ logger.info(
450
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
451
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
452
+ )
453
+
454
+ # Setup logging
455
+ logging.basicConfig(
456
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
457
+ datefmt="%m/%d/%Y %H:%M:%S",
458
+ handlers=[logging.StreamHandler(sys.stdout)],
459
+ )
460
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
461
+
462
+ # Log on each process the small summary:
463
+ logger.warning(
464
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
465
+ f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
466
+ )
467
+ # Set the verbosity to info of the Transformers logger (on main process only):
468
+ if is_main_process(training_args.local_rank):
469
+ transformers.utils.logging.set_verbosity_info()
470
+ logger.info("Training/evaluation parameters %s", training_args)
471
+
472
+ # Set seed before initializing model.
473
+ set_seed(training_args.seed)
474
+
475
+ # 1. First, let's load the dataset
476
+ raw_datasets = make_dataset(seed=training_args.seed)
477
+
478
+ if training_args.do_train:
479
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
480
+ raise ValueError(
481
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
482
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
483
+ f"{', '.join(raw_datasets['train'].column_names)}."
484
+ )
485
+
486
+ if data_args.text_column_name not in raw_datasets["train"].column_names:
487
+ raise ValueError(
488
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
489
+ "Make sure to set `--text_column_name` to the correct text column - one of "
490
+ f"{', '.join(raw_datasets['train'].column_names)}."
491
+ )
492
+
493
+ if data_args.max_train_samples is not None:
494
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
495
+
496
+ if training_args.do_eval:
497
+ if data_args.max_eval_samples is not None:
498
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
499
+
500
+ # 2. We remove some special characters from the datasets
501
+ # that make training complicated and do not help in transcribing the speech
502
+ # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
503
+ # that could be easily picked up by the model
504
+ # chars_to_ignore_regex = (
505
+ # f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
506
+ # )
507
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]'
508
+
509
+ text_column_name = data_args.text_column_name
510
+
511
+ def remove_special_characters(batch):
512
+ if chars_to_ignore_regex is not None:
513
+ batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
514
+ else:
515
+ batch["target_text"] = batch[text_column_name].lower() + " "
516
+ return batch
517
+
518
+ with training_args.main_process_first(desc="dataset map special characters removal"):
519
+ raw_datasets = raw_datasets.map(
520
+ remove_special_characters,
521
+ remove_columns=[text_column_name],
522
+ desc="remove special characters from datasets",
523
+ )
524
+
525
+ # save special tokens for tokenizer
526
+ word_delimiter_token = data_args.word_delimiter_token
527
+ unk_token = data_args.unk_token
528
+ pad_token = data_args.pad_token
529
+
530
+ # 3. Next, let's load the config as we might need it to create
531
+ # the tokenizer
532
+ # load config
533
+ config = AutoConfig.from_pretrained(
534
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
535
+ )
536
+
537
+ # 4. Next, if no tokenizer file is defined,
538
+ # we create the vocabulary of the model by extracting all unique characters from
539
+ # the training and evaluation datasets
540
+ # We need to make sure that only first rank saves vocabulary
541
+ # make sure all processes wait until vocab is created
542
+ tokenizer_name_or_path = model_args.tokenizer_name_or_path
543
+ tokenizer_kwargs = {}
544
+ if tokenizer_name_or_path is None:
545
+ # save vocab in training output dir
546
+ tokenizer_name_or_path = training_args.output_dir
547
+
548
+ vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
549
+
550
+ with training_args.main_process_first():
551
+ if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
552
+ os.remove(vocab_file)
553
+
554
+ with training_args.main_process_first(desc="dataset map vocabulary creation"):
555
+ if not os.path.isfile(vocab_file):
556
+ os.makedirs(tokenizer_name_or_path, exist_ok=True)
557
+ vocab_dict = create_vocabulary_from_data(
558
+ raw_datasets,
559
+ word_delimiter_token=word_delimiter_token,
560
+ unk_token=unk_token,
561
+ pad_token=pad_token,
562
+ )
563
+
564
+ # save vocab dict to be loaded into tokenizer
565
+ with open(vocab_file, "w") as file:
566
+ json.dump(vocab_dict, file)
567
+
568
+ # if tokenizer has just been created
569
+ # it is defined by `tokenizer_class` if present in config else by `model_type`
570
+ tokenizer_kwargs = {
571
+ "config": config if config.tokenizer_class is not None else None,
572
+ "tokenizer_type": config.model_type if config.tokenizer_class is None else None,
573
+ "unk_token": unk_token,
574
+ "pad_token": pad_token,
575
+ "word_delimiter_token": word_delimiter_token,
576
+ }
577
+
578
+ # 5. Now we can instantiate the feature extractor, tokenizer and model
579
+ # Note for distributed training, the .from_pretrained methods guarantee that only
580
+ # one local process can concurrently download model & vocab.
581
+
582
+ # load feature_extractor and tokenizer
583
+ tokenizer = AutoTokenizer.from_pretrained(
584
+ tokenizer_name_or_path,
585
+ use_auth_token=data_args.use_auth_token,
586
+ **tokenizer_kwargs,
587
+ )
588
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
589
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
590
+ )
591
+
592
+ # adapt config
593
+ config.update(
594
+ {
595
+ "feat_proj_dropout": model_args.feat_proj_dropout,
596
+ "attention_dropout": model_args.attention_dropout,
597
+ "hidden_dropout": model_args.hidden_dropout,
598
+ "final_dropout": model_args.final_dropout,
599
+ "mask_time_prob": model_args.mask_time_prob,
600
+ "mask_time_length": model_args.mask_time_length,
601
+ "mask_feature_prob": model_args.mask_feature_prob,
602
+ "mask_feature_length": model_args.mask_feature_length,
603
+ "gradient_checkpointing": training_args.gradient_checkpointing,
604
+ "layerdrop": model_args.layerdrop,
605
+ "ctc_loss_reduction": model_args.ctc_loss_reduction,
606
+ "ctc_zero_infinity": model_args.ctc_zero_infinity,
607
+ "pad_token_id": tokenizer.pad_token_id,
608
+ "vocab_size": len(tokenizer),
609
+ "activation_dropout": model_args.activation_dropout,
610
+ }
611
+ )
612
+
613
+ # create model
614
+ model = AutoModelForCTC.from_pretrained(
615
+ model_args.model_name_or_path,
616
+ cache_dir=model_args.cache_dir,
617
+ config=config,
618
+ use_auth_token=data_args.use_auth_token,
619
+ )
620
+
621
+ # freeze encoder
622
+ if model_args.freeze_feature_encoder:
623
+ model.freeze_feature_encoder()
624
+
625
+ # 6. Now we preprocess the datasets including loading the audio, resampling and normalization
626
+ # Thankfully, `datasets` takes care of automatically loading and resampling the audio,
627
+ # so that we just need to set the correct target sampling rate and normalize the input
628
+ # via the `feature_extractor`
629
+
630
+ # make sure that dataset decodes audio with correct sampling rate
631
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
632
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
633
+ raw_datasets = raw_datasets.cast_column(
634
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
635
+ )
636
+
637
+ # derive max & min input length for sample rate & max duration
638
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
639
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
640
+ audio_column_name = data_args.audio_column_name
641
+ num_workers = data_args.preprocessing_num_workers
642
+
643
+ # `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
644
+ phoneme_language = data_args.phoneme_language
645
+
646
+ # Preprocessing the datasets.
647
+ # We need to read the audio files as arrays and tokenize the targets.
648
+ def prepare_dataset(batch):
649
+ # load audio
650
+ sample = batch[audio_column_name]
651
+
652
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
653
+ batch["input_values"] = inputs.input_values[0]
654
+ batch["input_length"] = len(batch["input_values"])
655
+
656
+ # encode targets
657
+ additional_kwargs = {}
658
+ if phoneme_language is not None:
659
+ additional_kwargs["phonemizer_lang"] = phoneme_language
660
+
661
+ batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
662
+ return batch
663
+
664
+ with training_args.main_process_first(desc="dataset map preprocessing"):
665
+ vectorized_datasets = raw_datasets.map(
666
+ prepare_dataset,
667
+ remove_columns=next(iter(raw_datasets.values())).column_names,
668
+ num_proc=num_workers,
669
+ desc="preprocess datasets",
670
+ )
671
+
672
+ def is_audio_in_length_range(length):
673
+ return length > min_input_length and length < max_input_length
674
+
675
+ # filter data that is shorter than min_input_length
676
+ vectorized_datasets = vectorized_datasets.filter(
677
+ is_audio_in_length_range,
678
+ num_proc=num_workers,
679
+ input_columns=["input_length"],
680
+ )
681
+
682
+ # 7. Next, we can prepare the training.
683
+ # Let's use word error rate (WER) as our evaluation metric,
684
+ # instantiate a data collator and the trainer
685
+
686
+ # Define evaluation metrics during training, *i.e.* word error rate, character error rate
687
+ eval_metrics = {metric: load_metric(metric) for metric in data_args.eval_metrics}
688
+
689
+ # for large datasets it is advised to run the preprocessing on a
690
+ # single machine first with ``args.preprocessing_only`` since there will mostly likely
691
+ # be a timeout when running the script in distributed mode.
692
+ # In a second step ``args.preprocessing_only`` can then be set to `False` to load the
693
+ # cached dataset
694
+ if data_args.preprocessing_only:
695
+ logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
696
+ return
697
+
698
+ def compute_metrics(pred):
699
+ pred_logits = pred.predictions
700
+ pred_ids = np.argmax(pred_logits, axis=-1)
701
+
702
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
703
+
704
+ pred_str = tokenizer.batch_decode(pred_ids)
705
+ # we do not want to group tokens when computing the metrics
706
+ label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
707
+
708
+ metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
709
+
710
+ return metrics
711
+
712
+ # Now save everything to be able to create a single processor later
713
+ if is_main_process(training_args.local_rank):
714
+ # save feature extractor, tokenizer and config
715
+ feature_extractor.save_pretrained(training_args.output_dir)
716
+ tokenizer.save_pretrained(training_args.output_dir)
717
+ config.save_pretrained(training_args.output_dir)
718
+
719
+ try:
720
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
721
+ except (OSError, KeyError):
722
+ warnings.warn(
723
+ "Loading a processor from a feature extractor config that does not"
724
+ " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
725
+ " attribute to your `preprocessor_config.json` file to suppress this warning: "
726
+ " `'processor_class': 'Wav2Vec2Processor'`",
727
+ FutureWarning,
728
+ )
729
+ processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
730
+
731
+ # Instantiate custom data collator
732
+ data_collator = DataCollatorCTCWithPadding(processor=processor)
733
+
734
+ # Initialize Trainer
735
+ trainer = Trainer(
736
+ model=model,
737
+ data_collator=data_collator,
738
+ args=training_args,
739
+ compute_metrics=compute_metrics,
740
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
741
+ eval_dataset=vectorized_datasets["validation"] if training_args.do_eval else None,
742
+ tokenizer=feature_extractor,
743
+ )
744
+
745
+ # 8. Finally, we can start training
746
+
747
+ # Training
748
+ if training_args.do_train:
749
+
750
+ # use last checkpoint if exist
751
+ if last_checkpoint is not None:
752
+ checkpoint = last_checkpoint
753
+ elif os.path.isdir(model_args.model_name_or_path):
754
+ checkpoint = model_args.model_name_or_path
755
+ else:
756
+ checkpoint = None
757
+
758
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
759
+ trainer.save_model()
760
+
761
+ metrics = train_result.metrics
762
+ max_train_samples = (
763
+ data_args.max_train_samples
764
+ if data_args.max_train_samples is not None
765
+ else len(vectorized_datasets["train"])
766
+ )
767
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
768
+
769
+ trainer.log_metrics("train", metrics)
770
+ trainer.save_metrics("train", metrics)
771
+ trainer.save_state()
772
+
773
+ # Evaluation
774
+ results = {}
775
+ if training_args.do_eval:
776
+ logger.info("*** Evaluate ***")
777
+ metrics = trainer.evaluate()
778
+ max_eval_samples = (
779
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
780
+ )
781
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
782
+
783
+ trainer.log_metrics("eval", metrics)
784
+ trainer.save_metrics("eval", metrics)
785
+
786
+ # Write model card and (optionally) push to hub
787
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
788
+ kwargs = {
789
+ "finetuned_from": model_args.model_name_or_path,
790
+ "tasks": "speech-recognition",
791
+ "tags": ["automatic-speech-recognition", data_args.dataset_name],
792
+ "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
793
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
794
+ }
795
+ if "common_voice" in data_args.dataset_name:
796
+ kwargs["language"] = config_name
797
+
798
+ if training_args.push_to_hub:
799
+ trainer.push_to_hub(**kwargs)
800
+ else:
801
+ trainer.create_model_card(**kwargs)
802
+
803
+ return results
804
+
805
+
806
+ if __name__ == "__main__":
807
+ main()
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "[UNK]", "pad_token": "[PAD]", "additional_special_tokens": [{"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}]}
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "bos_token": "<s>", "eos_token": "</s>", "pad_token": "[PAD]", "do_lower_case": false, "word_delimiter_token": "|", "replace_word_delimiter_char": " ", "special_tokens_map_file": null, "name_or_path": "./", "tokenizer_class": "Wav2Vec2CTCTokenizer", "processor_class": "Wav2Vec2ProcessorWithLM"}
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d63c31e6cdc4ad990144c981422252a8ee34040e3eb92deeb7c6f36e75ccdee2
3
+ size 3055
vocab.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"(": 1, ")": 2, "0": 3, "3": 4, "7": 5, "8": 6, "9": 7, "a": 8, "b": 9, "c": 10, "d": 11, "e": 12, "f": 13, "g": 14, "h": 15, "i": 16, "j": 17, "k": 18, "l": 19, "m": 20, "n": 21, "o": 22, "p": 23, "q": 24, "r": 25, "s": 26, "t": 27, "u": 28, "v": 29, "w": 30, "x": 31, "y": 32, "z": 33, "å": 34, "æ": 35, "ø": 36, "|": 0, "[UNK]": 37, "[PAD]": 38}