Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

eval.py 5.5 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...