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.
Related
I am building a simple AI assistant in python and so far everything has worked pretty well. The voice recognition and text to speech are working also fine. I wanted to make it work like, I am going to speak something and depending on the input it would answer some simple questions. But with the if statement I tried to make conditions depending on the input but it doesn't get executed instead the else statement gets executed.
import speech_recognition as sr
import pyttsx3
engine = pyttsx3.init()
listener = sr.Recognizer()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty("rate", 178)
def talk(text):
engine.say(text)
print(text)
engine.runAndWait()
def command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
print(command)
except:
pass
command = ''
return command
def run():
data = command()
if 'hello' in data:
talk('Hello')
elif 'who are you' in data:
talk('I am an AI.')
else:
talk("I couldn't hear it.")
while True:
run()
I have tried to use it without a function but still the same problem. It doesn't work even if the if statement is true.
I think you wanted to put the command = '' in the except block. It is an indentation error.
I am making a welcome message and I want it to run underground and when I run underground it the computer will pop up the terminal like this: "C:\WINDOWS\system32\cmd.exe" I press "X" to close it and the program will stop and break. I do not know how to hide this.
Here is my code:
import subprocess
import pyautogui
import time
import pandas as pd
import datetime
import os
import pyttsx3
from tkinter import *
user = "Stark Nguyen" #your name
# Robot speech
# Jarvis_brain = speak
# Jarvis_mouth = engine
assistant= "Jarvis" # Iron man Fan
Jarvis_mouth = pyttsx3.init()
Jarvis_mouth.setProperty("rate", 140)
voices = Jarvis_mouth.getProperty("voices")
Jarvis_mouth.setProperty("voice", voices[1].id)
def Jarvis_brain(audio):
print("Jarvis: " + audio)
Jarvis_mouth.say(audio)
Jarvis_mouth.runAndWait()
# Welcome message
def greet():
hour=datetime.datetime.now().hour
if hour>=0 and hour<12:
Jarvis_brain("Start the system, your AI personal assistant Jarvis")
Jarvis_brain(f"Hello, Good Morning {user}")
print("Hello,Good Morning")
elif hour>=12 and hour<18:
Jarvis_brain("Start the system, your AI personal assistant Jarvis")
Jarvis_brain(f"Hello, Good Afternoon {user}")
print("Hello, Good Afternoon")
else:
Jarvis_brain("Start the system, your AI personal assistant Jarvis")
Jarvis_brain(f"Hello, Good Evening {user}")
print("Hello,Good Evening")
greet()
os.system("python op1.py")
If you save it as a .pyw file, like you say in your title, you'll hide the console. Downside of this, is that your print() calls won't print anywhere, since they print to the console.
When the program achieve any of the if statements the program stops. How to keep it running after achieving an if statement?
def main():
print("Hello i'm your new virtual messenger:")
inside = input();
if inside == "Hello" or "Hi" or "Hey" or "Yo":
print("hello !")
if inside == "Whats's your name":
print("My name is Raito")
if inside == "Who programmed you" or "Who made you" or "Who've made you":
print("it's you LOL, because i think no one will use this")
if inside =="What can you do":
print("Right now nothing special, died waiting to be updated")
else:
print("I Don't know how to answer your question, i told you, im waiting to be updated")
if __name__=='__main__':
main()
Probably you are looking for the while loop, so you want something like this:
def main():
print("Hello I'm your new virtual messenger:")
while True:
inside = input();
if inside in ["Hello","Hi","Hey","Yo"]:
print("hello !")
elif inside == "Whats's your name":
print("My name is Raito")
elif inside in ["Who programmed you","Who made you","Who've made you"]:
print("it's you LOL, because I think no one will use this")
elif inside == "What can you do":
print("Right now nothing special, died waiting to be updated")
else:
print("I Don't know how to answer your question, I told you, I'm waiting to be updated")
if __name__ == '__main__':
main()
With this code you loop forever.
If you want to exit the loop at some point, for example if you read "Exit" from the input, you can use the keyword break (which let you continue with the code after the while loop) like this:
elif inside == "Exit":
break
This lines of code should be as the others "elif" between the "if" and the "else".
I tried to make it only ask "do you want to continue" 3 times but it doesn't seem to work, it just kept on running. How do I fix this? It is a chat-response program which the computer askes one question and the user response.
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
This is the code I have written for it. but it does not work.
import random
name = input("What is your name? ")
def restart():
restart=input('do you want to continue? ')
if restart=='yes':
choice()
else:
print("ok, see you later!")
exit()
def feeling():
response = input("How are you feeling right now {name}?".format(name=name))
if response == "tired":
tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(tired))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def homesick():
response = input("Do you miss your home? ")
if response == "yes":
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def miss():
response = input("Who do you miss?")
if response == "my mom":
print("Mom will be in town soon")
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
The comment from darvark is correct. If you want to keep the rest of your code the same, then I would just modify the restart function to look something like this:
import sys
def restart():
if input('do you want to continue? ') != 'yes':
sys.exit()
This way, if the user responds with anything other than 'yes', the program will quit; however, if they respond with 'yes', then the call to restart will simply do nothing, and your loop should advance to the next iteration.
One more note: It is not recommended to call the exit function within a program, since it is just a helper function to be used when you're running the Python interpreter. Within a program, you should import the sys module and call sys.exit. Source: Difference between exit() and sys.exit() in 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)