File size: 6,722 Bytes
63ee3e5
 
 
 
d744aff
 
63ee3e5
d744aff
 
 
63ee3e5
 
35bcda1
63ee3e5
 
d744aff
 
 
63ee3e5
 
 
c098e72
63ee3e5
 
c7f56a8
 
 
c098e72
c7f56a8
 
d744aff
1ee4794
d744aff
1ee4794
d744aff
 
 
1ee4794
d744aff
 
 
 
 
 
1ee4794
 
d744aff
63ee3e5
 
d744aff
 
 
63ee3e5
d744aff
63ee3e5
d744aff
 
 
 
 
 
 
 
c7f56a8
d744aff
63ee3e5
 
d744aff
1ee4794
d744aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7f56a8
1ee4794
 
 
c7f56a8
d744aff
 
 
 
63ee3e5
1ee4794
 
 
d744aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee4794
d744aff
1ee4794
d744aff
 
1ee4794
d744aff
 
 
 
1ee4794
d744aff
63ee3e5
d744aff
1ee4794
d744aff
1ee4794
d744aff
 
c7f56a8
63ee3e5
 
 
d744aff
 
63ee3e5
 
d744aff
1ee4794
63ee3e5
 
d744aff
 
63ee3e5
 
d744aff
 
 
63ee3e5
 
 
 
d744aff
63ee3e5
c7f56a8
 
 
 
 
 
d744aff
c7f56a8
d744aff
c7f56a8
 
63ee3e5
d744aff
63ee3e5
d744aff
1ee4794
d744aff
63ee3e5
 
 
 
 
d744aff
63ee3e5
 
 
 
 
 
1ee4794
63ee3e5
d744aff
 
1ee4794
 
 
 
63ee3e5
 
 
 
 
 
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
import gradio as gr
import torch
import numpy as np
import librosa
from transformers import pipeline, VitsModel, AutoTokenizer
import scipy  # if needed for processing

# -----------------------------------------------
# 1. ASR Pipeline (English)
# -----------------------------------------------
asr = pipeline(
    "automatic-speech-recognition",
    model="facebook/wav2vec2-base-960h"
)

# -----------------------------------------------
# 2. Translation Models (3 languages)
# -----------------------------------------------
translation_models = {
    "Spanish": "Helsinki-NLP/opus-mt-en-es",
    "Chinese": "Helsinki-NLP/opus-mt-en-zh",
    "Japanese": "Helsinki-NLP/opus-mt-en-ja"
}

translation_tasks = {
    "Spanish": "translation_en_to_es",
    "Chinese": "translation_en_to_zh",
    "Japanese": "translation_en_to_ja"
}

# -----------------------------------------------
# 3. TTS Model Configurations (All VITS)
# -----------------------------------------------
# Make sure these model IDs exist on Hugging Face.
tts_config = {
    "Spanish": {
        "model_id": "facebook/mms-tts-spa",
        "architecture": "vits"
    },
    "Chinese": {
        "model_id": "facebook/mms-tts-che",
        "architecture": "vits"
    },
    "Japanese": {
        "model_id": "facebook/mms-tts-jpn",
        "architecture": "vits"
    }
}

# -----------------------------------------------
# 4. Caches
# -----------------------------------------------
translator_cache = {}
tts_model_cache = {}  # store (model, tokenizer, architecture)

# -----------------------------------------------
# 5. Translator Helper
# -----------------------------------------------
def get_translator(lang):
    if lang in translator_cache:
        return translator_cache[lang]
    model_name = translation_models[lang]
    task_name = translation_tasks[lang]
    translator = pipeline(task_name, model=model_name)
    translator_cache[lang] = translator
    return translator

# -----------------------------------------------
# 6. TTS Loading Helper
# -----------------------------------------------
def get_tts_model(lang):
    """
    Loads (model, tokenizer, architecture) from Hugging Face once, then caches.
    """
    if lang in tts_model_cache:
        return tts_model_cache[lang]
    
    config = tts_config.get(lang)
    if config is None:
        raise ValueError(f"No TTS config found for language: {lang}")
    
    model_id = config["model_id"]
    arch = config["architecture"]
    
    try:
        # Since arch == "vits" for all three languages, we load VitsModel + AutoTokenizer
        model = VitsModel.from_pretrained(model_id)
        tokenizer = AutoTokenizer.from_pretrained(model_id)
    except Exception as e:
        raise RuntimeError(f"Failed to load TTS model {model_id}: {e}")
    
    tts_model_cache[lang] = (model, tokenizer, arch)
    return tts_model_cache[lang]

# -----------------------------------------------
# 7. TTS Inference Helper
# -----------------------------------------------
def run_tts_inference(lang, text):
    """
    Generates waveform using the loaded TTS model and tokenizer.
    Returns (sample_rate, np_array).
    """
    model, tokenizer, arch = get_tts_model(lang)
    inputs = tokenizer(text, return_tensors="pt")
    
    with torch.no_grad():
        output = model(**inputs)
    
    # VitsModel output is typically `.waveform`
    if hasattr(output, "waveform"):
        waveform_tensor = output.waveform
    else:
        raise RuntimeError("TTS model output does not contain 'waveform'.")
    
    # Convert to numpy
    waveform = waveform_tensor.squeeze().cpu().numpy()
    
    # MMS TTS typically uses 16 kHz
    sample_rate = 16000
    return (sample_rate, waveform)

# -----------------------------------------------
# 8. Prediction Function
# -----------------------------------------------
def predict(audio, text, target_language):
    """
    1. Obtain English text (from text input or ASR).
    2. Translate English -> target_language.
    3. Run VITS-based TTS for that language.
    """
    # Step 1: English text
    if text.strip():
        english_text = text.strip()
    elif audio is not None:
        sample_rate, audio_data = audio
        
        # Convert to float32
        if audio_data.dtype not in [np.float32, np.float64]:
            audio_data = audio_data.astype(np.float32)
        
        # Convert stereo to mono if needed
        if len(audio_data.shape) > 1 and audio_data.shape[1] > 1:
            audio_data = np.mean(audio_data, axis=1)
        
        # Resample to 16k
        if sample_rate != 16000:
            audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=16000)
        
        asr_input = {"array": audio_data, "sampling_rate": 16000}
        asr_result = asr(asr_input)
        english_text = asr_result["text"]
    else:
        return "No input provided.", "", None

    # Step 2: Translation
    translator = get_translator(target_language)
    try:
        translation_result = translator(english_text)
        translated_text = translation_result[0]["translation_text"]
    except Exception as e:
        return english_text, f"Translation error: {e}", None

    # Step 3: TTS
    try:
        sample_rate, waveform = run_tts_inference(target_language, translated_text)
    except Exception as e:
        return english_text, translated_text, f"TTS error: {e}"

    return english_text, translated_text, (sample_rate, waveform)

# -----------------------------------------------
# 9. Gradio Interface
# -----------------------------------------------
iface = gr.Interface(
    fn=predict,
    inputs=[
        gr.Audio(type="numpy", label="Record/Upload English Audio (optional)"),
        gr.Textbox(lines=4, placeholder="Or enter English text here", label="English Text Input (optional)"),
        gr.Dropdown(choices=["Spanish", "Chinese", "Japanese"], value="Spanish", label="Target Language")
    ],
    outputs=[
        gr.Textbox(label="English Transcription"),
        gr.Textbox(label="Translation (Target Language)"),
        gr.Audio(label="Synthesized Speech in Target Language")
    ],
    title="Multimodal Language Learning Aid (MMS TTS / VITS)",
    description=(
        "This app:\n"
        "1. Transcribes English speech (via ASR) or accepts English text.\n"
        "2. Translates to Spanish, Chinese, or Japanese (Helsinki-NLP).\n"
        "3. Synthesizes speech with VITS-based MMS TTS models.\n\n"
        "Note: Ensure the MMS model IDs exist on Hugging Face. If not, you'll see an error.\n"
        "Record/upload English audio or enter text, then select a target language."
    ),
    allow_flagging="never"
)

if __name__ == "__main__":
    iface.launch()