Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import MarianMTModel, MarianTokenizer
|
3 |
+
|
4 |
+
# Define a dictionary to map language names to model identifiers
|
5 |
+
models = {
|
6 |
+
'French': 'Helsinki-NLP/opus-mt-en-fr',
|
7 |
+
'Spanish': 'Helsinki-NLP/opus-mt-en-es',
|
8 |
+
'German': 'Helsinki-NLP/opus-mt-en-de',
|
9 |
+
'Italian': 'Helsinki-NLP/opus-mt-en-it',
|
10 |
+
'Urdu': 'Helsinki-NLP/opus-mt-en-ur',
|
11 |
+
'Arabic': 'Helsinki-NLP/opus-mt-en-ar',
|
12 |
+
# Add more language models if needed
|
13 |
+
}
|
14 |
+
|
15 |
+
def load_model(model_name):
|
16 |
+
"""Load the model and tokenizer based on the selected model name."""
|
17 |
+
model = MarianMTModel.from_pretrained(model_name)
|
18 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
19 |
+
return model, tokenizer
|
20 |
+
|
21 |
+
def translate_text(text, model, tokenizer):
|
22 |
+
"""Translate text using the provided model and tokenizer."""
|
23 |
+
inputs = tokenizer.encode(text, return_tensors="pt")
|
24 |
+
translated = model.generate(inputs)
|
25 |
+
translated_text = tokenizer.decode(translated[0], skip_special_tokens=True)
|
26 |
+
return translated_text
|
27 |
+
|
28 |
+
def main():
|
29 |
+
st.title("Multilingual Translator")
|
30 |
+
|
31 |
+
# User input for English text
|
32 |
+
text_to_translate = st.text_area("Enter text in English:")
|
33 |
+
|
34 |
+
# Language options
|
35 |
+
selected_language = st.selectbox("Select target language:", list(models.keys()))
|
36 |
+
|
37 |
+
if st.button("Translate"):
|
38 |
+
if text_to_translate:
|
39 |
+
# Load the selected model
|
40 |
+
model_name = models[selected_language]
|
41 |
+
model, tokenizer = load_model(model_name)
|
42 |
+
|
43 |
+
translated_text = translate_text(text_to_translate, model, tokenizer)
|
44 |
+
st.write(f"**Translation in {selected_language}:**")
|
45 |
+
st.write(translated_text)
|
46 |
+
else:
|
47 |
+
st.warning("Please enter text to translate.")
|
48 |
+
|
49 |
+
if __name__ == "__main__":
|
50 |
+
main()
|