stanfous commited on
Commit
04fb6f8
1 Parent(s): 71e2448
Files changed (2) hide show
  1. README.md +23 -3
  2. eval.py +197 -0
README.md CHANGED
@@ -1,12 +1,32 @@
1
  ---
2
  language:
3
  - fr
 
4
  tags:
5
  - automatic-speech-recognition
6
  - mozilla-foundation/common_voice_8_0
 
7
  - robust-speech-event
8
  datasets:
9
  - mozilla-foundation/common_voice_8_0
10
- metrics:
11
- - wer
12
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  language:
3
  - fr
4
+ license: apache-2.0
5
  tags:
6
  - automatic-speech-recognition
7
  - mozilla-foundation/common_voice_8_0
8
+ - fr
9
  - robust-speech-event
10
  datasets:
11
  - mozilla-foundation/common_voice_8_0
12
+ model-index:
13
+ - name: XLS-R-1B - French
14
+ results:
15
+ - task:
16
+ name: Automatic Speech Recognition
17
+ type: automatic-speech-recognition
18
+ dataset:
19
+ name: Common Voice 8
20
+ type: mozilla-foundation/common_voice_8_0
21
+ args: fr
22
+ metrics:
23
+ - name: Test WER (without LM)
24
+ type: wer
25
+ value: 15.405483405483406
26
+ - name: Test CER (without LM)
27
+ type: cer
28
+ value: 4.8773030225289137
29
+ - name: Test WER (with LM)
30
+ type: wer
31
+ value: 12.5
32
+ ---
eval.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from datasets import load_dataset, load_metric, Audio, Dataset
3
+ from transformers import pipeline, AutoFeatureExtractor, AutoTokenizer
4
+ import re
5
+ import torch
6
+ import argparse
7
+ from typing import Dict
8
+
9
+
10
+ def log_results(result: Dataset, args: Dict[str, str]):
11
+ """ DO NOT CHANGE. This function computes and logs the result metrics. """
12
+
13
+ log_outputs = args.log_outputs
14
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
15
+
16
+ # load metric
17
+ wer = load_metric("wer")
18
+ cer = load_metric("cer")
19
+
20
+ # compute metrics
21
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
22
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
23
+
24
+ # print & log results
25
+ result_str = (
26
+ f"WER: {wer_result}\n"
27
+ f"CER: {cer_result}"
28
+ )
29
+ print(result_str)
30
+
31
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
32
+ f.write(result_str)
33
+
34
+ # log all results in text file. Possibly interesting for analysis
35
+ if log_outputs is not None:
36
+ pred_file = f"log_{dataset_id}_predictions.txt"
37
+ target_file = f"log_{dataset_id}_targets.txt"
38
+
39
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
40
+
41
+ # mapping function to write output
42
+ def write_to_file(batch, i):
43
+ p.write(f"{i}" + "\n")
44
+ p.write(batch["prediction"] + "\n")
45
+ t.write(f"{i}" + "\n")
46
+ t.write(batch["target"] + "\n")
47
+
48
+ result.map(write_to_file, with_indices=True)
49
+
50
+
51
+ def normalize_text(text: str, invalid_chars_regex: str, to_lower: bool) -> str:
52
+ # remove special characters
53
+ chars_to_ignore_regex = '[\µ\я\ひ\ⱎ\ⱅ\ḥ\ӌ\џ\ŵ\ʋ\λ\φ\χ\г\и\к\п\ц\ч\э\я\џ\ӌ\ቀ\ከ\ጀ\ḥ\牡\津\宇\厳\保\丹\三\む\も\ⱎ\ⱅ\⋅\⊨\↔\ℚ\э\п\к\и\г\|\£\§\·\½\º\ə\ơ\ǀ\ː\ʾ\ˢ\г\и\к\э\п\∨\„\,\?\.\!\—\―\–\;\:\"\‘\»\%\ł\_\€\×\ぬ\;\±\ß\Þ\«\Ø\°\…\”\“\`\ʿ\&\=\+\の\~\(\)\Σ\ı\ጠ\ℵ\馆\青\貴\西\美\甌\杜\术\星\文\扬\北\京\乃\ゔ\や\め\ま\へ\つ\た\う\い\☉\≥\®\/\∞\∆\∅\→\ℰ\ω\ψ\Μ\Θ\Κ\Π\Σ\Ω\α\γ\δ\ε\ζ\η\κ\ι\ν\μ\ρ\ς\σ\τ\υ\ℤ\ℝ\ℂ\ℕ\₽\∈\›\ο\‹\†\}\{\}\_\ደ\Δ\ወ\ي\و\ب\ة\د\ن\ن\ل\را\э\р\п\н\м\к\и\з\ψ\υ\θ\ṭ\ṯ\ḍ\*\^\∼\م\э\п\ǃ\$\Ꝑ]'
54
+ chars_to_replace_a = '[\ɑ\ạ\ả\ầ\ậ\ắ\ẵ\а\ǎ\ā\ă\ą\á\ã\ä\å]'
55
+ chars_to_replace_i = '[\ɨ\ị\ı\ī\ĩ\í\ì\і]'
56
+ chars_to_replace_e = '[\ệ\ễ\ề\ě\ę\ė\ē\е\ế]'
57
+ chars_to_replace_o = '[\ồ\ộ\ờ\ợ\ő\ö\ŏ\ō\ø\õ\ó\ò\ð\ǫ\ό\ớ\ổ\ố]'
58
+ chars_to_replace_u = '[\ų\ʉ\ủ\ử\ù\ü\ư\ǔ\ů\ū\ũ\ú\ứ\ụ\ű\ŭ]'
59
+ chars_to_replace_c = '[\ς\ć\ċ\č\ҫ]'
60
+ chars_to_replace_y = '[\ÿ\ỳ\ÿ\ý]'
61
+ chars_to_replace_n = '[\ṇ\ṅ\ǹ\ħ\ñ\ň\ņ\ń]'
62
+ chars_to_replace_t = '[\ṭ\ț\ť\ţ]'
63
+ chars_to_replace_s = '[\ṣ\ș\š\ş\ś]'
64
+ chars_to_replace_q = '[\զ\գ\գ\զ]'
65
+ chars_to_replace_j = '[\ј]'
66
+ chars_to_replace_z = '[\ž\ż\ź\ẓ]'
67
+ chars_to_replace_r = '[\ř]'
68
+ chars_to_replace_l = '[\ł\ļ\ĺ]'
69
+ chars_to_replace_k = '[\ķ]'
70
+ chars_to_replace_g = '[\ġ\ğ]'
71
+ chars_to_replace_d = '[\đ\ď]'
72
+ chars_to_replace_b = '[\þ]'
73
+ chars_to_replace_p = '[\р]'
74
+ chars_to_replace_apostrophe = '[\´\′\ʼ\’\'\'\ʽ\ʻ\ʾ]'
75
+ chars_to_replace_tirets = '[\─\−\‐]'
76
+
77
+
78
+ text = re.sub(chars_to_ignore_regex, " ", text).lower() if to_lower
79
+ text = re.sub(chars_to_replace_a, "a", text)
80
+ text = re.sub(chars_to_replace_i, "i", text)
81
+ text = re.sub(chars_to_replace_e, "e", text)
82
+ text = re.sub(chars_to_replace_o, "o", text)
83
+ text = re.sub(chars_to_replace_u, "u", text)
84
+ text = re.sub(chars_to_replace_c, "c", text)
85
+ text = re.sub(chars_to_replace_y, "y", text)
86
+ text = re.sub(chars_to_replace_n, "n", text)
87
+ text = re.sub(chars_to_replace_t, "t", text)
88
+ text = re.sub(chars_to_replace_s, "s", text)
89
+ text = re.sub(chars_to_replace_q, "q", text)
90
+ text = re.sub(chars_to_replace_j, "j", text)
91
+ text = re.sub(chars_to_replace_z, "z", text)
92
+ text = re.sub(chars_to_replace_r, "r", text)
93
+ text = re.sub(chars_to_replace_l, "l", text)
94
+ text = re.sub(chars_to_replace_k, "k", text)
95
+ text = re.sub(chars_to_replace_g, "g", text)
96
+ text = re.sub(chars_to_replace_d, "d", text)
97
+ text = re.sub(chars_to_replace_b, "b", text)
98
+ text = re.sub(chars_to_replace_q, "q", text)
99
+ text = re.sub(chars_to_replace_p, "p", text)
100
+ text = re.sub(chars_to_replace_apostrophe, "'", text)
101
+ text = re.sub(chars_to_replace_tirets, "-", text)
102
+ text = re.sub("β", "beta", text)
103
+ text = re.sub("æ", "ae", text)
104
+ text = re.sub("œ", "oe", text)
105
+ text = re.sub("&", "et", text)
106
+ text = re.sub("π", "pi", text)
107
+ text = re.sub("ľ", "l'", text)
108
+ text = re.sub(r"^\s+|\s+$", "", text)
109
+ text = re.sub(" +", " ", text)
110
+ text = re.sub("\n", " ", text)
111
+ return text
112
+
113
+
114
+ def main(args):
115
+ # load dataset
116
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
117
+
118
+ # for testing: only process the first two examples as a test
119
+ # dataset = dataset.select(range(10))
120
+
121
+ # load processor
122
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
123
+ sampling_rate = feature_extractor.sampling_rate
124
+
125
+ # resample audio
126
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
127
+
128
+ # load eval pipeline
129
+ if args.device is None:
130
+ args.device = 0 if torch.cuda.is_available() else -1
131
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
132
+
133
+ # build normalizer config
134
+ tokenizer = AutoTokenizer.from_pretrained(args.model_id)
135
+ tokens = [x for x in tokenizer.convert_ids_to_tokens(range(0, tokenizer.vocab_size))]
136
+ special_tokens = [
137
+ tokenizer.pad_token, tokenizer.word_delimiter_token,
138
+ tokenizer.unk_token, tokenizer.bos_token,
139
+ tokenizer.eos_token,
140
+ ]
141
+ non_special_tokens = [x for x in tokens if x not in special_tokens]
142
+ invalid_chars_regex = f"[^\s{re.escape(''.join(set(non_special_tokens)))}]"
143
+ normalize_to_lower = False
144
+ for token in non_special_tokens:
145
+ if token.isalpha() and token.islower():
146
+ normalize_to_lower = True
147
+ break
148
+
149
+ # map function to decode audio
150
+ def map_to_pred(batch, args=args, asr=asr, invalid_chars_regex=invalid_chars_regex, normalize_to_lower=normalize_to_lower):
151
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
152
+
153
+ batch["prediction"] = prediction["text"]
154
+ batch["target"] = normalize_text(batch["sentence"], invalid_chars_regex, normalize_to_lower)
155
+ return batch
156
+
157
+ # run inference on all examples
158
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
159
+
160
+ # compute and log_results
161
+ # do not change function below
162
+ log_results(result, args)
163
+
164
+
165
+ if __name__ == "__main__":
166
+ parser = argparse.ArgumentParser()
167
+
168
+ parser.add_argument(
169
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
170
+ )
171
+ parser.add_argument(
172
+ "--dataset", type=str, required=True, 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(
178
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
179
+ )
180
+ parser.add_argument(
181
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to None. For long audio files a good value would be 5.0 seconds."
182
+ )
183
+ parser.add_argument(
184
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to None. For long audio files a good value would be 1.0 seconds."
185
+ )
186
+ parser.add_argument(
187
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
188
+ )
189
+ parser.add_argument(
190
+ "--device",
191
+ type=int,
192
+ default=None,
193
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
194
+ )
195
+ args = parser.parse_args()
196
+
197
+ main(args)