Adding eval script
Browse files
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(eh)?>", "e", text)
|
94 |
+
text = re.sub("<mmm?>", "m", text)
|
95 |
+
text = re.sub("<qq>", "q", text)
|
96 |
+
text = re.sub("<inaudible>", "i", 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[args.text_column]
|
156 |
+
batch["target"] = normalize_text(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)
|