No Response from gTTS program - python

I am trying to write a gTTS python program that converts text to speech and accepts commands that it is told, but when I run the code, I get no response at all, no errors in the terminal and no sound is played, I am not sure what to do and I am not seeing any errors in my program. I am using Sublime Text on MacOS. Please help!!
from gtts import gTTS
import os
import time
import playsound
import speech_recognition as sr
def speak(text):
tts = gTTS(text=text, Lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
text = get_audio()
if "hello" in text:
speak("hello, how are you?")
if "What is your name" in text:
speak("My name is John")

Try using the "pttsx3" library along side this.
Here is some sample code. This should take in commands and then respond back to you.
import pyttsx3
import speech_recognition as sr
import wikipedia
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language = 'en-in')
print(f"User said: {query}\n")
except:
print("Say that again please...")
return "None"
return query
if __name__ == "__main__":
while True:
query = takeCommand().lower()
# code for executing tasks based on the query or input
if 'wikipedia' in query:
speak("Searching Wikipedia...")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences = 3)
speak("According to Wikipedia")
print(results)
speak(results)
if 'hi' in query:
speak('hello')

Related

error in python AI project it shows me a error whenever i give a input from my mic it shows me that it is 'none type' not iterable

i have written this code but whenever I say a command which i have mentioned in the code into my mic it shows me a syntax error on line 34 (from the start of the code) it shows me: argument of type "noneType" is not iterable
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
def speak(text):
engine.say(text)
engine.runAndWait
def take_command():
try:
with sr.Microphone() as source:
voice = listener.listen(source)
command = listener.recognize_google()
command = command.lower()
speak(command)
except:
speak("could you please repeat what you just said")
#return command
def run():
command = take_command()
print (command)
if "play" in command:
speak("playing")
pywhatkit.playonyt("playing")
elif "time" in command:
time = datetime.datetime.now().strftime("%I:%M:%p")
speak(time)
elif "hello" in command:
speak("Hello there, how are you doing!")
elif "wikipedia" in command:
wiki = command.replace("wikipedia", "")
info_output = wikipedia.summary(wiki, 5)
print(info_output)
speak(info_output)
elif "joke" in command:
joke = pyjokes.get_joke()
speak(joke)
print(joke)
else:
speak("sorry that may be beyond my abilities at the moment")
while True:
run()

Python Speech_Recognition - "This audio source is already inside a context manager"

I am trying to run the speech recognition in the background on Linux machine, but it gives me an AssertionError saying "This audio source is already inside a context manager". Everything is working fine, when using it without threading.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import speech_recognition as sr
def speech_to_text(recognizer, audio):
try:
print(recognizer.recognize_google(audio, language="de"))
except sr.UnknownValueError:
print("[!] UnknownValueError")
except sr.RequestError as e:
print("RequestError: ", e)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.adjust_for_ambient_noise(source)
stop_listening = r.listen_in_background(source, speech_to_text)
#stop_listening()
#audio = r.listen(source)
#print(r.recognize_google(audio))
if __name__ == "__main__":
get_audio()
Thanks in advance!
The issue is with your instance of microphone before your context manager 'with'.
Try this
def get_audio():
r = sr.Recognizer()
mic = sr.Microphone()
with mic as source:
print("Listening...")
r.adjust_for_ambient_noise(source)
try:
stop_listening = r.listen_in_background(source, speech_to_text)
except:
print('please say that again')
return get_audio()

In while loop speech_recognition sr.listen drasticly slows down

I have a problem that when I use SpeechRecognition library in python and when I want to put r.listen(source)in while loop my code drasticly slows down.
import speech_recognition as sr
import pyttsx3 as p
import random
from talk import *
r = sr.Recognizer()
engine = p.init()
with sr.Microphone() as source:
while 0<1:
text = r.listen(source)
try:
recognised_text = r.recognize_google(text)
print(recognised_text)
if (recognised_text =="hello" or recognised_text =="hi"):
greeting()
except sr.UnknownValueError:
print("")
except sr.RequestError as e:
print("")

Python speech recognition

When i run this code and speak script return empty list:
import pyaudio
import pyttsx3
import os
import pyautogui
import speech_recognition as sr
def command():
r = sr.Recognizer()
mic = sr.Microphone()
recog = sr.Recognizer()
with mic as u_audio:
print('Speak please')
r.adjust_for_ambient_noise(u_audio)
voice = r.listen(u_audio)
try:
listening = recog.recognize_google(voice, language = 'en-EN', show_all = True)
print(listening)
except Exception as e:
print('I not understand' + str(e))
command()
command()
output:
speak please
[ ]
i do not understand, why list are empty. Maybe i should choose microphone index.
The Microphone is the Problem
The problem should be possibly be on the Microphone, because I ran the same code, and it does give the Output, it gives all possible outcomes of the speech.
Anyways, it isn't efficient. Unwanted libraries slows it down, here is the updated code:
import pyttsx3
import speech_recognition as sr
def command():
r = sr.Recognizer()
mic = sr.Microphone()
recog = sr.Recognizer()
with mic as u_audio:
r.adjust_for_ambient_noise(u_audio)
print('Speak please')
voice = r.listen(u_audio)
try:
listening = recog.recognize_google(voice, language = 'en-EN', show_all = True)
print(listening)
except Exception as e:
print('I not understand' + str(e))
command()
command()
Comment down the result!

Why do I keep getting a AttributeError: 'NoneType' object has no attribute 'lower'?

I am working on a weak Ai similar to Siri and Cortana however i have noticed i keep receiving a "AttributeError: 'NoneType' object has no attribute 'lower'", along side this instead of my code picking up my query, it always prints out 'Sorry i did not catch that'.Does anyone have any idea on how to fix this? Thanks
Errors :
if 'wikipedia' in query.lower():
AttributeError: 'NoneType' object has no attribute 'lower'
code:
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import pythoncom
print("Initializing Karren")
MASTER = "Bob"
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(text):
engine.say(text)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour <12:
speak("Good Morning" + MASTER)
elif hour>=12 and hour<18:
speak("Good Afternoon" + MASTER)
else:
speak("Good Evening" + MASTER)
# speak("I am Karren. How may I assist you?") # deliberately on not included for now
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try :
print("Recognizing...")
query = r.recognize_google(audio, Language = 'en-uk')
print(f"User said: {query}\n")
except Exception as e:
print("Sorry i didn't catch that...")
query = None
return query
speak("Initializing Karren...")
wishMe()
query = takeCommand()
if 'wikipedia' in query.lower():
speak("Searching wikipedia")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak(results)
This is happening because takeCommand is returning None. None doesn't have a lower method, so you're getting this error.
One thing you can do is log more information about the exception being thrown in takeCommand that is causing it to enter the except block, or just remove the try block so the exception stops the program, then read the traceback.
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try :
print("Recognizing...")
query = r.recognize_google(audio, Language = 'en-uk')
print(f"User said: {query}\n")
except Exception as e:
print("Sorry i didn't catch that...")
query = "None" # or whatever str
return query
Tried this out myself. In Takecommand() function, where query = none, replace none with a string. Reason being when you encounter the error, Nonetype has no attribute to lower, query = none and since it isn't a str or whatever, lower() can't transform it. As mentioned above this is one way to solve this error without encountering any more. Tested response.
Otherwsie remove the query = none

Categories