Update eval.py
Browse files
eval.py
CHANGED
|
@@ -5,10 +5,14 @@ from typing import Dict
|
|
| 5 |
|
| 6 |
import torch
|
| 7 |
from datasets import Audio, Dataset, load_dataset, load_metric
|
|
|
|
|
|
|
| 8 |
|
| 9 |
from transformers import AutoFeatureExtractor, AutoModelForCTC, pipeline, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM, Wav2Vec2FeatureExtractor
|
| 10 |
# from pyctcdecode import BeamSearchDecoderCTC
|
| 11 |
|
|
|
|
|
|
|
| 12 |
|
| 13 |
def log_results(result: Dataset, args: Dict[str, str]):
|
| 14 |
"""DO NOT CHANGE. This function computes and logs the result metrics."""
|
|
@@ -16,7 +20,11 @@ def log_results(result: Dataset, args: Dict[str, str]):
|
|
| 16 |
log_outputs = args.log_outputs
|
| 17 |
lm = "withLM" if args.use_lm else "noLM"
|
| 18 |
model_id = args.model_id.replace("/", "_").replace(".", "")
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# load metric
|
| 22 |
wer = load_metric("wer")
|
|
@@ -32,6 +40,8 @@ def log_results(result: Dataset, args: Dict[str, 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:
|
|
@@ -49,15 +59,46 @@ def log_results(result: Dataset, args: Dict[str, str]):
|
|
| 49 |
result.map(write_to_file, with_indices=True)
|
| 50 |
|
| 51 |
|
| 52 |
-
def normalize_text(
|
| 53 |
"""DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\'\–\_\\\+\#\/]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
|
| 56 |
-
text = re.sub(chars_to_ignore_regex, "", text
|
| 57 |
|
| 58 |
if dataset.lower().endswith("nst"):
|
| 59 |
text = text.lower()
|
| 60 |
-
text = text.replace("(...
|
| 61 |
text = re.sub('[áàâ]', 'a', text)
|
| 62 |
text = re.sub('[ä]', 'æ', text)
|
| 63 |
text = re.sub('[éèëê]', 'e', text)
|
|
@@ -77,11 +118,22 @@ def normalize_text(text: str, dataset: str) -> str:
|
|
| 77 |
text = re.sub('[ö]', 'ø', text)
|
| 78 |
text = re.sub('[ç]', 'c', text)
|
| 79 |
text = re.sub('[úùüû]', 'u', text)
|
| 80 |
-
text = re.sub('\s', ' ', text)
|
| 81 |
-
|
| 82 |
-
text = re.sub('
|
| 83 |
-
text = re.sub('
|
| 84 |
-
text = re.sub('
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
# # In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
| 87 |
# # note that order is important here!
|
|
@@ -90,13 +142,18 @@ def normalize_text(text: str, dataset: str) -> str:
|
|
| 90 |
# for t in token_sequences_to_ignore:
|
| 91 |
# text = " ".join(text.split(t))
|
| 92 |
|
| 93 |
-
return text
|
| 94 |
|
| 95 |
|
| 96 |
def main(args):
|
| 97 |
# load dataset
|
| 98 |
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
# for testing: only process the first two examples as a test
|
| 101 |
# dataset = dataset.select(range(10))
|
| 102 |
|
|
@@ -141,7 +198,7 @@ def main(args):
|
|
| 141 |
)
|
| 142 |
|
| 143 |
batch["prediction"] = prediction["text"]
|
| 144 |
-
batch["target"] = normalize_text(batch[
|
| 145 |
return batch
|
| 146 |
|
| 147 |
# run inference on all examples
|
|
@@ -167,7 +224,13 @@ if __name__ == "__main__":
|
|
| 167 |
parser.add_argument(
|
| 168 |
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
| 169 |
)
|
|
|
|
|
|
|
|
|
|
| 170 |
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
|
|
|
|
|
|
|
|
|
|
| 171 |
parser.add_argument(
|
| 172 |
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
|
| 173 |
)
|
|
|
|
| 5 |
|
| 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()
|
| 101 |
+
text = text.replace("(...vær stille under dette opptaket...)", "")
|
| 102 |
text = re.sub('[áàâ]', 'a', text)
|
| 103 |
text = re.sub('[ä]', 'æ', text)
|
| 104 |
text = re.sub('[éèëê]', 'e', text)
|
|
|
|
| 118 |
text = re.sub('[ö]', 'ø', text)
|
| 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)
|
| 126 |
+
text = re.sub('[íìïî]', 'i', text)
|
| 127 |
+
text = re.sub('[óòöô]', 'o', 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('<ee>', 'eee', text)
|
| 134 |
+
text = re.sub('<qq>', 'qqq', text)
|
| 135 |
+
text = re.sub('<mm>', 'mmm', text)
|
| 136 |
+
text = re.sub('<inaudible>', 'xxx', text)
|
| 137 |
|
| 138 |
# # In addition, we can normalize the target text, e.g. removing new lines characters etc...
|
| 139 |
# # note that order is important here!
|
|
|
|
| 142 |
# for t in token_sequences_to_ignore:
|
| 143 |
# text = " ".join(text.split(t))
|
| 144 |
|
| 145 |
+
return text.strip()
|
| 146 |
|
| 147 |
|
| 148 |
def main(args):
|
| 149 |
# load dataset
|
| 150 |
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
| 151 |
+
if args.filter:
|
| 152 |
+
attribute, value = list(map(str.strip, args.filter.split(":")))
|
| 153 |
+
dataset = dataset.filter(
|
| 154 |
+
lambda x: x[attribute] == value,
|
| 155 |
+
desc=f"Filtering on {args.filter}",
|
| 156 |
+
)
|
| 157 |
# for testing: only process the first two examples as a test
|
| 158 |
# dataset = dataset.select(range(10))
|
| 159 |
|
|
|
|
| 198 |
)
|
| 199 |
|
| 200 |
batch["prediction"] = prediction["text"]
|
| 201 |
+
batch["target"] = normalize_text(batch[args.text_column], args.dataset)
|
| 202 |
return batch
|
| 203 |
|
| 204 |
# run inference on all examples
|
|
|
|
| 224 |
parser.add_argument(
|
| 225 |
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
| 226 |
)
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"--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"
|
| 229 |
+
)
|
| 230 |
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--text_column", type=str, default="text", help="Column name containing the transcription."
|
| 233 |
+
)
|
| 234 |
parser.add_argument(
|
| 235 |
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
|
| 236 |
)
|