Rolv-Arild commited on
Commit
22fa673
1 Parent(s): 080c1e8

Adding KenLM and eval scripts

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