versae commited on
Commit
e0cc13d
1 Parent(s): f704685

Add 5-gram lang model and eval code

Browse files
.gitattributes CHANGED
@@ -37,3 +37,4 @@ wandb/run-20220919_091309-2lk1vb0u/logs/debug-internal.log filter=lfs diff=lfs m
37
  wandb/run-20220919_091309-2lk1vb0u/files/output.log filter=lfs diff=lfs merge=lfs -text
38
  wandb/run-20221025_092127-29xi74uq/logs/debug-internal.log filter=lfs diff=lfs merge=lfs -text
39
  wandb/run-20221025_092127-29xi74uq/files/output.log filter=lfs diff=lfs merge=lfs -text
 
 
37
  wandb/run-20220919_091309-2lk1vb0u/files/output.log filter=lfs diff=lfs merge=lfs -text
38
  wandb/run-20221025_092127-29xi74uq/logs/debug-internal.log filter=lfs diff=lfs merge=lfs -text
39
  wandb/run-20221025_092127-29xi74uq/files/output.log filter=lfs diff=lfs merge=lfs -text
40
+ language_model/unigrams.txt filter=lfs diff=lfs merge=lfs -text
add_kenlm.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from transformers import AutoProcessor
3
+ from transformers import Wav2Vec2ProcessorWithLM
4
+ from pyctcdecode import build_ctcdecoder
5
+
6
+
7
+ def main(args):
8
+ processor = AutoProcessor.from_pretrained(args.model_name_or_path)
9
+ vocab_dict = processor.tokenizer.get_vocab()
10
+ sorted_vocab_dict = {
11
+ k.lower(): v for k, v in sorted(vocab_dict.items(), key=lambda item: item[1])
12
+ }
13
+ decoder = build_ctcdecoder(
14
+ labels=list(sorted_vocab_dict.keys()),
15
+ kenlm_model_path=args.kenlm_model_path,
16
+ )
17
+ processor_with_lm = Wav2Vec2ProcessorWithLM(
18
+ feature_extractor=processor.feature_extractor,
19
+ tokenizer=processor.tokenizer,
20
+ decoder=decoder,
21
+ )
22
+ processor_with_lm.save_pretrained(args.model_name_or_path)
23
+ print(
24
+ f"Run: ~/bin/build_binary language_model/*.arpa language_model/5gram.bin -T $(pwd) && rm language_model/*.arpa")
25
+
26
+
27
+ def parse_args():
28
+ parser = argparse.ArgumentParser()
29
+ parser.add_argument('--model_name_or_path', default="./", help='Model name or path. Defaults to ./')
30
+ parser.add_argument('--kenlm_model_path', required=True, help='Path to KenLM arpa file.')
31
+ args = parser.parse_args()
32
+ return args
33
+
34
+
35
+ if __name__ == "__main__":
36
+ main(parse_args())
37
+
added_tokens.json CHANGED
@@ -1 +1,4 @@
1
- {"<s>": 39, "</s>": 40}
 
 
 
 
1
+ {
2
+ "</s>": 40,
3
+ "<s>": 39
4
+ }
alphabet.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"labels": [" ", "(", ")", "0", "3", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u00e5", "\u00e6", "\u00f8", "\u2047", "", "<s>", "</s>"], "is_bpe": false}
eval.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ from transformers import AutoFeatureExtractor, AutoModelForCTC, pipeline, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM, Wav2Vec2FeatureExtractor
11
+ # from pyctcdecode import BeamSearchDecoderCTC
12
+
13
+
14
+ def log_results(result: Dataset, args: Dict[str, str]):
15
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
16
+
17
+ log_outputs = args.log_outputs
18
+ lm = "withLM" if args.use_lm else "noLM"
19
+ model_id = args.model_id.replace("/", "_").replace(".", "")
20
+ dataset_id = "_".join([model_id] + args.dataset.split("/") + [args.config, args.split, lm])
21
+
22
+ # load metric
23
+ wer = load_metric("wer")
24
+ cer = load_metric("cer")
25
+
26
+ # compute metrics
27
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
28
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
29
+
30
+ # print & log results
31
+ result_str = f"{dataset_id}\nWER: {wer_result}\nCER: {cer_result}"
32
+ print(result_str)
33
+
34
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
35
+ f.write(result_str)
36
+
37
+ # log all results in text file. Possibly interesting for analysis
38
+ if log_outputs is not None:
39
+ pred_file = f"log_{dataset_id}_predictions.txt"
40
+ target_file = f"log_{dataset_id}_targets.txt"
41
+
42
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
43
+ # mapping function to write output
44
+ def write_to_file(batch, i):
45
+ p.write(f"{i}" + "\n")
46
+ p.write(batch["prediction"] + "\n")
47
+ t.write(f"{i}" + "\n")
48
+ t.write(batch["target"] + "\n")
49
+
50
+ result.map(write_to_file, with_indices=True)
51
+
52
+
53
+ def normalize_text(text: str, dataset: str) -> str:
54
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
55
+
56
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
57
+ text = re.sub(chars_to_ignore_regex, "", text.lower()) + " "
58
+
59
+ if dataset.lower().endswith("nst"):
60
+ text = text.lower()
61
+ text = text.replace("(...vær stille under dette opptaket...)", "")
62
+ text = re.sub('[áàâ]', 'a', text)
63
+ text = re.sub('[ä]', 'æ', text)
64
+ text = re.sub('[éèëê]', 'e', text)
65
+ text = re.sub('[íìïî]', 'i', text)
66
+ text = re.sub('[óòöô]', 'o', text)
67
+ text = re.sub('[ö]', 'ø', text)
68
+ text = re.sub('[ç]', 'c', text)
69
+ text = re.sub('[úùüû]', 'u', text)
70
+ # text = re.sub('\\(?=(Punktum|Komma|Utropstegn|Spørsmålstegn))', ' ', text)
71
+ text = re.sub('\s+', ' ', text)
72
+ elif dataset.lower().endswith("npsc"):
73
+ text = re.sub('[áàâ]', 'a', text)
74
+ text = re.sub('[ä]', 'æ', text)
75
+ text = re.sub('[éèëê]', 'e', text)
76
+ text = re.sub('[íìïî]', 'i', text)
77
+ text = re.sub('[óòöô]', 'o', text)
78
+ text = re.sub('[ö]', 'ø', text)
79
+ text = re.sub('[ç]', 'c', text)
80
+ text = re.sub('[úùüû]', 'u', text)
81
+ text = re.sub('\s+', ' ', text)
82
+ elif dataset.lower().endswith("fleurs"):
83
+ text = re.sub('[áàâ]', 'a', text)
84
+ text = re.sub('[ä]', 'æ', text)
85
+ text = re.sub('[éèëê]', 'e', text)
86
+ text = re.sub('[íìïî]', 'i', text)
87
+ text = re.sub('[óòöô]', 'o', text)
88
+ text = re.sub('[ö]', 'ø', text)
89
+ text = re.sub('[ç]', 'c', text)
90
+ text = re.sub('[úùüû]', 'u', text)
91
+ text = re.compile(r"-?[1-9][\d.]*").sub(lambda x: n2w(x.group(0), lang="no"), text)
92
+ text = re.sub('\s+', ' ', text)
93
+ text = re.sub('<ee>', 'eee', text)
94
+ text = re.sub('<qq>', 'qqq', text)
95
+ text = re.sub('<mm>', 'mmm', text)
96
+ text = re.sub('<inaudible>', 'xxx', text)
97
+
98
+ # # In addition, we can normalize the target text, e.g. removing new lines characters etc...
99
+ # # note that order is important here!
100
+ # token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
101
+
102
+ # for t in token_sequences_to_ignore:
103
+ # text = " ".join(text.split(t))
104
+
105
+ return text
106
+
107
+
108
+ def main(args):
109
+ # load dataset
110
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
111
+
112
+ # for testing: only process the first two examples as a test
113
+ # dataset = dataset.select(range(10))
114
+
115
+ # load processor
116
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
117
+ sampling_rate = feature_extractor.sampling_rate
118
+
119
+ # resample audio
120
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
121
+
122
+ # load eval pipeline
123
+ if args.device is None:
124
+ args.device = 0 if torch.cuda.is_available() else -1
125
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
126
+
127
+ model_instance = AutoModelForCTC.from_pretrained(args.model_id)
128
+ if args.use_lm:
129
+ processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
130
+ decoder = processor.decoder
131
+ else:
132
+ processor = Wav2Vec2Processor.from_pretrained(args.model_id)
133
+ decoder = None
134
+ asr = pipeline(
135
+ "automatic-speech-recognition",
136
+ model=model_instance,
137
+ tokenizer=processor.tokenizer,
138
+ feature_extractor=processor.feature_extractor,
139
+ decoder=decoder,
140
+ device=args.device
141
+ )
142
+
143
+ # feature_extractor_dict, _ = Wav2Vec2FeatureExtractor.get_feature_extractor_dict(args.model_id)
144
+ # feature_extractor_dict["processor_class"] = "Wav2Vec2Processor" if not args.use_lm else "Wav2Vec2ProcessorWithLM"
145
+ # feature_extractor = Wav2Vec2FeatureExtractor.from_dict(feature_extractor_dict)
146
+
147
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id, feature_extractor=feature_extractor, device=args.device, decoder=BeamSearchDecoderCTC.load_from_dir("./"))
148
+
149
+ # map function to decode audio
150
+ def map_to_pred(batch):
151
+ prediction = asr(
152
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
153
+ )
154
+
155
+ batch["prediction"] = prediction["text"]
156
+ batch["target"] = normalize_text(batch[args.text_column], args.dataset)
157
+ return batch
158
+
159
+ # run inference on all examples
160
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
161
+
162
+ # compute and log_results
163
+ # do not change function below
164
+ log_results(result, args)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ parser = argparse.ArgumentParser()
169
+
170
+ parser.add_argument(
171
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
172
+ )
173
+ parser.add_argument(
174
+ "--dataset",
175
+ type=str,
176
+ required=True,
177
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
178
+ )
179
+ parser.add_argument(
180
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
181
+ )
182
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
183
+ parser.add_argument(
184
+ "--text_column", type=str, default="text", help="Column name containing the transcription."
185
+ )
186
+ parser.add_argument(
187
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
188
+ )
189
+ parser.add_argument(
190
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
191
+ )
192
+ parser.add_argument(
193
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
194
+ )
195
+ parser.add_argument(
196
+ "--device",
197
+ type=int,
198
+ default=None,
199
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
200
+ )
201
+ parser.add_argument(
202
+ "--use_lm", action="store_true", help="If defined, use included language model as the decoder."
203
+ )
204
+ args = parser.parse_args()
205
+
206
+ 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 CHANGED
@@ -4,6 +4,7 @@
4
  "feature_size": 1,
5
  "padding_side": "right",
6
  "padding_value": 0,
 
7
  "return_attention_mask": true,
8
  "sampling_rate": 16000
9
  }
 
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
  }
special_tokens_map.json CHANGED
@@ -1 +1,64 @@
1
- {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "[UNK]", "pad_token": "[PAD]", "additional_special_tokens": [{"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": true,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ {
11
+ "content": "</s>",
12
+ "lstrip": false,
13
+ "normalized": true,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ {
18
+ "content": "<s>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ {
25
+ "content": "</s>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ {
32
+ "content": "<s>",
33
+ "lstrip": false,
34
+ "normalized": true,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ {
39
+ "content": "</s>",
40
+ "lstrip": false,
41
+ "normalized": true,
42
+ "rstrip": false,
43
+ "single_word": false
44
+ },
45
+ {
46
+ "content": "<s>",
47
+ "lstrip": false,
48
+ "normalized": true,
49
+ "rstrip": false,
50
+ "single_word": false
51
+ },
52
+ {
53
+ "content": "</s>",
54
+ "lstrip": false,
55
+ "normalized": true,
56
+ "rstrip": false,
57
+ "single_word": false
58
+ }
59
+ ],
60
+ "bos_token": "<s>",
61
+ "eos_token": "</s>",
62
+ "pad_token": "[PAD]",
63
+ "unk_token": "[UNK]"
64
+ }
tokenizer_config.json CHANGED
@@ -1 +1,13 @@
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"}
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "do_lower_case": false,
4
+ "eos_token": "</s>",
5
+ "name_or_path": "./",
6
+ "pad_token": "[PAD]",
7
+ "processor_class": "Wav2Vec2ProcessorWithLM",
8
+ "replace_word_delimiter_char": " ",
9
+ "special_tokens_map_file": null,
10
+ "tokenizer_class": "Wav2Vec2CTCTokenizer",
11
+ "unk_token": "[UNK]",
12
+ "word_delimiter_token": "|"
13
+ }
vocab.json CHANGED
@@ -1 +1,41 @@
1
- {"(": 1, ")": 2, "0": 3, "3": 4, "7": 5, "8": 6, "9": 7, "a": 8, "b": 9, "c": 10, "d": 11, "e": 12, "f": 13, "g": 14, "h": 15, "i": 16, "j": 17, "k": 18, "l": 19, "m": 20, "n": 21, "o": 22, "p": 23, "q": 24, "r": 25, "s": 26, "t": 27, "u": 28, "v": 29, "w": 30, "x": 31, "y": 32, "z": 33, "å": 34, "æ": 35, "ø": 36, "|": 0, "[UNK]": 37, "[PAD]": 38}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "(": 1,
3
+ ")": 2,
4
+ "0": 3,
5
+ "3": 4,
6
+ "7": 5,
7
+ "8": 6,
8
+ "9": 7,
9
+ "[PAD]": 38,
10
+ "[UNK]": 37,
11
+ "a": 8,
12
+ "b": 9,
13
+ "c": 10,
14
+ "d": 11,
15
+ "e": 12,
16
+ "f": 13,
17
+ "g": 14,
18
+ "h": 15,
19
+ "i": 16,
20
+ "j": 17,
21
+ "k": 18,
22
+ "l": 19,
23
+ "m": 20,
24
+ "n": 21,
25
+ "o": 22,
26
+ "p": 23,
27
+ "q": 24,
28
+ "r": 25,
29
+ "s": 26,
30
+ "t": 27,
31
+ "u": 28,
32
+ "v": 29,
33
+ "w": 30,
34
+ "x": 31,
35
+ "y": 32,
36
+ "z": 33,
37
+ "|": 0,
38
+ "å": 34,
39
+ "æ": 35,
40
+ "ø": 36
41
+ }