TANVEERMAKHDOOM
commited on
Commit
•
ce1f204
1
Parent(s):
f68ccc7
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import MarianMTModel, MarianTokenizer
|
3 |
+
|
4 |
+
# Initialize the model and tokenizer
|
5 |
+
def load_model_and_tokenizer(target_lang):
|
6 |
+
model_name = f'Helsinki-NLP/opus-mt-en-{target_lang}'
|
7 |
+
model = MarianMTModel.from_pretrained(model_name)
|
8 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
9 |
+
return model, tokenizer
|
10 |
+
|
11 |
+
# Function to translate text
|
12 |
+
def translate_text(text, model, tokenizer):
|
13 |
+
tokens = tokenizer(text, return_tensors="pt", padding=True)
|
14 |
+
translated_tokens = model.generate(**tokens)
|
15 |
+
translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
|
16 |
+
return translated_text
|
17 |
+
|
18 |
+
# Streamlit app
|
19 |
+
st.title("Language Translator")
|
20 |
+
|
21 |
+
# Input text
|
22 |
+
input_text = st.text_area("Enter text to translate", "Hello, how are you?")
|
23 |
+
|
24 |
+
# Language selection
|
25 |
+
target_language = st.selectbox(
|
26 |
+
"Select target language",
|
27 |
+
["fr", "de", "es", "it", "pt", "ru", "zh", "ja", "ar"]
|
28 |
+
)
|
29 |
+
|
30 |
+
# Load model and tokenizer based on selected language
|
31 |
+
if target_language:
|
32 |
+
model, tokenizer = load_model_and_tokenizer(target_language)
|
33 |
+
|
34 |
+
if st.button("Translate"):
|
35 |
+
if input_text:
|
36 |
+
translated_text = translate_text(input_text, model, tokenizer)
|
37 |
+
st.subheader("Translated text")
|
38 |
+
st.write(translated_text)
|
39 |
+
else:
|
40 |
+
st.error("Please enter some text to translate.")
|
41 |
+
|
42 |
+
streamlit run app.py
|