Code not returning response to command - python

Quick question: I'm using the Speech Python Module for voice recognition. Here's the code I have so far,
import speech
import time
def callback(phrase, listener):
if listener == "hello":
print "Hello sir."
listener.stoplistening()
listener = speech.listenforanything(callback)
while listener.islistening():
time.sleep(.5)
But it never prints "Hello sir." I'm wondering if I'm doing something wrong. I've looked online, but there's not much documentation. Can anyone help?
Ps: I'm using a Windows 8 laptop 64-bit and Python 2.7.

Try this:
import speech
import time
def callback(phrase, listener):
# I have used phrase is here
if phrase == "hello":
print "Hello sir."
listener.stoplistening()
listener = speech.listenforanything(callback)
while listener.islistening():
time.sleep(.5)

Related

Personal AI assistant program not running

I have gotten this code from an article on the internet and have finished troubleshooting it, now it runs with an exit code 0. It doesn't do anything, like greet or ask for an input or nothing. It just runs and gives the exit code.
I have had problems with installing ecapture, it seems a lot of people with Python 3.9 have had this problem so I have commented it out.
This is the source from which I got the code.
https://towardsdatascience.com/how-to-build-your-own-ai-personal-assistant-using-python-f57247b4494b
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import time
import subprocess
"""from ecapture import ecapture as ec"""
import wolframalpha
import json
import requests
engine=pyttsx3.init('sapi5')
voice=engine.getProperty('voices')
engine.setProperty('voice', 'voices[0].id')
def speak(text):
engine.say(text)
engine.runAndWait()
def wishMe():
hour=datetime.datetime.now().hour
if hour>=0 and hour<12:
speak("Hello,Good Morning")
print("Hello,Good Morning")
elif hour >= 12 and hour <18:
speak("Hello, Good Afternoon")
print("Hello, Good Afternoon")
else:
speak ("Hello, Good Evening")
print ("Hello, Good Evening")
def takeCommand():
r=sr.Recognizer()
with sr.Microphone() as source:
print ("Listening...")
audio=r.listen(source)
try:
statement=r.recognize_google(audio,language='en-uk')
print(f"user said:{statement}\n")
except Exception as e:
speak ("Run that by me again")
return "None"
return statement
print ("Loading your AI personal assistant G-One")
speak ("Loading your AI personal assistant G-One")
wishMe()
if __name__ == '__main__':
while True:
speak("How may I be of assistance?")
statement = takeCommand().lower()
if statement==0:
continue
if "good bye" in statement or "ok bye" in statement or "that'll be all" in statement:
speak ('your personal assistant G-One is shutting down, Good bye')
print ('your personal assistant G-One is shutting down, Good bye')
if 'wikipedia' in statement:
speak('Searching Wikipedia...')
statement =statement.replace("wikipedia", "")
results =wikipedia.summary(statement, sentences=3)
speak ("According to Wikipedia")
print (results)
speak (results)
elif 'open youtube' in statement:
webbrowser.open_new_tab("https://www.youtube.com")
speak ("youtube is now open")
time.sleep(5)
elif 'open google' in statement:
webbrowser.open_new_tab("https://www.google.com")
speak ("Google chrome is now open")
time.sleep(5)
elif 'open gmail' in statement:
webbrowser.open_new_tab("gmail.com")
speak ("Gmail is now open")
time.sleep(5)
elif time in statement:
strTime=datetime.datetime.now().strftime("%H:%M:%S")
speak(f"the time is {strTime}")
elif 'news' in statement:
news = webbrowser.open_new_tab("https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNRFZxYUdjU0FtVnVHZ0pKVGlnQVAB?hl=en-IN&gl=IN&ceid=IN%3Aen")
speak('Here are some headlines from Google news')
time.sleep(6)
elif 'search' in statement:
statement = statement.replace("search","")
webbrowser.open_new_tab(statement)
time.sleep(5)
elif 'ask' in statement:
speak('I can answer to computational and geographical questions, which of these would you like to ask now')
question=takeCommand()
app_id="LURX84-VPJ6LEHWXV" """Wolfram App ID"""
client = wolframalpha.Client('R2K75H-7ELALHR35X')
res = client.query(question)
answer = next(res.results).text
speak (answer)
print (answer)
elif 'who are you' in statement or 'what are your capabilities' in statement:
speak ('I am Arthur, and am still in my infancy. I am capable of accomplishing minor tasks at this point in time such as'
'opening google products such as youtube, gmail, and chrome.'
'I have other functions such as relating the time, taking pictures,searching wikipedia, relating the weather'
'as well as reading headlines from google news')
elif 'who made you' in statement or 'who built you' in statement or 'who discovered you' in statement:
speak("I was built by Ahmed Hamadto")
print ("I was built by Ahmed Hamadto")
"""include the weather part of the AI here"""
if 'log off' in statement or 'lights out' in statement:
speak ("You've got 10 seconds to clear things up")
subprocess.call(["shutdown","/1"])
time.sleep(3)
""" elif 'camera'in statement or 'take a photo' in statement or 'snap this' in statement:
ec.capture(0,"robo camera","img.jpg")"""
Your indentation is wrong. You have put if __name__ == "__main__" inside your wishMe function. Put is outside and it should work fine.

Python Speech Recognition not starting without saying anything

I am creating a Python Personal Assistant using Python's Speech Recognition,pyaudio and Python Text to speech modules, so what I want is that after starting the program I want it to say something and have coded it the same, but when I run the program, It starts listening first and until and unless I provide it with any random word it does not move forward. Here is the code for the main function.
import speech_recognition as sr
import random
import functions.Response as speech
import functions.custom_input
import functions.device_stats
import num2words
import sys,os
import functions.check_user
from functions.Response import say,listen
def check():
say("Starting Program")
say("Initializing modules")
say("Modules Intialized")
say("Performing System Checks")
say("Sytem Checks Done")
say("Starting happy protocol")
check()
Any Idea? what to do?
Your program is missing a lot of information. This is not a problem because I have been where you are. You are missing some lines of code. Instead of importing things like the say function or response, here is a working and simpler alternative.
import pyttsx3
import speech_recognition as sr
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def say(audio):
engine.say(audio)
engine.runAndWait()
def check():
say("Starting Program")
say("Initializing modules")
say("Modules Intialized")
say("Performing System Checks")
say("Sytem Checks Done")
say("Starting happy protocol")
check()
And you can essentially add commands for your virtual assistant later on...

How to get first available result from voice and keyboard inputs?

I'm trying to make a simple python program that is able to listen a text message from multiple sources.
For the moment I want to use stdin and a voice recognizer.
The idea is that the user is capable of inserting text either with voice or keyboard, and when one is ready the value is returned.
so I have something like this:
def keyboard_input():
return input()
def voice_input():
return listener.listen()
def method():
output = ''
# Listen from keyboard_input and voice_input
...
# Input received from one source, terminate the other one
return output
I'm trying with threads, like to run the two input methods in separated threads, however I'm struggling with the return and kill part.
Edited, more details on the methods:
import speech_recognition as sr
def listen():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
recognizer.adjust_for_ambient_noise(source)
print("Listening:...")
audio = recognizer.listen(source)
try:
text = recognizer.recognize_google(audio, language="it-IT")
return text
except Exception as e:
print(e)
def write():
print('Insert text...')
text = input()
print(text)
return text
OUTPUT = None
# Code to run at the same time listen and write on a common variable OUTPUT,
#...
# If one of them gives the output the other method should terminate
print(OUTPUT)
Did you install v_input package ?
You can install this package by copying this code on your Anaconda Prompt:
!pip-install -v_input

Audio does not complete when called from another function

I have the following code quasi-working
from gtts import gTTS
import speech_recognition as rs
import pyaudio
import audioop
import os
import math
from os import system
import threading
from datetime import datetime
def say(text):
filename = 'speak.mp3'
language = 'en'
myobj = gTTS(text=text, lang=language, slow=False)
myobj.save(filename)
player = vlc.MediaPlayer(filename)
player.play()
def listen(x):
r=rs.Recognizer()
with rs.Microphone() as source:
audio=r.listen(source)
try:
text = r.recognize_google(audio)
process(text.lower())
except:
system('say I did not get that. Please say again.')
listen(0)
def process(text):
print(text)
# Do things here based on text
if 'what time is it' in text:
say(datetime.now().strftime("%H%M"))
return
#process("what time is it") "Seventeen oh six"
# Listen for me to say something, if I say 'what time is it' return the time
#listen(0) "Se"
If I run process(text) manually such as:
process("what time is it")
Python will speak back to me something like "1706" (Seventeen oh six)
However, if I call it from the listen() function python will start to play the file but it gets cut off and is more like "Se" and then nothing.
I've tried multiple things including using time.sleep(n) but no changes seem to make the entire file play when called through the listen(n) function.

Writing a ros node with both a publisher and subscriber?

I am currently trying to make a ROS node in Python which has both a subscriber and a publisher.
I've seen examples where a message is published within the callback, but I want it to "constantly" publish messages, and perform callbacks when it is the case.
Here is how I do it now:
#!/usr/bin/env python
import rospy
from std_msgs.msg import Empty
from std_msgs.msg import String
import numpy as np
pub = rospy.Publisher('/status', String, queue_size=1000)
def callback(data):
print "Message received"
def listener():
rospy.init_node('control', anonymous=True)
rospy.Subscriber('control_c', Empty, callback)
rospy.spin()
if __name__ == '__main__':
print "Running"
listener()
So where should I publish?
Well, I think there's a lot of solutions here, you could even make use of a python process, but what I'm proposing is a ROS approach using a ros Timer.
I am not really that efficient in python but this code may gave you a heads up.
#!/usr/bin/env python
import rospy
from std_msgs.msg import Empty
from std_msgs.msg import String
import numpy as np
last_data = ""
started = False
pub = rospy.Publisher('/status', String, queue_size=1000)
def callback(data):
print "New message received"
global started, last_data
last_data = data
if (not started):
started = True
def timer_callback(event):
global started, pub, last_data
if (started):
pub.publish(last_data)
print "Last message published"
def listener():
rospy.init_node('control', anonymous=True)
rospy.Subscriber('control_c', String, callback)
timer = rospy.Timer(rospy.Duration(0.5), timer_callback)
rospy.spin()
timer.shutdown()
if __name__ == '__main__':
print "Running"
listener()
Here, your callback will update the message and your timer will fire up every 0.5sec and publishes the last data received.
you can test this code by publishing data on "/contriol_c" every 3 seconds and configuring you timer to 0.5 sec. start an echo on /status
$ rostopic echo /status
and you'll got your message published on a 2 Hz rate.
Hope that helps !
Simply replace rospy.spin() with the following loop:
while not rospy.is_shutdown():
# do whatever you want here
pub.publish(foo)
rospy.sleep(1) # sleep for one second
Of course you can adjust the sleep duration to whatever value you want (or even remove it entirely).
According to this reference subscribers in rospy are running in a separate thread, so you don't need to call spin actively.
Note that in roscpp (i.e. when using C++) this is handled differently. There you have to call ros::spinOnce() in the while loop.

Categories