kingabzpro commited on
Commit
a24ea1d
β€’
1 Parent(s): 597f880
.ipynb_checkpoints/Boosting_Wav2Vec2_with_n_grams_in_πŸ€—_Transformers_(1)-checkpoint.ipynb ADDED
The diff for this file is too large to render. See raw diff
Boosting_Wav2Vec2_with_n_grams_in_πŸ€—_Transformers_(1).ipynb ADDED
The diff for this file is too large to render. See raw diff
eval.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = '[,?.!\-\;\:\"β€œ%β€˜β€οΏ½β€”β€™β€¦β€“Β€β€“β€™]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
54
+ alpha_numerical = "[0-9A-Za-z]"
55
+ text = re.sub(chars_to_ignore_regex, "", text.lower())
56
+ text = re.sub(alpha_numerical, "",text)
57
+ text = re.sub("[β€”]", '', text)
58
+ text = re.sub("[_]", '', text)
59
+ text = re.sub("[Β«]", '', text)
60
+ text = re.sub("[Β»]", '', text)
61
+ # batch["sentence"] = re.sub("['ِ]", '', batch["sentence"])
62
+ text = re.sub("[،]", '', text)
63
+ text = re.sub("[Ψ›]", '', text)
64
+ text = re.sub("[؟]", '', text)
65
+ text = re.sub("['Ϋ–]", '', text)
66
+ text = re.sub("[Ω€]", '', text)
67
+ text = re.sub("[☭]", '', text)
68
+ text = re.sub("[…]", '', text)
69
+ text = re.sub("['Ϋ—]", '', text)
70
+ text = re.sub("[،]", '', text)
71
+ text = re.sub("[Ψ›]", '', text)
72
+ text = re.sub("['ۘ]", '', text)
73
+ text = re.sub("['ۚ]", '', text)
74
+ text = re.sub("['Ϋ›]", '', text)
75
+ text = re.sub("['Ω‹]", '', text)
76
+ text = re.sub("['ٌ]", '', text)
77
+ text = re.sub("['ٍ]", '', text)
78
+ text = re.sub("['Ω‘]", '', text)
79
+ text = re.sub("['Ω°]", '', text)
80
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
81
+ # note that order is important here!
82
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
83
+
84
+ for t in token_sequences_to_ignore:
85
+ text = " ".join(text.split(t))
86
+
87
+ return text
88
+
89
+
90
+ def main(args):
91
+ # load dataset
92
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
93
+
94
+ # for testing: only process the first two examples as a test
95
+ # dataset = dataset.select(range(10))
96
+
97
+ # load processor
98
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
99
+ sampling_rate = feature_extractor.sampling_rate
100
+
101
+ # resample audio
102
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
103
+
104
+ # load eval pipeline
105
+ if args.device is None:
106
+ args.device = 0 if torch.cuda.is_available() else -1
107
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
108
+
109
+ # map function to decode audio
110
+ def map_to_pred(batch):
111
+ prediction = asr(
112
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
113
+ )
114
+
115
+ batch["prediction"] = prediction["text"]
116
+ batch["target"] = normalize_text(batch["sentence"])
117
+ return batch
118
+
119
+ # run inference on all examples
120
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
121
+
122
+ # compute and log_results
123
+ # do not change function below
124
+ log_results(result, args)
125
+
126
+
127
+ if __name__ == "__main__":
128
+ parser = argparse.ArgumentParser()
129
+
130
+ parser.add_argument(
131
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with πŸ€— Transformers"
132
+ )
133
+ parser.add_argument(
134
+ "--dataset",
135
+ type=str,
136
+ required=True,
137
+ help="Dataset name to evaluate the `model_id`. Should be loadable with πŸ€— Datasets",
138
+ )
139
+ parser.add_argument(
140
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
141
+ )
142
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
143
+ parser.add_argument(
144
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
145
+ )
146
+ parser.add_argument(
147
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
148
+ )
149
+ parser.add_argument(
150
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
151
+ )
152
+ parser.add_argument(
153
+ "--device",
154
+ type=int,
155
+ default=None,
156
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
157
+ )
158
+ args = parser.parse_args()
159
+
160
+ main(args)
log_mozilla-foundation_common_voice_7_0_ar_test_predictions.txt ADDED
The diff for this file is too large to render. See raw diff
log_mozilla-foundation_common_voice_7_0_ar_test_targets.txt ADDED
The diff for this file is too large to render. See raw diff
mozilla-foundation_common_voice_7_0_ar_test_eval_results.txt ADDED
@@ -0,0 +1,2 @@
 
 
1
+ WER: 0.3882512836001208
2
+ CER: 0.15335327074758484