Akashpb13 commited on
Commit
7c6d868
1 Parent(s): a6f874f

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +129 -0
eval.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset, load_metric, Audio, Dataset
2
+ from transformers import pipeline, AutoFeatureExtractor
3
+ import re
4
+ import argparse
5
+ import unicodedata
6
+ from typing import Dict
7
+
8
+
9
+ def log_results(result: Dataset, args: Dict[str, str]):
10
+ """ DO NOT CHANGE. This function computes and logs the result metrics. """
11
+
12
+ log_outputs = args.log_outputs
13
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
14
+
15
+ # load metric
16
+ wer = load_metric("wer")
17
+ cer = load_metric("cer")
18
+
19
+ # compute metrics
20
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
21
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
22
+
23
+ # print & log results
24
+ result_str = (
25
+ f"WER: {wer_result}\n"
26
+ f"CER: {cer_result}"
27
+ )
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
+
40
+ # mapping function to write output
41
+ def write_to_file(batch, i):
42
+ p.write(f"{i}" + "\n")
43
+ p.write(batch["prediction"] + "\n")
44
+ t.write(f"{i}" + "\n")
45
+ t.write(batch["target"] + "\n")
46
+
47
+ result.map(write_to_file, with_indices=True)
48
+
49
+
50
+ def normalize_text(text: str) -> str:
51
+ """ DO ADAPT FOR YOUR USE CASE. this function normalizes the target text. """
52
+
53
+ CHARS_TO_IGNORE = [",", "?", "¿", ".", "!", "¡", ";", ";", ":", '""', "%", '"', "�", "ʿ", "·", "჻", "~", "՞",
54
+ "؟", "،", "।", "॥", "«", "»", "„", "“", "”", "「", "」", "‘", "’", "《", "》", "(", ")", "[", "]",
55
+ "{", "}", "=", "`", "_", "+", "<", ">", "…", "–", "°", "´", "ʾ", "‹", "›", "©", "®", "—", "→", "。",
56
+ "、", "﹂", "﹁", "‧", "~", "﹏", ",", "{", "}", "(", ")", "[", "]", "【", "】", "‥", "〽",
57
+ "『", "』", "〝", "〟", "⟨", "⟩", "〜", ":", "!", "?", "♪", "؛", "/", "\\",]
58
+ chars_to_ignore_regex = f"[{re.escape(''.join(CHARS_TO_IGNORE))}]"
59
+
60
+ text = text.lower()
61
+
62
+ text = re.sub(chars_to_ignore_regex, "", text)
63
+
64
+ text = " ".join(text.split())
65
+
66
+ return text
67
+
68
+
69
+ def main(args):
70
+ # load dataset
71
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
72
+
73
+ # for testing: only process the first two examples as a test
74
+ # dataset = dataset.select(range(10))
75
+
76
+ # load processor
77
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
78
+ sampling_rate = feature_extractor.sampling_rate
79
+
80
+ # resample audio
81
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
82
+
83
+ # load eval pipeline
84
+ asr = pipeline("automatic-speech-recognition", model=args.model_id)
85
+
86
+ # map function to decode audio
87
+ def map_to_pred(batch):
88
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
89
+
90
+ batch["prediction"] = prediction["text"]
91
+ batch["target"] = normalize_text(batch["sentence"])
92
+ return batch
93
+
94
+ # run inference on all examples
95
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
96
+
97
+ # compute and log_results
98
+ # do not change function below
99
+ log_results(result, args)
100
+
101
+
102
+ if __name__ == "__main__":
103
+ parser = argparse.ArgumentParser()
104
+
105
+ parser.add_argument(
106
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
107
+ )
108
+ parser.add_argument(
109
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
110
+ )
111
+ parser.add_argument(
112
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
113
+ )
114
+ parser.add_argument(
115
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
116
+ )
117
+ parser.add_argument(
118
+ "--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."
119
+ )
120
+ parser.add_argument(
121
+ "--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."
122
+ )
123
+ parser.add_argument(
124
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
125
+ )
126
+ args = parser.parse_args()
127
+
128
+ main(args)
129
+