NB-Wav2Vec2-300M-Bokmaal-v2
Browse files- .gitattributes +11 -5
- add_kenlm.py +36 -0
- added_tokens.json +1 -0
- all_results.json +8 -0
- alphabet.json +1 -0
- cardinal_numbers.py +690 -0
- config.json +115 -0
- eval.py +255 -0
- language_model/5gram.bin +3 -0
- language_model/attrs.json +1 -0
- language_model/unigrams.txt +3 -0
- preprocessor_config.json +10 -0
- pytorch_model.bin +3 -0
- run.sh +39 -0
- run_speech_recognition_ctc.py +822 -0
- special_tokens_map.json +1 -0
- tokenizer_config.json +1 -0
- train_results.json +8 -0
- trainer_state.json +0 -0
- training_args.bin +3 -0
- vocab.json +1 -0
.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,22 @@
|
|
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 |
-
*.
|
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-20220725_150933-2x1p7456 filter=lfs diff=lfs merge=lfs -text
|
33 |
+
wandb/debug-internal.log filter=lfs diff=lfs merge=lfs -text
|
34 |
+
wandb/debug.log filter=lfs diff=lfs merge=lfs -text
|
35 |
+
wandb/latest-run filter=lfs diff=lfs merge=lfs -text
|
36 |
+
wandb/run-20220725_150933-2x1p7456/files filter=lfs diff=lfs merge=lfs -text
|
37 |
+
wandb/run-20220725_150933-2x1p7456/logs filter=lfs diff=lfs merge=lfs -text
|
38 |
+
wandb/run-20220725_150933-2x1p7456/run-2x1p7456.wandb filter=lfs diff=lfs merge=lfs -text
|
39 |
+
wandb/run-20220725_150933-2x1p7456/tmp filter=lfs diff=lfs merge=lfs -text
|
40 |
+
*.wandb filter=lfs diff=lfs merge=lfs -text
|
41 |
+
language_model/unigrams.txt filter=lfs diff=lfs merge=lfs -text
|
add_kenlm.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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())
|
added_tokens.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"<s>": 33, "</s>": 34}
|
all_results.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 15.0,
|
3 |
+
"train_loss": 0.17642972585578237,
|
4 |
+
"train_runtime": 792752.3013,
|
5 |
+
"train_samples": 302347,
|
6 |
+
"train_samples_per_second": 5.721,
|
7 |
+
"train_steps_per_second": 0.179
|
8 |
+
}
|
alphabet.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"labels": [" ", "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", "\u0125", "\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,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "KBLab/wav2vec2-large-voxrex",
|
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": 768,
|
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": 1024,
|
58 |
+
"initializer_range": 0.02,
|
59 |
+
"intermediate_size": 4096,
|
60 |
+
"layer_norm_eps": 1e-05,
|
61 |
+
"layerdrop": 0.041,
|
62 |
+
"mask_channel_length": 10,
|
63 |
+
"mask_channel_min_space": 1,
|
64 |
+
"mask_channel_other": 0.0,
|
65 |
+
"mask_channel_prob": 0.0,
|
66 |
+
"mask_channel_selection": "static",
|
67 |
+
"mask_feature_length": 64,
|
68 |
+
"mask_feature_min_masks": 0,
|
69 |
+
"mask_feature_prob": 0.25,
|
70 |
+
"mask_time_length": 10,
|
71 |
+
"mask_time_min_masks": 2,
|
72 |
+
"mask_time_min_space": 1,
|
73 |
+
"mask_time_other": 0.0,
|
74 |
+
"mask_time_prob": 0.082,
|
75 |
+
"mask_time_selection": "static",
|
76 |
+
"model_type": "wav2vec2",
|
77 |
+
"num_adapter_layers": 3,
|
78 |
+
"num_attention_heads": 16,
|
79 |
+
"num_codevector_groups": 2,
|
80 |
+
"num_codevectors_per_group": 320,
|
81 |
+
"num_conv_pos_embedding_groups": 16,
|
82 |
+
"num_conv_pos_embeddings": 128,
|
83 |
+
"num_feat_extract_layers": 7,
|
84 |
+
"num_hidden_layers": 24,
|
85 |
+
"num_negatives": 100,
|
86 |
+
"output_hidden_size": 1024,
|
87 |
+
"pad_token_id": 32,
|
88 |
+
"proj_codevector_dim": 768,
|
89 |
+
"tdnn_dilation": [
|
90 |
+
1,
|
91 |
+
2,
|
92 |
+
3,
|
93 |
+
1,
|
94 |
+
1
|
95 |
+
],
|
96 |
+
"tdnn_dim": [
|
97 |
+
512,
|
98 |
+
512,
|
99 |
+
512,
|
100 |
+
512,
|
101 |
+
1500
|
102 |
+
],
|
103 |
+
"tdnn_kernel": [
|
104 |
+
5,
|
105 |
+
3,
|
106 |
+
3,
|
107 |
+
1,
|
108 |
+
1
|
109 |
+
],
|
110 |
+
"torch_dtype": "float32",
|
111 |
+
"transformers_version": "4.18.0",
|
112 |
+
"use_weighted_layer_sum": false,
|
113 |
+
"vocab_size": 35,
|
114 |
+
"xvector_output_dim": 512
|
115 |
+
}
|
eval.py
ADDED
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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('<e+h?>', 'ĥ', text)
|
134 |
+
text = re.sub('<m+>', 'ĥ', text)
|
135 |
+
text = re.sub('<q+>', 'ĥ', text)
|
136 |
+
text = re.sub('<inaudible>', 'ĥ', text)
|
137 |
+
text = re.sub('[<>]', '', text)
|
138 |
+
|
139 |
+
# # In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
140 |
+
# # note that order is important here!
|
141 |
+
# token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
|
142 |
+
|
143 |
+
# for t in token_sequences_to_ignore:
|
144 |
+
# text = " ".join(text.split(t))
|
145 |
+
|
146 |
+
return text.strip()
|
147 |
+
|
148 |
+
|
149 |
+
def main(args):
|
150 |
+
# load dataset
|
151 |
+
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
152 |
+
if args.filter:
|
153 |
+
attribute, value = list(map(str.strip, args.filter.split(":")))
|
154 |
+
dataset = dataset.filter(
|
155 |
+
lambda x: x[attribute] == value,
|
156 |
+
desc=f"Filtering on {args.filter}",
|
157 |
+
)
|
158 |
+
# for testing: only process the first two examples as a test
|
159 |
+
# dataset = dataset.select(range(10))
|
160 |
+
|
161 |
+
# load processor
|
162 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
|
163 |
+
sampling_rate = feature_extractor.sampling_rate
|
164 |
+
|
165 |
+
# resample audio
|
166 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
|
167 |
+
|
168 |
+
# load eval pipeline
|
169 |
+
if args.device is None:
|
170 |
+
args.device = 0 if torch.cuda.is_available() else -1
|
171 |
+
# asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
|
172 |
+
|
173 |
+
model_instance = AutoModelForCTC.from_pretrained(args.model_id)
|
174 |
+
if args.use_lm:
|
175 |
+
processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
|
176 |
+
decoder = processor.decoder
|
177 |
+
else:
|
178 |
+
processor = Wav2Vec2Processor.from_pretrained(args.model_id)
|
179 |
+
decoder = None
|
180 |
+
asr = pipeline(
|
181 |
+
"automatic-speech-recognition",
|
182 |
+
model=model_instance,
|
183 |
+
tokenizer=processor.tokenizer,
|
184 |
+
feature_extractor=processor.feature_extractor,
|
185 |
+
decoder=decoder,
|
186 |
+
device=args.device
|
187 |
+
)
|
188 |
+
|
189 |
+
# feature_extractor_dict, _ = Wav2Vec2FeatureExtractor.get_feature_extractor_dict(args.model_id)
|
190 |
+
# feature_extractor_dict["processor_class"] = "Wav2Vec2Processor" if not args.use_lm else "Wav2Vec2ProcessorWithLM"
|
191 |
+
# feature_extractor = Wav2Vec2FeatureExtractor.from_dict(feature_extractor_dict)
|
192 |
+
|
193 |
+
# asr = pipeline("automatic-speech-recognition", model=args.model_id, feature_extractor=feature_extractor, device=args.device, decoder=BeamSearchDecoderCTC.load_from_dir("./"))
|
194 |
+
|
195 |
+
# map function to decode audio
|
196 |
+
def map_to_pred(batch):
|
197 |
+
prediction = asr(
|
198 |
+
batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
|
199 |
+
)
|
200 |
+
|
201 |
+
batch["prediction"] = prediction["text"]
|
202 |
+
batch["target"] = normalize_text(batch[args.text_column], args.dataset)
|
203 |
+
return batch
|
204 |
+
|
205 |
+
# run inference on all examples
|
206 |
+
result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
|
207 |
+
|
208 |
+
# compute and log_results
|
209 |
+
# do not change function below
|
210 |
+
log_results(result, args)
|
211 |
+
|
212 |
+
|
213 |
+
if __name__ == "__main__":
|
214 |
+
parser = argparse.ArgumentParser()
|
215 |
+
|
216 |
+
parser.add_argument(
|
217 |
+
"--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
|
218 |
+
)
|
219 |
+
parser.add_argument(
|
220 |
+
"--dataset",
|
221 |
+
type=str,
|
222 |
+
required=True,
|
223 |
+
help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
|
224 |
+
)
|
225 |
+
parser.add_argument(
|
226 |
+
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
227 |
+
)
|
228 |
+
parser.add_argument(
|
229 |
+
"--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"
|
230 |
+
)
|
231 |
+
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
|
232 |
+
parser.add_argument(
|
233 |
+
"--text_column", type=str, default="text", help="Column name containing the transcription."
|
234 |
+
)
|
235 |
+
parser.add_argument(
|
236 |
+
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
|
237 |
+
)
|
238 |
+
parser.add_argument(
|
239 |
+
"--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
|
240 |
+
)
|
241 |
+
parser.add_argument(
|
242 |
+
"--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
|
243 |
+
)
|
244 |
+
parser.add_argument(
|
245 |
+
"--device",
|
246 |
+
type=int,
|
247 |
+
default=None,
|
248 |
+
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
|
249 |
+
)
|
250 |
+
parser.add_argument(
|
251 |
+
"--use_lm", action="store_true", help="If defined, use included language model as the decoder."
|
252 |
+
)
|
253 |
+
args = parser.parse_args()
|
254 |
+
|
255 |
+
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:5ecb597e9e18695f8f63e8b845ec3c635e8e559f7da920072736f443e26ca568
|
3 |
+
size 1262042225
|
run.sh
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
WANDB_ENTITY=NbAiLab WANDB_PROJECT=wav2vec2 python run_speech_recognition_ctc.py \
|
2 |
+
--model_name_or_path="KBLab/wav2vec2-large-voxrex" \
|
3 |
+
--hub_model_id="NbAiLab/wav2vec2-large-voxrex-npsc-nst-bokmaal-fixed" \
|
4 |
+
--output_dir="./" \
|
5 |
+
--overwrite_output_dir \
|
6 |
+
--num_train_epochs="15" \
|
7 |
+
--per_device_train_batch_size="16" \
|
8 |
+
--per_device_eval_batch_size="16" \
|
9 |
+
--gradient_accumulation_steps="2" \
|
10 |
+
--learning_rate="1e-4" \
|
11 |
+
--warmup_steps="2000" \
|
12 |
+
--length_column_name="input_length" \
|
13 |
+
--evaluation_strategy="steps" \
|
14 |
+
--text_column_name="text" \
|
15 |
+
--save_steps="500" \
|
16 |
+
--eval_steps="500" \
|
17 |
+
--logging_steps="100" \
|
18 |
+
--layerdrop="0.041" \
|
19 |
+
--attention_dropout="0.094" \
|
20 |
+
--activation_dropout="0.055" \
|
21 |
+
--hidden_dropout="0.047" \
|
22 |
+
--save_total_limit="3" \
|
23 |
+
--freeze_feature_encoder \
|
24 |
+
--feat_proj_dropout="0.04" \
|
25 |
+
--mask_time_prob="0.082" \
|
26 |
+
--mask_time_length="10" \
|
27 |
+
--mask_feature_prob="0.25" \
|
28 |
+
--mask_feature_length="64" \
|
29 |
+
--gradient_checkpointing \
|
30 |
+
--min_duration_in_seconds="0.5" \
|
31 |
+
--max_duration_in_seconds="20.0" \
|
32 |
+
--use_auth_token \
|
33 |
+
--seed="42" \
|
34 |
+
--fp16 \
|
35 |
+
--group_by_length \
|
36 |
+
--do_train --do_eval \
|
37 |
+
--push_to_hub \
|
38 |
+
--preprocessing_num_workers="32" \
|
39 |
+
--ctc_zero_infinity
|
run_speech_recognition_ctc.py
ADDED
@@ -0,0 +1,822 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 replace_strange_characters(text):
|
352 |
+
text = re.sub('[áàâ]', 'a', text)
|
353 |
+
text = re.sub('[ä]', 'æ', text)
|
354 |
+
text = re.sub('[éèëê]', 'e', text)
|
355 |
+
text = re.sub('[íìïî]', 'i', text)
|
356 |
+
text = re.sub('[óòöô]', 'o', text)
|
357 |
+
text = re.sub('[ö]', 'ø', text)
|
358 |
+
text = re.sub('[ç]', 'c', text)
|
359 |
+
text = re.sub('[úùüû]', 'u', text)
|
360 |
+
text = re.sub('\*', '', text)
|
361 |
+
return text
|
362 |
+
|
363 |
+
def replace_hesitations(text):
|
364 |
+
# text = re.sub("<[^>]*>", " ", text) # <ee>, <qq>, <mm>, <inaudible> for NPSC. <eeeh>, <mmm> for NST-hesitate
|
365 |
+
text = re.sub("<ee(eh)?>", "ĥ", text)
|
366 |
+
text = re.sub("<mmm?>", "ĥ", text)
|
367 |
+
text = re.sub("<qq>", "ĥ", text)
|
368 |
+
# text = re.sub("<inaudible>", "I", text)
|
369 |
+
return text
|
370 |
+
|
371 |
+
def is_too_short(entry):
|
372 |
+
return len(entry["text"]) > len(entry["audio"]["array"]) // 320 or len(entry["text"]) <=1
|
373 |
+
|
374 |
+
def map_nst(entry):
|
375 |
+
text = entry["text"].lower()
|
376 |
+
text = text.replace("(...vær stille under dette opptaket...)", " ")
|
377 |
+
text = replace_hesitations(text)
|
378 |
+
text = replace_strange_characters(text)
|
379 |
+
text = re.sub('\s+', ' ', text)
|
380 |
+
return {"text": text.strip()}
|
381 |
+
|
382 |
+
def filter_nst(entry):
|
383 |
+
if is_too_short(entry):
|
384 |
+
return False # Too short
|
385 |
+
if re.match(entry["type"], "pIW|CA"):
|
386 |
+
return False # Spelling out words
|
387 |
+
if re.search("\d", entry["text"]):
|
388 |
+
return False
|
389 |
+
return True
|
390 |
+
|
391 |
+
def filter_npsc(entry):
|
392 |
+
if is_too_short(entry):
|
393 |
+
return False # Too short
|
394 |
+
if re.search("\d", entry["text"]):
|
395 |
+
return False
|
396 |
+
if re.search("<inaudible>", entry["text"]):
|
397 |
+
return False
|
398 |
+
return True
|
399 |
+
|
400 |
+
def map_npsc(entry):
|
401 |
+
text = entry["transsentence_text"] if entry["sentence_language_code"].startswith("nn") else entry["text"]
|
402 |
+
text = text.lower()
|
403 |
+
text = replace_strange_characters(text)
|
404 |
+
text = replace_hesitations(text)
|
405 |
+
text = re.sub('\s+', ' ', text)
|
406 |
+
return {"text": text.strip()}
|
407 |
+
|
408 |
+
nst = datasets.load_dataset("NbAiLab/NST", "no-close")
|
409 |
+
npsc = datasets.load_dataset("NbAiLab/NPSC", "16K_mp3")
|
410 |
+
nsth = datasets.load_dataset("NbAiLab/NST_hesitate", "no")
|
411 |
+
|
412 |
+
nst = nst.map(map_nst).filter(filter_nst)
|
413 |
+
npsc = npsc.map(map_npsc).filter(filter_npsc)
|
414 |
+
nsth = nsth.map(map_nst).filter(filter_npsc)
|
415 |
+
|
416 |
+
split = len(npsc["train"]) / (len(npsc["train"]) + len(npsc["validation"])) # Use same train/val ratio as NPSC
|
417 |
+
nst_train = nst["train"].train_test_split(train_size=split, seed=seed)
|
418 |
+
nst["train"] = nst_train["train"]
|
419 |
+
nst["validation"] = nst_train["test"]
|
420 |
+
|
421 |
+
nsth_train = nsth["train"].train_test_split(train_size=split, seed=seed)
|
422 |
+
nsth["train"] = nsth_train["train"]
|
423 |
+
nsth["validation"] = nsth_train["test"]
|
424 |
+
|
425 |
+
nst_base = nst.remove_columns([col for col in nst["train"].column_names if col not in ["text", "audio"]])
|
426 |
+
npsc_base = npsc.remove_columns([col for col in npsc["train"].column_names if col not in ["text", "audio"]])
|
427 |
+
nsth_base = nsth.remove_columns([col for col in nsth["train"].column_names if col not in ["text", "audio"]])
|
428 |
+
|
429 |
+
combined = {}
|
430 |
+
for split in "train", "validation", "test":
|
431 |
+
# Weight by number of examples
|
432 |
+
probs = np.array([len(nst_base[split]), len(npsc_base[split]), len(nsth_base[split])])
|
433 |
+
probs = (probs / probs.sum()).tolist()
|
434 |
+
comb = datasets.interleave_datasets([nst_base[split], npsc_base[split], nsth_base[split]],
|
435 |
+
probabilities=probs, seed=seed)
|
436 |
+
combined[split] = comb
|
437 |
+
|
438 |
+
return datasets.DatasetDict(**combined)
|
439 |
+
|
440 |
+
|
441 |
+
def main():
|
442 |
+
# See all possible arguments in src/transformers/training_args.py
|
443 |
+
# or by passing the --help flag to this script.
|
444 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
445 |
+
|
446 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
447 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
448 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
449 |
+
# let's parse it to get our arguments.
|
450 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
451 |
+
else:
|
452 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
453 |
+
|
454 |
+
# Detecting last checkpoint.
|
455 |
+
last_checkpoint = None
|
456 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
457 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
458 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
459 |
+
raise ValueError(
|
460 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
461 |
+
"Use --overwrite_output_dir to overcome."
|
462 |
+
)
|
463 |
+
elif last_checkpoint is not None:
|
464 |
+
logger.info(
|
465 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
466 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
467 |
+
)
|
468 |
+
|
469 |
+
# Setup logging
|
470 |
+
logging.basicConfig(
|
471 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
472 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
473 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
474 |
+
)
|
475 |
+
logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
|
476 |
+
|
477 |
+
# Log on each process the small summary:
|
478 |
+
logger.warning(
|
479 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
|
480 |
+
f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
|
481 |
+
)
|
482 |
+
# Set the verbosity to info of the Transformers logger (on main process only):
|
483 |
+
if is_main_process(training_args.local_rank):
|
484 |
+
transformers.utils.logging.set_verbosity_info()
|
485 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
486 |
+
|
487 |
+
# Set seed before initializing model.
|
488 |
+
set_seed(training_args.seed)
|
489 |
+
|
490 |
+
# 1. First, let's load the dataset
|
491 |
+
raw_datasets = make_dataset(seed=training_args.seed)
|
492 |
+
|
493 |
+
if training_args.do_train:
|
494 |
+
if data_args.audio_column_name not in raw_datasets["train"].column_names:
|
495 |
+
raise ValueError(
|
496 |
+
f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. "
|
497 |
+
"Make sure to set `--audio_column_name` to the correct audio column - one of "
|
498 |
+
f"{', '.join(raw_datasets['train'].column_names)}."
|
499 |
+
)
|
500 |
+
|
501 |
+
if data_args.text_column_name not in raw_datasets["train"].column_names:
|
502 |
+
raise ValueError(
|
503 |
+
f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
|
504 |
+
"Make sure to set `--text_column_name` to the correct text column - one of "
|
505 |
+
f"{', '.join(raw_datasets['train'].column_names)}."
|
506 |
+
)
|
507 |
+
|
508 |
+
if data_args.max_train_samples is not None:
|
509 |
+
raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
|
510 |
+
|
511 |
+
if training_args.do_eval:
|
512 |
+
if data_args.max_eval_samples is not None:
|
513 |
+
raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
|
514 |
+
|
515 |
+
# 2. We remove some special characters from the datasets
|
516 |
+
# that make training complicated and do not help in transcribing the speech
|
517 |
+
# E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
|
518 |
+
# that could be easily picked up by the model
|
519 |
+
# chars_to_ignore_regex = (
|
520 |
+
# f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
|
521 |
+
# )
|
522 |
+
chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]'
|
523 |
+
|
524 |
+
text_column_name = data_args.text_column_name
|
525 |
+
|
526 |
+
def remove_special_characters(batch):
|
527 |
+
if chars_to_ignore_regex is not None:
|
528 |
+
batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
|
529 |
+
else:
|
530 |
+
batch["target_text"] = batch[text_column_name].lower() + " "
|
531 |
+
return batch
|
532 |
+
|
533 |
+
with training_args.main_process_first(desc="dataset map special characters removal"):
|
534 |
+
raw_datasets = raw_datasets.map(
|
535 |
+
remove_special_characters,
|
536 |
+
remove_columns=[text_column_name],
|
537 |
+
desc="remove special characters from datasets",
|
538 |
+
)
|
539 |
+
|
540 |
+
# save special tokens for tokenizer
|
541 |
+
word_delimiter_token = data_args.word_delimiter_token
|
542 |
+
unk_token = data_args.unk_token
|
543 |
+
pad_token = data_args.pad_token
|
544 |
+
|
545 |
+
# 3. Next, let's load the config as we might need it to create
|
546 |
+
# the tokenizer
|
547 |
+
# load config
|
548 |
+
config = AutoConfig.from_pretrained(
|
549 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
|
550 |
+
)
|
551 |
+
|
552 |
+
# 4. Next, if no tokenizer file is defined,
|
553 |
+
# we create the vocabulary of the model by extracting all unique characters from
|
554 |
+
# the training and evaluation datasets
|
555 |
+
# We need to make sure that only first rank saves vocabulary
|
556 |
+
# make sure all processes wait until vocab is created
|
557 |
+
tokenizer_name_or_path = model_args.tokenizer_name_or_path
|
558 |
+
tokenizer_kwargs = {}
|
559 |
+
if tokenizer_name_or_path is None:
|
560 |
+
# save vocab in training output dir
|
561 |
+
tokenizer_name_or_path = training_args.output_dir
|
562 |
+
|
563 |
+
vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
|
564 |
+
|
565 |
+
with training_args.main_process_first():
|
566 |
+
if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
|
567 |
+
os.remove(vocab_file)
|
568 |
+
|
569 |
+
with training_args.main_process_first(desc="dataset map vocabulary creation"):
|
570 |
+
if not os.path.isfile(vocab_file):
|
571 |
+
os.makedirs(tokenizer_name_or_path, exist_ok=True)
|
572 |
+
vocab_dict = create_vocabulary_from_data(
|
573 |
+
raw_datasets,
|
574 |
+
word_delimiter_token=word_delimiter_token,
|
575 |
+
unk_token=unk_token,
|
576 |
+
pad_token=pad_token,
|
577 |
+
)
|
578 |
+
|
579 |
+
# save vocab dict to be loaded into tokenizer
|
580 |
+
with open(vocab_file, "w") as file:
|
581 |
+
json.dump(vocab_dict, file)
|
582 |
+
|
583 |
+
# if tokenizer has just been created
|
584 |
+
# it is defined by `tokenizer_class` if present in config else by `model_type`
|
585 |
+
tokenizer_kwargs = {
|
586 |
+
"config": config if config.tokenizer_class is not None else None,
|
587 |
+
"tokenizer_type": config.model_type if config.tokenizer_class is None else None,
|
588 |
+
"unk_token": unk_token,
|
589 |
+
"pad_token": pad_token,
|
590 |
+
"word_delimiter_token": word_delimiter_token,
|
591 |
+
}
|
592 |
+
|
593 |
+
# 5. Now we can instantiate the feature extractor, tokenizer and model
|
594 |
+
# Note for distributed training, the .from_pretrained methods guarantee that only
|
595 |
+
# one local process can concurrently download model & vocab.
|
596 |
+
|
597 |
+
# load feature_extractor and tokenizer
|
598 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
599 |
+
tokenizer_name_or_path,
|
600 |
+
use_auth_token=data_args.use_auth_token,
|
601 |
+
**tokenizer_kwargs,
|
602 |
+
)
|
603 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
604 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
|
605 |
+
)
|
606 |
+
|
607 |
+
# adapt config
|
608 |
+
config.update(
|
609 |
+
{
|
610 |
+
"feat_proj_dropout": model_args.feat_proj_dropout,
|
611 |
+
"attention_dropout": model_args.attention_dropout,
|
612 |
+
"hidden_dropout": model_args.hidden_dropout,
|
613 |
+
"final_dropout": model_args.final_dropout,
|
614 |
+
"mask_time_prob": model_args.mask_time_prob,
|
615 |
+
"mask_time_length": model_args.mask_time_length,
|
616 |
+
"mask_feature_prob": model_args.mask_feature_prob,
|
617 |
+
"mask_feature_length": model_args.mask_feature_length,
|
618 |
+
"gradient_checkpointing": training_args.gradient_checkpointing,
|
619 |
+
"layerdrop": model_args.layerdrop,
|
620 |
+
"ctc_loss_reduction": model_args.ctc_loss_reduction,
|
621 |
+
"ctc_zero_infinity": model_args.ctc_zero_infinity,
|
622 |
+
"pad_token_id": tokenizer.pad_token_id,
|
623 |
+
"vocab_size": len(tokenizer),
|
624 |
+
"activation_dropout": model_args.activation_dropout,
|
625 |
+
}
|
626 |
+
)
|
627 |
+
|
628 |
+
# create model
|
629 |
+
model = AutoModelForCTC.from_pretrained(
|
630 |
+
model_args.model_name_or_path,
|
631 |
+
cache_dir=model_args.cache_dir,
|
632 |
+
config=config,
|
633 |
+
use_auth_token=data_args.use_auth_token,
|
634 |
+
)
|
635 |
+
|
636 |
+
# freeze encoder
|
637 |
+
if model_args.freeze_feature_encoder:
|
638 |
+
model.freeze_feature_encoder()
|
639 |
+
|
640 |
+
# 6. Now we preprocess the datasets including loading the audio, resampling and normalization
|
641 |
+
# Thankfully, `datasets` takes care of automatically loading and resampling the audio,
|
642 |
+
# so that we just need to set the correct target sampling rate and normalize the input
|
643 |
+
# via the `feature_extractor`
|
644 |
+
|
645 |
+
# make sure that dataset decodes audio with correct sampling rate
|
646 |
+
dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
|
647 |
+
if dataset_sampling_rate != feature_extractor.sampling_rate:
|
648 |
+
raw_datasets = raw_datasets.cast_column(
|
649 |
+
data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
|
650 |
+
)
|
651 |
+
|
652 |
+
# derive max & min input length for sample rate & max duration
|
653 |
+
max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
|
654 |
+
min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
|
655 |
+
audio_column_name = data_args.audio_column_name
|
656 |
+
num_workers = data_args.preprocessing_num_workers
|
657 |
+
|
658 |
+
# `phoneme_language` is only relevant if the model is fine-tuned on phoneme classification
|
659 |
+
phoneme_language = data_args.phoneme_language
|
660 |
+
|
661 |
+
# Preprocessing the datasets.
|
662 |
+
# We need to read the audio files as arrays and tokenize the targets.
|
663 |
+
def prepare_dataset(batch):
|
664 |
+
# load audio
|
665 |
+
sample = batch[audio_column_name]
|
666 |
+
|
667 |
+
inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
|
668 |
+
batch["input_values"] = inputs.input_values[0]
|
669 |
+
batch["input_length"] = len(batch["input_values"])
|
670 |
+
|
671 |
+
# encode targets
|
672 |
+
additional_kwargs = {}
|
673 |
+
if phoneme_language is not None:
|
674 |
+
additional_kwargs["phonemizer_lang"] = phoneme_language
|
675 |
+
|
676 |
+
batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
|
677 |
+
return batch
|
678 |
+
|
679 |
+
with training_args.main_process_first(desc="dataset map preprocessing"):
|
680 |
+
vectorized_datasets = raw_datasets.map(
|
681 |
+
prepare_dataset,
|
682 |
+
remove_columns=next(iter(raw_datasets.values())).column_names,
|
683 |
+
num_proc=num_workers,
|
684 |
+
desc="preprocess datasets",
|
685 |
+
)
|
686 |
+
|
687 |
+
def is_audio_in_length_range(length):
|
688 |
+
return length > min_input_length and length < max_input_length
|
689 |
+
|
690 |
+
# filter data that is shorter than min_input_length
|
691 |
+
vectorized_datasets = vectorized_datasets.filter(
|
692 |
+
is_audio_in_length_range,
|
693 |
+
num_proc=num_workers,
|
694 |
+
input_columns=["input_length"],
|
695 |
+
)
|
696 |
+
|
697 |
+
# 7. Next, we can prepare the training.
|
698 |
+
# Let's use word error rate (WER) as our evaluation metric,
|
699 |
+
# instantiate a data collator and the trainer
|
700 |
+
|
701 |
+
# Define evaluation metrics during training, *i.e.* word error rate, character error rate
|
702 |
+
eval_metrics = {metric: load_metric(metric) for metric in data_args.eval_metrics}
|
703 |
+
|
704 |
+
# for large datasets it is advised to run the preprocessing on a
|
705 |
+
# single machine first with ``args.preprocessing_only`` since there will mostly likely
|
706 |
+
# be a timeout when running the script in distributed mode.
|
707 |
+
# In a second step ``args.preprocessing_only`` can then be set to `False` to load the
|
708 |
+
# cached dataset
|
709 |
+
if data_args.preprocessing_only:
|
710 |
+
logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
|
711 |
+
return
|
712 |
+
|
713 |
+
def compute_metrics(pred):
|
714 |
+
pred_logits = pred.predictions
|
715 |
+
pred_ids = np.argmax(pred_logits, axis=-1)
|
716 |
+
|
717 |
+
pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
|
718 |
+
|
719 |
+
pred_str = tokenizer.batch_decode(pred_ids)
|
720 |
+
# we do not want to group tokens when computing the metrics
|
721 |
+
label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
|
722 |
+
|
723 |
+
metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
|
724 |
+
|
725 |
+
return metrics
|
726 |
+
|
727 |
+
# Now save everything to be able to create a single processor later
|
728 |
+
if is_main_process(training_args.local_rank):
|
729 |
+
# save feature extractor, tokenizer and config
|
730 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
731 |
+
tokenizer.save_pretrained(training_args.output_dir)
|
732 |
+
config.save_pretrained(training_args.output_dir)
|
733 |
+
|
734 |
+
try:
|
735 |
+
processor = AutoProcessor.from_pretrained(training_args.output_dir)
|
736 |
+
except (OSError, KeyError):
|
737 |
+
warnings.warn(
|
738 |
+
"Loading a processor from a feature extractor config that does not"
|
739 |
+
" include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
|
740 |
+
" attribute to your `preprocessor_config.json` file to suppress this warning: "
|
741 |
+
" `'processor_class': 'Wav2Vec2Processor'`",
|
742 |
+
FutureWarning,
|
743 |
+
)
|
744 |
+
processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
|
745 |
+
|
746 |
+
# Instantiate custom data collator
|
747 |
+
data_collator = DataCollatorCTCWithPadding(processor=processor)
|
748 |
+
|
749 |
+
# Initialize Trainer
|
750 |
+
trainer = Trainer(
|
751 |
+
model=model,
|
752 |
+
data_collator=data_collator,
|
753 |
+
args=training_args,
|
754 |
+
compute_metrics=compute_metrics,
|
755 |
+
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
|
756 |
+
eval_dataset=vectorized_datasets["validation"] if training_args.do_eval else None,
|
757 |
+
tokenizer=feature_extractor,
|
758 |
+
)
|
759 |
+
|
760 |
+
# 8. Finally, we can start training
|
761 |
+
|
762 |
+
# Training
|
763 |
+
if training_args.do_train:
|
764 |
+
|
765 |
+
# use last checkpoint if exist
|
766 |
+
if last_checkpoint is not None:
|
767 |
+
checkpoint = last_checkpoint
|
768 |
+
elif os.path.isdir(model_args.model_name_or_path):
|
769 |
+
checkpoint = model_args.model_name_or_path
|
770 |
+
else:
|
771 |
+
checkpoint = None
|
772 |
+
|
773 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
774 |
+
trainer.save_model()
|
775 |
+
|
776 |
+
metrics = train_result.metrics
|
777 |
+
max_train_samples = (
|
778 |
+
data_args.max_train_samples
|
779 |
+
if data_args.max_train_samples is not None
|
780 |
+
else len(vectorized_datasets["train"])
|
781 |
+
)
|
782 |
+
metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
|
783 |
+
|
784 |
+
trainer.log_metrics("train", metrics)
|
785 |
+
trainer.save_metrics("train", metrics)
|
786 |
+
trainer.save_state()
|
787 |
+
|
788 |
+
# Evaluation
|
789 |
+
results = {}
|
790 |
+
if training_args.do_eval:
|
791 |
+
logger.info("*** Evaluate ***")
|
792 |
+
metrics = trainer.evaluate()
|
793 |
+
max_eval_samples = (
|
794 |
+
data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
|
795 |
+
)
|
796 |
+
metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
|
797 |
+
|
798 |
+
trainer.log_metrics("eval", metrics)
|
799 |
+
trainer.save_metrics("eval", metrics)
|
800 |
+
|
801 |
+
# Write model card and (optionally) push to hub
|
802 |
+
config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
|
803 |
+
kwargs = {
|
804 |
+
"finetuned_from": model_args.model_name_or_path,
|
805 |
+
"tasks": "speech-recognition",
|
806 |
+
"tags": ["automatic-speech-recognition", data_args.dataset_name],
|
807 |
+
"dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}",
|
808 |
+
"dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
|
809 |
+
}
|
810 |
+
if "common_voice" in data_args.dataset_name:
|
811 |
+
kwargs["language"] = config_name
|
812 |
+
|
813 |
+
if training_args.push_to_hub:
|
814 |
+
trainer.push_to_hub(**kwargs)
|
815 |
+
else:
|
816 |
+
trainer.create_model_card(**kwargs)
|
817 |
+
|
818 |
+
return results
|
819 |
+
|
820 |
+
|
821 |
+
if __name__ == "__main__":
|
822 |
+
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}]}
|
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"}
|
train_results.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"epoch": 15.0,
|
3 |
+
"train_loss": 0.17642972585578237,
|
4 |
+
"train_runtime": 792752.3013,
|
5 |
+
"train_samples": 302347,
|
6 |
+
"train_samples_per_second": 5.721,
|
7 |
+
"train_steps_per_second": 0.179
|
8 |
+
}
|
trainer_state.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2af229c7525c840d522bb39bbd590e1f1317ab166105438a5094178bf818b6e8
|
3 |
+
size 3055
|
vocab.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26, "å": 27, "æ": 28, "ø": 29, "ĥ": 30, "|": 0, "[UNK]": 31, "[PAD]": 32}
|