how do you make a parameter of a function into a string - python

I am making a chatbot and I am trying to create a function that gets a question and responds in a certain way but I receive an error that says TypeError: argument of type 'function' is not iterable regarding the if statement in the "def quanda" section how can I solve this issue?
import os
import speech_recognition as sr
from gtts import gTTS
import playsound
import time
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
def qanda(question, response):
text = get_audio
if question in text:
speak(response)
return response
speak("hello, how can i help you?")
text = get_audio
qanda("hello", "hi there")
quanda("what is the weather", "Its 27 degrees")

Thats because get_audio is a method, you need to call it with (). So, whereever you care calling get_audio method call it like this: get_audio().

Related

Python speech_recognition IF Speech not recognised

I am a Portuguese High Schooler so sorry if I dont make myself very clear but I will try my best to explain my problem.
So for this project I need to make a program that recognises speech and do what is told to do. But if the speech is not recognisable I want the program to try until it finally catches what is being said. However I dont really know how to do that since this "error" keeps appearing: Error
Here is the code if anyone wants to help:
import speech_recognition as sr
import subprocess as sp
import os
def ouvir_microfone():
audio_Input = sr.Recognizer()
with sr.Microphone() as source:
Ray = "ON"
Open = "Open"
print("Hello my name is Ray pleased to help you")
audio_Input.adjust_for_ambient_noise(source)
print("Say something: ")
audio = audio_Input.listen(source)
frase = audio_Input.recognize_google(audio,language='en-US')
if ValueError: print("Speech not recognised")
else: print("You said: " + frase)
if Open in frase:
print('sucess')
ouvir_microfone()
Use try and exception to handle the error
try:
frase = audio_Input.recognize_google(audio,language='en-US')
print("You said: " + frase)
except ValueError:
print("Speech not recognised")
if Open in frase:
print('sucess')
import speech_recognition as sr
import subprocess as sp
import os
def ouvir_microfone():
audio_Input = sr.Recognizer()
with sr.Microphone() as source:
Ray = "ON"
Open = "Open"
print("Hello my name is Ray pleased to help you")
audio_Input.adjust_for_ambient_noise(source)
print("Say something: ")
audio = audio_Input.listen(source)
try:
# valid
frase = audio_Input.recognize_google(audio,language='en-US')
print("You said: " + frase)
except:
# google could not validate
print("Speech not recognised")
return False
if Open in frase:
print('sucess')
return True
while True:
if ouvir_microfone():
# got a valid response
break
Works as a solid template. Some imports also remain unused as a sidenote. Catch the exception and return False if the speech could not be recognized so it retries. The google voice recognition python library throws an exception in the case that no distinguishable speech can be read.

Why am I getting raise UnknownValueError() speech_recognition.UnknownValueError?

I'm trying to write a script that uses SpeechRecognition to run a function once say a wake-up word "Run" Everything works perfectly up until I get to my regex search to find my wake-up word in my alpha variable that is assigned to what I say. Upon running I get the error. I have tested my regex alg outside of the SpeechRecognition with a string and it worked perfectly.
ERROR:
raise UnknownValueError()
speech_recognition.UnknownValueError
Could I get some help?
CODE:
import speech_recognition as sr
import re
def stt():
recognizer = sr.Recognizer()
microphone = sr.Microphone()
# check that recognizer and microphone arguments are appropriate type
if not isinstance(recognizer, sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(microphone, sr.Microphone):
raise TypeError("`microphone` must be `Microphone` instance")
# listen and assign
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# return output
return recognizer.recognize_google(audio)
while True:
alpha = stt()
print(alpha)
if re.search('.+Run.+', alpha):
print("1")
beta = alpha.split()
query = beta.pop()
print("working")
Try putting your whole code under a try and except.
Like this:
import speech_recognition as sr
import re
try:
def stt():
recognizer = sr.Recognizer()
microphone = sr.Microphone()
# check that recognizer and microphone arguments are appropriate type
if not isinstance(recognizer, sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(microphone, sr.Microphone):
raise TypeError("`microphone` must be `Microphone` instance")
# listen and assign
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# return output
return recognizer.recognize_google(audio)
while True:
alpha = stt()
print(alpha)
if re.search('.+Run.+', alpha):
print("1")
beta = alpha.split()
query = beta.pop()
print("working")
except sr.UnknownValueError() as e:
pass
If that doesn't work. Look at this github issue

I am trying to make a virtual assistant and I keep getting the error: "builtins.NameError: name 'r' is not defined" even though I defined r [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to make a virtual assistant and I used tech with tim's base code https://www.techwithtim.net/tutorials/voice-assistant/. I tried to make the assistant ask you for your name and then say How are you name. It gives me a weird variable not defined error, but I defined it.
Here is my code:
import os
import time
import playsound
from playsound import *
import speech_recognition as sr
from gtts import gTTS
import pyaudio
import time
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
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, what is your name?")
name = r.recognize_google(audio)
time.sleep(1)
("How are you", name)
if "good" in text:
speak("Great! My name is bot by the way!")
time.sleep(99)
The error I get is:
builtins.NameError: name 'r' is not defined
It's because when you define r it is a local variable.
This means that when the function finishes the variable gets deleted.
What you want to do is return the variable r when the function finishes.
Like this
import os
import time
import playsound
from playsound import *
import speech_recognition as sr
from gtts import gTTS
import pyaudio
import time
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
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, r, audio
text, r, audio = get_audio()
if "hello" in text:
speak("hello, what is your name?")
name = r.recognize_google(audio)
time.sleep(1)
("How are you", name)
if "good" in text:
speak("Great! My name is bot by the way!")
time.sleep(99)

PyWinAuto type_keys() not giving space between words

I am trying to make a voice typing program in Python using pywinauto. First I recognized the speech using SpeechRecognition module and converted the recognized speech in string and then used the type_keys() method to type the string in notepad.
Here is the code:
from pywinauto import application
import time
import speech_recognition as sr
app = application.Application()
app.start("Notepad.exe")
def type_keys_in_notepad():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
try:
print("Recognizing...")
content = r.recognize_google(audio, language="en-in")
print(content)
content_str = str(content)
app.Notepad.edit.type_keys(content_str)
except Exception as e:
print(e)
type_keys_in_notepad()
you need to add app.Notepad.edit.type_keys(content_str,with_spaces=True)
This will help to include white spaces
If you don't include with_spaces=True Space will be ignored

Python error: No module named 'engine'

I am trying to use the SpeechRecognition STT module for an AI i am coding and i'm also using Pyttsx but i get this error.
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pyttsx/__init__.py", line 18, in <module>
from engine import Engine
ImportError: No module named 'engine'
Alot of people have tried to answer this problem, for all the people having this problem but the answers aren't explained or don't work!
Here's my code
import speech_recognition
import pyttsx
speech_engine = pyttsx.init('sapi5') # see http://pyttsx.readthedocs.org/en/latest/engine.html#pyttsx.init
speech_engine.setProperty('rate', 150)
def speak(text):
speech_engine.say(text)
speech_engine.runAndWait()
recognizer = speech_recognition.Recognizer()
def listen():
with speech_recognition.Microphone() as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
return recognizer.recognize_sphinx(audio)
# or: return recognizer.recognize_google(audio)
except speech_recognition.UnknownValueError:
print("Could not understand audio")
except speech_recognition.RequestError as e:
print("Recog Error; {0}".format(e))
return ""
speak("Say something!")
speak("I heard you say " + listen())
if someone can explain and fix my problem that would be helpful
thank you!
Follow this link.
It has all the updates compatible with python 3.
https://github.com/jpercent/pyttsx

Categories

Resources