AI-powered Speech Translator Python, AI

👤 Sharing: AI
```python
import speech_recognition as sr
from googletrans import Translator

def speech_to_text(language='en-US'):
    """
    Converts speech to text using Google Speech Recognition.

    Args:
        language (str): The language code for the speech recognition. Defaults to 'en-US'.

    Returns:
        str: The transcribed text, or None if speech recognition fails.
    """
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)

    try:
        text = r.recognize_google(audio, language=language)
        print("You said: {}".format(text))
        return text
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
        return None
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
        return None

def translate_text(text, target_language='es'):
    """
    Translates text using Google Translate.

    Args:
        text (str): The text to translate.
        target_language (str): The target language code. Defaults to 'es' (Spanish).

    Returns:
        str: The translated text, or None if translation fails.
    """
    translator = Translator()
    try:
        translation = translator.translate(text, dest=target_language)
        print("Translated to {}: {}".format(target_language, translation.text))
        return translation.text
    except Exception as e:
        print(f"Translation error: {e}")
        return None


def speech_translator(source_language='en-US', target_language='es'):
    """
    Combines speech recognition and translation to translate spoken language.

    Args:
        source_language (str): The language code for the speech recognition. Defaults to 'en-US'.
        target_language (str): The target language code for the translation. Defaults to 'es' (Spanish).
    """
    text = speech_to_text(source_language)
    if text:
        translated_text = translate_text(text, target_language)
        if translated_text:
            print("Translation complete.")
        else:
            print("Translation failed.")
    else:
        print("Speech recognition failed.")


if __name__ == '__main__':
    # Example usage: Translate English speech to Spanish
    speech_translator(source_language='en-US', target_language='es')

    # Example usage: Translate French speech to English
    # speech_translator(source_language='fr-FR', target_language='en')
```
👁️ Viewed: 19

Comments