Spaces:
Running

Gradiotranslate / app.py
snowmeii's picture
Update app.py
53e7e3d verified
Raw History Blame Contribute Delete
3.71 kB
# -*- coding: utf-8 -*-
"""MaiNguyen_1646004_Interactive_English_to_Vietnamese_Translator_with_audio.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1RCNFslhFIQ88FLxOI97-PtbR9R1B5xry
# Project Title: Interactive English-to-Vietnamese Translator
**What you will learn:**
How to load pre-trained Neural Machine Translation (NMT) models.
How to use the Hugging Face pipeline API.
How to build a quick, shareable Web UI using Gradio.
This project uses Hugging Face Transformers (the industry standard for NLP) and Gradio to build an interactive, web-based Translation App
"""
install transformers gradio gTTS sentencepiece sacremoses -q
"""Import Libraries and Load the Model
We will use a MarianMT model specifically trained to translate from English to Vietnamese.
(Note: The first time you run this, it will take about 30-60 seconds to download the model weights).
"""
import gradio as gr
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
print("Loading translation model... (this may take a minute)")
# Helsinki-NLP provides excellent, lightweight open-source translation models
model_name = "Helsinki-NLP/opus-mt-en-vi"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# Define a custom translator callable that behaves like the pipeline
def translator(sentences):
# Handle both a single string and a list of strings
is_list = isinstance(sentences, list)
inputs = [sentences] if not is_list else sentences
# Tokenize, generate translations, and decode
inputs_tokenized = tokenizer(inputs, return_tensors="pt", padding=True, truncation=True)
translated_tokens = model.generate(**inputs_tokenized)
decoded_translations = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
# Re-format output to match the original pipeline structure: list of dicts
output = [{"translation_text": text} for text in decoded_translations]
return output if is_list else output
print("Model loaded successfully!")
"""Create the Translation Function & Web UI
Now we will wrap the model in a Python function and use Gradio to create a visual text box where you can type and translate.
"""
import gradio as gr
from gtts import gTTS
import os
# 1. Define the translation and speech function
def translate_and_speak(text):
if not text.strip():
return "Please enter some text to translate.", None
# Generate translation
result = translator(text)
translated_text = result[0]['translation_text']
# Generate Vietnamese speech audio
tts = gTTS(text=translated_text, lang='vi')
audio_path = "translation.mp3"
tts.save(audio_path)
return translated_text, audio_path
# 2. Build the Gradio Interface with both Text and Audio outputs
iface = gr.Interface(
fn=translate_and_speak,
inputs=gr.Textbox(lines=5, placeholder="Type your English text here..."),
outputs=[
gr.Textbox(label="Vietnamese Translation"),
gr.Audio(label="Pronunciation (Audio)", type="filepath")
],
title="🌍 English to Vietnamese Translator with Audio",
description="Type a sentence to get both the Vietnamese text translation and the spoken audio pronunciation!",
examples=[
["Hello, how are you doing today?"],
["I am learning about artificial intelligence and machine learning."],
["The weather is beautiful, let's go to the park."]
]
)
# 3. Launch the app
iface.launch(share=True)
"""You will modify the above code translate from English to Vietnamese.
You must send me the public URL generated so that I can test your output
"""