import gradio as gr from transformers import pipeline from gtts import gTTS import os # Define translation models for each language pair translation_models = { 'Chinese': "Helsinki-NLP/opus-mt-en-zh", 'French': "Helsinki-NLP/opus-mt-en-fr", 'Spanish': "Helsinki-NLP/opus-mt-en-es", 'Russian': "Helsinki-NLP/opus-mt-en-ru", 'Arabic': "Helsinki-NLP/opus-mt-en-ar", 'Urdu': "Helsinki-NLP/opus-mt-en-ur", 'German': "Helsinki-NLP/opus-mt-en-de" } # Initialize translators translators = {lang: pipeline("translation", model=model) for lang, model in translation_models.items() if model} # Supported Languages language_options = { 'Arabic': 'ar', 'Chinese': 'zh', 'French': 'fr', 'German': 'de', 'Russian': 'ru', 'Spanish': 'es', 'Urdu': 'ur', } def translate_text(input_text, language): if language == 'English': return input_text model_name = translation_models.get(language) if model_name: try: translator = translators[language] translation = translator(input_text) return translation[0]['translation_text'] except Exception as e: return f"Error during translation: {str(e)}" else: return "Translation model not available." def text_to_speech(output_text, language): tts = gTTS(output_text, lang=language_options[language]) tts.save("output.mp3") return "output.mp3" def input_to_speech(input_text): tts = gTTS(input_text, lang='en') tts.save("input_speech.mp3") return "input_speech.mp3" def generate(input_text, language, translate, text_to_speech_opt, input_to_speech_opt): translated_text = "" translated_audio = None input_audio = None if translate: translated_text = translate_text(input_text, language) if text_to_speech_opt and translated_text: translated_audio = text_to_speech(translated_text, language) if input_to_speech_opt: input_audio = input_to_speech(input_text) return translated_text, translated_audio, input_audio def clear_fields(input_text, output_text, translated_audio_output, input_audio_output, translate_checkbox, text_to_speech_checkbox, input_to_speech_checkbox): """Clear input and output fields and uncheck option boxes.""" return "", "", None, None, False, False, False # Clear and set checkboxes to False # Gradio Interface with gr.Blocks() as demo: # Add a caption at the top gr.Markdown("
By Khalid Baig - Thanks to Aspire Pakistan
") demo.launch() share=True