Spaces:
Runtime error
Runtime error
zahoor54321
commited on
Commit
•
ac24b67
1
Parent(s):
58ebc86
Create eval.py
Browse files
eval.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
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(
|
24 |
+
references=result["target"], predictions=result["prediction"]
|
25 |
+
)
|
26 |
+
cer_result = cer.compute(
|
27 |
+
references=result["target"], predictions=result["prediction"]
|
28 |
+
)
|
29 |
+
|
30 |
+
# print & log results
|
31 |
+
result_str = f"WER: {wer_result}\n" f"CER: {cer_result}"
|
32 |
+
print(result_str)
|
33 |
+
|
34 |
+
with open(f"{dataset_id}_eval_results.txt", "w") as f:
|
35 |
+
f.write(result_str)
|
36 |
+
|
37 |
+
# log all results in text file. Possibly interesting for analysis
|
38 |
+
if log_outputs is not None:
|
39 |
+
pred_file = f"log_{dataset_id}_predictions.txt"
|
40 |
+
target_file = f"log_{dataset_id}_targets.txt"
|
41 |
+
|
42 |
+
with open(pred_file, "w") as p, open(target_file, "w") as t:
|
43 |
+
|
44 |
+
# mapping function to write output
|
45 |
+
def write_to_file(batch, i):
|
46 |
+
p.write(f"{i}" + "\n")
|
47 |
+
p.write(batch["prediction"] + "\n")
|
48 |
+
t.write(f"{i}" + "\n")
|
49 |
+
t.write(batch["target"] + "\n")
|
50 |
+
|
51 |
+
result.map(write_to_file, with_indices=True)
|
52 |
+
|
53 |
+
|
54 |
+
def normalize_text(text: str) -> str:
|
55 |
+
"""DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
|
56 |
+
|
57 |
+
chars_to_ignore_regex = """[\!\؛\،\٫\؟\۔\٪\"\'\:\-\‘\’]""" # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
|
58 |
+
|
59 |
+
text = re.sub(chars_to_ignore_regex, "", text.lower())
|
60 |
+
text = re.sub("[،]", "", text)
|
61 |
+
text = re.sub("[؟]", "", text)
|
62 |
+
text = re.sub("['َ]", "", text)
|
63 |
+
text = re.sub("['ُ]", "", text)
|
64 |
+
text = re.sub("['ِ]", "", text)
|
65 |
+
text = re.sub("['ّ]", "", text)
|
66 |
+
text = re.sub("['ٔ]", "", text)
|
67 |
+
text = re.sub("['ٰ]", "", text)
|
68 |
+
text = re.sub("[ۂ]", "ہ", text)
|
69 |
+
text = re.sub("[ي]", "ی", text)
|
70 |
+
text = re.sub("[ؤ]", "و", text)
|
71 |
+
# batch["sentence"] = re.sub("[ئ]", 'ى', batch["sentence"])
|
72 |
+
text = re.sub("[ى]", "ی", text)
|
73 |
+
text = re.sub("[۔]", "", text)
|
74 |
+
|
75 |
+
# In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
76 |
+
# note that order is important here!
|
77 |
+
token_sequences_to_ignore = ["\n\n", "\n", " ", " "]
|
78 |
+
|
79 |
+
for t in token_sequences_to_ignore:
|
80 |
+
text = " ".join(text.split(t))
|
81 |
+
|
82 |
+
return text
|
83 |
+
|
84 |
+
|
85 |
+
def path_adjust(batch):
|
86 |
+
batch["path"] = "Data/ur/clips/" + str(batch["path"])
|
87 |
+
return batch
|
88 |
+
|
89 |
+
|
90 |
+
def main(args):
|
91 |
+
# load dataset
|
92 |
+
dataset = load_dataset(args.dataset, args.config, delimiter="\t", split=args.split)
|
93 |
+
|
94 |
+
# for testing: only process the first two examples as a test
|
95 |
+
# dataset = dataset.select(range(10))
|
96 |
+
|
97 |
+
# load processor
|
98 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
|
99 |
+
sampling_rate = feature_extractor.sampling_rate
|
100 |
+
|
101 |
+
# resample audio
|
102 |
+
dataset = dataset.map(path_adjust)
|
103 |
+
dataset = dataset.cast_column("path", Audio(sampling_rate=sampling_rate))
|
104 |
+
|
105 |
+
# load eval pipeline
|
106 |
+
if args.device is None:
|
107 |
+
args.device = 0 if torch.cuda.is_available() else -1
|
108 |
+
asr = pipeline(
|
109 |
+
"automatic-speech-recognition", model=args.model_id, device=args.device
|
110 |
+
)
|
111 |
+
|
112 |
+
# map function to decode audio
|
113 |
+
def map_to_pred(batch):
|
114 |
+
prediction = asr(
|
115 |
+
batch["path"]["array"],
|
116 |
+
chunk_length_s=args.chunk_length_s,
|
117 |
+
stride_length_s=args.stride_length_s,
|
118 |
+
)
|
119 |
+
|
120 |
+
batch["prediction"] = prediction["text"]
|
121 |
+
batch["target"] = normalize_text(batch["sentence"])
|
122 |
+
return batch
|
123 |
+
|
124 |
+
# run inference on all examples
|
125 |
+
result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
|
126 |
+
|
127 |
+
# compute and log_results
|
128 |
+
# do not change function below
|
129 |
+
log_results(result, args)
|
130 |
+
|
131 |
+
|
132 |
+
if __name__ == "__main__":
|
133 |
+
parser = argparse.ArgumentParser()
|
134 |
+
|
135 |
+
parser.add_argument(
|
136 |
+
"--model_id",
|
137 |
+
type=str,
|
138 |
+
required=True,
|
139 |
+
help="Model identifier. Should be loadable with 🤗 Transformers",
|
140 |
+
)
|
141 |
+
parser.add_argument(
|
142 |
+
"--dataset",
|
143 |
+
type=str,
|
144 |
+
required=True,
|
145 |
+
help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
|
146 |
+
)
|
147 |
+
parser.add_argument(
|
148 |
+
"--config",
|
149 |
+
type=str,
|
150 |
+
required=True,
|
151 |
+
help="Config of the dataset. *E.g.* `'en'` for Common Voice",
|
152 |
+
)
|
153 |
+
parser.add_argument(
|
154 |
+
"--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
|
155 |
+
)
|
156 |
+
parser.add_argument(
|
157 |
+
"--chunk_length_s",
|
158 |
+
type=float,
|
159 |
+
default=None,
|
160 |
+
help="Chunk length in seconds. Defaults to 5 seconds.",
|
161 |
+
)
|
162 |
+
parser.add_argument(
|
163 |
+
"--stride_length_s",
|
164 |
+
type=float,
|
165 |
+
default=None,
|
166 |
+
help="Stride of the audio chunks. Defaults to 1 second.",
|
167 |
+
)
|
168 |
+
parser.add_argument(
|
169 |
+
"--log_outputs",
|
170 |
+
action="store_true",
|
171 |
+
help="If defined, write outputs to log file for analysis.",
|
172 |
+
)
|
173 |
+
parser.add_argument(
|
174 |
+
"--device",
|
175 |
+
type=int,
|
176 |
+
default=None,
|
177 |
+
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
|
178 |
+
)
|
179 |
+
args = parser.parse_args()
|
180 |
+
|
181 |
+
main(args)
|