Spaces:
Sleeping
Sleeping
Download app.py from Hassan501/PythonAIBOOTCAMP: direct link, hf CLI and curl.
- Browser
- Download file 2.31 kB
-
https://huggingface.co/spaces/Hassan501/PythonAIBOOTCAMP/resolve/main/app.py
- Command line
-
hf download hf://spaces/Hassan501/PythonAIBOOTCAMP/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Hassan501/PythonAIBOOTCAMP/resolve/main/app.py
2.31 kB
| import streamlit as st | |
| from transformers import MBartForConditionalGeneration, MBart50Tokenizer | |
| # Load the model and tokenizer. Use st.cache_resource to cache the model, | |
| # preventing it from reloading every time the app updates. | |
| def load_translation_model(): | |
| model_name = "facebook/mbart-large-50-many-to-many-mmt" | |
| # Use the standard MBart50Tokenizer instead of the fast version | |
| tokenizer = MBart50Tokenizer.from_pretrained(model_name) | |
| model = MBartForConditionalGeneration.from_pretrained(model_name) | |
| return tokenizer, model | |
| tokenizer, model = load_translation_model() | |
| # Define the supported languages with their language codes | |
| LANGUAGES = { | |
| "English": "en_XX", | |
| "French": "fr_XX", | |
| "Spanish": "es_XX", | |
| "German": "de_DE", | |
| "Hindi": "hi_IN", | |
| "Chinese": "zh_CN", | |
| "Russian": "ru_RU", | |
| } | |
| def translate_text(text, source_lang, target_lang): | |
| """ | |
| Translates the input text from a source language to a target language. | |
| """ | |
| tokenizer.src_lang = source_lang | |
| encoded_text = tokenizer(text, return_tensors="pt") | |
| generated_tokens = model.generate( | |
| **encoded_text, | |
| forced_bos_token_id=tokenizer.lang_code_to_id[target_lang] | |
| ) | |
| translated_text = tokenizer.decode(generated_tokens[0], skip_special_tokens=True) | |
| return translated_text | |
| # Streamlit App Interface | |
| st.title("Multilingual Translator") | |
| st.markdown("Powered by **Hugging Face Transformers** and **Streamlit**") | |
| # Create a layout with two columns | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| source_lang_name = st.selectbox("Source Language", list(LANGUAGES.keys())) | |
| source_text = st.text_area("Enter text to translate", height=250) | |
| with col2: | |
| target_lang_name = st.selectbox("Target Language", list(LANGUAGES.keys())) | |
| if st.button("Translate"): | |
| if source_text: | |
| source_lang_code = LANGUAGES[source_lang_name] | |
| target_lang_code = LANGUAGES[target_lang_name] | |
| with st.spinner("Translating..."): | |
| translated_text = translate_text(source_text, source_lang_code, target_lang_code) | |
| st.text_area("Translated Text", value=translated_text, height=250, disabled=True) | |
| else: | |
| st.warning("Please enter some text to translate.") |