Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,72 +1,108 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
import torch
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
import torch
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
import logging
|
| 7 |
+
import asyncio
|
| 8 |
+
from typing import Optional
|
| 9 |
+
from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq, AutoModelForTextToSpectrogram
|
| 10 |
+
from deep_translator import GoogleTranslator
|
| 11 |
+
import time
|
| 12 |
+
import threading
|
| 13 |
+
import torchaudio
|
| 14 |
+
|
| 15 |
+
# Set up logging
|
| 16 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Device setup
|
| 20 |
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 21 |
+
logger.info(f"Device set to use {device}")
|
| 22 |
+
|
| 23 |
+
# Supported languages
|
| 24 |
+
SUPPORTED_LANGUAGES = {
|
| 25 |
+
"English": "en",
|
| 26 |
+
"Hindi": "hi",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
# Load ASR (Speech Recognition) Model
|
| 30 |
+
asr_processor = AutoProcessor.from_pretrained("openai/whisper-base")
|
| 31 |
+
asr_model = AutoModelForSpeechSeq2Seq.from_pretrained("openai/whisper-base").to(device)
|
| 32 |
+
|
| 33 |
+
# Load TTS (Text-to-Speech) Model
|
| 34 |
+
tts_processor = AutoProcessor.from_pretrained("microsoft/speecht5_tts")
|
| 35 |
+
tts_model = AutoModelForTextToSpectrogram.from_pretrained("microsoft/speecht5_tts").to(device)
|
| 36 |
+
|
| 37 |
+
def speech_to_text(audio_data: np.ndarray, sample_rate: int) -> str:
|
| 38 |
+
try:
|
| 39 |
+
if len(audio_data.shape) > 1:
|
| 40 |
+
audio_data = np.mean(audio_data, axis=1)
|
| 41 |
+
audio_data = torch.tensor(audio_data, dtype=torch.float32).to(device)
|
| 42 |
+
|
| 43 |
+
inputs = asr_processor(audio_data, sampling_rate=sample_rate, return_tensors="pt").to(device)
|
| 44 |
+
outputs = asr_model.generate(**inputs)
|
| 45 |
+
text = asr_processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 46 |
+
logger.info(f"Transcribed text: {text}")
|
| 47 |
+
return text if text else ""
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logger.error(f"STT failed: {str(e)}")
|
| 50 |
+
return ""
|
| 51 |
+
|
| 52 |
+
def text_to_speech(text: str, lang: str) -> Optional[str]:
|
| 53 |
+
try:
|
| 54 |
+
if not text or not text.strip():
|
| 55 |
+
logger.warning("Empty text received for TTS.")
|
| 56 |
+
return None
|
| 57 |
+
target_lang_code = SUPPORTED_LANGUAGES.get(lang, "en")
|
| 58 |
+
translated_text = GoogleTranslator(source="auto", target=target_lang_code).translate(text)
|
| 59 |
+
|
| 60 |
+
inputs = tts_processor(translated_text, return_tensors="pt").to(device)
|
| 61 |
+
spectrogram = tts_model.generate(**inputs)
|
| 62 |
+
|
| 63 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_file:
|
| 64 |
+
torchaudio.save(temp_file.name, spectrogram.cpu(), 16000)
|
| 65 |
+
return temp_file.name
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.error(f"TTS failed: {str(e)}")
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
async def process_audio_stream(audio_stream, target_lang: str):
|
| 71 |
+
async for sample_rate, audio_chunk in audio_stream:
|
| 72 |
+
try:
|
| 73 |
+
if audio_chunk is None or not isinstance(audio_chunk, np.ndarray):
|
| 74 |
+
yield "", None
|
| 75 |
+
continue
|
| 76 |
+
text = speech_to_text(audio_chunk, sample_rate)
|
| 77 |
+
dubbed_audio = text_to_speech(text, target_lang) if text and text.strip() else None
|
| 78 |
+
yield text, dubbed_audio
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"Stream processing failed: {str(e)}")
|
| 81 |
+
yield "", None
|
| 82 |
+
|
| 83 |
+
def run_cleanup():
|
| 84 |
+
while True:
|
| 85 |
+
for root, dirs, files in os.walk(tempfile.gettempdir()):
|
| 86 |
+
for file in files:
|
| 87 |
+
if file.endswith(".wav"):
|
| 88 |
+
try:
|
| 89 |
+
os.remove(os.path.join(root, file))
|
| 90 |
+
except:
|
| 91 |
+
pass
|
| 92 |
+
time.sleep(300)
|
| 93 |
+
|
| 94 |
+
with gr.Blocks(title="Real-Time Multilingual Dubbing") as demo:
|
| 95 |
+
gr.Markdown("<h1>Real-Time Multilingual Dubbing</h1>")
|
| 96 |
+
with gr.Row():
|
| 97 |
+
audio_input = gr.Audio(sources=["microphone"], type="numpy", streaming=True, label="Speak")
|
| 98 |
+
lang_dropdown = gr.Dropdown(choices=list(SUPPORTED_LANGUAGES.keys()), label="Target Language", value="English")
|
| 99 |
+
with gr.Row():
|
| 100 |
+
stt_output = gr.Textbox(label="Transcription")
|
| 101 |
+
dub_output = gr.Audio(label="Dubbed Audio", autoplay=True)
|
| 102 |
+
|
| 103 |
+
audio_input.stream(fn=process_audio_stream, inputs=[audio_input, lang_dropdown], outputs=[stt_output, dub_output])
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
cleanup_thread = threading.Thread(target=run_cleanup, daemon=True)
|
| 107 |
+
cleanup_thread.start()
|
| 108 |
+
demo.launch()
|