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

asr_etox.py 7.1 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
  1. # Copyright (c) Meta Platforms, Inc. and affiliates
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # MIT_LICENSE file in the root directory of this source tree.
  6. import argparse
  7. import tempfile
  8. import typing as tp
  9. import torchaudio
  10. from tqdm import tqdm
  11. from seamless_communication.cli.eval_utils.compute_metrics import init_whisper_model
  12. from seamless_communication.cli.eval_utils.lang_mapping import LANG3_LANG2
  13. from seamless_communication.inference.translator import Modality
  14. import torch
  15. from pathlib import Path
  16. from seamless_communication.inference import Translator
  17. from fairseq2.data import Collater, DataPipeline, FileMapper
  18. from fairseq2.data.audio import AudioDecoder, WaveformToFbankConverter
  19. from fairseq2.data.text import StrSplitter, read_text
  20. from fairseq2.typing import DataType, Device
  21. from seamless_communication.toxicity import load_etox_bad_word_checker
  22. from whisper.model import Whisper
  23. import logging
  24. logging.basicConfig(
  25. level=logging.INFO,
  26. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  27. )
  28. logger = logging.getLogger(__name__)
  29. def main() -> None:
  30. parser = argparse.ArgumentParser(
  31. description="ASR ETOX will compute the toxicity level of speech inputs."
  32. )
  33. parser.add_argument(
  34. "data_file",
  35. type=Path,
  36. help="Path to the input TSV manifest that list the audio files.",
  37. )
  38. parser.add_argument(
  39. "output_file",
  40. type=Path,
  41. help="Path to a TSV file where to save the results.",
  42. )
  43. parser.add_argument(
  44. "--lang",
  45. type=str,
  46. help="Language, language of the speech to transcribe",
  47. required=True,
  48. )
  49. parser.add_argument(
  50. "--audio_root_dir",
  51. type=str,
  52. help="Root directory for the audio filenames in the data file.",
  53. )
  54. parser.add_argument(
  55. "--audio_column",
  56. type=str,
  57. help="Name of the column where the audiofile is listed in the input tsv.",
  58. default="audio",
  59. )
  60. parser.add_argument(
  61. "--model_name",
  62. type=str,
  63. help=(
  64. "Base model name (`seamlessM4T_medium`, "
  65. "`seamlessM4T_large`, `seamlessM4T_v2_large`), "
  66. " or whisper model, e.g. 'whisper_large'"
  67. ),
  68. default="seamlessM4T_v2_large",
  69. )
  70. parser.add_argument(
  71. "--batch_size",
  72. type=int,
  73. help="Inference batch size.",
  74. default=4,
  75. )
  76. parser.add_argument(
  77. "--n_parallel",
  78. type=int,
  79. help="Number of data loading in parallel.",
  80. default=4,
  81. )
  82. args, _unknown = parser.parse_known_args()
  83. if torch.cuda.is_available():
  84. device = torch.device("cuda:0")
  85. dtype = torch.float16
  86. else:
  87. device = torch.device("cpu")
  88. dtype = torch.float32
  89. whisper_model = None
  90. translator = None
  91. is_whisper = False
  92. if args.model_name.startswith("whisper_"):
  93. logger.info("loading whisper model.")
  94. _, model_name = args.model_name.split("_", maxsplit=1)
  95. whisper_model = init_whisper_model(device, model_name)
  96. is_whisper = True
  97. else:
  98. logger.info(f"loading {args.model_name} model.")
  99. translator = Translator(
  100. args.model_name,
  101. None,
  102. device,
  103. text_tokenizer=None,
  104. dtype=dtype,
  105. input_modality=Modality.SPEECH,
  106. output_modality=Modality.TEXT,
  107. apply_mintox=False,
  108. )
  109. logger.info("loading etox.")
  110. bad_word_checker = load_etox_bad_word_checker("mintox")
  111. pipeline = build_data_pipeline(
  112. data_file=args.data_file,
  113. audio_root_dir=args.audio_root_dir,
  114. batch_size=args.batch_size,
  115. is_whisper=is_whisper,
  116. device=device,
  117. dtype=dtype,
  118. n_parallel=args.n_parallel,
  119. audio_column=args.audio_column,
  120. )
  121. logger.info("running ASR-ETOX.")
  122. with open(args.output_file, "w", encoding="utf-8") as outf:
  123. print("text", "toxicity", "bad_words", file=outf, sep="\t")
  124. for example in tqdm(pipeline, unit="line"):
  125. texts = get_text(
  126. lang=args.lang,
  127. example=example,
  128. whisper_model=whisper_model,
  129. translator=translator,
  130. audio_column=args.audio_column,
  131. )
  132. for t in texts:
  133. bad_words = bad_word_checker.get_bad_words(
  134. text=str(t),
  135. lang=args.lang,
  136. )
  137. print(
  138. t,
  139. len(bad_words),
  140. ",".join(bad_words),
  141. file=outf,
  142. sep="\t",
  143. )
  144. def get_text(
  145. lang: str,
  146. example: tp.Dict[str, tp.Any],
  147. whisper_model: Whisper,
  148. translator: Translator,
  149. audio_column: str,
  150. ):
  151. if whisper_model:
  152. with tempfile.NamedTemporaryFile(suffix=".wav") as temp:
  153. torchaudio.save(
  154. temp.name,
  155. example[audio_column]["data"]["waveform"]["seqs"][0]
  156. .transpose(0, 1)
  157. .cpu(),
  158. int(example[audio_column]["data"]["sample_rate"][0]),
  159. format="wav",
  160. )
  161. results = whisper_model.transcribe(
  162. temp.name,
  163. language=LANG3_LANG2[lang],
  164. )
  165. return [results["text"]]
  166. else:
  167. (text_output, _speech_output) = translator.predict(
  168. example[audio_column]["data"]["fbank"],
  169. "ASR",
  170. lang,
  171. src_lang=lang,
  172. )
  173. return text_output
  174. def build_data_pipeline(
  175. data_file: Path,
  176. audio_root_dir: str,
  177. batch_size: int,
  178. is_whisper: bool,
  179. device: Device,
  180. dtype: DataType,
  181. audio_column: str = "audio",
  182. n_parallel: int = 4,
  183. ) -> DataPipeline:
  184. with data_file.open("r", encoding="utf-8") as f:
  185. header = f.readline().strip("\n").split("\t")
  186. split_tsv = StrSplitter(names=header)
  187. pipeline_builder = read_text(data_file, rtrim=True).skip(1).map(split_tsv)
  188. map_file = FileMapper(root_dir=audio_root_dir, cached_fd_count=10)
  189. pipeline_builder.map(
  190. map_file,
  191. selector=audio_column,
  192. num_parallel_calls=n_parallel,
  193. )
  194. decode_audio = AudioDecoder(dtype=torch.float32, device=device)
  195. convert_to_fbank = WaveformToFbankConverter(
  196. num_mel_bins=80,
  197. waveform_scale=2**15,
  198. channel_last=True,
  199. standardize=True,
  200. device=device,
  201. dtype=dtype,
  202. )
  203. # get tensor in waveform
  204. steps = [decode_audio]
  205. if not is_whisper:
  206. # also get the fbanks
  207. steps.append(convert_to_fbank)
  208. pipeline_builder.map(
  209. steps,
  210. selector=f"{audio_column}.data",
  211. num_parallel_calls=n_parallel,
  212. )
  213. if is_whisper:
  214. # no batching for whisper
  215. pipeline_builder.bucket(bucket_size=batch_size)
  216. collate = Collater(pad_value=0, pad_to_multiple=1)
  217. pipeline_builder.map(collate, num_parallel_calls=n_parallel)
  218. pipeline_builder.prefetch(4)
  219. return pipeline_builder.and_return()
  220. if __name__ == "__main__":
  221. main()
Tip!

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

Comments

Loading...