vutankiet2901 commited on
Commit
18c7dbf
1 Parent(s): b0be33d

Upload eval.py

Browse files
Files changed (1) hide show
  1. eval.py +138 -0
eval.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import MeCab
9
+ import pykakasi
10
+ import torch
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 = (
28
+ f"WER: {wer_result}\n"
29
+ f"CER: {cer_result}"
30
+ )
31
+ print(result_str)
32
+
33
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
34
+ f.write(result_str)
35
+
36
+ # log all results in text file. Possibly interesting for analysis
37
+ if log_outputs is not None:
38
+ pred_file = f"log_{dataset_id}_predictions.txt"
39
+ target_file = f"log_{dataset_id}_targets.txt"
40
+
41
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
42
+
43
+ # mapping function to write output
44
+ def write_to_file(batch, i):
45
+ p.write(f"{i}" + "\n")
46
+ p.write(batch["prediction"] + "\n")
47
+ t.write(f"{i}" + "\n")
48
+ t.write(batch["target"] + "\n")
49
+
50
+ result.map(write_to_file, with_indices=True)
51
+
52
+
53
+ def normalize_text(text: str) -> str:
54
+ """ DO ADAPT FOR YOUR USE CASE. this function normalizes the target text. """
55
+
56
+ chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\‘\”\�\‘\、\。\.\!\,\・\―\─\~\「\」\『\』\〆\。\※\[\]\{\}\「\」\〇\?\…\=\+\〜\'\-\・\(\)\/\—\`\’\–]'
57
+ FULLWIDTH_TO_HALFWIDTH = str.maketrans(
58
+ ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!゛#$%&()*+、ー。/:;〈=〉?@[]^_‘{|}~',
59
+ ' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@[]^_`{|}~',
60
+ )
61
+ wakati = MeCab.Tagger("-Owakati")
62
+ kakasi = pykakasi.kakasi()
63
+ kakasi.setMode("J","H") # kanji to hiragana
64
+ kakasi.setMode("K","H") # katakana to hiragana
65
+ conv = kakasi.getConverter()
66
+
67
+ def fullwidth_to_halfwidth(s):
68
+ return s.translate(FULLWIDTH_TO_HALFWIDTH)
69
+
70
+ text = fullwidth_to_halfwidth(text)
71
+ text = re.sub(chars_to_ignore_regex, " ", text).lower()
72
+ text = wakati.parse(text)
73
+ text = conv.do(text)
74
+ text = " ".join(text.split()) + " "
75
+ return text
76
+
77
+
78
+ def main(args):
79
+ # load dataset
80
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
81
+
82
+ # for testing: only process the first two examples as a test
83
+ # dataset = dataset.select(range(10))
84
+
85
+ # load processor
86
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
87
+ sampling_rate = feature_extractor.sampling_rate
88
+
89
+ # resample audio
90
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
91
+
92
+ # load eval pipeline
93
+ device = torch.cuda.current_device() if torch.cuda.is_available() else -1
94
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device = device)
95
+
96
+ # map function to decode audio
97
+ def map_to_pred(batch):
98
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
99
+
100
+ batch["prediction"] = prediction["text"]
101
+ batch["target"] = normalize_text(batch["sentence"])
102
+ return batch
103
+
104
+ # run inference on all examples
105
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
106
+
107
+ # compute and log_results
108
+ # do not change function below
109
+ log_results(result, args)
110
+
111
+
112
+ if __name__ == "__main__":
113
+ parser = argparse.ArgumentParser()
114
+
115
+ parser.add_argument(
116
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
117
+ )
118
+ parser.add_argument(
119
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
120
+ )
121
+ parser.add_argument(
122
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
123
+ )
124
+ parser.add_argument(
125
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
126
+ )
127
+ parser.add_argument(
128
+ "--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."
129
+ )
130
+ parser.add_argument(
131
+ "--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."
132
+ )
133
+ parser.add_argument(
134
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
135
+ )
136
+ args = parser.parse_args()
137
+
138
+ main(args)