manifoldix commited on
Commit
26b3728
1 Parent(s): 9542577

eval script with normalization

Browse files
Files changed (1) hide show
  1. eval.py +195 -0
eval.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import re
12
+ from num2words import num2words
13
+
14
+
15
+ def log_results(result: Dataset, args: Dict[str, str]):
16
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
17
+
18
+ log_outputs = args.log_outputs
19
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
20
+
21
+ # load metric
22
+ wer = load_metric("wer")
23
+ cer = load_metric("cer")
24
+
25
+ # compute metrics
26
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
27
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
28
+
29
+ # print & log results
30
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
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 spell_num(text):
54
+ l = []
55
+ for t in text.split():
56
+ if t.isdigit():
57
+ l.append(num2words(t, lang='de'))
58
+ else:
59
+ l.append(t)
60
+
61
+ return ' '.join(l)
62
+
63
+ ALLOWED_CHARS = {
64
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
65
+ 'ä', 'ö', 'ü',
66
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
67
+ ' ',
68
+ ',', ';', ':', '.', '?', '!',
69
+ }
70
+ WHITESPACE_REGEX = re.compile(r'[ \t]+')
71
+
72
+
73
+ def preprocess_transcript_for_corpus(transcript):
74
+ transcript = transcript.lower()
75
+ transcript = transcript.replace('á', 'a')
76
+ transcript = transcript.replace('à', 'a')
77
+ transcript = transcript.replace('â', 'a')
78
+ transcript = transcript.replace('ç', 'c')
79
+ transcript = transcript.replace('é', 'e')
80
+ transcript = transcript.replace('è', 'e')
81
+ transcript = transcript.replace('ê', 'e')
82
+ transcript = transcript.replace('í', 'i')
83
+ transcript = transcript.replace('ì', 'i')
84
+ transcript = transcript.replace('î', 'i')
85
+ transcript = transcript.replace('ñ', 'n')
86
+ transcript = transcript.replace('ó', 'o')
87
+ transcript = transcript.replace('ò', 'o')
88
+ transcript = transcript.replace('ô', 'o')
89
+ transcript = transcript.replace('ú', 'u')
90
+ transcript = transcript.replace('ù', 'u')
91
+ transcript = transcript.replace('û', 'u')
92
+ transcript = transcript.replace('ș', 's')
93
+ transcript = transcript.replace('ş', 's')
94
+ transcript = transcript.replace('ß', 'ss')
95
+ transcript = transcript.replace('-', ' ')
96
+ # Not used consistently, better to replace with space as well
97
+ transcript = transcript.replace('–', ' ')
98
+ transcript = transcript.replace('/', ' ')
99
+ transcript = WHITESPACE_REGEX.sub(' ', transcript)
100
+ transcript = ''.join([char for char in transcript if char in ALLOWED_CHARS])
101
+ transcript = WHITESPACE_REGEX.sub(' ', transcript)
102
+ transcript = spell_num(transcript)
103
+ transcript = transcript.replace('ß', 'ss')
104
+ transcript = transcript.strip()
105
+
106
+ return transcript
107
+
108
+ def normalize_text(text: str) -> str:
109
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
110
+
111
+ text = preprocess_transcript_for_corpus(txt)
112
+ chars_to_ignore_regex = '[,?.!\-\;\:"“%‘”�—’…–]'
113
+ text = re.sub(chars_to_ignore_regex, "", text.lower())
114
+
115
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
116
+ # note that order is important here!
117
+ #token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
118
+
119
+ #for t in token_sequences_to_ignore:
120
+ # text = " ".join(text.split(t))
121
+
122
+ return text.strip()
123
+
124
+
125
+ def main(args):
126
+ # load dataset
127
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
128
+
129
+ # for testing: only process the first two examples as a test
130
+ # dataset = dataset.select(range(10))
131
+
132
+ # load processor
133
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
134
+ sampling_rate = feature_extractor.sampling_rate
135
+
136
+ # resample audio
137
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
138
+
139
+ # load eval pipeline
140
+ if args.device is None:
141
+ args.device = 0 if torch.cuda.is_available() else -1
142
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
143
+
144
+ # map function to decode audio
145
+ def map_to_pred(batch):
146
+ prediction = asr(
147
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
148
+ )
149
+
150
+ batch["prediction"] = prediction["text"]
151
+ batch["target"] = normalize_text(batch["sentence"])
152
+ return batch
153
+
154
+ # run inference on all examples
155
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
156
+
157
+ # compute and log_results
158
+ # do not change function below
159
+ log_results(result, args)
160
+
161
+
162
+ if __name__ == "__main__":
163
+ parser = argparse.ArgumentParser()
164
+
165
+ parser.add_argument(
166
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
167
+ )
168
+ parser.add_argument(
169
+ "--dataset",
170
+ type=str,
171
+ required=True,
172
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
173
+ )
174
+ parser.add_argument(
175
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
176
+ )
177
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
178
+ parser.add_argument(
179
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
180
+ )
181
+ parser.add_argument(
182
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
183
+ )
184
+ parser.add_argument(
185
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
186
+ )
187
+ parser.add_argument(
188
+ "--device",
189
+ type=int,
190
+ default=None,
191
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
192
+ )
193
+ args = parser.parse_args()
194
+
195
+ main(args)