rohanmiriyala commited on
Commit
ad94dbf
Β·
verified Β·
1 Parent(s): a660cd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -198
app.py CHANGED
@@ -1,210 +1,161 @@
1
- from __future__ import annotations
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
- from lang_list import (
17
- ASR_TARGET_LANGUAGE_NAMES,
18
- LANGUAGE_NAME_TO_CODE,
19
- S2ST_TARGET_LANGUAGE_NAMES,
20
- S2TT_TARGET_LANGUAGE_NAMES,
21
- T2ST_TARGET_LANGUAGE_NAMES,
22
- TEXT_SOURCE_LANGUAGE_NAMES,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  )
24
 
25
-
26
- DESCRIPTION = """\
27
- ### Translation Model for Indian Languages** πŸŽ™οΈβž‘οΈπŸ“œ
28
- #### **How to Use:**
29
- 1. **Upload or record** an audio clip in any supported Indian language.
30
- 2. Click **"Translate"** to generate the corresponding text in the target language.
31
- 3. View or copy the output for further use.
32
- πŸš€ Try it out and experience seamless speech to speech translation for Indian languages!
33
- """
34
-
35
- hf_token = os.getenv("HF_TOKEN")
36
- device = "cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
37
- torch_dtype = torch.bfloat16 if device != "cpu" else torch.float32
38
-
39
- model = SeamlessM4Tv2ForSpeechToText.from_pretrained("ai4bharat/indic-seamless", torch_dtype=torch_dtype, token=hf_token).to(device)
40
- processor = SeamlessM4TFeatureExtractor.from_pretrained("ai4bharat/indic-seamless", token=hf_token)
41
- tokenizer = SeamlessM4TTokenizer.from_pretrained("ai4bharat/indic-seamless", token=hf_token)
42
-
43
- CACHE_EXAMPLES = os.getenv("CACHE_EXAMPLES") == "1" and torch.cuda.is_available()
44
-
45
- AUDIO_SAMPLE_RATE = 16000
46
- MAX_INPUT_AUDIO_LENGTH = 60 # in seconds
47
- DEFAULT_TARGET_LANGUAGE = "Hindi"
48
-
49
- def preprocess_audio(input_audio: str) -> None:
50
- arr, org_sr = torchaudio.load(input_audio)
51
- new_arr = torchaudio.functional.resample(arr, orig_freq=org_sr, new_freq=AUDIO_SAMPLE_RATE)
52
- max_length = int(MAX_INPUT_AUDIO_LENGTH * AUDIO_SAMPLE_RATE)
53
- if new_arr.shape[1] > max_length:
54
- new_arr = new_arr[:, :max_length]
55
- gr.Warning(f"Input audio is too long. Only the first {MAX_INPUT_AUDIO_LENGTH} seconds is used.")
56
- torchaudio.save(input_audio, new_arr, sample_rate=int(AUDIO_SAMPLE_RATE))
57
-
58
- def run_s2tt(input_audio: str, source_language: str, target_language: str) -> str:
59
- # preprocess_audio(input_audio)
60
- # source_language_code = LANGUAGE_NAME_TO_CODE[source_language]
61
- target_language_code = LANGUAGE_NAME_TO_CODE[target_language]
62
-
63
- input_audio, orig_freq = torchaudio.load(input_audio)
64
- input_audio = torchaudio.functional.resample(input_audio, orig_freq=orig_freq, new_freq=16000)
65
- audio_inputs= processor(input_audio, sampling_rate=16000, return_tensors="pt").to(device=device, dtype=torch_dtype)
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
- with gr.Blocks() as demo_t2st:
138
- with gr.Row():
139
- with gr.Column():
140
- with gr.Group():
141
- input_text = gr.Textbox(label="Input text")
142
- with gr.Row():
143
- source_language = gr.Dropdown(
144
- label="Source language",
145
- choices=TEXT_SOURCE_LANGUAGE_NAMES,
146
- value="English",
147
- )
148
- target_language = gr.Dropdown(
149
- label="Target language",
150
- choices=T2ST_TARGET_LANGUAGE_NAMES,
151
- value=DEFAULT_TARGET_LANGUAGE,
152
- )
153
- btn = gr.Button("Translate")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  with gr.Column():
155
- with gr.Group():
156
- output_audio = gr.Audio(
157
- label="Translated speech",
158
- autoplay=False,
159
- streaming=False,
160
- type="numpy",
161
- )
162
- output_text = gr.Textbox(label="Translated text")
163
-
164
-
165
-
166
- with gr.Blocks() as demo_asr:
167
- with gr.Row():
168
- with gr.Column():
169
- with gr.Group():
170
- input_audio = gr.Audio(label="Input speech", type="filepath")
171
- target_language = gr.Dropdown(
172
- label="Target language",
173
- choices=ASR_TARGET_LANGUAGE_NAMES,
174
- value=DEFAULT_TARGET_LANGUAGE,
175
- )
176
- btn = gr.Button("Transcribe")
177
- with gr.Column():
178
- output_text = gr.Textbox(label="Transcribed text")
179
-
180
- btn.click(
181
- fn=run_asr,
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
+ ```