manifoldix commited on
Commit
41e1c31
1 Parent(s): 9206210

eval script with normalizer

Browse files
Files changed (1) hide show
  1. eval.py +129 -0
eval.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from normalizer import normalizer
11
+
12
+
13
+ def log_results(result: Dataset, args: Dict[str, str]):
14
+ """DO NOT CHANGE. This function computes and logs the result metrics."""
15
+
16
+ log_outputs = args.log_outputs
17
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
18
+
19
+ # load metric
20
+ wer = load_metric("wer")
21
+ cer = load_metric("cer")
22
+
23
+ # compute metrics
24
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
25
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
26
+
27
+ # print & log results
28
+ result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
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) -> str:
52
+ """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
53
+ if not isinstance(batch, str):
54
+ return None
55
+
56
+ return normalizer({"sentence": batch}, return_dict=False)
57
+
58
+
59
+ def main(args):
60
+ # load dataset
61
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
62
+
63
+ # for testing: only process the first two examples as a test
64
+ # dataset = dataset.select(range(10))
65
+
66
+ # load processor
67
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
68
+ sampling_rate = feature_extractor.sampling_rate
69
+
70
+ # resample audio
71
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
72
+
73
+ # load eval pipeline
74
+ if args.device is None:
75
+ args.device = 0 if torch.cuda.is_available() else -1
76
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
77
+
78
+ # map function to decode audio
79
+ def map_to_pred(batch):
80
+ prediction = asr(
81
+ batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s
82
+ )
83
+
84
+ batch["prediction"] = prediction["text"]
85
+ batch["target"] = normalize_text(batch["sentence"])
86
+ return batch
87
+
88
+ # run inference on all examples
89
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
90
+
91
+ # compute and log_results
92
+ # do not change function below
93
+ log_results(result, args)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ parser = argparse.ArgumentParser()
98
+
99
+ parser.add_argument(
100
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
101
+ )
102
+ parser.add_argument(
103
+ "--dataset",
104
+ type=str,
105
+ required=True,
106
+ help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
107
+ )
108
+ parser.add_argument(
109
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
110
+ )
111
+ parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
112
+ parser.add_argument(
113
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
114
+ )
115
+ parser.add_argument(
116
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
117
+ )
118
+ parser.add_argument(
119
+ "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
120
+ )
121
+ parser.add_argument(
122
+ "--device",
123
+ type=int,
124
+ default=None,
125
+ help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
126
+ )
127
+ args = parser.parse_args()
128
+
129
+ main(args)