sainkan commited on
Commit
073d7e9
1 Parent(s): 2860826

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -0
main.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import MarianMTModel, MarianTokenizer
3
+
4
+ # Define available languages with MarianMT models
5
+ LANGUAGES = {
6
+ 'Spanish': 'es',
7
+ 'French': 'fr',
8
+ 'German': 'de',
9
+ 'Chinese': 'zh',
10
+ 'Hindi': 'hi',
11
+ 'Arabic': 'ar',
12
+ 'Japanese': 'ja',
13
+ 'Russian': 'ru',
14
+ 'Italian': 'it',
15
+ 'Portuguese': 'pt',
16
+ # Add more languages if needed
17
+ }
18
+
19
+ # Function to load the model based on the selected language
20
+ @st.cache_resource
21
+ def load_model(src_lang='en', tgt_lang='es'):
22
+ model_name = f'Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}'
23
+ model = MarianMTModel.from_pretrained(model_name)
24
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
25
+ return model, tokenizer
26
+
27
+ # Function to translate text
28
+ def translate_text(model, tokenizer, text):
29
+ inputs = tokenizer.encode(text, return_tensors='pt', truncation=True, padding=True)
30
+ translated = model.generate(inputs, max_length=512, num_beams=5, early_stopping=True)
31
+ translated_text = tokenizer.decode(translated[0], skip_special_tokens=True)
32
+ return translated_text
33
+
34
+ # Streamlit app
35
+ st.title("Language Translator")
36
+ st.write("Translate English text to any language using Hugging Face models.")
37
+
38
+ # Input text
39
+ text = st.text_area("Enter text in English to translate:")
40
+
41
+ # Language selection
42
+ language = st.selectbox("Choose target language", list(LANGUAGES.keys()))
43
+
44
+ if st.button("Translate"):
45
+ if text:
46
+ # Load model and tokenizer based on selected language
47
+ tgt_lang = LANGUAGES[language]
48
+ model, tokenizer = load_model('en', tgt_lang)
49
+
50
+ # Perform translation
51
+ translated_text = translate_text(model, tokenizer, text)
52
+
53
+ # Display the translation
54
+ st.write(f"**Translated text ({language}):**")
55
+ st.write(translated_text)
56
+ else:
57
+ st.write("Please enter text to translate.")