ayameRushia
commited on
Commit
•
1e97e95
1
Parent(s):
9ae1879
Upload eval.py
Browse files
eval.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datasets import load_dataset, load_metric, Audio, Dataset
|
2 |
+
from transformers import pipeline, AutoFeatureExtractor, AutoTokenizer, AutoConfig, AutoModelForCTC, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM
|
3 |
+
import re
|
4 |
+
import torch
|
5 |
+
import argparse
|
6 |
+
from typing import Dict
|
7 |
+
|
8 |
+
def log_results(result: Dataset, args: Dict[str, str]):
|
9 |
+
""" DO NOT CHANGE. This function computes and logs the result metrics. """
|
10 |
+
|
11 |
+
log_outputs = args.log_outputs
|
12 |
+
dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
|
13 |
+
|
14 |
+
# load metric
|
15 |
+
wer = load_metric("wer")
|
16 |
+
cer = load_metric("cer")
|
17 |
+
|
18 |
+
# compute metrics
|
19 |
+
wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
|
20 |
+
cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
|
21 |
+
|
22 |
+
# print & log results
|
23 |
+
result_str = (
|
24 |
+
f"WER: {wer_result}\n"
|
25 |
+
f"CER: {cer_result}"
|
26 |
+
)
|
27 |
+
print(result_str)
|
28 |
+
|
29 |
+
with open(f"{dataset_id}_eval_results.txt", "w") as f:
|
30 |
+
f.write(result_str)
|
31 |
+
|
32 |
+
# log all results in text file. Possibly interesting for analysis
|
33 |
+
if log_outputs is not None:
|
34 |
+
pred_file = f"log_{dataset_id}_predictions.txt"
|
35 |
+
target_file = f"log_{dataset_id}_targets.txt"
|
36 |
+
|
37 |
+
with open(pred_file, "w") as p, open(target_file, "w") as t:
|
38 |
+
|
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) -> str:
|
50 |
+
"""DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
|
51 |
+
|
52 |
+
CHARS_TO_IGNORE = [",", "?", "¿", ".", "!", "¡", ";", ";", ":", '""', "%", '"', "�", "ʿ", "·", "჻", "~", "՞",
|
53 |
+
"؟", "،", "।", "॥", "«", "»", "„", "“", "”", "「", "」", "‘", "’", "《", "》", "(", ")", "[", "]",
|
54 |
+
"{", "}", "=", "`", "_", "+", "<", ">", "…", "–", "°", "´", "ʾ", "‹", "›", "©", "®", "—", "→", "。",
|
55 |
+
"、", "﹂", "﹁", "‧", "~", "﹏", ",", "{", "}", "(", ")", "[", "]", "【", "】", "‥", "〽",
|
56 |
+
"『", "』", "〝", "〟", "⟨", "⟩", "〜", ":", "!", "?", "♪", "؛", "/", "\\", "º", "−", "^", "ʻ", "ˆ"]
|
57 |
+
chars_to_ignore_regex = f"[{re.escape(''.join(CHARS_TO_IGNORE))}]"
|
58 |
+
|
59 |
+
text = re.sub(chars_to_ignore_regex, "", text.lower())
|
60 |
+
|
61 |
+
# In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
62 |
+
# note that order is important here!
|
63 |
+
token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
|
64 |
+
|
65 |
+
for t in token_sequences_to_ignore:
|
66 |
+
text = " ".join(text.split(t))
|
67 |
+
|
68 |
+
return text
|
69 |
+
|
70 |
+
|
71 |
+
def main(args):
|
72 |
+
# load dataset
|
73 |
+
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
74 |
+
|
75 |
+
# for testing: only process the first two examples as a test
|
76 |
+
# dataset = dataset.select(range(10))
|
77 |
+
|
78 |
+
# load processor
|
79 |
+
if args.greedy:
|
80 |
+
processor = Wav2Vec2Processor.from_pretrained(args.model_id)
|
81 |
+
decoder = None
|
82 |
+
else:
|
83 |
+
processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
|
84 |
+
decoder = processor.decoder
|
85 |
+
|
86 |
+
feature_extractor = processor.feature_extractor
|
87 |
+
tokenizer = processor.tokenizer
|
88 |
+
|
89 |
+
# resample audio
|
90 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
|
91 |
+
|
92 |
+
# load eval pipeline
|
93 |
+
if args.device is None:
|
94 |
+
args.device = 0 if torch.cuda.is_available() else -1
|
95 |
+
|
96 |
+
config = AutoConfig.from_pretrained(args.model_id)
|
97 |
+
model = AutoModelForCTC.from_pretrained(args.model_id)
|
98 |
+
|
99 |
+
#asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
|
100 |
+
asr = pipeline("automatic-speech-recognition", config=config, model=model, tokenizer=tokenizer,
|
101 |
+
feature_extractor=feature_extractor, decoder=decoder, device=args.device)
|
102 |
+
|
103 |
+
|
104 |
+
# map function to decode audio
|
105 |
+
def map_to_pred(batch, args=args, asr=asr):
|
106 |
+
prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
|
107 |
+
|
108 |
+
batch["prediction"] = prediction["text"]
|
109 |
+
batch["target"] = normalize_text(batch["sentence"])
|
110 |
+
return batch
|
111 |
+
|
112 |
+
# run inference on all examples
|
113 |
+
result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
|
114 |
+
|
115 |
+
# filtering out empty targets
|
116 |
+
result = result.filter(lambda example: example["target"] != "")
|
117 |
+
|
118 |
+
# compute and log_results
|
119 |
+
# do not change function below
|
120 |
+
log_results(result, args)
|
121 |
+
|
122 |
+
|
123 |
+
if __name__ == "__main__":
|
124 |
+
parser = argparse.ArgumentParser()
|
125 |
+
|
126 |
+
parser.add_argument(
|
127 |
+
"--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
|
128 |
+
)
|
129 |
+
parser.add_argument(
|
130 |
+
"--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
|
131 |
+
)
|
132 |
+
parser.add_argument(
|
133 |
+
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
134 |
+
)
|
135 |
+
parser.add_argument(
|
136 |
+
"--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
|
137 |
+
)
|
138 |
+
parser.add_argument(
|
139 |
+
"--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."
|
140 |
+
)
|
141 |
+
parser.add_argument(
|
142 |
+
"--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."
|
143 |
+
)
|
144 |
+
parser.add_argument(
|
145 |
+
"--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
|
146 |
+
)
|
147 |
+
parser.add_argument(
|
148 |
+
"--greedy", action='store_true', help="If defined, the LM will be ignored during inference."
|
149 |
+
)
|
150 |
+
parser.add_argument(
|
151 |
+
"--device",
|
152 |
+
type=int,
|
153 |
+
default=None,
|
154 |
+
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
|
155 |
+
)
|
156 |
+
args = parser.parse_args()
|
157 |
+
|
158 |
+
main(args)
|