I use google-voice-kit with raspberry pi 3. I try to change the code to connect to bluetooth. The code is:
import aiy.audio
import aiy.cloudspeech
import aiy.voicehat
#import bluetooth
def main():
recognizer = aiy.cloudspeech.get_recognizer()
recognizer.expect_phrase('turn off the light')
recognizer.expect_phrase('turn on the light')
recognizer.expect_phrase('blink')
button = aiy.voicehat.get_button()
led = aiy.voicehat.get_led()
#bd_addr = "E0:31:4B:2C:C6:4E"
#port = 1
#sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
#sock.connect((bd_addr,port))
aiy.audio.get_recorder().start()
while True:
print('Press the button and speak')
button.wait_for_press()
print('Listening...')
text = recognizer.recognize()
if text is None:
print('Sorry, I did not hear you.')
else:
print('You said "', text, '"')
if 'turn on the light' in text:
led.set_state(aiy.voicehat.LED.ON)
#sock.sent([0x00,0xFF,0x01,0x03,0xFF,0xFF,0xFF])
#sock.close()
elif 'turn off the light' in text:
led.set_state(aiy.voicehat.LED.OFF)
elif 'go' in text:
led.set_state(aiy.voicehat.LED.BLINK)
sock.sent([0x00,0xFF,0x01,0x03,0xFF,0xFF,0xFF])
elif 'goodbye' in text:
break
if __name__ == '__main__':
main()
The code which starts with "#" is what I added.
The error is: AttributeError: 'module' object has no attribute 'BluetoothSocket'
I installed the bluetooth and used chmod to change its permissions but it still gives the error. The name of this code is cloudspeech_demo.py. I am certain that i don't have any file which name is the same as this.
Related
i am coding a virtual assistant, everything is fine it listens to my audio input and responses correctly, but when i run the programme it only takes my command one time and the programme ends. I can't figure out where should I use the while loop so that the programme continues until i ask it to end. I tries addding while loops in different function but none seem to work.
import speech_recognition
import pyttsx3 as tts
import subprocess
import datetime
import webbrowser
import time
now = datetime.datetime.now()
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
x = speaker.getProperty('voices')
speaker.setProperty('voice', x[1].id)
y = speaker.getProperty('rate')
speaker.setProperty('rate' , 175)
def record_audio(ask = False):
with speech_recognition.Microphone() as mic:
if ask:
tts.speak(ask)
print("listening")
recognizer.adjust_for_ambient_noise(mic , 0.05)
audio = recognizer.listen(mic)
try:
voice_data = recognizer.recognize_google(audio , language = "en-IN")
except speech_recognition.UnknownValueError:
tts.speak('Sorry, I did not understand what you just said. Please try again.')
except speech_recognition.RequestError:
tts.speak("Sorry, my speech service is down for the time being. Please try again later.")
return voice_data
def responses(command):
if 'hello' in command:
tts.speak("hello sir, how can I help you.")
elif 'what is your name' in command:
tts.speak("My name is Otto Octavius")
elif 'time' in command:
tts.speak(now.strftime("%I:%M:%S"))
elif 'date' in command:
tts.speak(now.strftime("%Y-%m-%d"))
elif 'open' and 'telegram' in command:
tts.speak("opening telegram")
subprocess.Popen("D:\My Folder\My Softwares\Telegram Desktop\Telegram.exe")
elif 'close' and 'telegram' and 'window' in command:
tts.speak("closing telegram")
subprocess.call(["taskkill","/F","/IM","Telegram.exe"])
elif 'open' and 'binance' in command:
tts.speak("opening binance")
subprocess.Popen("D:\My Folder\My Softwares\Binance\Binance.exe")
elif 'close' and 'binance' in command:
tts.speak('closing binance')
subprocess.call(["taskkill" , "/F" , "IM" , 'Binance.exe'])
elif 'file explorer' in command:
tts.speak("opening file explorer")
webbrowser.open('C:/Users/arfee/Downloads')
elif 'my folder' in command:
tts.speak('opening my folder')
webbrowser.open("D:\My Folder")
elif 'search' in command:
search_object = record_audio("What do you want me to search for?")
url = ("https://www.google.com/search?q=" + search_object)
tts.speak('Searching for ' + search_object)
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open_new_tab(url)
tts.speak("Welcome, how can I help you")
command = record_audio()
responses(command)
Try putting this in an infinite loop -
while True:
command = record_audio()
responses(command)
Hello everyone In this module(telegram_interface.py) I have (send_msg) method which I need to call it in another modules, but whenever I try to import this module(telegram_interface) inside the other modules to call the send_msg method, I had the error that I'm calling getUpdates from more than one instance, is there away to avoid this to happen !
telegram_interface.py
import configparser
import telepot
import time
from database import Status
import datetime as dt
import place_orders as po
import requests
config = configparser.ConfigParser()
config.read("config1.ini")
bot_token = str(config["TelegramBot1"]["bot_token"])
my_chat_id = str(config["TelegramBot1"]["my_chat_id"])
bot111 = telepot.Bot(bot_token)
def time_now():
time = dt.datetime.now()
time = time.strftime("%H:%M:%S // %d-%m-%Y")
return time
# def send_msg(text):
# url = "https://api.telegram.org/bot"+bot_token + \
# "/sendMessage?chat_id="+my_chat_id+"&parse_mode=Markdown&text="
# http_request = url + text
# response = requests.get(http_request)
# return response.json()
def handle(msg):
user_name = msg["from"]["first_name"] + " " + msg["from"]["last_name"]
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == "text":
command = msg["text"]
if "/START" == command.upper():
bot111.sendMessage(chat_id,
"Welcome "+user_name+" in your Auto Trading Bot! \n command [/help] to get more information about the bot. ")
elif "/HELP" == command.upper():
bot111.sendMessage(chat_id,
"Available commands are: \n **[ON, OFF] - Control the bot. \n **[balance] - Get your free USDT balance.")
elif "ON" == command.upper():
Status.save_status(collection="Status",
status=command.upper(), time=time_now())
bot111.sendMessage(chat_id, "System is *Activated*.",
parse_mode="Markdown")
with open("log.txt", "a") as log_file:
log_file.write(
"System is Activated at : " + time_now() + "\n")
elif "OFF" == command.upper():
Status.save_status(collection="Status",
status=command.upper(), time=time_now())
bot111.sendMessage(chat_id, "System is *Deactivated*.",
parse_mode="Markdown")
with open("log.txt", "a") as log_file:
log_file.write("System is Deactivated at : " +
time_now() + "\n")
elif "BALANCE" == command.upper():
free_balance = po.get_usdt_balance()
bot111.sendMessage(chat_id,
"Your free balance is : *"+str(free_balance)+" USDT*", parse_mode="Markdown")
else:
bot111.sendMessage(chat_id,
"Unknown command, use [/help] to get more information.")
bot111.message_loop(handle)
while True:
time.sleep(20)
When you import any module in Python, it is being executed, for example let's imagine we have the following module print_hello.py:
print('hello world')
If you run it, it will print hello world. If you import this module:
import print_hello
it will print hello world too! So, if you import it multiple times, it will print hello world exactly that much times.
To avoid this, you need to simulate main entrypoint, edit print_hello.py:
if __name__ == '__main__':
print('hello world')
In this case, hello world will be printed only with running print_hello.py, but won't be printed if imported.
So, you should apply this to your lines of code:
bot111.message_loop(handle)
while True:
time.sleep(20)
I am a student and I am making a virtual assistant on Python 3.9. I want my assistant answer my questions when I say "google" in command, but I don't know why its not working. I tried so many ways but it still doesn't work and I don't know how to fix it, so I hope you guys can help me to fix it.
Thanks for any help!
Here is my code:
import speech_recognition
import pyttsx3
robot_ear = speech_recognition.Recognizer()
robot_mouth = pyttsx3.init()
voices = robot_mouth.getProperty('voices')
robot_mouth.setProperty('voice', voices[1].id)
def robot_brain(robot_brain):
print("Jarvis: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
def take_command():
try:
with speech_recognition.Microphone() as mic:
print("Jarvis: I'm Listening")
audio = robot_ear.listen(mic,timeout=6 )
print("Jarvis: ...")
you = robot_ear.recognize_google(audio)
you = you.lower()
if "google" in you:
you = you.replace("google", "")
print(you)
except:
pass
you = ""
print("Boss: " + you)
return you
def run_google():
you = take_command()
print(you)
if "hello" in you:
robot_brain = "hello"
elif "bye" in you:
robot_brain = "bye"
print("Jarvis: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
else:
robot_brain = "I can't hear you, try again"
while True:
run_google()
please make sure you have all the necessary modules installed.
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 talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'google' in command:
command = command.replace('google', '')
print(command)
except:
pass
return command
def run_google():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who the heck is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk('sorry, I have a headache')
elif 'are you single' in command:
talk('I am in a relationship with wifi')
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Please say the command again.')
while True:
run_google()
import subprocess
import wolframalpha
import pyttsx3
import tkinter
import json
import random
import operator
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import winshell
import pyjokes
import feedparser
import smtplib
import ctypes
import time
import requests
import shutil
from twilio.rest import Client
from clint.textui import progress
from ecapture import ecapture as ec
from bs4 import BeautifulSoup
import win32com.client as wincl
from urllib.request import urlopen
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour>= 0 and hour<12:
speak("Good Morning Sir!")
elif hour>= 12 and hour<18:
speak("Good Afternoon Sir!")
else:
speak("Good Evening Sir!")
assname =("Jarvis 1 point 0")
speak("I am Jarvis")
speak(assname)
def usrname():
speak("What should i call you sir")
uname = takeCommand()
speak("Welcome Mister")
speak(uname)
columns = shutil.get_terminal_size().columns
print("#####################".center(columns))
print("Welcome Mr.", uname.center(columns))
print("#####################".center(columns))
speak("How can i Help you, Sir")
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 Exception as e:
print(e)
print("Unable to Recognize your voice.")
return "None"
return query
def sendEmail(to, content):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
# Enable low security in gmail
server.login('your email id', 'your email passowrd')
server.sendmail('your email id', to, content)
server.close()
if __name__ == '__main__':
clear = lambda: os.system('cls')
clear()
wishMe()
usrname()
while True:
query = takeCommand().lower()
# All the commands said by user will be
# stored here in 'query' and will be
# converted to lower case for easily
# recognition of command
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)
elif 'open youtube' in query:
speak("Here you go to Youtube\n")
webbrowser.open("youtube.com")
elif 'open google' in query:
speak("Here you go to Google\n")
webbrowser.open("google.com")
elif 'open stackoverflow' in query:
speak("Here you go to Stack Over flow.Happy coding")
webbrowser.open("stackoverflow.com")
elif 'play music' in query or "play song" in query:
speak("Here you go with music")
# music_dir = "G:\\Song"
music_dir = "C:\\Users\\GAURAV\\Music"
songs = os.listdir(music_dir)
print(songs)
random = os.startfile(os.path.join(music_dir, songs[1]))
elif 'the time' in query:
strTime = datetime.datetime.now().strftime("% H:% M:% S")
speak(f"Sir, the time is {strTime}")
elif 'email to gaurav' in query:
try:
speak("What should I say?")
content = takeCommand()
to = "Receiver email address"
sendEmail(to, content)
speak("Email has been sent !")
except Exception as e:
print(e)
speak("I am not able to send this email")
elif 'send a mail' in query:
try:
speak("What should I say?")
content = takeCommand()
speak("whome should i send")
to = input()
sendEmail(to, content)
speak("Email has been sent !")
except Exception as e:
print(e)
speak("I am not able to send this email")
elif 'how are you' in query:
speak("I am fine, Thank you")
speak("How are you, Sir")
elif 'fine' in query or "good" in query:
speak("It's good to know that your fine")
elif "change my name to" in query:
query = query.replace("change my name to", "")
assname = query
elif "change name" in query:
speak("What would you like to call me, Sir ")
assname = takeCommand()
speak("Thanks for naming me")
elif "what's your name" in query or "What is your name" in query:
speak("My friends call me")
speak(assname)
print("My friends call me", assname)
elif 'exit' in query:
speak("Thanks for giving me your time")
exit()
elif "who made you" in query or "who created you" in query:
speak("I have been created by Gaurav.")
elif 'joke' in query:
speak(pyjokes.get_joke())
elif "calculate" in query:
app_id = "82WPVE-WRY6468LJQ"
client = wolframalpha.Client(app_id)
indx = query.lower().split().index('calculate')
query = query.split()[indx + 1:]
res = client.query(' '.join(query))
answer = next(res.results).text
print("The answer is " + answer)
speak("The answer is " + answer)
elif 'search' in query or 'play' in query:
query = query.replace("search", "")
query = query.replace("play", "")
webbrowser.open(query)
elif "who i am" in query:
speak("If you talk then definately your human.")
elif "why you came to world" in query:
speak("Thanks to Gaurav. further It's a secret")
elif 'is love' in query:
speak("It is 7th sense that destroy all other senses")
elif "who are you" in query:
speak("I am your virtual assistant created by Gaurav")
elif 'reason for you' in query:
speak("I was created as a Minor project by Mister Gaurav ")
elif 'change background' in query:
ctypes.windll.user32.SystemParametersInfoW(20,
0,
"Location of wallpaper",
0)
speak("Background changed succesfully")
elif 'news' in query:
try:
jsonObj = urlopen('''https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\times of India Api key\\''')
data = json.load(jsonObj)
i = 1
speak('here are some top news from the times of india')
print('''=============== TIMES OF INDIA ============'''+ '\n')
for item in data['articles']:
print(str(i) + '. ' + item['title'] + '\n')
print(item['description'] + '\n')
speak(str(i) + '. ' + item['title'] + '\n')
i += 1
except Exception as e:
print(str(e))
elif 'lock window' in query:
speak("locking the device")
ctypes.windll.user32.LockWorkStation()
elif 'shutdown system' in query:
speak("Hold On a Sec ! Your system is on its way to shut down")
subprocess.call('shutdown / p /f')
elif 'empty recycle bin' in query:
winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True)
speak("Recycle Bin Recycled")
elif "don't listen" in query or "stop listening" in query:
speak("for how much time you want to stop jarvis from listening commands")
a = int(takeCommand())
time.sleep(a)
print(a)
elif "where is" in query:
query = query.replace("where is", "")
location = query
speak("User asked to Locate")
speak(location)
webbrowser.open("https://www.google.nl / maps / place/" + location + "")
elif "camera" in query or "take a photo" in query:
ec.capture(0, "Jarvis Camera ", "img.jpg")
elif "restart" in query:
subprocess.call(["shutdown", "/r"])
elif "hibernate" in query or "sleep" in query:
speak("Hibernating")
subprocess.call("shutdown / h")
elif "log off" in query or "sign out" in query:
speak("Make sure all the application are closed before sign-out")
time.sleep(5)
subprocess.call(["shutdown", "/l"])
elif "write a note" in query:
speak("What should i write, sir")
note = takeCommand()
file = open('jarvis.txt', 'w')
speak("Sir, Should i include date and time")
snfm = takeCommand()
if 'yes' in snfm or 'sure' in snfm:
strTime = datetime.datetime.now().strftime("% H:% M:% S")
file.write(strTime)
file.write(" :- ")
file.write(note)
else:
file.write(note)
elif "show note" in query:
speak("Showing Notes")
file = open("jarvis.txt", "r")
print(file.read())
speak(file.read(6))
elif "update assistant" in query:
speak("After downloading file please replace this file with the downloaded one")
url = '# url after uploading file'
r = requests.get(url, stream = True)
with open("Voice.py", "wb") as Pypdf:
total_length = int(r.headers.get('content-length'))
for ch in progress.bar(r.iter_content(chunk_size = 2391975),
expected_size =(total_length / 1024) + 1):
if ch:
Pypdf.write(ch)
# NPPR9-FWDCX-D2C8J-H872K-2YT43
elif "jarvis" in query:
wishMe()
speak("Jarvis 1 point o in your service Mister")
speak(assname)
elif "weather" in query:
# Google Open weather website
# to get API of Open weather
api_key = "Api key"
base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
speak(" City name ")
print("City name : ")
city_name = takeCommand()
complete_url = base_url + "appid =" + api_key + "&q =" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(" Temperature (in kelvin unit) = " +str(current_temperature)+"\n atmospheric pressure (in hPa unit) ="+str(current_pressure) +"\n humidity (in percentage) = " +str(current_humidiy) +"\n description = " +str(weather_description))
else:
speak(" City Not Found ")
elif "send message " in query:
# You need to create an account on Twilio to use this service
account_sid = 'Account Sid key'
auth_token = 'Auth token'
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body = takeCommand(),
from_='Sender No',
to ='Receiver No'
)
print(message.sid)
elif "wikipedia" in query:
webbrowser.open("wikipedia.com")
elif "Good Morning" in query:
speak("A warm" +query)
speak("How are you Mister")
speak(assname)
# most asked question from google Assistant
elif "will you be my gf" in query or "will you be my bf" in query:
speak("I'm not sure about, may be you should give me some time")
elif "how are you" in query:
speak("I'm fine, glad you me that")
elif "i love you" in query:
speak("It's hard to understand")
elif "what is" in query or "who is" in query:
# Use the same API key
# that we have generated earlier
client = wolframalpha.Client("API_ID")
res = client.query(query)
try:
print (next(res.results).text)
speak (next(res.results).text)
except StopIteration:
print ("No results")
# elif "" in query:
# Command go here
# For adding more commands
Here is when i try to run it:
PS C:\Users\"My Username"\Desktop\Jarvis> & C:/Users/"My username"/AppData/Local/Programs/Python/Python39/python.exe c:/Users/"My username"/Desktop/Jarvis/jarvis.py
File "c:\Users\"My username"\Desktop\Jarvis\jarvis.py", line 98
clear = lambda: os.system('cls')
^
IndentationError: unindent does not match any outer indentation level
Can someone help?
I tried whatever i found on the internet. And they didn't help me. This isn't my code this is just a template.
if __name__ == '__main__':
clear = lambda: os.system('cls')
clear()
wishMe()
usrname()
This is taken from your code. Notice how clear = lambda: os.system('cls') is indented one space too little. Fix that, it should work.
An almost identical snippet on https://www.geeksforgeeks.org/voice-assistant-using-python/ shows that line 97 should probably have no indentation.
Line 98 is missing a single space before clear (to be in line with the below code).
Python is very indent-dependant.
i'm trying to run this program in Python, but i'm not able to execute def. this is an assistant who shuold be able to catch words from the users and execute orders accordingly
the main question is:
how can I built an run more actions. example:
user said: stevens, what do you think about sports?
the IA (Steven) should be able to catch this string as an input order and execute a function and/or reply accordingly (based upon a pre-existing command line). Possible outputs should be: a. run a mp3 file, print a sentence, run a program
how can I execute def greeting?
this is the whole code:
import gtts
from gtts import gTTS
import warnings
import speech_recognition as sr
import os
import google
import random
warnings.filterwarnings('ignore')
def record_audio():
r = sr.Recognizer()
global data
with sr.Microphone() as source:
print('Say something! ')
audio = r.listen(source)
try:
data = r.recognize_google(audio)
print(data)
except sr.UnknownValueError:
print('I am waiting for your orders')
except sr.RequestError as e:
print('Google speech rec error')
return data
def assistant_responses(text):
print(text)
myobj = gTTS(text= text, lang= 'en', slow=False)
myobj.save('assistant_response.mp3')
os.system('start assistant_response.mp3')
def wake_words(text):
WAKE_WORDS = ['stevens', 'hi stevens']
text = text.lower()
for phrase in WAKE_WORDS:
if phrase in text:
return True
return False
def greeting(text):
GREETING_INPUTS = ['hi', 'hey', 'hola', 'ciao', 'hello', 'good morning']
GREETING_RESPONSES = ['hello sir', 'good morning sir', 'how can i help you sir?']
for word in text.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES) +'.'
return ''
while True:
text = record_audio()
response = greeting(text)
if wake_words(text) == True:
print('Good day sir')
elif greeting(text) == True:
print('Hello sir')
The issue is that you want to have the result of greeting be displayed, but you're not displaying the result anywhere. This is how you currently call greeting:
response = greeting(text)
All this is doing is setting the variable response to something from GREETING_RESPONSES. It's not telling Python to display anything. You have to actually print the response (or do something else with it besides nothing):
response = greeting(text)
print(response)
Or just:
print(greeting(text))