umarigan commited on
Commit
b2e4995
·
verified ·
1 Parent(s): dbfdf1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -52
app.py CHANGED
@@ -2,71 +2,87 @@ import gradio as gr
2
  import numpy as np
3
  import torch
4
  from datasets import load_dataset
5
-
6
  from transformers import SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5Processor, pipeline
7
 
8
-
9
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
10
 
11
- # load speech translation checkpoint
12
- asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-base", device=device)
13
-
14
- # load text-to-speech checkpoint and speaker embeddings
15
- processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
16
-
17
- model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts").to(device)
18
- vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan").to(device)
19
-
20
- embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
21
- speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
22
-
23
-
24
- def translate(audio):
25
- outputs = asr_pipe(audio, max_new_tokens=256, generate_kwargs={"task": "translate"})
26
- return outputs["text"]
27
-
28
-
29
- def synthesise(text):
 
 
 
 
 
 
 
 
 
 
 
 
30
  inputs = processor(text=text, return_tensors="pt")
31
- speech = model.generate_speech(inputs["input_ids"].to(device), speaker_embeddings.to(device), vocoder=vocoder)
32
  return speech.cpu()
33
 
34
-
35
- def speech_to_speech_translation(audio):
36
- translated_text = translate(audio)
37
- synthesised_speech = synthesise(translated_text)
38
  synthesised_speech = (synthesised_speech.numpy() * 32767).astype(np.int16)
39
  return 16000, synthesised_speech
40
 
41
-
42
- title = "Cascaded STST"
43
  description = """
44
- Demo for cascaded speech-to-speech translation (STST), mapping from source speech in any language to target speech in English. Demo uses OpenAI's [Whisper Base](https://huggingface.co/openai/whisper-base) model for speech translation, and Microsoft's
45
- [SpeechT5 TTS](https://huggingface.co/microsoft/speecht5_tts) model for text-to-speech:
46
-
47
- ![Cascaded STST](https://huggingface.co/datasets/huggingface-course/audio-course-images/resolve/main/s2st_cascaded.png "Diagram of cascaded speech to speech translation")
48
  """
49
 
50
  demo = gr.Blocks()
51
 
52
- mic_translate = gr.Interface(
53
- fn=speech_to_speech_translation,
54
- inputs=gr.Audio(source="microphone", type="filepath"),
55
- outputs=gr.Audio(label="Generated Speech", type="numpy"),
56
- title=title,
57
- description=description,
58
- )
59
-
60
- file_translate = gr.Interface(
61
- fn=speech_to_speech_translation,
62
- inputs=gr.Audio(source="upload", type="filepath"),
63
- outputs=gr.Audio(label="Generated Speech", type="numpy"),
64
- examples=[["./example.wav"]],
65
- title=title,
66
- description=description,
67
- )
68
-
69
  with demo:
70
- gr.TabbedInterface([mic_translate, file_translate], ["Microphone", "Audio File"])
71
-
72
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import numpy as np
3
  import torch
4
  from datasets import load_dataset
 
5
  from transformers import SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5Processor, pipeline
6
 
 
7
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
8
 
9
+ # Load Whisper large-v2 model for multilingual speech translation
10
+ asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-large-v2", device=device)
11
+
12
+ # Load MMS TTS model for multilingual text-to-speech
13
+ processor = SpeechT5Processor.from_pretrained("facebook/mms-tts-eng")
14
+ model = SpeechT5ForTextToSpeech.from_pretrained("facebook/mms-tts-eng").to(device)
15
+ vocoder = SpeechT5HifiGan.from_pretrained("facebook/mms-tts-eng").to(device)
16
+
17
+ # Define supported languages
18
+ LANGUAGES = {
19
+ "French": "fra", "German": "deu", "Spanish": "spa", "Italian": "ita",
20
+ "Portuguese": "por", "Dutch": "nld", "Russian": "rus", "Chinese": "cmn",
21
+ "Japanese": "jpn", "Korean": "kor"
22
+ }
23
+
24
+ def translate(audio, source_lang, target_lang):
25
+ outputs = asr_pipe(audio, max_new_tokens=256, generate_kwargs={
26
+ "task": "transcribe",
27
+ "language": source_lang,
28
+ })
29
+ transcription = outputs["text"]
30
+
31
+ # Use Whisper for translation
32
+ translation = asr_pipe(transcription, max_new_tokens=256, generate_kwargs={
33
+ "task": "translate",
34
+ "language": target_lang,
35
+ })["text"]
36
+
37
+ return translation
38
+
39
+ def synthesise(text, target_lang):
40
  inputs = processor(text=text, return_tensors="pt")
41
+ speech = model.generate_speech(inputs["input_ids"].to(device), vocoder=vocoder, language=target_lang)
42
  return speech.cpu()
43
 
44
+ def speech_to_speech_translation(audio, source_lang, target_lang):
45
+ translated_text = translate(audio, source_lang, target_lang)
46
+ synthesised_speech = synthesise(translated_text, target_lang)
 
47
  synthesised_speech = (synthesised_speech.numpy() * 32767).astype(np.int16)
48
  return 16000, synthesised_speech
49
 
50
+ title = "Multilingual Speech-to-Speech Translation"
 
51
  description = """
52
+ Demo for multilingual speech-to-speech translation (STST), mapping from source speech in any supported language to target speech in any other supported language.
 
 
 
53
  """
54
 
55
  demo = gr.Blocks()
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  with demo:
58
+ gr.Markdown(f"# {title}")
59
+ gr.Markdown(description)
60
+
61
+ with gr.Row():
62
+ source_lang = gr.Dropdown(choices=list(LANGUAGES.keys()), label="Source Language")
63
+ target_lang = gr.Dropdown(choices=list(LANGUAGES.keys()), label="Target Language")
64
+
65
+ with gr.Tabs():
66
+ with gr.TabItem("Microphone"):
67
+ mic_input = gr.Audio(source="microphone", type="filepath")
68
+ mic_output = gr.Audio(label="Generated Speech", type="numpy")
69
+ mic_button = gr.Button("Translate")
70
+
71
+ with gr.TabItem("Audio File"):
72
+ file_input = gr.Audio(source="upload", type="filepath")
73
+ file_output = gr.Audio(label="Generated Speech", type="numpy")
74
+ file_button = gr.Button("Translate")
75
+
76
+ mic_button.click(
77
+ speech_to_speech_translation,
78
+ inputs=[mic_input, source_lang, target_lang],
79
+ outputs=mic_output
80
+ )
81
+
82
+ file_button.click(
83
+ speech_to_speech_translation,
84
+ inputs=[file_input, source_lang, target_lang],
85
+ outputs=file_output
86
+ )
87
+
88
+ demo.launch()