Voice Assistant
#listenToMe.py
import speech_recognition as sr
import os
import keyboard
import openai
import pyttsx3
import subprocess
# Initialize the text-to-speech engine
engine = pyttsx3.init()
# Set the rate of speech
rate = engine.getProperty('rate')
engine.setProperty('rate', rate - 20)
# Set the voice
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
# Function to speak the given text
def speak(text):
engine.say(text)
engine.runAndWait()
# Initialize the recognizer
r = sr.Recognizer()
# Use the default microphone as the audio source
with sr.Microphone() as source:
while True:
print("Ready for speech...")
# Wait for the keyboard combination to start listening
keyboard.wait("ctrl+alt+s")
print("Listening...")
# Start listening for audio
audio_data = r.listen(source, phrase_time_limit=5)
# Wait for the keyboard combination to stop listening
print("Recognizing...")
try:
# Use Google speech recognition to convert audio to text
text = r.recognize_google(audio_data)
print(f"You said: {text}")
# Perform an action based on the recognized text
if "open notepad" in text.lower():
speak("Opening notepad")
subprocess.Popen(['C:\Windows\System32\\notepad.exe'])
elif "like this song" in text.lower() or "like song" in text.lower():
speak("Liking Song")
exec(open(r"C:\Users\Hjosh\BOC_Python\Spotify_Testing\likeSong.py").read())
elif "start music" in text.lower():
speak("opening music")
exec(open(r"C:\Users\Hjosh\BOC_Python\Spotify_Testing\openAndPlay.py").read())
elif "pause music" in text.lower() or "pause song" in text.lower() or "play music" in text.lower() or "resume music" in text.lower():
exec(open(r"C:\Users\Hjosh\BOC_Python\Spotify_Testing\pausePlayMusic.py").read())
elif "search google for" in text.lower():
query = text.lower().split("search google for ")[1]
speak(f"searching google for {query}")
query = query.replace(" ", "+")
os.system(f"start https://www.google.com/search?q={query}")
elif "good night computer" in text.lower():
speak("sweet dreams}")
elif "welcome everyone" in text.lower():
speak("Welcome........To Bytes Of Code")
elif "gpt " in text.lower():
#use openai key
openai.api_key = "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"
#setup gpt-3
model_engine = "davinci"
query = text.lower().split("gpt ")[1]
temperature = 0.7
max_tokens = 256
response=openai.Completion.create(
model="text-davinci-003",
prompt=query,
temperature=temperature,
max_tokens=max_tokens
)
print(response.choices[0].text.strip())
speak(response.choices[0].text.strip())
elif "computer" in text.lower():
openai.api_key = "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"
query = text.lower().split("computer ")[1]
conversation.append({"role":"user","content":query})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation
)
chatGPT_response = response['choices'][0]['message']['content']
print(chatGPT_response)
speak(chatGPT_response)
elif "copilot" in text.lower():
openai.api_key = "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"
query = text.lower().split("copilot ")[1]
query = query + "Do not respond with additional text. respond in python code only. Do not respond with any explination or greeting whatsoever. Your response in its entirety should only have python code."
conversation.append({"role":"user","content":query})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation
)
chatGPT_response = response['choices'][0]['message']['content']
print(chatGPT_response)
#speak(chatGPT_response)
pyautogui.write(chatGPT_response)
elif "stop listening" in text.lower():
speak('goodbye')
exit()
else:
speak('Command not recognized')
print("Command not recognized")
except sr.UnknownValueError:
print("Unable to recognize speech")
except sr.RequestError as e:
print(f"Error occurred: {e}")
---------------------------------------------------------------------------
#openAndPlay.py
import pyautogui
import time
import psutil
import time
pyautogui.press('win') # Press Windows key to open Start menu
time.sleep(1)
pyautogui.write('Spotify') # Type "Spotify" to search for Spotify
time.sleep(1)
pyautogui.press('enter') # Open Spotify
program_name = "Spotify.exe"
# Set a timeout of 2 minutes
timeout = time.time() + 120 # 120 seconds = 2 minutes
while True:
# Check if the program is open
for process in psutil.process_iter():
try:
if process.name() == program_name:
print("Spotify is open!")
break
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
else:
# If the program is not open, check if we have timed out
if time.time() > timeout:
print("Timed out!")
break
else:
# Wait for a short amount of time before checking again
time.sleep(1)
continue
# If we reach this point, the program is open, so break out of the loop
break
time.sleep(7) # Wait for Spotify to load
pyautogui.press('space') # Play the song
---------------------------------------------------------------------------
#pausePlayMusic.py
import pyautogui
import time
import psutil
import win32gui
import win32process
from pywinauto import Application
#locate physical window
def get_spotify_window_title(pids):
titles = []
returnpid = 0
def _enum_cb(hwnd, results):
if win32gui.IsWindowVisible(hwnd):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pids is None or pid in pids:
nonlocal returnpid
returnpid = pid
win32gui.EnumWindows(_enum_cb, titles)
return returnpid
#press space to play/pause the song
def press_key(spotify_pids):
app = Application().connect(process=get_spotify_window_title(spotify_pids))
app.top_window().set_focus()
time.sleep(1) # Wait for Spotify to load
pyautogui.press('space') # Play the song
# Get the window object
window = app.top_window()
# Minimize the window
window.Minimize()
program_name = "Spotify.exe"
process_ids = []
# Set a timeout of 2 minutes
timeout = time.time() + 120 # 120 seconds = 2 minutes
isOpen = False
while True and time.time() < timeout:
# Check if the program is open
for process in psutil.process_iter():
try:
if program_name in process.name():
isOpen = True
process_ids.append(process.pid)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
else:
if isOpen:
print("Spotify is OPEN")
# finished looping succesfully
time.sleep(1)
press_key(process_ids)
else:
print("Spotify is CLOSED")
break
---------------------------------------------------------------------------
#likeSong.py
import pyautogui
import time
import psutil
import win32gui
import win32process
from pywinauto import Application
def get_spotify_window_title(pids):
titles = []
returnpid = 0
def _enum_cb(hwnd, results):
if win32gui.IsWindowVisible(hwnd):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pids is None or pid in pids:
nonlocal returnpid
returnpid = pid
win32gui.EnumWindows(_enum_cb, titles)
return returnpid
# Specify the name of the program you want to check
program_name = "Spotify.exe"
# Set a timeout of 2 minutes
timeout = time.time() + 120 # 120 seconds = 2 minutes
isOpen = False
# Check if the program is open
for process in psutil.process_iter():
try:
if process.name() == program_name:
print("Spotify is open!")
isOpen = True
break
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
else:
print("Spotify is not open!")
exit()
if isOpen:
spotify_pids = []
process_name = "Spotify.exe"
for proc in psutil.process_iter():
if process_name in proc.name():
spotify_pids.append(proc.pid)
app = Application().connect(process=get_spotify_window_title(spotify_pids))
app.top_window().set_focus()
time.sleep(1)
pyautogui.hotkey('alt', 'shift', 'b', interval=0.25)
# Get the window object
window = app.top_window()
# Minimize the window
window.minimize()