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

predict.py 7.6 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
256
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. #
  3. # This source code is licensed under the license found in the
  4. # MIT_LICENSE file in the root directory of this source tree.
  5. import argparse
  6. import logging
  7. from argparse import Namespace
  8. from pathlib import Path
  9. from typing import Tuple
  10. import torch
  11. import torchaudio
  12. from fairseq2.generation import NGramRepeatBlockProcessor
  13. from seamless_communication.inference import SequenceGeneratorOptions, Translator
  14. logging.basicConfig(
  15. level=logging.INFO,
  16. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  17. )
  18. logger = logging.getLogger(__name__)
  19. def add_inference_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
  20. parser.add_argument(
  21. "--task",
  22. type=str,
  23. choices=["ASR", "S2ST", "S2TT"],
  24. help=(
  25. "* `ASR` -- automatic speech recognition (transcription);"
  26. "* `S2ST` -- speech to speech translation;"
  27. "* `S2TT` -- speech to text translation;"
  28. )
  29. )
  30. parser.add_argument(
  31. "--tgt_lang", type=str, help="Target language to translate/transcribe into."
  32. )
  33. parser.add_argument(
  34. "--src_lang",
  35. type=str,
  36. help="Source language, only required if input is text.",
  37. default=None,
  38. )
  39. parser.add_argument(
  40. "--output_path",
  41. type=Path,
  42. help="Path to save the generated audio.",
  43. default=None,
  44. )
  45. parser.add_argument(
  46. "--model_name",
  47. type=str,
  48. help=(
  49. "Base model name (`seamlessM4T_medium`, "
  50. "`seamlessM4T_large`, `seamlessM4T_v2_large`)"
  51. ),
  52. default="seamlessM4T_v2_large",
  53. )
  54. parser.add_argument(
  55. "--vocoder_name",
  56. type=str,
  57. help="Vocoder model name",
  58. default="vocoder_v2",
  59. )
  60. # Text generation args.
  61. parser.add_argument(
  62. "--text_generation_beam_size",
  63. type=int,
  64. help="Beam size for incremental text decoding.",
  65. default=5,
  66. )
  67. parser.add_argument(
  68. "--text_generation_max_len_a",
  69. type=int,
  70. help="`a` in `ax + b` for incremental text decoding.",
  71. default=1,
  72. )
  73. parser.add_argument(
  74. "--text_generation_max_len_b",
  75. type=int,
  76. help="`b` in `ax + b` for incremental text decoding.",
  77. default=200,
  78. )
  79. parser.add_argument(
  80. "--text_generation_ngram_blocking",
  81. type=bool,
  82. help=(
  83. "Enable ngram_repeat_block for incremental text decoding."
  84. "This blocks hypotheses with repeating ngram tokens."
  85. ),
  86. default=False,
  87. )
  88. parser.add_argument(
  89. "--no_repeat_ngram_size",
  90. type=int,
  91. help="Size of ngram repeat block for both text & unit decoding.",
  92. default=4,
  93. )
  94. # Unit generation args.
  95. parser.add_argument(
  96. "--unit_generation_beam_size",
  97. type=int,
  98. help=(
  99. "Beam size for incremental unit decoding"
  100. "not applicable for the NAR T2U decoder."
  101. ),
  102. default=5,
  103. )
  104. parser.add_argument(
  105. "--unit_generation_max_len_a",
  106. type=int,
  107. help=(
  108. "`a` in `ax + b` for incremental unit decoding"
  109. "not applicable for the NAR T2U decoder."
  110. ),
  111. default=25,
  112. )
  113. parser.add_argument(
  114. "--unit_generation_max_len_b",
  115. type=int,
  116. help=(
  117. "`b` in `ax + b` for incremental unit decoding"
  118. "not applicable for the NAR T2U decoder."
  119. ),
  120. default=50,
  121. )
  122. parser.add_argument(
  123. "--unit_generation_ngram_blocking",
  124. type=bool,
  125. help=(
  126. "Enable ngram_repeat_block for incremental unit decoding."
  127. "This blocks hypotheses with repeating ngram tokens."
  128. ),
  129. default=False,
  130. )
  131. parser.add_argument(
  132. "--unit_generation_ngram_filtering",
  133. type=bool,
  134. help=(
  135. "If True, removes consecutive repeated ngrams"
  136. "from the decoded unit output."
  137. ),
  138. default=False,
  139. )
  140. parser.add_argument(
  141. "--text_unk_blocking",
  142. type=bool,
  143. help=(
  144. "If True, set penalty of UNK to inf in text generator "
  145. "to block unk output."
  146. ),
  147. default=False,
  148. )
  149. return parser
  150. def set_generation_opts(
  151. args: Namespace,
  152. ) -> Tuple[SequenceGeneratorOptions, SequenceGeneratorOptions]:
  153. # Set text, unit generation opts.
  154. text_generation_opts = SequenceGeneratorOptions(
  155. beam_size=args.text_generation_beam_size,
  156. soft_max_seq_len=(
  157. args.text_generation_max_len_a,
  158. args.text_generation_max_len_b,
  159. ),
  160. )
  161. if args.text_unk_blocking:
  162. text_generation_opts.unk_penalty = torch.inf
  163. if args.text_generation_ngram_blocking:
  164. text_generation_opts.step_processor = NGramRepeatBlockProcessor(
  165. ngram_size=args.no_repeat_ngram_size
  166. )
  167. unit_generation_opts = SequenceGeneratorOptions(
  168. beam_size=args.unit_generation_beam_size,
  169. soft_max_seq_len=(
  170. args.unit_generation_max_len_a,
  171. args.unit_generation_max_len_b,
  172. ),
  173. )
  174. if args.unit_generation_ngram_blocking:
  175. unit_generation_opts.step_processor = NGramRepeatBlockProcessor(
  176. ngram_size=args.no_repeat_ngram_size
  177. )
  178. return text_generation_opts, unit_generation_opts
  179. def main() -> None:
  180. parser = argparse.ArgumentParser(
  181. description="M4T inference on supported tasks using Translator."
  182. )
  183. parser.add_argument("input", type=str, help="Audio WAV file path or text input.")
  184. parser = add_inference_arguments(parser)
  185. args = parser.parse_args()
  186. if not args.task or not args.tgt_lang:
  187. raise Exception(
  188. "Please provide required arguments for evaluation - task, tgt_lang"
  189. )
  190. if args.task.upper() in {"S2ST", "T2ST"} and args.output_path is None:
  191. raise ValueError("output_path must be provided to save the generated audio")
  192. if torch.cuda.is_available():
  193. device = torch.device("cuda:0")
  194. dtype = torch.float16
  195. else:
  196. device = torch.device("cpu")
  197. dtype = torch.float32
  198. logger.info(f"Running inference on {device=} with {dtype=}.")
  199. translator = Translator(args.model_name, args.vocoder_name, device, dtype=dtype)
  200. text_generation_opts, unit_generation_opts = set_generation_opts(args)
  201. logger.info(f"{text_generation_opts=}")
  202. logger.info(f"{unit_generation_opts=}")
  203. logger.info(
  204. f"unit_generation_ngram_filtering={args.unit_generation_ngram_filtering}"
  205. )
  206. # If the input is audio, resample to 16kHz
  207. if args.task.upper() in {"S2ST", "ASR", "S2TT"}:
  208. wav, sample_rate = torchaudio.load(args.input)
  209. translator_input = torchaudio.functional.resample(
  210. wav, orig_freq=sample_rate, new_freq=16_000
  211. )
  212. else:
  213. translator_input = args.input
  214. text_output, speech_output = translator.predict(
  215. translator_input,
  216. args.task,
  217. args.tgt_lang,
  218. src_lang=args.src_lang,
  219. text_generation_opts=text_generation_opts,
  220. unit_generation_opts=unit_generation_opts,
  221. unit_generation_ngram_filtering=args.unit_generation_ngram_filtering,
  222. )
  223. if speech_output is not None:
  224. logger.info(f"Saving translated audio in {args.tgt_lang}")
  225. torchaudio.save(
  226. args.output_path,
  227. speech_output.audio_wavs[0][0].to(torch.float32).cpu(),
  228. sample_rate=speech_output.sample_rate,
  229. )
  230. logger.info(f"Translated text in {args.tgt_lang}: {text_output[0]}")
  231. if __name__ == "__main__":
  232. main()
Tip!

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

Comments

Loading...