kasper-boy's picture
Create app.py
65354be verified
raw
history blame
3.18 kB
import streamlit as st
import torch
import json
from transformers import pipeline
from PIL import Image
# Initialize the translation pipeline
text_translator = pipeline("translation", model="facebook/nllb-200-distilled-600M", torch_dtype=torch.bfloat16)
# Load the JSON data from the file
with open('language.json', 'r') as file:
language_data = json.load(file)
# Extract language names from the JSON data
language_names = [entry['Language'] for entry in language_data]
def get_FLORES_code_from_language(language):
for entry in language_data:
if entry['Language'].lower() == language.lower():
return entry['FLORES-200 code']
return None
def translate_text(text, destination_language):
dest_code = get_FLORES_code_from_language(destination_language)
if dest_code:
translation = text_translator(text, src_lang="eng_Latn", tgt_lang=dest_code)
return translation[0]["translation_text"]
else:
return "Destination language code not found."
# Custom CSS for styling
st.markdown("""
<style>
.main {
background-color: #f0f2f6;
color: #4f4f4f;
}
.title {
font-family: 'Arial', sans-serif;
color: #336699;
font-size: 32px;
}
.description {
font-family: 'Arial', sans-serif;
color: #4f4f4f;
font-size: 18px;
}
.footer {
font-family: 'Arial', sans-serif;
color: #999999;
font-size: 12px;
text-align: center;
}
.textbox {
font-family: 'Courier New', monospace;
color: #333333;
background-color: #ffffff;
}
</style>
""", unsafe_allow_html=True)
# App layout
st.markdown('<div class="title">🌐 Multi-language Translator</div>', unsafe_allow_html=True)
st.markdown('<div class="description">This application translates any English text to multiple languages with ease and efficiency.</div>', unsafe_allow_html=True)
# Display a header image
image = Image.open('translator.png')
st.image(image, use_column_width=True)
# Create a sidebar for navigation
st.sidebar.header("Translation Settings")
text_to_translate = st.sidebar.text_area("Input text to translate", height=150, key="input_text")
destination_language = st.sidebar.selectbox("Select Destination Language", language_names, key="language_select")
# Translate button
if st.sidebar.button("Translate", key="translate_button"):
if text_to_translate:
translated_text = translate_text(text_to_translate, destination_language)
st.markdown("### Translated text")
st.text_area("", value=translated_text, height=150, key="translated_text", help="This is the translated text.", class_="textbox")
else:
st.warning("Please enter text to translate")
# Footer
st.markdown('<div class="footer">Developed with ❤️ using Streamlit</div>', unsafe_allow_html=True)
# Instructions or any additional information
st.sidebar.write("Instructions")
st.sidebar.write("1. Enter the text you want to translate in the input box.")
st.sidebar.write("2. Select the desired language from the dropdown menu.")
st.sidebar.write("3. Click 'Translate' to get the translation.")