RuudVelo commited on
Commit
e15b2f0
1 Parent(s): c97a4fc

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +154 -0
eval.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(references=result["target"], predictions=result["prediction"])
24
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
25
+
26
+ # print & log results
27
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
28
+ print(result_str)
29
+
30
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
31
+ f.write(result_str)
32
+
33
+ # log all results in text file. Possibly interesting for analysis
34
+ if log_outputs is not None:
35
+ pred_file = f"log_{dataset_id}_predictions.txt"
36
+ target_file = f"log_{dataset_id}_targets.txt"
37
+
38
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
39
+
40
+ # mapping function to write output
41
+ def write_to_file(batch, i):
42
+ p.write(f"{i}" + "\n")
43
+ p.write(batch["prediction"] + "\n")
44
+ t.write(f"{i}" + "\n")
45
+ t.write(batch["target"] + "\n")
46
+
47
+ result.map(write_to_file, with_indices=True)
48
+
49
+
50
+ def normalize_text(text: str) -> str:
51
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
52
+
53
+ chars_to_ignore_regex = '[\,\?\¿\.\!\¡\;\;\:\""\%\"\�\&\-\ʿ\·\჻\~\՞\؟\،\।\॥\«\»\„\“\”\」\‘\’\《\》\(\)\[\]\{\}\=\`_\
54
+ #+\<\>\…\–\°\´\ʾ\‹\›\©\®\—\→\。\、\﹂\﹁\‧~\﹏\,\}\(\)\[\]\【\】\‥\〽\『\』\〝\〟\⟨\⟩\〜\:\!\?\♪\؛\/\\\\º\−\^\ʻ\ˆ\']'
55
+
56
+ text=re.sub(chars_to_ignore_regex, "",text.lower())
57
+ #text=re.sub('[î]','i',text)
58
+ #text=re.sub('[ô]','o',text)
59
+ #text=re.sub('[û]','u',text)
60
+ #text=re.sub('[ä]','a',text)
61
+ #text=re.sub('[à]','a',text)
62
+ #text=re.sub('[á]','a',text)
63
+ #text=re.sub('[ç]','c',text)
64
+ #text=re.sub('[ö]','o',text)
65
+ #text=re.sub('[ó]','o',text)
66
+ #text=re.sub('[ü]','u',text)
67
+ #text=re.sub('[ú]','u',text)
68
+ #text=re.sub('[ï]','i',text)
69
+ #text=re.sub('[ë]','e',text)
70
+ #text=re.sub('[é]','e',text)
71
+ #text=re.sub('[è]','e',text)
72
+ #text=re.sub('[ê]','e',text)
73
+
74
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
75
+ # note that order is important here!
76
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
77
+
78
+ for t in token_sequences_to_ignore:
79
+ text = " ".join(text.split(t))
80
+
81
+ return text
82
+
83
+
84
+ def main(args):
85
+ # load dataset
86
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
87
+
88
+ # for testing: only process the first two examples as a test
89
+ # dataset = dataset.select(range(10))
90
+
91
+ # load processor
92
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
93
+ sampling_rate = feature_extractor.sampling_rate
94
+
95
+ # resample audio
96
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
97
+
98
+ # load eval pipeline
99
+ if args.device is None:
100
+ args.device = 0 if torch.cuda.is_available() else -1
101
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
102
+
103
+ # map function to decode audio
104
+ def map_to_pred(batch):
105
+ prediction = asr(
106
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
107
+ )
108
+
109
+ batch["prediction"] = prediction["text"]
110
+ batch["target"] = normalize_text(batch["sentence"])
111
+ return batch
112
+
113
+ # run inference on all examples
114
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
115
+
116
+ # compute and log_results
117
+ # do not change function below
118
+ log_results(result, args)
119
+
120
+
121
+ if __name__ == "__main__":
122
+ parser = argparse.ArgumentParser()
123
+
124
+ parser.add_argument(
125
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
126
+ )
127
+ parser.add_argument(
128
+ "--dataset",
129
+ type=str,
130
+ required=True,
131
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
132
+ )
133
+ parser.add_argument(
134
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
135
+ )
136
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
137
+ parser.add_argument(
138
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
139
+ )
140
+ parser.add_argument(
141
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
142
+ )
143
+ parser.add_argument(
144
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
145
+ )
146
+ parser.add_argument(
147
+ "--device",
148
+ type=int,
149
+ default=None,
150
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
151
+ )
152
+ args = parser.parse_args()
153
+
154
+ main(args)