AigizK commited on
Commit
6f4a5fd
1 Parent(s): 38bf59d

add eval.py

Browse files
Files changed (1) hide show
  1. eval.py +159 -0
eval.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ chars_to_remove_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\«\»\–\—aijno]'
52
+ text = re.sub(chars_to_remove_regex, ' ', text).lower()
53
+
54
+ chars_to_replace_regex = {'й':'й','i':''}
55
+ for k in chars_to_replace_regex:
56
+ text = re.sub(k, chars_to_replace_regex[k], text)
57
+
58
+
59
+ text = re.sub('[я]', 'йа', text)
60
+ text = re.sub('[ю]', 'йу', text)
61
+ text = re.sub('[ё]', 'йо', text)
62
+ text = re.sub('[ъ]', '', text)
63
+ text = re.sub('[ь]', '', text)
64
+ if 'е' in text:
65
+ words=text.split(' ')
66
+ new_list=[]
67
+ for word in words:
68
+ if len(word)==0:
69
+ continue
70
+ new_word=word
71
+ if word[0]=='е':
72
+ new_word='йэ'+word[1:]
73
+ new_word=re.sub('[е]', 'э', new_word)
74
+ new_list.append(new_word)
75
+
76
+ text = " ".join(new_list)
77
+
78
+ words=text.split(' ')
79
+ while '' in words:
80
+ words.remove('')
81
+
82
+ text=" ".join(words)
83
+
84
+
85
+ return text
86
+
87
+
88
+ def main(args):
89
+ # load dataset
90
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
91
+
92
+ # for testing: only process the first two examples as a test
93
+ # dataset = dataset.select(range(10))
94
+
95
+ # load processor
96
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
97
+ sampling_rate = feature_extractor.sampling_rate
98
+
99
+ # resample audio
100
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
101
+
102
+ # load eval pipeline
103
+ if args.device is None:
104
+ args.device = 0 if torch.cuda.is_available() else -1
105
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
106
+
107
+ # map function to decode audio
108
+ def map_to_pred(batch):
109
+ prediction = asr(
110
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
111
+ )
112
+
113
+ batch["prediction"] = prediction["text"]
114
+ batch["target"] = normalize_text(batch["sentence"])
115
+ return batch
116
+
117
+ # run inference on all examples
118
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
119
+
120
+ # compute and log_results
121
+ # do not change function below
122
+ log_results(result, args)
123
+
124
+
125
+ if __name__ == "__main__":
126
+ parser = argparse.ArgumentParser()
127
+
128
+ parser.add_argument(
129
+ "--model_id", type=str, default="AigizK/wav2vec2-large-xls-r-300m-bashkir-cv7_opt", help="Model identifier. Should be loadable with 🤗 Transformers"
130
+ )
131
+ parser.add_argument(
132
+ "--dataset",
133
+ type=str,
134
+
135
+ default="mozilla-foundation/common_voice_7_0",
136
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
137
+ )
138
+ parser.add_argument(
139
+ "--config", type=str, default="ba", help="Config of the dataset. *E.g.* `'en'` for Common Voice"
140
+ )
141
+ parser.add_argument("--split", type=str,default="test", help="Split of the dataset. *E.g.* `'test'`")
142
+ parser.add_argument(
143
+ "--chunk_length_s", type=float, default=15, help="Chunk length in seconds. Defaults to 5 seconds."
144
+ )
145
+ parser.add_argument(
146
+ "--stride_length_s", type=float, default=1, help="Stride of the audio chunks. Defaults to 1 second."
147
+ )
148
+ parser.add_argument(
149
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
150
+ )
151
+ parser.add_argument(
152
+ "--device",
153
+ type=int,
154
+ default=-1,
155
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
156
+ )
157
+ args = parser.parse_args()
158
+
159
+ main(args)