Update eval.py
Browse files
eval.py
CHANGED
@@ -6,10 +6,13 @@ from typing import Dict
|
|
6 |
import torch
|
7 |
from datasets import Audio, Dataset, load_dataset, load_metric
|
8 |
from num2words import num2words as n2w
|
|
|
9 |
|
10 |
from transformers import AutoFeatureExtractor, AutoModelForCTC, pipeline, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM, Wav2Vec2FeatureExtractor
|
11 |
# from pyctcdecode import BeamSearchDecoderCTC
|
12 |
|
|
|
|
|
13 |
|
14 |
def log_results(result: Dataset, args: Dict[str, str]):
|
15 |
"""DO NOT CHANGE. This function computes and logs the result metrics."""
|
@@ -17,7 +20,11 @@ def log_results(result: Dataset, args: Dict[str, str]):
|
|
17 |
log_outputs = args.log_outputs
|
18 |
lm = "withLM" if args.use_lm else "noLM"
|
19 |
model_id = args.model_id.replace("/", "_").replace(".", "")
|
20 |
-
|
|
|
|
|
|
|
|
|
21 |
|
22 |
# load metric
|
23 |
wer = load_metric("wer")
|
@@ -33,6 +40,8 @@ def log_results(result: Dataset, args: Dict[str, 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:
|
@@ -50,11 +59,42 @@ def log_results(result: Dataset, args: Dict[str, str]):
|
|
50 |
result.map(write_to_file, with_indices=True)
|
51 |
|
52 |
|
53 |
-
def normalize_text(
|
54 |
"""DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
|
55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
|
57 |
-
text = re.sub(chars_to_ignore_regex, "", text
|
58 |
|
59 |
if dataset.lower().endswith("nst"):
|
60 |
text = text.lower()
|
@@ -79,7 +119,7 @@ def normalize_text(text: str, dataset: str) -> str:
|
|
79 |
text = re.sub('[ç]', 'c', text)
|
80 |
text = re.sub('[úùüû]', 'u', text)
|
81 |
text = re.sub('\s+', ' ', text)
|
82 |
-
elif dataset.lower().endswith("fleurs"):
|
83 |
text = re.sub('[áàâ]', 'a', text)
|
84 |
text = re.sub('[ä]', 'æ', text)
|
85 |
text = re.sub('[éèëê]', 'e', text)
|
@@ -88,12 +128,13 @@ def normalize_text(text: str, dataset: str) -> str:
|
|
88 |
text = re.sub('[ö]', 'ø', text)
|
89 |
text = re.sub('[ç]', 'c', text)
|
90 |
text = re.sub('[úùüû]', 'u', text)
|
91 |
-
text = re.
|
92 |
text = re.sub('\s+', ' ', text)
|
93 |
-
text = re.sub('<
|
94 |
-
text = re.sub('<
|
95 |
-
text = re.sub('<
|
96 |
text = re.sub('<inaudible>', 'xxx', text)
|
|
|
97 |
|
98 |
# # In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
99 |
# # note that order is important here!
|
@@ -102,13 +143,18 @@ def normalize_text(text: str, dataset: str) -> str:
|
|
102 |
# for t in token_sequences_to_ignore:
|
103 |
# text = " ".join(text.split(t))
|
104 |
|
105 |
-
return text
|
106 |
|
107 |
|
108 |
def main(args):
|
109 |
# load dataset
|
110 |
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
112 |
# for testing: only process the first two examples as a test
|
113 |
# dataset = dataset.select(range(10))
|
114 |
|
@@ -179,6 +225,9 @@ if __name__ == "__main__":
|
|
179 |
parser.add_argument(
|
180 |
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
181 |
)
|
|
|
|
|
|
|
182 |
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
|
183 |
parser.add_argument(
|
184 |
"--text_column", type=str, default="text", help="Column name containing the transcription."
|
|
|
6 |
import torch
|
7 |
from datasets import Audio, Dataset, load_dataset, load_metric
|
8 |
from num2words import num2words as n2w
|
9 |
+
from slugify import slugify
|
10 |
|
11 |
from transformers import AutoFeatureExtractor, AutoModelForCTC, pipeline, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM, Wav2Vec2FeatureExtractor
|
12 |
# from pyctcdecode import BeamSearchDecoderCTC
|
13 |
|
14 |
+
from cardinal_numbers import convert_nums
|
15 |
+
|
16 |
|
17 |
def log_results(result: Dataset, args: Dict[str, str]):
|
18 |
"""DO NOT CHANGE. This function computes and logs the result metrics."""
|
|
|
20 |
log_outputs = args.log_outputs
|
21 |
lm = "withLM" if args.use_lm else "noLM"
|
22 |
model_id = args.model_id.replace("/", "_").replace(".", "")
|
23 |
+
if args.filter:
|
24 |
+
extra_args = [args.config, slugify(args.filter), args.split, lm]
|
25 |
+
else:
|
26 |
+
extra_args = [args.config, args.split, lm]
|
27 |
+
dataset_id = "_".join([model_id] + args.dataset.split("/") + extra_args)
|
28 |
|
29 |
# load metric
|
30 |
wer = load_metric("wer")
|
|
|
40 |
|
41 |
with open(f"{dataset_id}_eval_results.txt", "w") as f:
|
42 |
f.write(result_str)
|
43 |
+
with open(f"{dataset_id}_eval_results.tsv", "w") as f:
|
44 |
+
f.write("\t".join([args.model_id, args.dataset, args.config, args.filter, args.split, str(lm), str(wer_result), str(cer_result)]))
|
45 |
|
46 |
# log all results in text file. Possibly interesting for analysis
|
47 |
if log_outputs is not None:
|
|
|
59 |
result.map(write_to_file, with_indices=True)
|
60 |
|
61 |
|
62 |
+
def normalize_text(original_text: str, dataset: str) -> str:
|
63 |
"""DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
|
64 |
|
65 |
+
text = original_text.lower()
|
66 |
+
if dataset.lower().endswith("fleurs"):
|
67 |
+
replacements = (
|
68 |
+
(r"\be\.kr", "etter kristus fødsel"),
|
69 |
+
(r"\bf\.kr", "før kristi fødsel"),
|
70 |
+
(r"\bca[.]?\b", "circa"),
|
71 |
+
(r"(\d)\s*km/t", r"\1 kilometer i timen"),
|
72 |
+
(r"(\d)\s*km", r"\1 kilometer"),
|
73 |
+
(r"(\d)\s*cm", r"\1 centimeter"),
|
74 |
+
(r"(\d)\s*mm", r"\1 millimeter"),
|
75 |
+
(r"kl\.", "klokka"),
|
76 |
+
(r"f\.eks", "for eksempel"),
|
77 |
+
)
|
78 |
+
for abrev, expasion in replacements:
|
79 |
+
text = re.sub(abrev, expasion, text)
|
80 |
+
text = re.sub(r'(\d+)[-–](\d+)', r'\1 til \2', text) # 1-89, 70-90
|
81 |
+
text = re.sub(r'(\d{2}):00', r'\1', text) # 21:00
|
82 |
+
text = re.sub(r"(\d{2}):0(\d{1})", r"\1 null \2", text) # 17:03
|
83 |
+
text = re.sub(r"(\d{1,2}):(\d{1,2})", r"\1 \2", text) # 17:23 (time), 4:3 (aspect ratios)
|
84 |
+
text = re.sub(r"(1[1-9])00", r"\1 hundre", text) # 1800, 1900
|
85 |
+
text = re.sub(r"(1[1-9])0([1-9])", r"\1 null \2 ", text) # 1901, 1909
|
86 |
+
text = re.sub(r"(1[1-9])([1-9]\d)", r"\1 \2 ", text) # 1911, 1987
|
87 |
+
text = re.sub(r"(20)0([1-9])", r"\1 null \2 ", text) # 2009
|
88 |
+
text = re.sub(r"(20)(\d{2})", r"\1 \2 ", text) # 2009
|
89 |
+
text = re.sub(r"(\d{1,3})[.](\d{1,2})", r"\1 dot \2 ", text) # 802.11n, 2.5ghz (in English)
|
90 |
+
text = re.sub(r"(\d{1,2})[ .](\d{3})", r"\1\2", text) # 10 000, 32.000
|
91 |
+
text = re.sub(r'(\w+)-(\w+)', r'\1 \2', text) # n-standard
|
92 |
+
# text = re.compile(r"-?0?[1-9][\d.]*").sub(lambda x: n2w(x.group(0), lang="no"), text.replace(".", ""))
|
93 |
+
text = re.compile(r"-?0?[1-9][\d.]*").sub(lambda x: convert_nums(int(x.group(0)), nn=True), text.replace(".", ""))
|
94 |
+
|
95 |
+
|
96 |
chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
|
97 |
+
text = re.sub(chars_to_ignore_regex, "", text) + " "
|
98 |
|
99 |
if dataset.lower().endswith("nst"):
|
100 |
text = text.lower()
|
|
|
119 |
text = re.sub('[ç]', 'c', text)
|
120 |
text = re.sub('[úùüû]', 'u', text)
|
121 |
text = re.sub('\s+', ' ', text)
|
122 |
+
elif dataset.lower().endswith("fleurs"):
|
123 |
text = re.sub('[áàâ]', 'a', text)
|
124 |
text = re.sub('[ä]', 'æ', text)
|
125 |
text = re.sub('[éèëê]', 'e', text)
|
|
|
128 |
text = re.sub('[ö]', 'ø', text)
|
129 |
text = re.sub('[ç]', 'c', text)
|
130 |
text = re.sub('[úùüû]', 'u', text)
|
131 |
+
text = re.sub('[«»]', '', text)
|
132 |
text = re.sub('\s+', ' ', text)
|
133 |
+
text = re.sub('<e+h?>', 'eee', text)
|
134 |
+
text = re.sub('<m+>', 'mmm', text)
|
135 |
+
text = re.sub('<q+>', 'qqq', text)
|
136 |
text = re.sub('<inaudible>', 'xxx', text)
|
137 |
+
text = re.sub('[<>]', '', text)
|
138 |
|
139 |
# # In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
140 |
# # note that order is important here!
|
|
|
143 |
# for t in token_sequences_to_ignore:
|
144 |
# text = " ".join(text.split(t))
|
145 |
|
146 |
+
return text.strip()
|
147 |
|
148 |
|
149 |
def main(args):
|
150 |
# load dataset
|
151 |
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
152 |
+
if args.filter:
|
153 |
+
attribute, value = list(map(str.strip, args.filter.split(":")))
|
154 |
+
dataset = dataset.filter(
|
155 |
+
lambda x: x[attribute] == value,
|
156 |
+
desc=f"Filtering on {args.filter}",
|
157 |
+
)
|
158 |
# for testing: only process the first two examples as a test
|
159 |
# dataset = dataset.select(range(10))
|
160 |
|
|
|
225 |
parser.add_argument(
|
226 |
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
227 |
)
|
228 |
+
parser.add_argument(
|
229 |
+
"--filter", type=str, default="", help="Simple filter on attributes. *E.g.* `region_of_youth:Troms` would pnly keep those samplesfor which the condition is met"
|
230 |
+
)
|
231 |
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
|
232 |
parser.add_argument(
|
233 |
"--text_column", type=str, default="text", help="Column name containing the transcription."
|