sammy786 commited on
Commit
ceb329d
1 Parent(s): 15ec860

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +125 -0
eval.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ pred_string = [element.lower() for element in result["prediction"]]
20
+ actual = [element.lower() for element in result["target"]]
21
+
22
+ # compute metrics
23
+ wer_result = wer.compute(references=actual, predictions=pred_string)
24
+ cer_result = cer.compute(references=actual, predictions=pred_string)
25
+
26
+ # print & log results
27
+ result_str = (
28
+ f"WER: {wer_result}\n"
29
+ f"CER: {cer_result}"
30
+ )
31
+ print(result_str)
32
+
33
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
34
+ f.write(result_str)
35
+
36
+ # log all results in text file. Possibly interesting for analysis
37
+ if log_outputs is not None:
38
+ pred_file = f"log_{dataset_id}_predictions.txt"
39
+ target_file = f"log_{dataset_id}_targets.txt"
40
+
41
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
42
+
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) -> str:
54
+ """ DO ADAPT FOR YOUR USE CASE. this function normalizes the target text. """
55
+
56
+ chars_to_ignore_regex = '[\,\.\!\-\;\:\"\“\%\”\�\'\...\…\–\é]'
57
+
58
+ text = re.sub(chars_to_ignore_regex, "", text).lower().strip()
59
+ text = re.sub(r"([b-df-hj-np-tv-z])' ([aeiou])", r"\1'\2", text)
60
+ text = re.sub(r"(-| '|' | +)", " ", text)
61
+
62
+ return text
63
+
64
+
65
+ def main(args):
66
+ # load dataset
67
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
68
+
69
+ # for testing: only process the first two examples as a test
70
+ # dataset = dataset.select(range(10))
71
+
72
+ # load processor
73
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
74
+ sampling_rate = feature_extractor.sampling_rate
75
+
76
+ # resample audio
77
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
78
+
79
+ # load eval pipeline
80
+ asr = pipeline("automatic-speech-recognition", model=args.model_id)
81
+
82
+ # map function to decode audio
83
+ def map_to_pred(batch):
84
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
85
+
86
+ batch["prediction"] = prediction["text"]
87
+ batch["target"] = normalize_text(batch["sentence"])
88
+ return batch
89
+
90
+ # run inference on all examples
91
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
92
+
93
+ # compute and log_results
94
+ # do not change function below
95
+ log_results(result, args)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ parser = argparse.ArgumentParser()
100
+
101
+ parser.add_argument(
102
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
103
+ )
104
+ parser.add_argument(
105
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
106
+ )
107
+ parser.add_argument(
108
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
109
+ )
110
+ parser.add_argument(
111
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
112
+ )
113
+ parser.add_argument(
114
+ "--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."
115
+ )
116
+ parser.add_argument(
117
+ "--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."
118
+ )
119
+ parser.add_argument(
120
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
121
+ )
122
+ args = parser.parse_args()
123
+
124
+ main(args)
125
+