nouamanetazi HF staff commited on
Commit
d24b6e0
1 Parent(s): 060d6a9

add eval script

Browse files
.ipynb_checkpoints/README-checkpoint.md CHANGED
@@ -1,12 +1,32 @@
1
  ---
 
 
2
  license: apache-2.0
3
  tags:
 
 
4
  - generated_from_trainer
 
 
5
  datasets:
6
  - common_voice
7
  model-index:
8
  - name: wav2vec2-xls-r-300m-ar
9
- results: []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  ---
11
 
12
  <!-- This model card has been generated automatically according to the information the Trainer had access to. You
@@ -14,7 +34,15 @@ should probably proofread and complete it, then remove this comment. -->
14
 
15
  # wav2vec2-xls-r-300m-ar
16
 
17
- This model is a fine-tuned version of [facebook/wav2vec2-xls-r-300m](https://huggingface.co/facebook/wav2vec2-xls-r-300m) on the common_voice dataset.
 
 
 
 
 
 
 
 
18
 
19
  ## Model description
20
 
@@ -49,3 +77,13 @@ The following hyperparameters were used during training:
49
  - Pytorch 1.10.2+cu102
50
  - Datasets 1.18.2.dev0
51
  - Tokenizers 0.11.0
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - ar
4
  license: apache-2.0
5
  tags:
6
+ - automatic-speech-recognition
7
+ - common_voice
8
  - generated_from_trainer
9
+ - sv
10
+ - robust-speech-event
11
  datasets:
12
  - common_voice
13
  model-index:
14
  - name: wav2vec2-xls-r-300m-ar
15
+ results:
16
+ - task:
17
+ name: Automatic Speech Recognition
18
+ type: automatic-speech-recognition
19
+ dataset:
20
+ name: Robust Speech Event - Dev Data
21
+ type: speech-recognition-community-v2/dev_data
22
+ args: ar
23
+ metrics:
24
+ - name: Test WER
25
+ type: wer
26
+ value: 1.0
27
+ - name: Test CER
28
+ type: cer
29
+ value: 1.0
30
  ---
31
 
32
  <!-- This model card has been generated automatically according to the information the Trainer had access to. You
 
34
 
35
  # wav2vec2-xls-r-300m-ar
36
 
37
+ This model is a fine-tuned version of [facebook/wav2vec2-xls-r-300m](https://huggingface.co/facebook/wav2vec2-xls-r-300m) on the COMMON_VOICE - AR dataset.
38
+ It achieves the following results on the evaluation set:
39
+ - eval_loss: 3.0191
40
+ - eval_wer: 1.0
41
+ - eval_runtime: 252.2389
42
+ - eval_samples_per_second: 30.217
43
+ - eval_steps_per_second: 0.476
44
+ - epoch: 1.0
45
+ - step: 340
46
 
47
  ## Model description
48
 
 
77
  - Pytorch 1.10.2+cu102
78
  - Datasets 1.18.2.dev0
79
  - Tokenizers 0.11.0
80
+
81
+ #### Evaluation Commands
82
+
83
+ Please use the evaluation script `eval.py` included in the repo.
84
+
85
+ 1. To evaluate on `speech-recognition-community-v2/dev_data`
86
+
87
+ ```bash
88
+ python eval.py --model_id nouamanetazi/wav2vec2-xls-r-300m-ar --dataset speech-recognition-community-v2/dev_data --config ar --split validation --chunk_length_s 5.0 --stride_length_s 1.0
89
+ ```
.ipynb_checkpoints/eval-checkpoint.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from datasets import load_dataset, load_metric, Audio, Dataset
3
+ from transformers import pipeline, AutoFeatureExtractor
4
+ import re
5
+ import argparse
6
+ import unicodedata
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
+ # Normalize arabic
52
+ def normalizeArabic(text):
53
+ # https://alraqmiyyat.github.io/2013/01-02.html
54
+ text = re.sub("[إأٱآا]", "ا", text)
55
+ text = re.sub("ى", "ي", text)
56
+ text = re.sub("ؤ", "ء", text)
57
+ text = re.sub("ئ", "ء", text)
58
+
59
+ # keep only characters which unicode \u0600-\u06FF and space
60
+ text = re.sub(r"[^\u0600-\u06FF ]", "", text)
61
+ return text
62
+
63
+ def normalize_text(text: str) -> str:
64
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
65
+
66
+ chars_to_ignore_regex = '[,?.!\-\;\:"“%‘”�—’…–]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
67
+
68
+ text = re.sub(chars_to_ignore_regex, "", text.lower())
69
+
70
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
71
+ # note that order is important here!
72
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
73
+
74
+ for t in token_sequences_to_ignore:
75
+ text = " ".join(text.split(t))
76
+
77
+ text = normalizeArabic(text)
78
+
79
+ return text
80
+
81
+
82
+ def main(args):
83
+ # load dataset
84
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
85
+
86
+ # for testing: only process the first two examples as a test
87
+ # dataset = dataset.select(range(10))
88
+
89
+ # load processor
90
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
91
+ sampling_rate = feature_extractor.sampling_rate
92
+
93
+ # resample audio
94
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
95
+
96
+ # load eval pipeline
97
+ asr = pipeline("automatic-speech-recognition", model=args.model_id)
98
+
99
+ # map function to decode audio
100
+ def map_to_pred(batch):
101
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
102
+
103
+ batch["prediction"] = prediction["text"]
104
+ batch["target"] = normalize_text(batch["sentence"])
105
+ return batch
106
+
107
+ # run inference on all examples
108
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
109
+
110
+ # compute and log_results
111
+ # do not change function below
112
+ log_results(result, args)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ parser = argparse.ArgumentParser()
117
+
118
+ parser.add_argument(
119
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
120
+ )
121
+ parser.add_argument(
122
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
123
+ )
124
+ parser.add_argument(
125
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
126
+ )
127
+ parser.add_argument(
128
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
129
+ )
130
+ parser.add_argument(
131
+ "--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."
132
+ )
133
+ parser.add_argument(
134
+ "--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."
135
+ )
136
+ parser.add_argument(
137
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
138
+ )
139
+ args = parser.parse_args()
140
+
141
+ main(args)
README.md CHANGED
@@ -6,11 +6,27 @@ tags:
6
  - automatic-speech-recognition
7
  - common_voice
8
  - generated_from_trainer
 
 
9
  datasets:
10
  - common_voice
11
  model-index:
12
  - name: wav2vec2-xls-r-300m-ar
13
- results: []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  ---
15
 
16
  <!-- This model card has been generated automatically according to the information the Trainer had access to. You
@@ -61,3 +77,13 @@ The following hyperparameters were used during training:
61
  - Pytorch 1.10.2+cu102
62
  - Datasets 1.18.2.dev0
63
  - Tokenizers 0.11.0
 
 
 
 
 
 
 
 
 
 
 
6
  - automatic-speech-recognition
7
  - common_voice
8
  - generated_from_trainer
9
+ - sv
10
+ - robust-speech-event
11
  datasets:
12
  - common_voice
13
  model-index:
14
  - name: wav2vec2-xls-r-300m-ar
15
+ results:
16
+ - task:
17
+ name: Automatic Speech Recognition
18
+ type: automatic-speech-recognition
19
+ dataset:
20
+ name: Robust Speech Event - Dev Data
21
+ type: speech-recognition-community-v2/dev_data
22
+ args: ar
23
+ metrics:
24
+ - name: Test WER
25
+ type: wer
26
+ value: 1.0
27
+ - name: Test CER
28
+ type: cer
29
+ value: 1.0
30
  ---
31
 
32
  <!-- This model card has been generated automatically according to the information the Trainer had access to. You
 
77
  - Pytorch 1.10.2+cu102
78
  - Datasets 1.18.2.dev0
79
  - Tokenizers 0.11.0
80
+
81
+ #### Evaluation Commands
82
+
83
+ Please use the evaluation script `eval.py` included in the repo.
84
+
85
+ 1. To evaluate on `speech-recognition-community-v2/dev_data`
86
+
87
+ ```bash
88
+ python eval.py --model_id nouamanetazi/wav2vec2-xls-r-300m-ar --dataset speech-recognition-community-v2/dev_data --config ar --split validation --chunk_length_s 5.0 --stride_length_s 1.0
89
+ ```
eval.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from datasets import load_dataset, load_metric, Audio, Dataset
3
+ from transformers import pipeline, AutoFeatureExtractor
4
+ import re
5
+ import argparse
6
+ import unicodedata
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
+ # Normalize arabic
52
+ def normalizeArabic(text):
53
+ # https://alraqmiyyat.github.io/2013/01-02.html
54
+ text = re.sub("[إأٱآا]", "ا", text)
55
+ text = re.sub("ى", "ي", text)
56
+ text = re.sub("ؤ", "ء", text)
57
+ text = re.sub("ئ", "ء", text)
58
+
59
+ # keep only characters which unicode \u0600-\u06FF and space
60
+ text = re.sub(r"[^\u0600-\u06FF ]", "", text)
61
+ return text
62
+
63
+ def normalize_text(text: str) -> str:
64
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
65
+
66
+ chars_to_ignore_regex = '[,?.!\-\;\:"“%‘”�—’…–]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
67
+
68
+ text = re.sub(chars_to_ignore_regex, "", text.lower())
69
+
70
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
71
+ # note that order is important here!
72
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
73
+
74
+ for t in token_sequences_to_ignore:
75
+ text = " ".join(text.split(t))
76
+
77
+ text = normalizeArabic(text)
78
+
79
+ return text
80
+
81
+
82
+ def main(args):
83
+ # load dataset
84
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
85
+
86
+ # for testing: only process the first two examples as a test
87
+ # dataset = dataset.select(range(10))
88
+
89
+ # load processor
90
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
91
+ sampling_rate = feature_extractor.sampling_rate
92
+
93
+ # resample audio
94
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
95
+
96
+ # load eval pipeline
97
+ asr = pipeline("automatic-speech-recognition", model=args.model_id)
98
+
99
+ # map function to decode audio
100
+ def map_to_pred(batch):
101
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
102
+
103
+ batch["prediction"] = prediction["text"]
104
+ batch["target"] = normalize_text(batch["sentence"])
105
+ return batch
106
+
107
+ # run inference on all examples
108
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
109
+
110
+ # compute and log_results
111
+ # do not change function below
112
+ log_results(result, args)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ parser = argparse.ArgumentParser()
117
+
118
+ parser.add_argument(
119
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
120
+ )
121
+ parser.add_argument(
122
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
123
+ )
124
+ parser.add_argument(
125
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
126
+ )
127
+ parser.add_argument(
128
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
129
+ )
130
+ parser.add_argument(
131
+ "--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."
132
+ )
133
+ parser.add_argument(
134
+ "--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."
135
+ )
136
+ parser.add_argument(
137
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
138
+ )
139
+ args = parser.parse_args()
140
+
141
+ main(args)