Translate

This application allows the robot to use a microphone to record a phrase in spanish and then with the help of Google APIs translate it to English.

  • First we need to import the libraries that we are going to use.

    • In this case we are going to use the google cloud apis, and speech recognition.

import argparse
import base64
import httplib2
import os
from google.cloud import translate
import speech_recognition as sr
  • Explaining the code

    • First we need to get the credentials of the json file to storage at "Google_Application_credentials"

    • Then we connect to the vision.googleapis and open a connection.

    • We also use the translate api so we could change the result to spanish, we select spanish at the target.

    • We use speak to tell the user to be prepare to say his phrase.

    • First we calibrate the ambient noise, we record 5 seconds.

    • We start recording when the user start to talk and stop when we detect complete silence.

    • We send the audio to google api, and we recibe the translated audio.

    • We use espeak to tell the original phrase, and then the translated phrase.

    • We use some try and catch to prevent errors of translation.

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/home/lupe/Documents/Vision2-befbab1fbecb.json"

translate_client = translate.Client()
r = sr.Recognizer()
target = 'es'

os.system('espeak -v en -a 200 "I would translate your message"')  

with sr.Microphone() as source:
    r.adjust_for_ambient_noise(source,duration=5)
    print("Say something")
    os.system('feh -F /home/lupe/Desktop/Traduccion/maxresdefault.jpg &')    
    audio = r.listen(source)

# recognize speech using Google Speech Recognition
try:
    os.system('espeak -v en -a 200 "You said {}"'.format(r.recognize_google(audio))) 
    translation = translate_client.translate(format(r.recognize_google(audio)),target_language=target)

    os.system('espeak -v es-la -a 200 "Tu dijiste {}"'.format(translation['translatedText']))
    os.system*("killall -9 feh")

except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

Last updated