Spaces:
Sleeping
Sleeping
File size: 4,114 Bytes
c21e277 1ed3aa2 5c32f97 1c5c910 c21e277 1c5c910 a1040ef 1c5c910 a1040ef c21e277 1c5c910 a1040ef c21e277 1c5c910 8ef7659 1c5c910 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
import streamlit as st
import pandas as pd
from transformers import pipeline
from datetime import datetime
# ================================
# Streamlit Page Configuration
# ================================
st.set_page_config(
page_title="π Multi-Language Translator",
layout="centered",
initial_sidebar_state="auto",
)
# ================================
# Cache the Translation Pipelines
# ================================
@st.cache_resource
def load_translation_pipelines():
"""
Load and cache translation pipelines to avoid reloading on every interaction.
"""
enja = pipeline("translation", model="staka/fugumt-en-ja")
jaen = pipeline("translation", model="staka/fugumt-ja-en")
zhja = pipeline("translation", model="Helsinki-NLP/opus-mt-tc-big-zh-ja")
return {'enja': enja, 'jaen': jaen, 'zhja': zhja}
# Load the translation models
try:
session_models = load_translation_pipelines()
except Exception as e:
st.error(f"Error loading translation models: {e}")
session_models = {}
# ================================
# Streamlit Application Layout
# ================================
st.title("π Multi-Language Translator")
# Initialize session state for CSV creation flag
if 'csv_created' not in st.session_state:
st.session_state.csv_created = False
# ================================
# User Input Section
# ================================
st.header("π€ Enter Text to Translate")
# Model selection
model_options = {
'English to Japanese': 'enja',
'Japanese to English': 'jaen',
'Chinese to Japanese': 'zhja'
}
model_display = list(model_options.keys())
model_keys = list(model_options.values())
selected_model_display = st.selectbox("Select Translation Model", model_display, index=0)
selected_model = model_options[selected_model_display]
# Text input
text = st.text_area("Input Text", height=150)
# ================================
# Translation and Output
# ================================
if st.button("π Translate"):
if not text.strip():
st.warning("Please enter text to translate.")
elif selected_model not in session_models:
st.error("Selected translation model is not available.")
else:
with st.spinner("Translating..."):
try:
translator = session_models[selected_model]
translation = translator(text)[0]['translation_text']
st.success("Translation Successful!")
st.subheader("π Translation Result")
st.write(translation)
# Prepare data for CSV
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = {
'Timestamp': [timestamp],
'Model': [selected_model_display],
'Original Text': [text],
'Translated Text': [translation]
}
df = pd.DataFrame(data)
# Save to CSV
csv_file = 'translation_data.csv'
if not st.session_state.csv_created:
df.to_csv(csv_file, mode='w', header=True, index=False)
st.session_state.csv_created = True
else:
df.to_csv(csv_file, mode='a', header=False, index=False)
st.info(f"Translation saved to `{csv_file}`.")
except Exception as e:
st.error(f"An error occurred during translation: {e}")
# ================================
# Optional: Download Translation Data
# ================================
if st.button("π₯ Download Translation Data"):
try:
df = pd.read_csv('translation_data.csv')
csv = df.to_csv(index=False).encode('utf-8')
st.download_button(
label="Download CSV",
data=csv,
file_name='translation_data.csv',
mime='text/csv',
)
except FileNotFoundError:
st.warning("No translation data available to download.")
except Exception as e:
st.error(f"An error occurred while preparing the download: {e}")
|