RASMUS commited on
Commit
62b5c18
1 Parent(s): 853b18c

add evaluation notebook and scripts

Browse files
eval.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ from typing import Dict
5
+
6
+ from datasets import Audio, Dataset, load_dataset, load_metric
7
+
8
+ from transformers import AutoFeatureExtractor, pipeline
9
+
10
+
11
+ def log_results(result: Dataset, args: Dict[str, str]):
12
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
13
+
14
+ log_outputs = args.log_outputs
15
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
16
+
17
+ # load metric
18
+ wer = load_metric("wer")
19
+ cer = load_metric("cer")
20
+
21
+ # compute metrics
22
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
23
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
24
+
25
+ # print & log results
26
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
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_regex = [",", "?", "¿", ".", "!", "¡", ";", ";", ":", '""', "%", '"', "�", "ʿ", "·", "჻", "~", "՞",
53
+ "؟", "،", "।", "॥", "«", "»", "„", "“", "”", "「", "」", "‘", "’", "《", "》", "(", ")", "[", "]",
54
+ "{", "}", "=", "`", "_", "+", "<", ">", "…", "–", "°", "´", "ʾ", "‹", "›", "©", "®", "—", "→", "。",
55
+ "、", "﹂", "﹁", "‧", "~", "﹏", ",", "{", "}", "(", ")", "[", "]", "【", "】", "‥", "〽",
56
+ "『", "』", "〝", "〟", "⟨", "⟩", "〜", ":", "!", "?", "♪", "؛", "/", "\\", "º", "−", "^", "ʻ", "ˆ"] # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
57
+
58
+
59
+ chars_to_remove_regex = f"[{re.escape(''.join(chars_to_ignore_regex))}]"
60
+
61
+ text = text.lower()
62
+
63
+ # remove punctuation
64
+ text = re.sub(chars_to_remove_regex, '', text)
65
+
66
+ # Let's also make sure we split on all kinds of newlines, spaces, etc...
67
+ #text = " ".join(text.split())
68
+
69
+ return text
70
+
71
+
72
+ def main(args):
73
+ # load dataset
74
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
75
+
76
+ # for testing: only process the first two examples as a test
77
+ #dataset = dataset.select(range(10))
78
+ #print(dataset)
79
+
80
+ # load processor
81
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
82
+ sampling_rate = feature_extractor.sampling_rate
83
+ print(sampling_rate)
84
+
85
+ # resample audio
86
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
87
+
88
+ # load eval pipeline
89
+ asr = pipeline("automatic-speech-recognition", model=args.model_id)
90
+
91
+ # map function to decode audio
92
+ def map_to_pred(batch):
93
+ prediction = asr(
94
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
95
+ )
96
+
97
+ batch["prediction"] = prediction["text"]
98
+ batch["target"] = normalize_text(batch["sentence"])
99
+ return batch
100
+
101
+ # run inference on all examples
102
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
103
+
104
+ # compute and log_results
105
+ # do not change function below
106
+ log_results(result, args)
107
+
108
+
109
+ if __name__ == "__main__":
110
+ parser = argparse.ArgumentParser()
111
+
112
+ parser.add_argument(
113
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
114
+ )
115
+ parser.add_argument(
116
+ "--dataset",
117
+ type=str,
118
+ required=True,
119
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
120
+ )
121
+ parser.add_argument(
122
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
123
+ )
124
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
125
+ parser.add_argument(
126
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
127
+ )
128
+ parser.add_argument(
129
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
130
+ )
131
+ parser.add_argument(
132
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
133
+ )
134
+ args = parser.parse_args()
135
+
136
+ main(args)
run_eval.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ python eval.py --dataset mozilla-foundation/common_voice_7_0 --config fi --model_id RASMUS/wav2vec2-xlsr-fi-lm-1B --split test
run_evaluations_on_common_voice_test_7_0.ipynb ADDED
The diff for this file is too large to render. See raw diff