Spaces:
Runtime error
Runtime error
Download app.py from ShlomitL/Multilingual_translation_app: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/ShlomitL/Multilingual_translation_app/resolve/main/app.py
- Command line
-
hf download hf://spaces/ShlomitL/Multilingual_translation_app/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ShlomitL/Multilingual_translation_app/resolve/main/app.py
10.7 kB
| ''' | |
| This is a multilingual translation application built using Gradio and Hugging Face Transformers. | |
| It allows users to translate text from one language to another, with support for multiple languages. | |
| ''' | |
| import gradio as gr | |
| import json | |
| from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM | |
| from langdetect import detect, DetectorFactory | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| # Set seed for consistent language detection results | |
| DetectorFactory.seed = 0 | |
| class SmartTranslator: | |
| def __init__(self): | |
| self.load_language_models() | |
| self.supported_languages = { | |
| 'en': 'English', | |
| 'he': 'Hebrew', | |
| 'ar': 'Arabic', | |
| 'es': 'Spanish', | |
| 'fr': 'French', | |
| 'de': 'German', | |
| 'it': 'Italian', | |
| 'pt': 'Portuguese', | |
| 'ru': 'Russian', | |
| 'zh': 'Chinese', | |
| 'ja': 'Japanese', | |
| 'ko': 'Korean' | |
| } | |
| def load_language_models(self): | |
| """ | |
| Load translation models from Hugging Face Hub. | |
| Uses Helsinki-NLP OPUS-MT models for high-quality translation. | |
| Falls back to simpler models if main models fail to load. | |
| """ | |
| try: | |
| # Load Helsinki-NLP OPUS-MT models for better translation quality | |
| self.translators = { | |
| 'to_en': pipeline("translation", model="Helsinki-NLP/opus-mt-mul-en"), | |
| 'to_he': pipeline("translation", model="Helsinki-NLP/opus-mt-en-he"), | |
| 'to_es': pipeline("translation", model="Helsinki-NLP/opus-mt-en-es"), | |
| 'to_fr': pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr") | |
| } | |
| except Exception as e: | |
| print(f"Error loading primary models: {e}") | |
| # Fallback to simpler models if main models are unavailable | |
| self.translators = { | |
| 'to_en': pipeline("translation", model="t5-small"), | |
| 'to_he': None, # Hebrew model may not be available in fallback | |
| 'to_es': pipeline("translation", model="Helsinki-NLP/opus-mt-en-es"), | |
| 'to_fr': pipeline("translation", model="Helsinki-NLP/opus-mt-en-fr") | |
| } | |
| def detect_language(self, text): | |
| """ | |
| Detect the language of input text using langdetect library. | |
| Args: | |
| text (str): Input text to analyze | |
| Returns: | |
| tuple: (language_code, language_name) | |
| """ | |
| try: | |
| if not text.strip(): | |
| return "unknown", "Unknown" | |
| detected_lang = detect(text) | |
| language_name = self.supported_languages.get(detected_lang, detected_lang.upper()) | |
| return detected_lang, language_name | |
| except Exception as e: | |
| return "unknown", f"Detection Error: {str(e)}" | |
| def translate_text(self, text, source_lang, target_lang): | |
| """ | |
| Translate text from source language to target language. | |
| Uses two-step translation for non-English source languages. | |
| Args: | |
| text (str): Text to translate | |
| source_lang (str): Source language code | |
| target_lang (str): Target language code | |
| Returns: | |
| str: Translated text or error message | |
| """ | |
| try: | |
| if not text.strip(): | |
| return "No text to translate" | |
| # If source is same as target, return original text | |
| if source_lang == target_lang: | |
| return text | |
| # Handle non-English to non-English translation via English | |
| if source_lang != 'en' and target_lang != 'en': | |
| # Two-step translation: source -> English -> target | |
| if 'to_en' in self.translators and self.translators['to_en']: | |
| english_text = self.translators['to_en'](text)[0]['translation_text'] | |
| else: | |
| english_text = text # Fallback to original text | |
| # Then translate English to target language | |
| translator_key = f'to_{target_lang}' | |
| if translator_key in self.translators and self.translators[translator_key]: | |
| result = self.translators[translator_key](english_text)[0]['translation_text'] | |
| return result | |
| else: | |
| return f"Translation to {target_lang} not available" | |
| # Direct translation from non-English to English | |
| elif source_lang != 'en': | |
| if 'to_en' in self.translators and self.translators['to_en']: | |
| return self.translators['to_en'](text)[0]['translation_text'] | |
| else: | |
| return "Translation to English not available" | |
| # Direct translation from English to target language | |
| else: | |
| translator_key = f'to_{target_lang}' | |
| if translator_key in self.translators and self.translators[translator_key]: | |
| return self.translators[translator_key](text)[0]['translation_text'] | |
| else: | |
| return f"Translation to {target_lang} not available" | |
| except Exception as e: | |
| return f"Translation error: {str(e)}" | |
| def process_text(self, input_text): | |
| """ | |
| Main processing function that handles language detection and translation. | |
| Args: | |
| input_text (str): User input text | |
| Returns: | |
| tuple: (detection_result, translation1, translation2, translation3, status, original) | |
| """ | |
| if not input_text.strip(): | |
| return "Please enter some text to translate.", "", "", "", "", "" | |
| # Detect the language of input text | |
| detected_lang, language_name = self.detect_language(input_text) | |
| # Define target languages for translation (English, Hebrew, Spanish) | |
| target_languages = ['en', 'he', 'es'] | |
| # Generate translations for each target language | |
| translations = [] | |
| for target_lang in target_languages: | |
| if detected_lang != target_lang: | |
| translation = self.translate_text(input_text, detected_lang, target_lang) | |
| lang_name = self.supported_languages.get(target_lang, target_lang.upper()) | |
| translations.append(f"**{lang_name}:** {translation}") | |
| else: | |
| lang_name = self.supported_languages.get(target_lang, target_lang.upper()) | |
| translations.append(f"**{lang_name}:** (Original text)") | |
| # Prepare formatted output | |
| detection_result = f"**Detected Language:** {language_name} ({detected_lang})" | |
| return ( | |
| detection_result, | |
| translations[0] if len(translations) > 0 else "", | |
| translations[1] if len(translations) > 1 else "", | |
| translations[2] if len(translations) > 2 else "", | |
| f"✅ **Translation Complete!** Processed text in {language_name}", | |
| input_text | |
| ) | |
| # Initialize the translator instance | |
| translator = SmartTranslator() | |
| def create_interface(): | |
| """ | |
| Create the Gradio interface for the Smart Multilingual Translator. | |
| Returns: | |
| gr.Blocks: Configured Gradio application interface | |
| """ | |
| with gr.Blocks(title="Smart Multilingual Translator", theme=gr.themes.Soft()) as app: | |
| gr.Markdown(""" | |
| # 🌐 Smart Multilingual Translator | |
| ### Powered by Hugging Face Transformers | |
| Enter text in any language and get automatic translations to English, Hebrew, and Spanish! | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| input_text = gr.Textbox( | |
| label="Enter text to translate", | |
| placeholder="Type or paste text in any language...", | |
| lines=4, | |
| max_lines=10 | |
| ) | |
| translate_btn = gr.Button("🔄 Translate", variant="primary", size="lg") | |
| clear_btn = gr.Button("🗑️ Clear", variant="secondary") | |
| with gr.Column(scale=3): | |
| with gr.Group(): | |
| detection_output = gr.Markdown(label="Language Detection") | |
| translation1 = gr.Markdown(label="Translation 1") | |
| translation2 = gr.Markdown(label="Translation 2") | |
| translation3 = gr.Markdown(label="Translation 3") | |
| status_output = gr.Markdown(label="Status") | |
| original_display = gr.Textbox(label="Original Text", interactive=False, visible=False) | |
| # Example inputs for testing different languages | |
| gr.Markdown("### 📝 Try these examples:") | |
| gr.Examples( | |
| examples=[ | |
| ["Hello, how are you today?"], | |
| ["שלום, איך אתה היום?"], | |
| ["Hola, ¿cómo estás hoy?"], | |
| ["Bonjour, comment allez-vous?"], | |
| ["Guten Tag, wie geht es Ihnen?"], | |
| ["Привет, как дела?"], | |
| ["こんにちは、元気ですか?"], | |
| ["مرحبا، كيف حالك اليوم؟"] | |
| ], | |
| inputs=input_text | |
| ) | |
| # Event handlers for user interactions | |
| translate_btn.click( | |
| fn=translator.process_text, | |
| inputs=[input_text], | |
| outputs=[detection_output, translation1, translation2, translation3, status_output, original_display] | |
| ) | |
| clear_btn.click( | |
| fn=lambda: ("", "", "", "", "", ""), | |
| outputs=[input_text, detection_output, translation1, translation2, translation3, status_output] | |
| ) | |
| # Auto-translate when user presses Enter | |
| input_text.submit( | |
| fn=translator.process_text, | |
| inputs=[input_text], | |
| outputs=[detection_output, translation1, translation2, translation3, status_output, original_display] | |
| ) | |
| gr.Markdown(""" | |
| --- | |
| **Note:** This translator uses state-of-the-art models from Hugging Face. | |
| Translation quality may vary depending on the source and target languages. | |
| """) | |
| return app | |
| if __name__ == "__main__": | |
| # Create and launch the Gradio application | |
| app = create_interface() | |
| app.launch(share=True) # share=True creates a public link |