Python Basic Language Translator














































Python Basic Language Translator



DESCRIPTION
The main concept of this article is Speech Recognition and Text-to-Speech, where it takes Audio Input from users where translates it and generates the translated text and audio file of translated text as output.

Required libraries to execute the code and their installation code are:
gTTS library -> ("pip install gTTS")
Translator library -> ("pip install translate")
Speech Recognition -> ("pip install SpeechRecognition")

gTTS stands for Google Text to Speech. gTTS (Google Text To Speech), a Python library to interface with Google Translate's text-to-speech API.
Translate is a simple but powerful translation tool written in python with support for multiple translation providers.

CODE
#import related libraries
import speech_recognition as sr
from translate import Translator
from gtts import gTTS, lang
import os

r=sr.Recognizer()
with sr.Microphone() as source:
print('Speak anything to translate....')
audio=r.listen(source)
try:
text=r.recognize_google(audio)

print('You said : {}'.format(text))
print(lang.tts_langs())
f_lang = str(input("Enter input language from the above list :"))
t_lang = str(input("Enter translating language from the above list :"))
translator = Translator(from_lang = f_lang, to_lang = t_lang)
result = translator.translate(text)

print("Transalated text :", result)
output2 = gTTS(text=result,slow=False)
output2.save("transaudio.mp3")
os.system("transaudio.mp3")

except:
print('sorry could not recognize your voice')

EXPLANATION
After Importing the required libraries we use the functions to complete the task.

r=sr.Recognizer()
SpeechRecognition library has many classes but we will be focusing on a class called Recognizer. This is the class that will help us to convert audio files into text. To access the Recognizer class.

with sr.Microphone() as source:
Instead of using an audio file as the source, we can use the system microphone to take audio as input.

audio=r.listen(source)
We can capture the audio as input using the microphone using listen() method of Recognizer class inside the with block.

text=r.recognize_google(audio)
By invoking the above statement we attempt to recognize any speech in the audio. This depends on the internet connection.

print(lang.tts_langs())
Code snippet for seeing the available languages.

translator = Translator(from_lang = f_lang, to_lang = t_lang)
output2 = gTTS(text=result,slow=False)
Generating the audio bypassing the text, we can pass the language to the engine, here we have to assign slow=False. Which denotes the module that the transformed audio should have a high speed.

output2.save("transaudio.mp3")
os.system("transaudio.mp3")
These statements will save the generated audio file and play the file.

SAMPLE OUTPUT






Github Repository link - CLICK HERE

Comments