app.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #!/usr/bin/env python
  2. # Copyright (c) Meta Platforms, Inc. and affiliates
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the license found in the
  6. # MIT_LICENSE file in the root directory of this source tree.
  7. import os
  8. import pathlib
  9. import tempfile
  10. import gradio as gr
  11. import torch
  12. import torchaudio
  13. from fairseq2.assets import InProcAssetMetadataProvider, asset_store
  14. from fairseq2.data import Collater
  15. from fairseq2.data.audio import (
  16. AudioDecoder,
  17. WaveformToFbankConverter,
  18. WaveformToFbankOutput,
  19. )
  20. from seamless_communication.inference import SequenceGeneratorOptions
  21. from fairseq2.generation import NGramRepeatBlockProcessor
  22. from fairseq2.memory import MemoryBlock
  23. from huggingface_hub import snapshot_download
  24. from seamless_communication.inference import Translator, SequenceGeneratorOptions
  25. from seamless_communication.models.unity import (
  26. load_gcmvn_stats,
  27. load_unity_unit_tokenizer,
  28. )
  29. from seamless_communication.inference.pretssel_generator import PretsselGenerator
  30. from typing import Tuple
  31. from utils import LANGUAGE_CODE_TO_NAME
  32. DESCRIPTION = """\
  33. # Seamless Expressive
  34. [SeamlessExpressive](https://github.com/facebookresearch/seamless_communication) is a speech-to-speech translation model that captures certain underexplored aspects of prosody such as speech rate and pauses, while preserving the style of one's voice and high content translation quality.
  35. """
  36. CACHE_EXAMPLES = os.getenv("CACHE_EXAMPLES") == "1" and torch.cuda.is_available()
  37. CHECKPOINTS_PATH = pathlib.Path(os.getenv("CHECKPOINTS_PATH", "/home/user/app/models"))
  38. if not CHECKPOINTS_PATH.exists():
  39. snapshot_download(repo_id="facebook/seamless-expressive", repo_type="model", local_dir=CHECKPOINTS_PATH)
  40. snapshot_download(repo_id="facebook/seamless-m4t-v2-large", repo_type="model", local_dir=CHECKPOINTS_PATH)
  41. # Ensure that we do not have any other environment resolvers and always return
  42. # "demo" for demo purposes.
  43. asset_store.env_resolvers.clear()
  44. asset_store.env_resolvers.append(lambda: "demo")
  45. # Construct an `InProcAssetMetadataProvider` with environment-specific metadata
  46. # that just overrides the regular metadata for "demo" environment. Note the "@demo" suffix.
  47. demo_metadata = [
  48. {
  49. "name": "seamless_expressivity@demo",
  50. "checkpoint": f"file://{CHECKPOINTS_PATH}/m2m_expressive_unity.pt",
  51. "char_tokenizer": f"file://{CHECKPOINTS_PATH}/spm_char_lang38_tc.model",
  52. },
  53. {
  54. "name": "vocoder_pretssel@demo",
  55. "checkpoint": f"file://{CHECKPOINTS_PATH}/pretssel_melhifigan_wm-final.pt",
  56. },
  57. {
  58. "name": "seamlessM4T_v2_large@demo",
  59. "checkpoint": f"file://{CHECKPOINTS_PATH}/seamlessM4T_v2_large.pt",
  60. "char_tokenizer": f"file://{CHECKPOINTS_PATH}/spm_char_lang38_tc.model",
  61. },
  62. ]
  63. asset_store.metadata_providers.append(InProcAssetMetadataProvider(demo_metadata))
  64. LANGUAGE_NAME_TO_CODE = {v: k for k, v in LANGUAGE_CODE_TO_NAME.items()}
  65. if torch.cuda.is_available():
  66. device = torch.device("cuda:0")
  67. dtype = torch.float16
  68. else:
  69. device = torch.device("cpu")
  70. dtype = torch.float32
  71. MODEL_NAME = "seamless_expressivity"
  72. VOCODER_NAME = "vocoder_pretssel"
  73. # used for ASR for toxicity
  74. m4t_translator = Translator(
  75. model_name_or_card="seamlessM4T_v2_large",
  76. vocoder_name_or_card=None,
  77. device=device,
  78. dtype=dtype,
  79. )
  80. unit_tokenizer = load_unity_unit_tokenizer(MODEL_NAME)
  81. _gcmvn_mean, _gcmvn_std = load_gcmvn_stats(VOCODER_NAME)
  82. gcmvn_mean = torch.tensor(_gcmvn_mean, device=device, dtype=dtype)
  83. gcmvn_std = torch.tensor(_gcmvn_std, device=device, dtype=dtype)
  84. translator = Translator(
  85. MODEL_NAME,
  86. vocoder_name_or_card=None,
  87. device=device,
  88. dtype=dtype,
  89. apply_mintox=False,
  90. )
  91. text_generation_opts = SequenceGeneratorOptions(
  92. beam_size=5,
  93. unk_penalty=torch.inf,
  94. soft_max_seq_len=(0, 200),
  95. step_processor=NGramRepeatBlockProcessor(
  96. ngram_size=10,
  97. ),
  98. )
  99. m4t_text_generation_opts = SequenceGeneratorOptions(
  100. beam_size=5,
  101. unk_penalty=torch.inf,
  102. soft_max_seq_len=(1, 200),
  103. step_processor=NGramRepeatBlockProcessor(
  104. ngram_size=10,
  105. ),
  106. )
  107. pretssel_generator = PretsselGenerator(
  108. VOCODER_NAME,
  109. vocab_info=unit_tokenizer.vocab_info,
  110. device=device,
  111. dtype=dtype,
  112. )
  113. decode_audio = AudioDecoder(dtype=torch.float32, device=device)
  114. convert_to_fbank = WaveformToFbankConverter(
  115. num_mel_bins=80,
  116. waveform_scale=2**15,
  117. channel_last=True,
  118. standardize=False,
  119. device=device,
  120. dtype=dtype,
  121. )
  122. def normalize_fbank(data: WaveformToFbankOutput) -> WaveformToFbankOutput:
  123. fbank = data["fbank"]
  124. std, mean = torch.std_mean(fbank, dim=0)
  125. data["fbank"] = fbank.subtract(mean).divide(std)
  126. data["gcmvn_fbank"] = fbank.subtract(gcmvn_mean).divide(gcmvn_std)
  127. return data
  128. collate = Collater(pad_value=0, pad_to_multiple=1)
  129. AUDIO_SAMPLE_RATE = 16000
  130. MAX_INPUT_AUDIO_LENGTH = 10 # in seconds
  131. def remove_prosody_tokens_from_text(text):
  132. # filter out prosody tokens, there is only emphasis '*', and pause '='
  133. text = text.replace("*", "").replace("=", "")
  134. text = " ".join(text.split())
  135. return text
  136. def preprocess_audio(input_audio_path: str) -> None:
  137. arr, org_sr = torchaudio.load(input_audio_path)
  138. new_arr = torchaudio.functional.resample(arr, orig_freq=org_sr, new_freq=AUDIO_SAMPLE_RATE)
  139. max_length = int(MAX_INPUT_AUDIO_LENGTH * AUDIO_SAMPLE_RATE)
  140. if new_arr.shape[1] > max_length:
  141. new_arr = new_arr[:, :max_length]
  142. gr.Warning(f"Input audio is too long. Only the first {MAX_INPUT_AUDIO_LENGTH} seconds is used.")
  143. torchaudio.save(input_audio_path, new_arr, sample_rate=AUDIO_SAMPLE_RATE)
  144. def run(
  145. input_audio_path: str,
  146. source_language: str,
  147. target_language: str,
  148. ) -> Tuple[str, str]:
  149. target_language_code = LANGUAGE_NAME_TO_CODE[target_language]
  150. source_language_code = LANGUAGE_NAME_TO_CODE[source_language]
  151. preprocess_audio(input_audio_path)
  152. with pathlib.Path(input_audio_path).open("rb") as fb:
  153. block = MemoryBlock(fb.read())
  154. example = decode_audio(block)
  155. example = convert_to_fbank(example)
  156. example = normalize_fbank(example)
  157. example = collate(example)
  158. # get transcription for mintox
  159. source_sentences, _ = m4t_translator.predict(
  160. input=example["fbank"],
  161. task_str="S2TT", # get source text
  162. tgt_lang=source_language_code,
  163. text_generation_opts=m4t_text_generation_opts,
  164. )
  165. source_text = str(source_sentences[0])
  166. prosody_encoder_input = example["gcmvn_fbank"]
  167. text_output, unit_output = translator.predict(
  168. example["fbank"],
  169. "S2ST",
  170. tgt_lang=target_language_code,
  171. src_lang=source_language_code,
  172. text_generation_opts=text_generation_opts,
  173. unit_generation_ngram_filtering=False,
  174. duration_factor=1.0,
  175. prosody_encoder_input=prosody_encoder_input,
  176. src_text=source_text, # for mintox check
  177. )
  178. speech_output = pretssel_generator.predict(
  179. unit_output.units,
  180. tgt_lang=target_language_code,
  181. prosody_encoder_input=prosody_encoder_input,
  182. )
  183. with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
  184. torchaudio.save(
  185. f.name,
  186. speech_output.audio_wavs[0][0].to(torch.float32).cpu(),
  187. sample_rate=speech_output.sample_rate,
  188. )
  189. text_out = remove_prosody_tokens_from_text(str(text_output[0]))
  190. return f.name, text_out
  191. TARGET_LANGUAGE_NAMES = [
  192. "English",
  193. "French",
  194. "German",
  195. "Spanish",
  196. ]
  197. with gr.Blocks(css="style.css") as demo:
  198. gr.Markdown(DESCRIPTION)
  199. gr.DuplicateButton(
  200. value="Duplicate Space for private use",
  201. elem_id="duplicate-button",
  202. visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
  203. )
  204. with gr.Row():
  205. with gr.Column():
  206. with gr.Group():
  207. input_audio = gr.Audio(label="Input speech", type="filepath")
  208. source_language = gr.Dropdown(
  209. label="Source language",
  210. choices=TARGET_LANGUAGE_NAMES,
  211. value="English",
  212. )
  213. target_language = gr.Dropdown(
  214. label="Target language",
  215. choices=TARGET_LANGUAGE_NAMES,
  216. value="French",
  217. )
  218. btn = gr.Button()
  219. with gr.Column():
  220. with gr.Group():
  221. output_audio = gr.Audio(label="Translated speech")
  222. output_text = gr.Textbox(label="Translated text")
  223. gr.Examples(
  224. examples=[],
  225. inputs=[input_audio, source_language, target_language],
  226. outputs=[output_audio, output_text],
  227. fn=run,
  228. cache_examples=CACHE_EXAMPLES,
  229. api_name=False,
  230. )
  231. btn.click(
  232. fn=run,
  233. inputs=[input_audio, source_language, target_language],
  234. outputs=[output_audio, output_text],
  235. api_name="run",
  236. )
  237. if __name__ == "__main__":
  238. demo.queue(max_size=50).launch()