vumichien commited on
Commit
c798ce8
1 Parent(s): 322be16

Upload eval.py

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