versae commited on
Commit
a60f2ea
1 Parent(s): b2588d0

Update eval.py

Browse files
Files changed (1) hide show
  1. eval.py +75 -11
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
- dataset_id = "_".join([model_id] + args.dataset.split("/") + [args.config, args.split, lm])
 
 
 
 
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,11 +59,42 @@ def log_results(result: Dataset, args: Dict[str, str]):
49
  result.map(write_to_file, with_indices=True)
50
 
51
 
52
- def normalize_text(text: str, dataset: str) -> str:
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.lower()) + " "
57
 
58
  if dataset.lower().endswith("nst"):
59
  text = text.lower()
@@ -77,11 +118,23 @@ 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
- text = re.sub("<ee(eh)?>", "ĥ", text)
82
- text = re.sub("<mmm?>", "ĥ", text)
83
- text = re.sub("<qq>", "ĥ", text)
84
- text = re.sub("<inaudible>", "ĥ", text)
 
 
 
 
 
 
 
 
 
 
 
 
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 +143,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 +199,7 @@ def main(args):
141
  )
142
 
143
  batch["prediction"] = prediction["text"]
144
- batch["target"] = normalize_text(batch["text"], args.dataset)
145
  return batch
146
 
147
  # run inference on all examples
@@ -167,7 +225,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()
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('<e+h?>', 'ĥ', text)
134
+ text = re.sub('<m+>', 'ĥ', text)
135
+ text = re.sub('<q+>', 'ĥ', text)
136
+ text = re.sub('<inaudible>', 'ĥ', 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
 
199
  )
200
 
201
  batch["prediction"] = prediction["text"]
202
+ batch["target"] = normalize_text(batch[args.text_column], args.dataset)
203
  return batch
204
 
205
  # run inference on all examples
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."
234
+ )
235
  parser.add_argument(
236
  "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
237
  )