versae commited on
Commit
344dea8
1 Parent(s): a47f33f

Add 5gram languge model

Browse files
.gitattributes CHANGED
@@ -38,3 +38,4 @@ 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
 
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())
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}
eval.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ from transformers import AutoFeatureExtractor, AutoModelForCTC, pipeline, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM, Wav2Vec2FeatureExtractor
10
+ # from pyctcdecode import BeamSearchDecoderCTC
11
+
12
+
13
+ def log_results(result: Dataset, args: Dict[str, str]):
14
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
15
+
16
+ log_outputs = args.log_outputs
17
+ lm = "withLM" if args.use_lm else "noLM"
18
+ model_id = args.model_id.replace("/", "_").replace(".", "")
19
+ dataset_id = "_".join([model_id] + args.dataset.split("/") + [args.config, args.split, lm])
20
+
21
+ # load metric
22
+ wer = load_metric("wer")
23
+ cer = load_metric("cer")
24
+
25
+ # compute metrics
26
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
27
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
28
+
29
+ # print & log results
30
+ result_str = f"{dataset_id}\nWER: {wer_result}\nCER: {cer_result}"
31
+ print(result_str)
32
+
33
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
34
+ f.write(result_str)
35
+
36
+ # log all results in text file. Possibly interesting for analysis
37
+ if log_outputs is not None:
38
+ pred_file = f"log_{dataset_id}_predictions.txt"
39
+ target_file = f"log_{dataset_id}_targets.txt"
40
+
41
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
42
+ # mapping function to write output
43
+ def write_to_file(batch, i):
44
+ p.write(f"{i}" + "\n")
45
+ p.write(batch["prediction"] + "\n")
46
+ t.write(f"{i}" + "\n")
47
+ t.write(batch["target"] + "\n")
48
+
49
+ result.map(write_to_file, with_indices=True)
50
+
51
+
52
+ def normalize_text(text: str, dataset: str) -> str:
53
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
54
+
55
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
56
+ text = re.sub(chars_to_ignore_regex, "", text.lower()) + " "
57
+
58
+ if dataset.lower().endswith("nst"):
59
+ text = text.lower()
60
+ text = text.replace("(...Vær stille under dette opptaket...)", "")
61
+ text = re.sub('[áàâ]', 'a', text)
62
+ text = re.sub('[ä]', 'æ', text)
63
+ text = re.sub('[éèëê]', 'e', text)
64
+ text = re.sub('[íìïî]', 'i', text)
65
+ text = re.sub('[óòöô]', 'o', text)
66
+ text = re.sub('[ö]', 'ø', text)
67
+ text = re.sub('[ç]', 'c', text)
68
+ text = re.sub('[úùüû]', 'u', text)
69
+ # text = re.sub('\\(?=(Punktum|Komma|Utropstegn|Spørsmålstegn))', ' ', text)
70
+ text = re.sub('\s+', ' ', text)
71
+ elif dataset.lower().endswith("npsc"):
72
+ text = re.sub('[áàâ]', 'a', text)
73
+ text = re.sub('[ä]', 'æ', text)
74
+ text = re.sub('[éèëê]', 'e', text)
75
+ text = re.sub('[íìïî]', 'i', text)
76
+ text = re.sub('[óòöô]', 'o', text)
77
+ text = re.sub('[ö]', 'ø', text)
78
+ text = re.sub('[ç]', 'c', text)
79
+ text = re.sub('[úùüû]', 'u', text)
80
+ text = re.sub('\s', ' ', text)
81
+ text = re.sub("<ee(eh)?>", "e", text)
82
+ text = re.sub("<mmm?>", "m", text)
83
+ text = re.sub("<qq>", "q", text)
84
+ text = re.sub("<inaudible>", "i", text)
85
+
86
+ # # In addition, we can normalize the target text, e.g. removing new lines characters etc...
87
+ # # note that order is important here!
88
+ # token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
89
+
90
+ # for t in token_sequences_to_ignore:
91
+ # text = " ".join(text.split(t))
92
+
93
+ return text
94
+
95
+
96
+ def main(args):
97
+ # load dataset
98
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
99
+
100
+ # for testing: only process the first two examples as a test
101
+ # dataset = dataset.select(range(10))
102
+
103
+ # load processor
104
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
105
+ sampling_rate = feature_extractor.sampling_rate
106
+
107
+ # resample audio
108
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
109
+
110
+ # load eval pipeline
111
+ if args.device is None:
112
+ args.device = 0 if torch.cuda.is_available() else -1
113
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
114
+
115
+ model_instance = AutoModelForCTC.from_pretrained(args.model_id)
116
+ if args.use_lm:
117
+ processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
118
+ decoder = processor.decoder
119
+ else:
120
+ processor = Wav2Vec2Processor.from_pretrained(args.model_id)
121
+ decoder = None
122
+ asr = pipeline(
123
+ "automatic-speech-recognition",
124
+ model=model_instance,
125
+ tokenizer=processor.tokenizer,
126
+ feature_extractor=processor.feature_extractor,
127
+ decoder=decoder,
128
+ device=args.device
129
+ )
130
+
131
+ # feature_extractor_dict, _ = Wav2Vec2FeatureExtractor.get_feature_extractor_dict(args.model_id)
132
+ # feature_extractor_dict["processor_class"] = "Wav2Vec2Processor" if not args.use_lm else "Wav2Vec2ProcessorWithLM"
133
+ # feature_extractor = Wav2Vec2FeatureExtractor.from_dict(feature_extractor_dict)
134
+
135
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id, feature_extractor=feature_extractor, device=args.device, decoder=BeamSearchDecoderCTC.load_from_dir("./"))
136
+
137
+ # map function to decode audio
138
+ def map_to_pred(batch):
139
+ prediction = asr(
140
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
141
+ )
142
+
143
+ batch["prediction"] = prediction["text"]
144
+ batch["target"] = normalize_text(batch["text"], args.dataset)
145
+ return batch
146
+
147
+ # run inference on all examples
148
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
149
+
150
+ # compute and log_results
151
+ # do not change function below
152
+ log_results(result, args)
153
+
154
+
155
+ if __name__ == "__main__":
156
+ parser = argparse.ArgumentParser()
157
+
158
+ parser.add_argument(
159
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
160
+ )
161
+ parser.add_argument(
162
+ "--dataset",
163
+ type=str,
164
+ required=True,
165
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
166
+ )
167
+ parser.add_argument(
168
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
169
+ )
170
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
171
+ parser.add_argument(
172
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
173
+ )
174
+ parser.add_argument(
175
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
176
+ )
177
+ parser.add_argument(
178
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
179
+ )
180
+ parser.add_argument(
181
+ "--device",
182
+ type=int,
183
+ default=None,
184
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
185
+ )
186
+ parser.add_argument(
187
+ "--use_lm", action="store_true", help="If defined, use included language model as the decoder."
188
+ )
189
+ args = parser.parse_args()
190
+
191
+ 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 @@
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}]}
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 CHANGED
@@ -1 +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"}
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"}