fargerm commited on
Commit
56b97c3
1 Parent(s): 7b93a93

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import MarianMTModel, MarianTokenizer
3
+
4
+ # Define language options
5
+ LANGUAGES = {
6
+ "Spanish": "es",
7
+ "French": "fr",
8
+ "German": "de",
9
+ "Italian": "it",
10
+ "Portuguese": "pt",
11
+ }
12
+
13
+ # Load translation model and tokenizer
14
+ model_name = "Helsinki-NLP/opus-mt-en-ROMANCE"
15
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
16
+ model = MarianMTModel.from_pretrained(model_name)
17
+
18
+ def translate_text(text, target_language):
19
+ # Prepare the text for the model
20
+ translated = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
21
+ # Perform the translation
22
+ translated = model.generate(**translated, forced_bos_token_id=tokenizer.lang_code_to_id[target_language])
23
+ # Decode and return the translation
24
+ translated_text = tokenizer.decode(translated[0], skip_special_tokens=True)
25
+ return translated_text
26
+
27
+ # Streamlit app
28
+ st.title("Language Translator")
29
+
30
+ # User input
31
+ text_to_translate = st.text_area("Enter text in English:", "")
32
+ selected_language = st.selectbox("Select target language:", list(LANGUAGES.keys()))
33
+
34
+ if st.button("Translate"):
35
+ if text_to_translate:
36
+ target_language = LANGUAGES[selected_language]
37
+ translated_text = translate_text(text_to_translate, target_language)
38
+ st.write(f"Translated text ({selected_language}):")
39
+ st.write(translated_text)
40
+ else:
41
+ st.warning("Please enter text to translate.")
42
+