Harveenchadha commited on
Commit
2767bf3
1 Parent(s): 03a785f

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +153 -0
eval.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ #pip install indic-nlp-library
4
+ from indicnlp.tokenize.indic_tokenize import trivial_tokenize
5
+ from indicnlp.normalize.indic_normalize import IndicNormalizerFactory
6
+
7
+
8
+ import argparse
9
+ import re
10
+ from typing import Dict
11
+ import torch
12
+ from datasets import Audio, Dataset, load_dataset, load_metric
13
+
14
+ from transformers import AutoFeatureExtractor, pipeline
15
+
16
+
17
+ #indic_normalizer_factory = IndicNormalizerFactory()
18
+ #indic_normalizer = indic_normalizer_factory.get_normalizer('hi')
19
+
20
+ def log_results(result: Dataset, args: Dict[str, str]):
21
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
22
+
23
+ log_outputs = args.log_outputs
24
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
25
+
26
+ # load metric
27
+ wer = load_metric("wer")
28
+ cer = load_metric("cer")
29
+
30
+ # compute metrics
31
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
32
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
33
+
34
+ # print & log results
35
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
36
+ print(result_str)
37
+
38
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
39
+ f.write(result_str)
40
+
41
+ # log all results in text file. Possibly interesting for analysis
42
+ if log_outputs is not None:
43
+ pred_file = f"log_{dataset_id}_predictions.txt"
44
+ target_file = f"log_{dataset_id}_targets.txt"
45
+
46
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
47
+
48
+ # mapping function to write output
49
+ def write_to_file(batch, i):
50
+ p.write(f"{i}" + "\n")
51
+ p.write(batch["prediction"] + "\n")
52
+ t.write(f"{i}" + "\n")
53
+ t.write(batch["target"] + "\n")
54
+
55
+ result.map(write_to_file, with_indices=True)
56
+
57
+
58
+ def normalize_text(text: str) -> str:
59
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
60
+
61
+ chars_to_ignore_regex = '[।,?.!\-\;\:"“%‘”�—’…–]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
62
+
63
+ text = re.sub(chars_to_ignore_regex, "", text.lower().strip())
64
+
65
+ # In addition, we can normalize the target text, e.g. removing new lines characters etc...
66
+ # note that order is important here!
67
+ token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
68
+
69
+ for t in token_sequences_to_ignore:
70
+ text = " ".join(text.split(t))
71
+
72
+ return text
73
+
74
+ #def normalize_text_indic(text:str) -> str:
75
+ # lang='hi'
76
+ # normalized = indic_normalizer.normalize(text)
77
+ # processed = ' '.join(trivial_tokenize(normalized, lang))
78
+ # return processed
79
+
80
+
81
+ def main(args):
82
+ # load dataset
83
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
84
+
85
+ # for testing: only process the first two examples as a test
86
+ # dataset = dataset.select(range(10))
87
+
88
+ # load processor
89
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
90
+ sampling_rate = feature_extractor.sampling_rate
91
+
92
+ # resample audio
93
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
94
+
95
+ # load eval pipeline
96
+ if args.device is None:
97
+ args.device = 0 if torch.cuda.is_available() else -1
98
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
99
+
100
+ # map function to decode audio
101
+ def map_to_pred(batch):
102
+ prediction = asr(
103
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
104
+ )
105
+
106
+ batch["prediction"] = prediction["text"]
107
+ batch["target"] = normalize_text(batch["sentence"])
108
+ #batch["prediction"] = normalize_text_indic(batch["prediction"] )
109
+ #batch["target"] = normalize_text_indic(batch["target"] )
110
+ return batch
111
+
112
+ # run inference on all examples
113
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
114
+
115
+ # compute and log_results
116
+ # do not change function below
117
+ log_results(result, args)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ parser = argparse.ArgumentParser()
122
+
123
+ parser.add_argument(
124
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
125
+ )
126
+ parser.add_argument(
127
+ "--dataset",
128
+ type=str,
129
+ required=True,
130
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
131
+ )
132
+ parser.add_argument(
133
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
134
+ )
135
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
136
+ parser.add_argument(
137
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
138
+ )
139
+ parser.add_argument(
140
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
141
+ )
142
+ parser.add_argument(
143
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
144
+ )
145
+ parser.add_argument(
146
+ "--device",
147
+ type=int,
148
+ default=None,
149
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
150
+ )
151
+ args = parser.parse_args()
152
+
153
+ main(args)