File size: 6,635 Bytes
891f160 8040f65 e656608 891f160 e656608 8040f65 891f160 e656608 8040f65 7377987 8040f65 506a3c0 8040f65 7eeede4 891f160 8040f65 506a3c0 8040f65 7eeede4 8040f65 506a3c0 7eeede4 8040f65 7eeede4 7377987 f21f8ec 7377987 f21f8ec 7eeede4 f21f8ec 7377987 f21f8ec 7377987 f21f8ec 8040f65 f21f8ec 506a3c0 f21f8ec 891f160 7eeede4 8040f65 e656608 506a3c0 8040f65 7eeede4 8040f65 891f160 8040f65 e656608 8886a34 7377987 28870f9 8040f65 891f160 |
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 121 122 123 124 125 126 127 128 129 130 131 |
import streamlit as st
import os
import importlib
# Set page config as the absolute first Streamlit command
st.set_page_config(page_title="Multilingual Translator", page_icon="🌐", layout="centered")
# Main app function
def main():
# Lazy import modules to avoid Streamlit initialization during import
translation = importlib.import_module("translation")
lang_detect = importlib.import_module("lang_detect")
audio_processor = importlib.import_module("audio_processor")
# Title and header with styling
st.markdown("<h1 style='text-align: center; color: #2E86C1;'>Multilingual Translator</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; color: #666;'>Translate text or audio for multilingual support.</p>", unsafe_allow_html=True)
# Tabs for input methods
tab1, tab2, tab3 = st.tabs(["Text Input", "Audio Input", "Document Upload"])
# Initialize session state for results
if 'translated_text' not in st.session_state:
st.session_state.translated_text = None
st.session_state.audio_path = None
st.session_state.source_lang = None
st.session_state.detected_options = []
with tab1:
# Text input
user_text = st.text_area("Enter Text", placeholder="Type or paste your text here...", height=150, key="text_input").strip()
if user_text:
handle_input(user_text, "text", translation, lang_detect, audio_processor)
with tab2:
# Audio input
audio_file = st.file_uploader("Upload Audio (MP3/WAV)", type=["mp3", "wav"], key="audio_input")
if audio_file:
user_text = audio_processor.transcribe_audio(audio_file).strip()
st.write(f"Transcribed Text: {user_text}")
handle_input(user_text, "audio", translation, lang_detect, audio_processor)
with tab3:
# Document input
doc_file = st.file_uploader("Upload Document (TXT)", type=["txt"], key="doc_input")
if doc_file:
user_text = doc_file.read().decode("utf-8").strip() # Explicit decoding and stripping
st.write(f"Raw Document Text: {user_text}") # Debug raw input
handle_input(user_text, "doc", translation, lang_detect, audio_processor)
# Handle input processing
def handle_input(text, input_type, translation, lang_detect, audio_processor):
# Auto-detect source language with options
if len(text) < 10: # Minimum length for reliable detection
detected_options = [("English", 1.0, "English")]
else:
detected_options = lang_detect.detect_language(text)
st.session_state.detected_options = detected_options
# Set initial source language to the top detected option
st.session_state.source_lang = detected_options[0][0] if detected_options else "English"
# Display native language names for detected options
native_lang_map = {
"English": "English",
"French": "Français",
"Spanish": "Español",
"German": "Deutsch",
"Hindi": "हिन्दी",
"Chinese": "中文",
"Arabic": "العربية",
"Russian": "Русский",
"Japanese": "日本語",
}
display_options = ["Auto"] + [f"{native_lang_map.get(lang, lang)} ({conf:.2f})" for lang, conf, _ in detected_options] + list(translation.LANGUAGES.keys())
override_lang = st.selectbox("Override Detected Language", display_options, index=0, key=f"override_lang_{input_type}")
# Map override selection to supported language
if override_lang != "Auto":
selected_lang = next((lang for lang, _, _ in detected_options if native_lang_map.get(lang, lang) in override_lang), override_lang)
st.session_state.source_lang = selected_lang
st.info(f"Selected Source Language: {native_lang_map.get(st.session_state.source_lang, st.session_state.source_lang)}")
# Target language selection with native names
target_options = {lang: native_lang_map.get(lang, lang) for lang in translation.LANGUAGES}
target_lang = st.selectbox("Target Language", [target_options[lang] for lang in translation.LANGUAGES],
index=list(translation.LANGUAGES.keys()).index("Hindi") if "Hindi" in translation.LANGUAGES else 1,
key=f"target_lang_{input_type}", format_func=lambda x: x)
target_lang = next(key for key, value in target_options.items() if value == target_lang)
# Translate button
if st.button("Translate", key=f"translate_button_{input_type}"):
with st.spinner("Translating..."):
try:
# Translate the text
st.session_state.translated_text = translation.translate(text, st.session_state.source_lang, target_lang)
st.write(f"Translated Text (Debug): {st.session_state.translated_text}") # Debug output
# Display results in a styled container
st.markdown("<h3 style='color: #2E86C1;'>Translation Result</h3>", unsafe_allow_html=True)
# Output options: Text and Audio
output_option = st.radio("Output Format", ["Text", "Audio"], key=f"output_option_{input_type}")
if output_option == "Text":
st.success("Translated Text:")
st.write(st.session_state.translated_text)
elif output_option == "Audio":
st.success("Translated Audio:")
st.session_state.audio_path = audio_processor.text_to_speech(st.session_state.translated_text, target_lang)
if st.session_state.audio_path:
st.audio(st.session_state.audio_path)
else:
st.error("Failed to generate audio. Please check the target language or server permissions.")
# Show footer after translation
st.markdown("""
<p style='font-size: small; color: grey; text-align: center; margin-top: 20px;'>
Developed By: Krishna Prakash
<a href='https://www.linkedin.com/in/krishnaprakash-profile/' target='_blank'>
<img src='https://img.icons8.com/ios-filled/30/0077b5/linkedin.png' alt='LinkedIn' style='vertical-align: middle; margin: 0 5px;'/>
</a>
</p>
""", unsafe_allow_html=True)
except Exception as e:
st.error(f"Translation failed: {str(e)}")
# Run the app
if __name__ == "__main__":
main() |