rohanmiriyala commited on
Commit
451ec22
·
verified ·
1 Parent(s): 66a9507

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py
2
+ from __future__ import annotations
3
+ import os
4
+ import io
5
+ import torch
6
+ import numpy as np
7
+ import torchaudio
8
+ import nltk
9
+ import gradio as gr
10
+ from pydub import AudioSegment
11
+
12
+ from transformers import (
13
+ SeamlessM4TFeatureExtractor,
14
+ SeamlessM4TTokenizer,
15
+ SeamlessM4Tv2ForSpeechToText,
16
+ AutoTokenizer,
17
+ AutoFeatureExtractor
18
+ )
19
+ from parler_tts import ParlerTTSForConditionalGeneration
20
+
21
+ nltk.download('punkt')
22
+
23
+ # === CONFIG ===
24
+ HF_TOKEN = os.getenv("HF_TOKEN")
25
+ device = "cuda" if torch.cuda.is_available() else "cpu"
26
+ torch_dtype = torch.bfloat16 if device != "cpu" else torch.float32
27
+ SAMPLE_RATE = 16000
28
+ DEFAULT_TARGET_LANGUAGE = "Hindi"
29
+
30
+ # === Load translation model ===
31
+ trans_model = SeamlessM4Tv2ForSpeechToText.from_pretrained(
32
+ "ai4bharat/indic-seamless", torch_dtype=torch_dtype, token=HF_TOKEN
33
+ ).to(device)
34
+ processor = SeamlessM4TFeatureExtractor.from_pretrained("ai4bharat/indic-seamless", token=HF_TOKEN)
35
+ tokenizer = SeamlessM4TTokenizer.from_pretrained("ai4bharat/indic-seamless", token=HF_TOKEN)
36
+
37
+ # === Load TTS models ===
38
+ tts_repo = "ai4bharat/indic-parler-tts-pretrained"
39
+ tts_finetuned_repo = "ai4bharat/indic-parler-tts"
40
+ tts_model = ParlerTTSForConditionalGeneration.from_pretrained(
41
+ tts_repo, attn_implementation="eager", torch_dtype=torch_dtype
42
+ ).to(device)
43
+ tts_finetuned_model = ParlerTTSForConditionalGeneration.from_pretrained(
44
+ tts_finetuned_repo, attn_implementation="eager", torch_dtype=torch_dtype
45
+ ).to(device)
46
+ desc_tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-large")
47
+ text_tokenizer = AutoTokenizer.from_pretrained(tts_repo)
48
+
49
+ tts_sampling_rate = tts_model.audio_encoder.config.sampling_rate
50
+
51
+ # === Utilities ===
52
+ def numpy_to_mp3(audio_array, sampling_rate):
53
+ if np.issubdtype(audio_array.dtype, np.floating):
54
+ audio_array = (audio_array / np.max(np.abs(audio_array))) * 32767
55
+ audio_array = audio_array.astype(np.int16)
56
+ segment = AudioSegment(
57
+ audio_array.tobytes(),
58
+ frame_rate=sampling_rate,
59
+ sample_width=audio_array.dtype.itemsize,
60
+ channels=1
61
+ )
62
+ mp3_io = io.BytesIO()
63
+ segment.export(mp3_io, format="mp3", bitrate="320k")
64
+ return mp3_io.getvalue()
65
+
66
+ def chunk_text(text, max_words=25):
67
+ sentences = nltk.sent_tokenize(text)
68
+ chunks, curr = [], ""
69
+ for s in sentences:
70
+ candidate = f"{curr} {s}".strip()
71
+ if len(candidate.split()) > max_words:
72
+ if curr: chunks.append(curr)
73
+ curr = s
74
+ else:
75
+ curr = candidate
76
+ if curr: chunks.append(curr)
77
+ return chunks
78
+
79
+ # === Translation ===
80
+ def translate_audio(input_audio, target_language):
81
+ audio, orig_sr = torchaudio.load(input_audio)
82
+ audio = torchaudio.functional.resample(audio, orig_sr, SAMPLE_RATE)
83
+ inputs = processor(audio, sampling_rate=SAMPLE_RATE, return_tensors="pt").to(device, dtype=torch_dtype)
84
+ target_lang_code = "hin" # default Hindi, change as needed
85
+ gen_ids = trans_model.generate(**inputs, tgt_lang=target_lang_code)[0]
86
+ return tokenizer.decode(gen_ids, skip_special_tokens=True)
87
+
88
+ # === TTS generation ===
89
+ def generate_tts(text, description, use_finetuned=False):
90
+ model = tts_finetuned_model if use_finetuned else tts_model
91
+ inputs = desc_tokenizer(description, return_tensors="pt").to(device)
92
+ chunks = chunk_text(text)
93
+
94
+ all_audio = []
95
+ for chunk in chunks:
96
+ prompt = text_tokenizer(chunk, return_tensors="pt").to(device)
97
+ gen = model.generate(
98
+ input_ids=inputs.input_ids,
99
+ attention_mask=inputs.attention_mask,
100
+ prompt_input_ids=prompt.input_ids,
101
+ prompt_attention_mask=prompt.attention_mask,
102
+ do_sample=True,
103
+ return_dict_in_generate=True
104
+ )
105
+ if hasattr(gen, 'sequences') and hasattr(gen, 'audios_length'):
106
+ audio = gen.sequences[0, :gen.audios_length[0]]
107
+ audio_np = audio.float().cpu().numpy().flatten()
108
+ all_audio.append(audio_np)
109
+ combined = np.concatenate(all_audio)
110
+ return numpy_to_mp3(combined, sampling_rate=tts_sampling_rate)
111
+
112
+ # === Gradio UI ===
113
+ with gr.Blocks() as demo:
114
+ gr.Markdown("## 🎙️ Speech-to-Text → Text-to-Speech Demo")
115
+
116
+ with gr.Row():
117
+ with gr.Column():
118
+ input_audio = gr.Audio(label="Upload or record audio", type="filepath")
119
+ target_language = gr.Textbox(label="Target language (default Hindi)", value="Hindi")
120
+ btn_translate = gr.Button("Translate to text")
121
+ with gr.Column():
122
+ translated_text = gr.Textbox(label="Translated text")
123
+
124
+ btn_translate.click(
125
+ translate_audio,
126
+ inputs=[input_audio, target_language],
127
+ outputs=translated_text
128
+ )
129
+
130
+ with gr.Row():
131
+ with gr.Column():
132
+ voice_desc = gr.Textbox(label="Voice description", value="A calm, neutral Indian voice, clear audio.")
133
+ use_finetuned = gr.Checkbox(label="Use fine-tuned TTS", value=True)
134
+ btn_tts = gr.Button("Generate speech")
135
+ with gr.Column():
136
+ generated_audio = gr.Audio(label="Generated speech", format="mp3", autoplay=True)
137
+
138
+ btn_tts.click(
139
+ generate_tts,
140
+ inputs=[translated_text, voice_desc, use_finetuned],
141
+ outputs=generated_audio
142
+ )
143
+
144
+ demo.launch(share=True)