anuragshas commited on
Commit
3288d21
1 Parent(s): ccf7b8b

Create eval.py

Browse files
Files changed (1) hide show
  1. eval.py +153 -0
eval.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import re
4
+ import unicodedata
5
+ from typing import Dict
6
+
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
+ text = unicodedata.normalize("NFKC", text)
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
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=0)
89
+
90
+ # map function to decode audio
91
+ def map_to_pred(batch):
92
+ prediction = asr(
93
+ batch["audio"]["array"],
94
+ chunk_length_s=args.chunk_length_s,
95
+ stride_length_s=args.stride_length_s,
96
+ )
97
+
98
+ batch["prediction"] = prediction["text"]
99
+ batch["target"] = normalize_text(batch["sentence"])
100
+ return batch
101
+
102
+ # run inference on all examples
103
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
104
+
105
+ # compute and log_results
106
+ # do not change function below
107
+ log_results(result, args)
108
+
109
+
110
+ if __name__ == "__main__":
111
+ parser = argparse.ArgumentParser()
112
+
113
+ parser.add_argument(
114
+ "--model_id",
115
+ type=str,
116
+ required=True,
117
+ help="Model identifier. Should be loadable with 🤗 Transformers",
118
+ )
119
+ parser.add_argument(
120
+ "--dataset",
121
+ type=str,
122
+ required=True,
123
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
124
+ )
125
+ parser.add_argument(
126
+ "--config",
127
+ type=str,
128
+ required=True,
129
+ help="Config of the dataset. *E.g.* `'en'` for Common Voice",
130
+ )
131
+ parser.add_argument(
132
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
133
+ )
134
+ parser.add_argument(
135
+ "--chunk_length_s",
136
+ type=float,
137
+ default=None,
138
+ help="Chunk length in seconds. Defaults to 5 seconds.",
139
+ )
140
+ parser.add_argument(
141
+ "--stride_length_s",
142
+ type=float,
143
+ default=None,
144
+ help="Stride of the audio chunks. Defaults to 1 second.",
145
+ )
146
+ parser.add_argument(
147
+ "--log_outputs",
148
+ action="store_true",
149
+ help="If defined, write outputs to log file for analysis.",
150
+ )
151
+ args = parser.parse_args()
152
+
153
+ main(args)