Create eval.py
Browse files
eval.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
from datasets import load_dataset, load_metric, Audio, Dataset
|
3 |
+
from transformers import pipeline, AutoFeatureExtractor, AutoTokenizer, AutoConfig, AutoModelForCTC, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM
|
4 |
+
import re
|
5 |
+
import torch
|
6 |
+
import argparse
|
7 |
+
from typing import Dict
|
8 |
+
|
9 |
+
|
10 |
+
def log_results(result: Dataset, args: Dict[str, str]):
|
11 |
+
""" DO NOT CHANGE. This function computes and logs the result metrics. """
|
12 |
+
|
13 |
+
log_outputs = args.log_outputs
|
14 |
+
dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
|
15 |
+
|
16 |
+
# load metric
|
17 |
+
wer = load_metric("wer")
|
18 |
+
cer = load_metric("cer")
|
19 |
+
|
20 |
+
# compute metrics
|
21 |
+
wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
|
22 |
+
cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
|
23 |
+
|
24 |
+
# print & log results
|
25 |
+
result_str = (
|
26 |
+
f"WER: {wer_result}\n"
|
27 |
+
f"CER: {cer_result}"
|
28 |
+
)
|
29 |
+
print(result_str)
|
30 |
+
|
31 |
+
with open(f"{dataset_id}_eval_results.txt", "w") as f:
|
32 |
+
f.write(result_str)
|
33 |
+
|
34 |
+
# log all results in text file. Possibly interesting for analysis
|
35 |
+
if log_outputs is not None:
|
36 |
+
pred_file = f"log_{dataset_id}_predictions.txt"
|
37 |
+
target_file = f"log_{dataset_id}_targets.txt"
|
38 |
+
|
39 |
+
with open(pred_file, "w") as p, open(target_file, "w") as t:
|
40 |
+
|
41 |
+
# mapping function to write output
|
42 |
+
def write_to_file(batch, i):
|
43 |
+
p.write(f"{i}" + "\n")
|
44 |
+
p.write(batch["prediction"] + "\n")
|
45 |
+
t.write(f"{i}" + "\n")
|
46 |
+
t.write(batch["target"] + "\n")
|
47 |
+
|
48 |
+
result.map(write_to_file, with_indices=True)
|
49 |
+
|
50 |
+
|
51 |
+
def normalize_text(text: str, invalid_chars_regex: str, to_lower: bool) -> str:
|
52 |
+
# remove special characters
|
53 |
+
chars_to_ignore_regex = '[\µ\я\ひ\ⱎ\ⱅ\ḥ\ӌ\џ\ŵ\ʋ\λ\φ\χ\г\и\к\п\ц\ч\э\я\џ\ӌ\ቀ\ከ\ጀ\ḥ\牡\津\宇\厳\保\丹\三\む\も\ⱎ\ⱅ\⋅\⊨\↔\ℚ\э\п\к\и\г\|\£\§\·\½\º\ə\ơ\ǀ\ː\ʾ\ˢ\г\и\к\э\п\∨\„\,\?\.\!\—\―\–\;\:\"\‘\»\%\ł\_\€\×\ぬ\;\±\ß\Þ\«\Ø\°\…\”\“\`\ʿ\&\=\+\の\~\(\)\Σ\ı\ጠ\ℵ\馆\青\貴\西\美\甌\杜\术\星\文\扬\北\京\乃\ゔ\や\め\ま\へ\つ\た\う\い\☉\≥\®\/\∞\∆\∅\→\ℰ\ω\ψ\Μ\Θ\Κ\Π\Σ\Ω\α\γ\δ\ε\ζ\η\κ\ι\ν\μ\ρ\ς\σ\τ\υ\ℤ\ℝ\ℂ\ℕ\₽\∈\›\ο\‹\†\}\{\}\_\ደ\Δ\ወ\ي\و\ب\ة\د\ن\ن\ل\را\э\р\п\н\м\к\и\з\ψ\υ\θ\ṭ\ṯ\ḍ\*\^\∼\م\э\п\ǃ\$\Ꝑ]'
|
54 |
+
chars_to_replace_a = '[\ɑ\ạ\ả\ầ\ậ\ắ\ẵ\а\ǎ\ā\ă\ą\á\ã\ä\å]'
|
55 |
+
chars_to_replace_i = '[\ɨ\ị\ı\ī\ĩ\í\ì\і]'
|
56 |
+
chars_to_replace_e = '[\ệ\ễ\ề\ě\ę\ė\ē\е\ế]'
|
57 |
+
chars_to_replace_o = '[\ồ\ộ\ờ\ợ\ő\ö\ŏ\ō\ø\õ\ó\ò\ð\ǫ\ό\ớ\ổ\ố]'
|
58 |
+
chars_to_replace_u = '[\ų\ʉ\ủ\ử\ù\ü\ư\ǔ\ů\ū\ũ\ú\ứ\ụ\ű\ŭ]'
|
59 |
+
chars_to_replace_c = '[\ς\ć\ċ\č\ҫ]'
|
60 |
+
chars_to_replace_y = '[\ÿ\ỳ\ÿ\ý]'
|
61 |
+
chars_to_replace_n = '[\ṇ\ṅ\ǹ\ħ\ñ\ň\ņ\ń]'
|
62 |
+
chars_to_replace_t = '[\ṭ\ț\ť\ţ]'
|
63 |
+
chars_to_replace_s = '[\ṣ\ș\š\ş\ś]'
|
64 |
+
chars_to_replace_q = '[\զ\գ\գ\զ]'
|
65 |
+
chars_to_replace_j = '[\ј]'
|
66 |
+
chars_to_replace_z = '[\ž\ż\ź\ẓ]'
|
67 |
+
chars_to_replace_r = '[\ř]'
|
68 |
+
chars_to_replace_l = '[\ł\ļ\ĺ]'
|
69 |
+
chars_to_replace_k = '[\ķ]'
|
70 |
+
chars_to_replace_g = '[\ġ\ğ]'
|
71 |
+
chars_to_replace_d = '[\đ\ď]'
|
72 |
+
chars_to_replace_b = '[\þ]'
|
73 |
+
chars_to_replace_p = '[\р]'
|
74 |
+
chars_to_replace_apostrophe = '[\´\′\ʼ\’\'\'\ʽ\ʻ\ʾ]'
|
75 |
+
chars_to_replace_tirets = '[\─\−\‐]'
|
76 |
+
|
77 |
+
|
78 |
+
if to_lower:
|
79 |
+
text = re.sub(chars_to_ignore_regex, " ", text).lower()
|
80 |
+
text = re.sub(chars_to_replace_a, "a", text)
|
81 |
+
text = re.sub(chars_to_replace_i, "i", text)
|
82 |
+
text = re.sub(chars_to_replace_e, "e", text)
|
83 |
+
text = re.sub(chars_to_replace_o, "o", text)
|
84 |
+
text = re.sub(chars_to_replace_u, "u", text)
|
85 |
+
text = re.sub(chars_to_replace_c, "c", text)
|
86 |
+
text = re.sub(chars_to_replace_y, "y", text)
|
87 |
+
text = re.sub(chars_to_replace_n, "n", text)
|
88 |
+
text = re.sub(chars_to_replace_t, "t", text)
|
89 |
+
text = re.sub(chars_to_replace_s, "s", text)
|
90 |
+
text = re.sub(chars_to_replace_q, "q", text)
|
91 |
+
text = re.sub(chars_to_replace_j, "j", text)
|
92 |
+
text = re.sub(chars_to_replace_z, "z", text)
|
93 |
+
text = re.sub(chars_to_replace_r, "r", text)
|
94 |
+
text = re.sub(chars_to_replace_l, "l", text)
|
95 |
+
text = re.sub(chars_to_replace_k, "k", text)
|
96 |
+
text = re.sub(chars_to_replace_g, "g", text)
|
97 |
+
text = re.sub(chars_to_replace_d, "d", text)
|
98 |
+
text = re.sub(chars_to_replace_b, "b", text)
|
99 |
+
text = re.sub(chars_to_replace_q, "q", text)
|
100 |
+
text = re.sub(chars_to_replace_p, "p", text)
|
101 |
+
text = re.sub(chars_to_replace_apostrophe, "'", text)
|
102 |
+
text = re.sub(chars_to_replace_tirets, "-", text)
|
103 |
+
text = re.sub("β", "beta", text)
|
104 |
+
text = re.sub("æ", "ae", text)
|
105 |
+
text = re.sub("œ", "oe", text)
|
106 |
+
text = re.sub("&", "et", text)
|
107 |
+
text = re.sub("π", "pi", text)
|
108 |
+
text = re.sub("ľ", "l'", text)
|
109 |
+
text = re.sub(r"^\s+|\s+$", "", text)
|
110 |
+
text = re.sub(" +", " ", text)
|
111 |
+
text = re.sub("\n", " ", text)
|
112 |
+
return text
|
113 |
+
|
114 |
+
|
115 |
+
def main(args):
|
116 |
+
# load dataset
|
117 |
+
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
118 |
+
|
119 |
+
# for testing: only process the first two examples as a test
|
120 |
+
# dataset = dataset.select(range(10))
|
121 |
+
|
122 |
+
# load processor
|
123 |
+
if args.greedy:
|
124 |
+
processor = Wav2Vec2Processor.from_pretrained(args.model_id)
|
125 |
+
decoder = None
|
126 |
+
else:
|
127 |
+
processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
|
128 |
+
decoder = processor.decoder
|
129 |
+
|
130 |
+
# load processor
|
131 |
+
feature_extractor = processor.feature_extractor
|
132 |
+
tokenizer = processor.tokenizer
|
133 |
+
|
134 |
+
# resample audio
|
135 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
|
136 |
+
|
137 |
+
# load eval pipeline
|
138 |
+
if args.device is None:
|
139 |
+
args.device = 0 if torch.cuda.is_available() else -1
|
140 |
+
|
141 |
+
config = AutoConfig.from_pretrained(args.model_id)
|
142 |
+
model = AutoModelForCTC.from_pretrained(args.model_id)
|
143 |
+
|
144 |
+
#asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device, tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder)
|
145 |
+
asr = pipeline("automatic-speech-recognition", config=config, model=model, tokenizer=tokenizer,
|
146 |
+
feature_extractor=feature_extractor, decoder=decoder, device=args.device)
|
147 |
+
|
148 |
+
# build normalizer config
|
149 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_id)
|
150 |
+
tokens = [x for x in tokenizer.convert_ids_to_tokens(range(0, tokenizer.vocab_size))]
|
151 |
+
special_tokens = [
|
152 |
+
tokenizer.pad_token, tokenizer.word_delimiter_token,
|
153 |
+
tokenizer.unk_token, tokenizer.bos_token,
|
154 |
+
tokenizer.eos_token,
|
155 |
+
]
|
156 |
+
non_special_tokens = [x for x in tokens if x not in special_tokens]
|
157 |
+
invalid_chars_regex = f"[^\s{re.escape(''.join(set(non_special_tokens)))}]"
|
158 |
+
normalize_to_lower = False
|
159 |
+
for token in non_special_tokens:
|
160 |
+
if token.isalpha() and token.islower():
|
161 |
+
normalize_to_lower = True
|
162 |
+
break
|
163 |
+
|
164 |
+
# map function to decode audio
|
165 |
+
def map_to_pred(batch, args=args, asr=asr, invalid_chars_regex=invalid_chars_regex, normalize_to_lower=normalize_to_lower):
|
166 |
+
prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
|
167 |
+
|
168 |
+
batch["prediction"] = prediction["text"]
|
169 |
+
batch["target"] = normalize_text(batch["sentence"], invalid_chars_regex, normalize_to_lower)
|
170 |
+
return batch
|
171 |
+
|
172 |
+
# run inference on all examples
|
173 |
+
result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
|
174 |
+
|
175 |
+
# compute and log_results
|
176 |
+
# do not change function below
|
177 |
+
log_results(result, args)
|
178 |
+
|
179 |
+
|
180 |
+
if __name__ == "__main__":
|
181 |
+
parser = argparse.ArgumentParser()
|
182 |
+
|
183 |
+
parser.add_argument(
|
184 |
+
"--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
|
185 |
+
)
|
186 |
+
parser.add_argument(
|
187 |
+
"--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
|
188 |
+
)
|
189 |
+
parser.add_argument(
|
190 |
+
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
191 |
+
)
|
192 |
+
parser.add_argument(
|
193 |
+
"--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
|
194 |
+
)
|
195 |
+
parser.add_argument(
|
196 |
+
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to None. For long audio files a good value would be 5.0 seconds."
|
197 |
+
)
|
198 |
+
parser.add_argument(
|
199 |
+
"--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to None. For long audio files a good value would be 1.0 seconds."
|
200 |
+
)
|
201 |
+
parser.add_argument(
|
202 |
+
"--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
|
203 |
+
)
|
204 |
+
parser.add_argument(
|
205 |
+
"--greedy", action='store_true', help="If defined, the LM will be ignored during inference."
|
206 |
+
)
|
207 |
+
parser.add_argument(
|
208 |
+
"--device",
|
209 |
+
type=int,
|
210 |
+
default=None,
|
211 |
+
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
|
212 |
+
)
|
213 |
+
args = parser.parse_args()
|
214 |
+
|
215 |
+
main(args)
|