Spaces:
Sleeping
Sleeping
File size: 6,144 Bytes
93bb4f3 |
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 |
from pathlib import Path
import pandas as pd
import torchaudio
import torch
import numpy as np
import gradio as gr
from fastrtc import WebRTC, ReplyOnPause
from transformers import AutoProcessor, SeamlessM4Tv2Model
parent_dir = Path(__file__).parents[1]
config_path = Path(parent_dir, "configs")
processor = AutoProcessor.from_pretrained("facebook/seamless-m4t-v2-large")
model = SeamlessM4Tv2Model.from_pretrained("facebook/seamless-m4t-v2-large")
default_sampling_rate = 16_000
def translate_audio(
audio: tuple[int, np.ndarray], tgt_language: str
) -> tuple[int, np.ndarray]:
"""Translate the audio that is captured through the streaming component.
Source language of the audio has to be one of the supported languages to be successful.
:param audio: the captured audio
:type audio: tuple[int, np.ndarray]
:param tgt_language: the target language for translation
:type tgt_language: str
:yield: the tuple containing the sampling rate and the audio array
:rtype: tuple[int, np.ndarray]
"""
orig_freq, np_array = audio
waveform = torch.from_numpy(np_array)
waveform = waveform.to(torch.float32)
waveform = waveform / 32768.0 # normalize int16 to [-1, 1]
audio = torchaudio.functional.resample(
waveform, orig_freq=orig_freq, new_freq=default_sampling_rate
) # must be a 16 kHz waveform array
audio_inputs = processor(
audios=audio,
return_tensors="pt",
sampling_rate=default_sampling_rate,
)
audio_array_from_audio = (
model.generate(**audio_inputs, tgt_lang=tgt_language)[0].cpu().numpy().squeeze()
)
yield (default_sampling_rate, audio_array_from_audio)
# Supported target languages for speech
supported_langs_df = pd.read_excel(Path(config_path, "supported_languages.xlsx"))
supported_speech_langs_df = supported_langs_df[
supported_langs_df["Target"].str.contains("Sp")
]
# Labels and values for supported speech languages dropdown
supported_speech_langs = list(
zip(supported_speech_langs_df["language"], supported_speech_langs_df["code"])
)
# Sort by the first element of the tuple (full language name)
supported_speech_langs.sort()
css = """
#componentsContainer {
width: 70%;
display: block;
margin-left: auto;
margin-right: auto;
}
#langDropdown .container .wrap {
width: 230px;
}
.audio-container {
padding-bottom: 2rem !important;
margin-bottom: 2rem !important;
}
.vspace-sm { margin-bottom: 20px !important; }
.vspace-md { margin-bottom: 40px !important; }
.vspace-lg { margin-bottom: 60px !important; }
.tagline {
color: #4a5568;
}
.tagline-emphasis {
font-family: 'Playfair Display', serif;
font-style: italic;
color: #718096;
position: relative;
display: inline-block;
}
.tagline-emphasis:after {
content: "";
position: absolute;
bottom: -5px;
left: 0;
width: 100%;
height: 2px;
background: linear-gradient(90deg, transparent, #6a11cb, transparent);
}
.gradio-footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
text-align: center;
padding: 12px;
background: var(--background-fill-secondary);
border-top: 1px solid var(--border-color-primary);
font-size: 0.9em;
z-index: 100;
display: flex;
justify-content: center;
align-items: center;
gap: 6px;
}
.gradio-footer a {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--link-text-color);
text-decoration: none;
}
.fastrtc-icon {
height: 24px;
width: 24px;
}
"""
with gr.Blocks(
theme=gr.themes.Glass(),
css=css,
) as demo:
gr.HTML(
"""
<div style='display: flex; align-items: center; justify-content: center; gap: 20px'>
<div style="background-color: var(--block-background-fill); border-radius: 8px">
<img src="https://images.icon-icons.com/3975/PNG/512/translation_language_translator_icon_251869.png" style="width: 100px; height: 100px;">
</div>
<div>
<h1>TalkGlobe</h1>
<p class="tagline">
Break language barriers in real-time <span class="globe-icon">🌍</span><br>
<span class="tagline-emphasis">no more lost in translation</span> <span class="globe-icon">✨</span>
</p>
</div>
</div>
""",
elem_classes="vspace-sm",
)
# The main components (translation language dropdown and streaming capture component)
with gr.Group(elem_id="componentsContainer"):
with gr.Row(equal_height=True, min_height="11rem"):
with gr.Column(scale=5, elem_id="langCol"):
target_lang = gr.Dropdown(
choices=supported_speech_langs,
value="eng",
label="Supported Languages",
info="Select one of the supported languages for translation",
elem_id="langDropdown",
)
with gr.Column(scale=5, elem_id="micCol"):
audio = WebRTC(
modality="audio",
mode="send-receive",
label="Audio Stream",
)
# Trigger on pause
audio.stream(
ReplyOnPause(translate_audio),
inputs=[audio, target_lang],
outputs=[audio],
)
# Sticky footer (will stay at bottom on all screen sizes)
gr.HTML(
"""
<div class="gradio-footer">
Powered by
<a href="https://gradio.app/" target="_blank">
Gradio <img class="gradio-icon" src="https://www.gradio.app/_app/immutable/assets/gradio.CHB5adID.svg" alt="GradioIcon" style="height:24px; width:auto;">
</a>
•
<a href="https://freddyaboulton.github.io/gradio-webrtc/" target="_blank">
FastRTC <img class="fastrtc-icon" src="https://fastrtc.org/fastrtc_logo.png" alt="FastRTCIcon">
</a>
</div>
"""
)
demo.launch()
|