Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,210 +1,161 @@
|
|
1 |
-
|
2 |
-
|
3 |
import os
|
4 |
-
|
5 |
-
import gradio as gr
|
6 |
-
import spaces
|
7 |
import torch
|
8 |
import torchaudio
|
9 |
-
|
|
|
10 |
from transformers import (
|
11 |
SeamlessM4TFeatureExtractor,
|
12 |
SeamlessM4TTokenizer,
|
13 |
SeamlessM4Tv2ForSpeechToText,
|
|
|
|
|
14 |
)
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
)
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
torch_dtype
|
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 |
-
text_out = model.generate(**audio_inputs, tgt_lang=target_language_code)[0].float().cpu().numpy().squeeze()
|
68 |
-
|
69 |
-
return tokenizer.decode(text_out, clean_up_tokenization_spaces=True, skip_special_tokens=True)
|
70 |
-
|
71 |
-
def run_asr(input_audio: str, target_language: str) -> str:
|
72 |
-
# preprocess_audio(input_audio)
|
73 |
-
target_language_code = LANGUAGE_NAME_TO_CODE[target_language]
|
74 |
-
|
75 |
-
input_audio, orig_freq = torchaudio.load(input_audio)
|
76 |
-
input_audio = torchaudio.functional.resample(input_audio, orig_freq=orig_freq, new_freq=16000)
|
77 |
-
audio_inputs= processor(input_audio, sampling_rate=16000, return_tensors="pt").to(device=device, dtype=torch_dtype)
|
78 |
-
|
79 |
-
text_out = model.generate(**audio_inputs, tgt_lang=target_language_code)[0].float().cpu().numpy().squeeze()
|
80 |
-
|
81 |
-
return tokenizer.decode(text_out, clean_up_tokenization_spaces=True, skip_special_tokens=True)
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
with gr.Blocks() as demo_s2st:
|
86 |
-
with gr.Row():
|
87 |
-
with gr.Column():
|
88 |
-
with gr.Group():
|
89 |
-
input_audio = gr.Audio(label="Input speech", type="filepath")
|
90 |
-
source_language = gr.Dropdown(
|
91 |
-
label="Source language",
|
92 |
-
choices=ASR_TARGET_LANGUAGE_NAMES,
|
93 |
-
value="English",
|
94 |
-
)
|
95 |
-
target_language = gr.Dropdown(
|
96 |
-
label="Target language",
|
97 |
-
choices=S2ST_TARGET_LANGUAGE_NAMES,
|
98 |
-
value=DEFAULT_TARGET_LANGUAGE,
|
99 |
-
)
|
100 |
-
btn = gr.Button("Translate")
|
101 |
-
with gr.Column():
|
102 |
-
with gr.Group():
|
103 |
-
output_audio = gr.Audio(
|
104 |
-
label="Translated speech",
|
105 |
-
autoplay=False,
|
106 |
-
streaming=False,
|
107 |
-
type="numpy",
|
108 |
-
)
|
109 |
-
output_text = gr.Textbox(label="Translated text")
|
110 |
-
|
111 |
-
with gr.Blocks() as demo_s2tt:
|
112 |
-
with gr.Row():
|
113 |
-
with gr.Column():
|
114 |
-
with gr.Group():
|
115 |
-
input_audio = gr.Audio(label="Input speech", type="filepath")
|
116 |
-
source_language = gr.Dropdown(
|
117 |
-
label="Source language",
|
118 |
-
choices=ASR_TARGET_LANGUAGE_NAMES,
|
119 |
-
value="English",
|
120 |
-
)
|
121 |
-
target_language = gr.Dropdown(
|
122 |
-
label="Target language",
|
123 |
-
choices=S2TT_TARGET_LANGUAGE_NAMES,
|
124 |
-
value=DEFAULT_TARGET_LANGUAGE,
|
125 |
-
)
|
126 |
-
btn = gr.Button("Translate")
|
127 |
-
with gr.Column():
|
128 |
-
output_text = gr.Textbox(label="Translated text")
|
129 |
-
|
130 |
-
btn.click(
|
131 |
-
fn=run_s2tt,
|
132 |
-
inputs=[input_audio, source_language, target_language],
|
133 |
-
outputs=output_text,
|
134 |
-
api_name="s2tt",
|
135 |
)
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
with gr.Column():
|
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 |
-
inputs=[input_audio, target_language],
|
183 |
-
outputs=output_text,
|
184 |
-
api_name="asr",
|
185 |
-
)
|
186 |
-
|
187 |
-
|
188 |
-
with gr.Blocks(css="style.css") as demo:
|
189 |
-
gr.Markdown(DESCRIPTION)
|
190 |
-
gr.DuplicateButton(
|
191 |
-
value="Duplicate Space for private use",
|
192 |
-
elem_id="duplicate-button",
|
193 |
-
visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
|
194 |
-
)
|
195 |
-
|
196 |
-
with gr.Tabs():
|
197 |
-
# with gr.Tab(label="S2ST"):
|
198 |
-
# demo_s2st.render()
|
199 |
-
with gr.Tab(label="S2TT"):
|
200 |
-
demo_s2tt.render()
|
201 |
-
# with gr.Tab(label="T2ST"):
|
202 |
-
# demo_t2st.render()
|
203 |
-
# with gr.Tab(label="T2TT"):
|
204 |
-
# demo_t2tt.render()
|
205 |
-
with gr.Tab(label="ASR"):
|
206 |
-
demo_asr.render()
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
demo.launch(share=True)
|
|
|
1 |
+
```python
|
2 |
+
# app.py
|
3 |
import os
|
4 |
+
import io
|
|
|
|
|
5 |
import torch
|
6 |
import torchaudio
|
7 |
+
import numpy as np
|
8 |
+
import gradio as gr
|
9 |
from transformers import (
|
10 |
SeamlessM4TFeatureExtractor,
|
11 |
SeamlessM4TTokenizer,
|
12 |
SeamlessM4Tv2ForSpeechToText,
|
13 |
+
AutoTokenizer,
|
14 |
+
AutoFeatureExtractor,
|
15 |
)
|
16 |
+
from pydub import AudioSegment
|
17 |
+
import nltk
|
18 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
19 |
+
from lang_list import LANGUAGE_NAME_TO_CODE, ASR_TARGET_LANGUAGE_NAMES, S2TT_TARGET_LANGUAGE_NAMES
|
20 |
+
|
21 |
+
# Download punkt for sentence splitting
|
22 |
+
nltk.download('punkt_tab')
|
23 |
+
|
24 |
+
# Device and dtype
|
25 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
26 |
+
DTYPE = torch.bfloat16 if DEVICE != "cpu" else torch.float32
|
27 |
+
SAMPLE_RATE = 16000
|
28 |
+
|
29 |
+
# Load speech-to-text model
|
30 |
+
stt_model = SeamlessM4Tv2ForSpeechToText.from_pretrained(
|
31 |
+
"ai4bharat/indic-seamless",
|
32 |
+
torch_dtype=DTYPE
|
33 |
+
).to(DEVICE)
|
34 |
+
feature_extractor = SeamlessM4TFeatureExtractor.from_pretrained(
|
35 |
+
"ai4bharat/indic-seamless"
|
36 |
+
)
|
37 |
+
tt_tokenizer = SeamlessM4TTokenizer.from_pretrained(
|
38 |
+
"ai4bharat/indic-seamless"
|
39 |
)
|
40 |
|
41 |
+
# Load TTS models
|
42 |
+
repo_id = "ai4bharat/indic-parler-tts-pretrained"
|
43 |
+
finetuned_repo_id = "ai4bharat/indic-parler-tts"
|
44 |
+
|
45 |
+
tts_model = ParlerTTSForConditionalGeneration.from_pretrained(
|
46 |
+
repo_id,
|
47 |
+
attn_implementation="eager",
|
48 |
+
torch_dtype=DTYPE,
|
49 |
+
).to(DEVICE)
|
50 |
+
finetuned_tts = ParlerTTSForConditionalGeneration.from_pretrained(
|
51 |
+
finetuned_repo_id,
|
52 |
+
attn_implementation="eager",
|
53 |
+
torch_dtype=DTYPE,
|
54 |
+
).to(DEVICE)
|
55 |
+
|
56 |
+
tts_tokenizer = AutoTokenizer.from_pretrained(repo_id)
|
57 |
+
description_tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-large")
|
58 |
+
tts_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
|
59 |
+
|
60 |
+
# Voice options - example speakers
|
61 |
+
VOICES = [
|
62 |
+
"Sunita", "Suresh", "Aditi", "Prakash", "Rohit", "Anjali", "Jaya"
|
63 |
+
]
|
64 |
+
|
65 |
+
# Custom CSS for visual styling
|
66 |
+
CSS = '''
|
67 |
+
body { background-color: #f9fafb; }
|
68 |
+
.gradio-container { max-width: 900px; margin: auto; padding: 20px; }
|
69 |
+
.step-box { background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
|
70 |
+
'''
|
71 |
+
|
72 |
+
# Helpers
|
73 |
+
def numpy_to_mp3(audio_array, sampling_rate):
|
74 |
+
if np.issubdtype(audio_array.dtype, np.floating):
|
75 |
+
max_val = np.max(np.abs(audio_array))
|
76 |
+
audio_array = (audio_array / max_val) * 32767
|
77 |
+
audio_array = audio_array.astype(np.int16)
|
78 |
+
segment = AudioSegment(
|
79 |
+
audio_array.tobytes(),
|
80 |
+
frame_rate=sampling_rate,
|
81 |
+
sample_width=audio_array.dtype.itemsize,
|
82 |
+
channels=1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
)
|
84 |
+
mp3_io = io.BytesIO()
|
85 |
+
segment.export(mp3_io, format="mp3", bitrate="320k")
|
86 |
+
return mp3_io.getvalue()
|
87 |
+
|
88 |
+
# STT / Translation
|
89 |
+
def transcribe_and_translate(audio_path, source_language, target_language):
|
90 |
+
wav, orig_sr = torchaudio.load(audio_path)
|
91 |
+
wav = torchaudio.functional.resample(wav, orig_freq=orig_sr, new_freq=SAMPLE_RATE)
|
92 |
+
inputs = feature_extractor(wav, sampling_rate=SAMPLE_RATE, return_tensors="pt").to(DEVICE, DTYPE)
|
93 |
+
tgt = LANGUAGE_NAME_TO_CODE[target_language]
|
94 |
+
gen = stt_model.generate(**inputs, tgt_lang=tgt)[0]
|
95 |
+
text = tt_tokenizer.decode(gen, skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
96 |
+
return text
|
97 |
+
|
98 |
+
# TTS generation
|
99 |
+
def generate_tts(text, voice, finetuned=False):
|
100 |
+
description = f"{voice} speaks in a neutral tone with clear audio."
|
101 |
+
sentences = nltk.sent_tokenize(text)
|
102 |
+
all_audio = []
|
103 |
+
for sent in sentences:
|
104 |
+
desc_inputs = description_tokenizer(description, return_tensors="pt").to(DEVICE)
|
105 |
+
prompt_inputs = tts_tokenizer(sent, return_tensors="pt").to(DEVICE)
|
106 |
+
model = finetuned_tts if finetuned else tts_model
|
107 |
+
gen = model.generate(
|
108 |
+
input_ids=desc_inputs.input_ids,
|
109 |
+
attention_mask=desc_inputs.attention_mask,
|
110 |
+
prompt_input_ids=prompt_inputs.input_ids,
|
111 |
+
prompt_attention_mask=prompt_inputs.attention_mask,
|
112 |
+
do_sample=True,
|
113 |
+
return_dict_in_generate=True
|
114 |
+
)
|
115 |
+
if hasattr(gen, 'sequences') and hasattr(gen, 'audios_length'):
|
116 |
+
audio = gen.sequences[0, :gen.audios_length[0]]
|
117 |
+
audio_np = audio.to(torch.float32).cpu().numpy().flatten()
|
118 |
+
all_audio.append(audio_np)
|
119 |
+
combined = np.concatenate(all_audio)
|
120 |
+
return numpy_to_mp3(combined, tts_feature_extractor.sampling_rate)
|
121 |
+
|
122 |
+
# Combined pipeline to reduce duplicate STT calls
|
123 |
+
def pipeline(audio_path, source_language, target_language, voice, finetuned):
|
124 |
+
text = transcribe_and_translate(audio_path, source_language, target_language)
|
125 |
+
audio_bytes = generate_tts(text, voice, finetuned)
|
126 |
+
return text, audio_bytes
|
127 |
+
|
128 |
+
# Gradio UI
|
129 |
+
|
130 |
+
def build_ui():
|
131 |
+
with gr.Blocks(css=CSS) as demo:
|
132 |
+
gr.Markdown("ποΈ AUDIO TRANSLATION ποΈ")
|
133 |
+
# Usage Steps
|
134 |
with gr.Column():
|
135 |
+
gr.HTML("<div class='step-box'><strong>Step 1:</strong> Upload or record your audio clip.</div>")
|
136 |
+
gr.HTML("<div class='step-box'><strong>Step 2:</strong> Select the source and target languages.</div>")
|
137 |
+
gr.HTML("<div class='step-box'><strong>Step 3:</strong> Choose a voice persona.</div>")
|
138 |
+
gr.HTML("<div class='step-box'><strong>Step 4:</strong> (Optional) Toggle fine-tuned TTS for more natural speech.</div>")
|
139 |
+
gr.HTML("<div class='step-box'><strong>Step 5:</strong> Click <em>Run</em> and view your text & audio results on the right.</div>")
|
140 |
+
with gr.Row():
|
141 |
+
with gr.Column(scale=1):
|
142 |
+
audio_in = gr.Audio(label="Input Audio", type="filepath")
|
143 |
+
src = gr.Dropdown(ASR_TARGET_LANGUAGE_NAMES, label="Source Language", value="English")
|
144 |
+
tgt = gr.Dropdown(S2TT_TARGET_LANGUAGE_NAMES, label="Target Language", value="English")
|
145 |
+
voice = gr.Dropdown(VOICES, label="Voice Persona", value=VOICES[0])
|
146 |
+
finetune = gr.Checkbox(label="Use Fine-tuned TTS", value=False)
|
147 |
+
run_btn = gr.Button("Run", variant="primary")
|
148 |
+
with gr.Column(scale=1):
|
149 |
+
text_out = gr.Textbox(label="Translated Text")
|
150 |
+
audio_out = gr.Audio(label="Synthesized Speech", format="mp3")
|
151 |
+
run_btn.click(
|
152 |
+
fn=pipeline,
|
153 |
+
inputs=[audio_in, src, tgt, voice, finetune],
|
154 |
+
outputs=[text_out, audio_out]
|
155 |
+
)
|
156 |
+
return demo
|
157 |
+
|
158 |
+
if __name__ == "__main__":
|
159 |
+
ui = build_ui()
|
160 |
+
ui.launch(share=True)
|
161 |
+
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|