add eval_kenlm.py
Browse files- eval_kenlm.py +165 -0
eval_kenlm.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, Wav2Vec2ForCTC, Wav2Vec2Processor, set_seed
|
10 |
+
from pyctcdecode import build_ctcdecoder
|
11 |
+
from multiprocessing import Pool
|
12 |
+
|
13 |
+
class KenLM:
|
14 |
+
def __init__(self, tokenizer, model_name, unigrams=None, num_workers=8, beam_width=128):
|
15 |
+
self.num_workers = num_workers
|
16 |
+
self.beam_width = beam_width
|
17 |
+
vocab_dict = tokenizer.get_vocab()
|
18 |
+
self.vocabulary = [x[0] for x in sorted(vocab_dict.items(), key=lambda x: x[1], reverse=False)]
|
19 |
+
self.vocabulary = self.vocabulary[:-1]
|
20 |
+
self.decoder = build_ctcdecoder(self.vocabulary, model_name, unigrams=unigrams)
|
21 |
+
|
22 |
+
@staticmethod
|
23 |
+
def lm_postprocess(text):
|
24 |
+
return ' '.join([x if len(x) > 1 else "" for x in text.split()]).strip()
|
25 |
+
|
26 |
+
def decode(self, logits):
|
27 |
+
probs = logits.cpu().numpy()
|
28 |
+
# probs = logits.numpy()
|
29 |
+
with Pool(self.num_workers) as pool:
|
30 |
+
text = self.decoder.decode_batch(pool, probs)
|
31 |
+
text = [KenLM.lm_postprocess(x) for x in text]
|
32 |
+
return text
|
33 |
+
|
34 |
+
def log_results(result: Dataset, args: Dict[str, str]):
|
35 |
+
"""DO NOT CHANGE. This function computes and logs the result metrics."""
|
36 |
+
|
37 |
+
log_outputs = args.log_outputs
|
38 |
+
dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
|
39 |
+
|
40 |
+
# load metric
|
41 |
+
wer = load_metric("wer")
|
42 |
+
cer = load_metric("cer")
|
43 |
+
|
44 |
+
# compute metrics
|
45 |
+
wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
|
46 |
+
cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
|
47 |
+
|
48 |
+
# print & log results
|
49 |
+
result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
|
50 |
+
print(result_str)
|
51 |
+
|
52 |
+
with open(f"{dataset_id}_eval_results.txt", "w") as f:
|
53 |
+
f.write(result_str)
|
54 |
+
|
55 |
+
# log all results in text file. Possibly interesting for analysis
|
56 |
+
if log_outputs is not None:
|
57 |
+
pred_file = f"log_{dataset_id}_predictions.txt"
|
58 |
+
target_file = f"log_{dataset_id}_targets.txt"
|
59 |
+
|
60 |
+
with open(pred_file, "w") as p, open(target_file, "w") as t:
|
61 |
+
|
62 |
+
# mapping function to write output
|
63 |
+
def write_to_file(batch, i):
|
64 |
+
p.write(f"{i}" + "\n")
|
65 |
+
p.write(batch["prediction"] + "\n")
|
66 |
+
t.write(f"{i}" + "\n")
|
67 |
+
t.write(batch["target"] + "\n")
|
68 |
+
|
69 |
+
result.map(write_to_file, with_indices=True)
|
70 |
+
|
71 |
+
|
72 |
+
def normalize_text(text: str) -> str:
|
73 |
+
"""DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
|
74 |
+
chars_to_ignore_regex = '[,?.!-;:""%\'"\'\'`…’»«‘“”�éû]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
|
75 |
+
|
76 |
+
text = re.sub(chars_to_ignore_regex, "", text.lower())
|
77 |
+
|
78 |
+
# In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
79 |
+
# note that order is important here!
|
80 |
+
token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
|
81 |
+
|
82 |
+
for t in token_sequences_to_ignore:
|
83 |
+
text = " ".join(text.split(t))
|
84 |
+
|
85 |
+
return text
|
86 |
+
|
87 |
+
|
88 |
+
def main(args):
|
89 |
+
# load dataset
|
90 |
+
dataset = load_dataset(args.dataset, args.config, data_dir=args.data_dir, split=args.split, use_auth_token=True)
|
91 |
+
|
92 |
+
# for testing: only process the first two examples as a test
|
93 |
+
# dataset = dataset.select(range(10))
|
94 |
+
|
95 |
+
# load processor
|
96 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
|
97 |
+
sampling_rate = feature_extractor.sampling_rate
|
98 |
+
|
99 |
+
# resample audio
|
100 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
|
101 |
+
|
102 |
+
# load eval pipeline
|
103 |
+
if args.device is None:
|
104 |
+
args.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
105 |
+
|
106 |
+
set_seed(42) # set the random seed to have reproducible result.
|
107 |
+
processor = Wav2Vec2Processor.from_pretrained(args.model_id)
|
108 |
+
model = Wav2Vec2ForCTC.from_pretrained(args.model_id)
|
109 |
+
kenlm = KenLM(processor.tokenizer, "language_model/5gram.bin", unigrams="language_model/unigrams.txt")
|
110 |
+
|
111 |
+
# map function to decode audio
|
112 |
+
def map_to_pred(batch):
|
113 |
+
inputs = processor(batch["audio"]["array"], sampling_rate=16_000, return_tensors="pt", padding=True)
|
114 |
+
with torch.no_grad():
|
115 |
+
logits = model(inputs.input_values.to(args.device), attention_mask=inputs.attention_mask.to(args.device)).logits
|
116 |
+
prediction = kenlm.decode(logits)
|
117 |
+
|
118 |
+
batch["prediction"] = prediction
|
119 |
+
batch["target"] = normalize_text(batch["sentence"])
|
120 |
+
return batch
|
121 |
+
|
122 |
+
# run inference on all examples
|
123 |
+
result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
|
124 |
+
|
125 |
+
# compute and log_results
|
126 |
+
# do not change function below
|
127 |
+
log_results(result, args)
|
128 |
+
|
129 |
+
|
130 |
+
if __name__ == "__main__":
|
131 |
+
parser = argparse.ArgumentParser()
|
132 |
+
|
133 |
+
parser.add_argument(
|
134 |
+
"--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
|
135 |
+
)
|
136 |
+
parser.add_argument(
|
137 |
+
"--dataset",
|
138 |
+
type=str,
|
139 |
+
required=True,
|
140 |
+
help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
|
141 |
+
)
|
142 |
+
parser.add_argument(
|
143 |
+
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
144 |
+
)
|
145 |
+
parser.add_argument("--data_dir", type=str, required=False, default=None,
|
146 |
+
help="The directory contains the dataset")
|
147 |
+
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
|
148 |
+
parser.add_argument(
|
149 |
+
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
|
150 |
+
)
|
151 |
+
parser.add_argument(
|
152 |
+
"--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
|
153 |
+
)
|
154 |
+
parser.add_argument(
|
155 |
+
"--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
|
156 |
+
)
|
157 |
+
parser.add_argument(
|
158 |
+
"--device",
|
159 |
+
type=int,
|
160 |
+
default=None,
|
161 |
+
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
|
162 |
+
)
|
163 |
+
args = parser.parse_args()
|
164 |
+
|
165 |
+
main(args)
|