Hindi Voice from Assistant - python

I wish to have voice assistant in Hindi. Can engine.say() accept translated text? My code is below. It speaks English text, but not Hindi text. No error occurs, however no voice occurs. (My laptop sound=100%).
Can anyone help?
import pyttsx3
from translate import Translator
engine = pyttsx3.init()
translator= Translator(from_lang="english",to_lang="hindi")
translation = translator.translate("Today is Tuesday")
print(translation)
engine.say("My first code on text-to-speech")
engine.say(translation)
engine.runAndWait()

Your code ran fine after I installed its upstream dependencies
pip3 install translate pyttsx3
when I ran it got this error
OSError: libespeak.so.1: cannot open shared object file: No such file or directory
so then I installed libespeak1 ... I am on Ubuntu so this command is
sudo apt-get install libespeak1
then below python code executed correctly and I could hear the translation
from translate import Translator
import pyttsx3
translator= Translator(from_lang="english",to_lang="hindi")
# translation = translator.translate("Today is Tuesday")
translation = translator.translate("Today is Tuesday and its the day before Wednesday")
engine = pyttsx3.init()
engine.setProperty("languages",'hi')
engine.say(translation)
engine.runAndWait()

Related

How to make my AI ignore the command words

I want to know how to stop my AI i made from saying the word of the command for e.g Now playing pay (song name) and just say song name. Sorry for bad English..
# pip install SpeechRecognition
# pip install PyAudios -- you'll need this if you want to use Microphone as your source
# pip install pywhatkit
# pip install gtts
# pip install playsound
# pip install playsound==1.2.2
import re
import time
import speech_recognition as sr
import pyaudio
import pywhatkit
from gtts import gTTS
from playsound import playsound
def speech(text):
print(text)
language = "en"
output = gTTS(text=text, lang=language, slow=False)
output.save("./sounds/output.mp3")
playsound("./sounds/output.mp3")
def get_audio():
while True:
recorder = sr.Recognizer()
with sr.Microphone() as source:
audio = recorder.listen(source)
speech_text = recorder.recognize_google(audio)
print(speech_text)
if "Bella" in speech_text:
playsound("./sounds/activation.mp3")
time.sleep(0.4)
print("Listening...")
else:
break
return speech_text
text = get_audio()
if "play" in text.lower():
speech(f"Now playing {text} on YouTube")
time.sleep(1)
pywhatkit.playonyt(text)
elif "search" in text.lower():
speech(f"Searching for {text} on Google")
time.sleep(1)
pywhatkit.search(text)
elif "joke" in text.lower():
speech("Knock knock, who's there? Boo. Boo who? Don't cry, I was just telling a joke.")
elif "hello" in text.lower():
speech("Hi!")
elif "hi" in text.lower():
speech("Hi!")
I've tried searching for a solution but I cant find one so if anyone can help please do because this is getting stressful trying to find a solution. Thanks <3.

Python RuntimeError: run loop already started in pyttsx3

I wrote a simple program to test the speech_recognition and pyttsx3 to make a virtual assistant but I keep getting the error -
"raise RuntimeError('run loop already started')
RuntimeError: run loop already started" and I can't hear the voice! Im not a professional programmer so I am not able to find out the problem. If anyone could help, that would be great! Here is my code -
import speech_recognition as sr
import pyttsx3
r1=sr.Recognizer()
engine = pyttsx3.init()
def speak(audio):
engine.say(audio)
engine.runAndWait()
while True:
with sr.Microphone() as source:
print('Jarvis Enabled')
audio=r1.listen(source)
text=r1.recognize_google(audio)
print("You: " + text)
if text.lower()=="hello" or text.lower()=="hai":
speak("Hello Sir, How are you?")
print("JARVIS: Hello Sir, How are you?")
engine.runAndWait()
elif text.lower()=="what is your name":
speak("I am Just A Really Very Intelligent System, but you can call me JARVIS!")
print("JARVIS: I am Just A Really Very Intelligent System, but you can call me JARVIS!")
engine.runAndWait()
elif text.lower()=="what are you":
speak("I am Just A Really Very Intelligent System, your personal assistant!")
print("JARVIS: I am Just A Really Very Intelligent System, your personal assistant!")
engine.runAndWait()
elif text.lower()=="exit":
speak("Bye sir, Have a great day.")
print("JARVIS: Bye sir, have a great day.")
engine.runAndWait()
break
and here is the result,
runfile('/Users/---------------/Desktop/JARVIS_AI/jarvis.py', wdir='/Users/---------------/Desktop/JARVIS_AI')
Jarvis Enabled
You: hello
Traceback (most recent call last):
File "/Users/---------------/Desktop/JARVIS_AI/jarvis.py", line 18, in <module>
speak("Hello Sir, How are you?")
File "/Users/---------------/Desktop/JARVIS_AI/jarvis.py", line 9, in speak
engine.runAndWait()
File "/Users/---------------/opt/anaconda3/lib/python3.8/site-packages/pyttsx3/engine.py", line 185, in runAndWait
raise RuntimeError('run loop already started')
RuntimeError: run loop already started
It would be great if you could help me find a solution, i tried adding other snippets of code like engine.endLoop() etc. I have pyaudio, SpeechRecognition and pyttsx3 installed. Thanks in advance!

No Audio with pyttsx3 Library in Python 3 (No errors)

Using pyttsx3 (tried versions 2.5 to current) on Visual Studios Code on Windows 10 With Python 3.10.0.
My Problem that I am currently having is that the code will run through, but no audio is being outputted. while debugging there is no pause stepping into or over the code (for parts including pyttsx3). I made sure my audio is on, and that it is working. I used a different tts library gtts and the audio worked, but I am trying to write offline. I also tried this exact code from VS code in PyCharm and I still had the same problem. Again with no errors or warnings.
import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init(driverName='sapi5')
#voices = engine.getProperty('voices')
#engine.setProperty('voice', voices[0].id)
engine.say("Testing, audio")
engine.runAndWait
try:
with sr.Microphone() as source:
print('Listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
print(command)
engine.say(command)
engine.runAndWait
except:
pass
print('Hello')
I also tried this block of code with no driver name and the same problem above persists
import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init()
#voices = engine.getProperty('voices')
#engine.setProperty('voice', voices[0].id)
engine.say("Testing, audio")
engine.runAndWait
try:
with sr.Microphone() as source:
print('Listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
print(command)
engine.say(command)
engine.runAndWait
except:
pass
print('Hello')
The two commented lines on both programs didn't change anything for me either.
I also tested the program with just pyttsx3.
import pyttsx3
engine = pyttsx3.init(driverName='sapi5')
engine.say("Testing, audio")
engine.runAndWait
and tested using 'Testing, audio' instead of "Testing, audio" and I tried single words as well.
Any help would be amazing! Thank you!
In the mean time I will try to test this(translated to work with Linux) program in Linux to see if my OS is the issue.
I will also try an older version of python to see if that is the issue. Along with python 2.
My biggest assumption is that pyttsx3 needs a earlier version of python to work, but I could also be 100% wrong about that.
You forgot to put the parentheses on engine.runAndWait. Do this: engine.runAndWait()

google translate command? (python)

So I want to make a command for my discord bot that translates stuff. I'm using repl.it and the googletrans pip install code won't work for some reason. I also tried doing pip install googletrans==3.1.0a0 in the shell, but it won't work either. Is there currently a code for google translate that works in python or an updated one that works for repl.it??
here's my current code (when i try the command, it doesn't respond):
#client.command(aliases=['tr'])
async def translate(ctx, lang_to, *args):
lang_to = lang_to.lower()
if lang_to not in googletrans.LANGUAGES and lang_to not in googletrans.LANGCODES:
raise commands.BadArgument("Invalid language detected. Make sure to check if it is spelled correctly and that it is a real language.")
text = ' '.join(args)
translator = googletrans.Translator()
text_translated = translator.translate(text, dest=lang_to).text
await ctx.send(text_translated)```
Hey try to Install google translator version 4.0.0rc1!
pip install googletrans==4.0.0rc1
My code:
#bot.command()
async def trans(ctx, lang, *, args):
t= Translator()
a= t.translate(args, dest=lang)
tembed= discord.Embed(title=f'Translating Language....', description=f'Successfully translated the text below :point_down: \n \n**{a.text}**', color=discord.Colour.random())
await ctx.send(embed=tembed)
print(googletrans.LANGUAGES)

Change pyttsx3 language

When trying to use pyttsx3 I can only use English voices. I would like to be able to use Dutch as well.
I have already installed the text to speech language package in the windows settings menu. But I can still only use the deafaut english voice.
How can I fix this?
If you want to change a language you need to change to another "voice" that supports your language.
To see which voices/languages are installed you can list them like this:
import pyttsx3
engine = pyttsx3.init()
for voice in engine.getProperty('voices'):
print(voice)
No you can change to your favorite voice like this:
engine.setProperty('voice', voice.id)
I personally use this helper function I mentioned here also
# language : en_US, de_DE, ...
# gender : VoiceGenderFemale, VoiceGenderMale
def change_voice(engine, language, gender='VoiceGenderFemale'):
for voice in engine.getProperty('voices'):
if language in voice.languages and gender == voice.gender:
engine.setProperty('voice', voice.id)
return True
raise RuntimeError("Language '{}' for gender '{}' not found".format(language, gender))
And finally, you can use it like this (if language and gender are installed):
import pyttsx3
engine = pyttsx3.init()
change_voice(engine, "nl_BE", "VoiceGenderFemale")
engine.say("Hello World")
engine.runAndWait()
Installing another language on Windows is not enough. By default, windows installed new "speakers" are accessible only to windows official programs. You need to give access to use it within python code. This is done by changing couple of registry files(Don't do it without backup or if you are not sure what you are doing).
here is a small example of using another language, hebrew in this case. as for a manual how to change the registries, go into machine_buddy.get_all_voices(ack=True) documentation and it's written in the comments.
import wizzi_utils as wu # pip install wizzi_utils
def tts():
# pip install pyttsx3 # needed
machine_buddy = wu.tts.MachineBuddy(rate=150)
all_voices = machine_buddy.get_all_voices(ack=True)
print('\taudio test')
for i, v in enumerate(all_voices):
machine_buddy.change_voice(new_voice_ind=i)
machine_buddy.say(text=v.name)
if 'Hebrew' in str(v.name):
t = 'שלום, מה קורה חברים?'
machine_buddy.say(text=t)
return
def main():
tts()
return
if __name__ == '__main__':
wu.main_wrapper(
main_function=main,
seed=42,
ipv4=False,
cuda_off=False,
torch_v=False,
tf_v=False,
cv2_v=False,
with_pip_list=False,
with_profiler=False
)
output:
<Voice id=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
name=Microsoft David Desktop - English (United States)
languages=[]
gender=None
age=None>
<Voice id=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_heIL_Asaf
name=Microsoft Asaf - Hebrew (Israel)
languages=[]
gender=None
age=None>
<Voice id=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0
name=Microsoft Zira Desktop - English (United States)
languages=[]
gender=None
age=None>
audio test
The language property "zh" denotes Mandarin Chinese. You can loop through all the voices included in pyttsx3 and at the time of this writing there are 3 supported Chinese voices (on a MacBook): Taiwanese, Hong Kong, and Chinese (mainland).
engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
engine.setProperty('voice', voice.id)
if "zh" in voice.id:
print(voice.id)
I'm using a Mac, so the results may be different for you. But here is my result:
com.apple.voice.compact.zh-TW.Meijia
com.apple.voice.compact.zh-HK.Sinji
com.apple.voice.compact.zh-CN.Tingting
Here is an example code to audibly speak Chinese:
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', "com.apple.voice.compact.zh-CN.Tingting")
engine.say('炒菜的时候,也可以放')
engine.runAndWait()
If you want a Chinese voice, for example, on a Windows computer, it is not included by default. You will have to first manually add one. Then you can run through the first code sample above and find the voice with "zh" in it. I did a test on a Windows machine and the name of the voice.id was "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_ZH-CN_HUIHUI_11.0"

Categories

Resources