anuragshas commited on
Commit
fb5289d
1 Parent(s): d6a35fd

Create eval.py

Browse files
Files changed (1) hide show
  1. eval.py +158 -0
eval.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ text = text.replace("a", "а")
61
+ text = text.replace("e", "е")
62
+ text = text.replace("i", "і")
63
+ text = text.replace("o", "о")
64
+ text = text.replace("x", "х")
65
+
66
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
67
+ # note that order is important here!
68
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
69
+
70
+ for t in token_sequences_to_ignore:
71
+ text = " ".join(text.split(t))
72
+
73
+ return text
74
+
75
+
76
+ def main(args):
77
+ # load dataset
78
+ dataset = load_dataset(
79
+ args.dataset, args.config, split=args.split, use_auth_token=True
80
+ )
81
+
82
+ # for testing: only process the first two examples as a test
83
+ # dataset = dataset.select(range(10))
84
+
85
+ # load processor
86
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
87
+ sampling_rate = feature_extractor.sampling_rate
88
+
89
+ # resample audio
90
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
91
+
92
+ # load eval pipeline
93
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=0)
94
+
95
+ # map function to decode audio
96
+ def map_to_pred(batch):
97
+ prediction = asr(
98
+ batch["audio"]["array"],
99
+ chunk_length_s=args.chunk_length_s,
100
+ stride_length_s=args.stride_length_s,
101
+ )
102
+
103
+ batch["prediction"] = prediction["text"]
104
+ batch["target"] = normalize_text(batch["sentence"])
105
+ return batch
106
+
107
+ # run inference on all examples
108
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
109
+
110
+ # compute and log_results
111
+ # do not change function below
112
+ log_results(result, args)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ parser = argparse.ArgumentParser()
117
+
118
+ parser.add_argument(
119
+ "--model_id",
120
+ type=str,
121
+ required=True,
122
+ help="Model identifier. Should be loadable with 🤗 Transformers",
123
+ )
124
+ parser.add_argument(
125
+ "--dataset",
126
+ type=str,
127
+ required=True,
128
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
129
+ )
130
+ parser.add_argument(
131
+ "--config",
132
+ type=str,
133
+ required=True,
134
+ help="Config of the dataset. *E.g.* `'en'` for Common Voice",
135
+ )
136
+ parser.add_argument(
137
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
138
+ )
139
+ parser.add_argument(
140
+ "--chunk_length_s",
141
+ type=float,
142
+ default=None,
143
+ help="Chunk length in seconds. Defaults to 5 seconds.",
144
+ )
145
+ parser.add_argument(
146
+ "--stride_length_s",
147
+ type=float,
148
+ default=None,
149
+ help="Stride of the audio chunks. Defaults to 1 second.",
150
+ )
151
+ parser.add_argument(
152
+ "--log_outputs",
153
+ action="store_true",
154
+ help="If defined, write outputs to log file for analysis.",
155
+ )
156
+ args = parser.parse_args()
157
+
158
+ main(args)