w11wo commited on
Commit
af060e3
β€’
1 Parent(s): f6c67b2

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +169 -0
eval.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ from typing import Dict
5
+
6
+ import torch
7
+ from datasets import Audio, Dataset, load_dataset, load_metric
8
+
9
+ from transformers import AutoFeatureExtractor, pipeline
10
+
11
+
12
+ def log_results(result: Dataset, args: Dict[str, str]):
13
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
14
+
15
+ log_outputs = args.log_outputs
16
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
17
+
18
+ # load metric
19
+ wer = load_metric("wer")
20
+ cer = load_metric("cer")
21
+
22
+ # compute metrics
23
+ wer_result = wer.compute(
24
+ references=result["target"], predictions=result["prediction"]
25
+ )
26
+ cer_result = cer.compute(
27
+ references=result["target"], predictions=result["prediction"]
28
+ )
29
+
30
+ # print & log results
31
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
32
+ print(result_str)
33
+
34
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
35
+ f.write(result_str)
36
+
37
+ # log all results in text file. Possibly interesting for analysis
38
+ if log_outputs is not None:
39
+ pred_file = f"log_{dataset_id}_predictions.txt"
40
+ target_file = f"log_{dataset_id}_targets.txt"
41
+
42
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
43
+
44
+ # mapping function to write output
45
+ def write_to_file(batch, i):
46
+ p.write(f"{i}" + "\n")
47
+ p.write(batch["prediction"] + "\n")
48
+ t.write(f"{i}" + "\n")
49
+ t.write(batch["target"] + "\n")
50
+
51
+ result.map(write_to_file, with_indices=True)
52
+
53
+
54
+ def normalize_text(text: str) -> str:
55
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
56
+
57
+ chars_to_ignore_regex = '[,?.!\-\;\:"β€œ%β€˜β€οΏ½β€”β€™β€¦β€“]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
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(
74
+ args.dataset, args.config, split=args.split, use_auth_token=True
75
+ )
76
+
77
+ # for testing: only process the first two examples as a test
78
+ # dataset = dataset.select(range(10))
79
+
80
+ # load processor
81
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
82
+ sampling_rate = feature_extractor.sampling_rate
83
+
84
+ # resample audio
85
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
86
+
87
+ # load eval pipeline
88
+ if args.device is None:
89
+ args.device = 0 if torch.cuda.is_available() else -1
90
+ asr = pipeline(
91
+ "automatic-speech-recognition", model=args.model_id, device=args.device
92
+ )
93
+
94
+ # map function to decode audio
95
+ def map_to_pred(batch):
96
+ prediction = asr(
97
+ batch["audio"]["array"],
98
+ chunk_length_s=args.chunk_length_s,
99
+ stride_length_s=args.stride_length_s,
100
+ )
101
+
102
+ batch["prediction"] = prediction["text"]
103
+ batch["target"] = normalize_text(batch[args.text_column_name])
104
+ return batch
105
+
106
+ # run inference on all examples
107
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
108
+
109
+ # compute and log_results
110
+ # do not change function below
111
+ log_results(result, args)
112
+
113
+
114
+ if __name__ == "__main__":
115
+ parser = argparse.ArgumentParser()
116
+
117
+ parser.add_argument(
118
+ "--model_id",
119
+ type=str,
120
+ required=True,
121
+ help="Model identifier. Should be loadable with πŸ€— Transformers",
122
+ )
123
+ parser.add_argument(
124
+ "--dataset",
125
+ type=str,
126
+ required=True,
127
+ help="Dataset name to evaluate the `model_id`. Should be loadable with πŸ€— Datasets",
128
+ )
129
+ parser.add_argument(
130
+ "--config",
131
+ type=str,
132
+ required=True,
133
+ 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
+ "--text_column_name",
140
+ type=str,
141
+ default="text",
142
+ help="The name of the dataset column containing the text data. Defaults to 'text'",
143
+ )
144
+ parser.add_argument(
145
+ "--chunk_length_s",
146
+ type=float,
147
+ default=None,
148
+ help="Chunk length in seconds. Defaults to 5 seconds.",
149
+ )
150
+ parser.add_argument(
151
+ "--stride_length_s",
152
+ type=float,
153
+ default=None,
154
+ help="Stride of the audio chunks. Defaults to 1 second.",
155
+ )
156
+ parser.add_argument(
157
+ "--log_outputs",
158
+ action="store_true",
159
+ help="If defined, write outputs to log file for analysis.",
160
+ )
161
+ parser.add_argument(
162
+ "--device",
163
+ type=int,
164
+ default=None,
165
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
166
+ )
167
+ args = parser.parse_args()
168
+
169
+ main(args)