0% found this document useful (0 votes)
127 views6 pages

Import Datetime

The document defines functions for an AI assistant to take commands, speak responses, and perform tasks like opening apps, playing music, telling jokes, taking screenshots, and doing calculations. It imports necessary libraries and defines an OpenAI API key to generate responses from GPT-3. The main TaskExecution function contains an interactive loop that takes commands and executes the corresponding tasks or actions.

Uploaded by

hosahab133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views6 pages

Import Datetime

The document defines functions for an AI assistant to take commands, speak responses, and perform tasks like opening apps, playing music, telling jokes, taking screenshots, and doing calculations. It imports necessary libraries and defines an OpenAI API key to generate responses from GPT-3. The main TaskExecution function contains an interactive loop that takes commands and executes the corresponding tasks or actions.

Uploaded by

hosahab133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

import datetime

import openai
import pyttsx3
import speech_recognition as sr
import os
import cv2
from requests import get
import wikipedia
import webbrowser
import pywhatkit as kit
import sys
import pyjokes
import time
import instaloader
import requests
import operator
import pyautogui

#setting up OpenAI API key


openai.api_key = "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"

engine = pyttsx3.init()
engine.setProperty('voice',
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-
US_ZIRA_11.0")
engine.runAndWait()

#text to speech
def speak(audio): #normal voice assistant
engine.say(audio)
print(audio)
engine.runAndWait()

def speak_text(text): #chat gpt assistant


engine.say(text)
engine.runAndWait()

def transcribe_audio_to_text(filename): #chatgpt


recognizer = sr.Recognizer()
with sr.AudioFile(filename) as source:
audio = recognizer.record(source)
try:
return recognizer.recognize_google(audio)
except:
print('Skipping unknown error')

#converting spoken audio to text


def takecommand(): #jarvis
r = sr.Recognizer()
with sr.Microphone() as source:
print("listening...")
r.pause_threshold = 1
audio = r.listen(source, timeout=10, phrase_time_limit=10)

try:
print("recognizing...")
query = r.recognize_google(audio, language='en-US')
print(f"user said: {query}")

except Exception as e:
print("Say that again please")
return "none"
return query

def wish():
hour = int(datetime.datetime.now().hour)
tt = time.strftime("%I;%M %p")

if hour >=0 and hour <=12:


speak(f"good morning, it's {tt}")
elif hour > 12 and hour <18:
speak(f"good afternoon, it's {tt}")
else:
speak(f"good evening, it's {tt}")
speak("How can I help you")

def generate_response(prompt):
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=4000,
n=1,
stop=None,
temperature=0.5
)
return response["choices"][0]["text"]

def smallhelp():
speak("How can I be helpful?")
while True:
# wait for user to say hey brother

with sr.Microphone() as source:


recognizer = sr.Recognizer()
source.pause_threshold = 1
audio = recognizer.listen(source, phrase_time_limit=None,
timeout=None)
filename = "dowhatisay.wav"
with open(filename, "wb") as f:
f.write(audio.get_wav_data())

# transcribe audio to text


text = transcribe_audio_to_text(filename)
if text:
if "you can sleep" in text or "sleep now" in text or
"mute" in text:
print("muted")
break
else:
print(f"You said: {text}")

# generate response
response = generate_response(text)
print(f"GPT-3 says: {response}")

# read response with tts

speak_text(response)
speak("Can I do anything else?")

def TaskExecution():
wish()
while True:
query = takecommand()
# logic building for tasks

if "open Notepad" in query:


npath = "C:\\Windows\\System32\\notepad.exe"
os.startfile(npath)
speak("opening notepad")

elif "open Spotify" in query:


spath =
"C:\\Users\\Tobi\\AppData\\Local\\Microsoft\\WindowsApps\\Spotify.exe"
os.startfile(spath)

elif "open Ableton" in query:


apath = "C:\\ProgramData\\Ableton\\Live 11
Intro\\Program\\Ableton Live 11 Intro.exe"
os.startfile(apath)

elif "play song with doc" in query:


dpath = "C:\\Users\\Tobi\\Desktop\\Songs\\Songs mit
Tobi\\Urlaubssong.wav"
os.startfile(dpath)

elif "play song with surprise" in query:


d2path = "D:\\Schule\\Sport\\Ton\\Urlaubssong mit
Moritz(surprise edition).wav"
os.startfile(d2path)

elif "open Firefox" in query:


fpath = "C:\\ProgramData\\Microsoft\\Windows\\Start
Menu\\Programs\\Firefox.lnk"
os.startfile(fpath)

elif "open camera" in query:


cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
cv2.imshow('webcam', img)
k = cv2.waitKey(50)
if k == 27:
break
cap.release()
cv2.destroyAllWindows()

elif "play music" in query:


music_dir = "C:\\Users\\Tobi\\Desktop\\Songs\\Alle Songs"
songs = os.listdir(music_dir)
# rd = random.choice(songs)
for song in songs:
if song.endswith('.wav' or '.mp3'):
os.startfile(os.path.join(music_dir, song))

elif "IP address" in query:


ip = get('https://api.ipify.org').text
speak(f"your IP address is {ip}")

elif "Wikipedia" in query:


speak("searching wikipedia...")
query = query.replace("wikipedia", " ")
results = wikipedia.summary(query, sentences=2)
speak("akkording to wikipedia")
speak(results)
# print(results)
elif "open youtube" in query:
webbrowser.open("youtube.com")

elif "open Google" in query:


speak("what should I google?")
cm = takecommand().lower()
webbrowser.open(f"{cm}")

elif "play song on YouTube" in query:


kit.playonyt("Never gonna give you up")

elif "no thanks" in query:


speak("Ok sir, have a nice day")
sys.exit()

elif "Close notepad" in query:


speak("closing notepad")
os.system("taskkill /f /im notepad.exe")

elif "close Spotify" in query:


speak("closing spotify")
os.system("taskkill /f /im spotify.exe")

elif "close Firefox" in query:


speak("closing firefox")
os.system("taskkill /f /im Firefox.lnk")

elif "set alarm" in query:


nn = int(datetime.datetime.now().hour)
if nn == 22:
music_dir = 'C:\\Users\\Tobi\\Desktop\\Songs\\Alle Songs'
songs = os.listdir(music_dir)
os.startfile(os.path.join(music_dir, songs[0]))

elif "tell me a joke" in query:


joke = pyjokes.get_joke()
speak(joke)

elif "shut down the computer" in query or "shut down the PC" in
query:
os.system("shutdown /s /t 5")

elif "restart the computer" in query:


os.system("shutdown /r /t 5")

# orientation using the IP adress


elif "where am I" in query:
speak("let me check")
try:
ipAdd = requests.get('https://api.ipify.org').text
print(ipAdd)
url = 'https://get.geojs.io/v1/ip/geo/' + ipAdd + '.json'
geo_requests = requests.get(url)
geo_data = geo_requests.json()
city = geo_data['city']
country = geo_data['country']
speak(f"sir, we are in {city} of {country} ")
except Exception as e:
speak("sorry, i am not able to find our location")
pass
# instagram profile
elif "Instagram profile" in query:
speak("please enter the correct username.")
name = input("Enter username here:")
webbrowser.open(f"www.instagram.com/{name}")
speak(f"this is the profile of the user {name}")
time.sleep(10)
speak("Would you like to download the profile picture?")
condition = takecommand().lower()
if "yes" in condition:
mod = instaloader.Instaloader()
mod.download_profile(name, profile_pic_only=True)
speak(f"The profile picture of {name} has been downloaded
to your main folder.")
else:
pass

# take screenshot
elif "take screenshot" in query or "take a screenshot" in query:
speak("please name the screenshot file")
name = takecommand().lower()
speak("taking screenshot")
time.sleep(1)
img = pyautogui.screenshot()
img.save(f"{name}.png")
speak("the screenshot is saved in your main folder.")

elif "do some calculations" in query or "can you calculate" in


query or "open calculator" in query:
r = sr.Recognizer()
with sr.Microphone() as source:
speak("What should I calculate?")
print("listening...")
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
my_string = r.recognize_google(audio)
print(my_string)

def get_operator_fn(op):
return {
'+': operator.add, # addition
'-': operator.sub, # subtraktion
'x': operator.mul, # multiplikation
'divided': operator.__truediv__, # division
}[op]

def eval_binary_expr(op1, oper, op2): # 5 plus 8


op1, op2 = int(op1), int(op2)
return get_operator_fn(oper)(op1, op2)

speak("Thats")
speak(eval_binary_expr(*(my_string.split())))

elif "hello" in query or "hey" in query:


speak("hello, can I help you with something?")

elif "how are you" in query:


speak("I'm fine sir, what about you?")

elif "also good" in query or "fine" in query:


speak("that's great")

elif "thank you" in query or "thanks" in query:


speak("it's my pleasure")
elif "you can sleep" in query or "sleep now" in query or "mute" in
query:
print("muted")
break

if __name__ == "__main__":
while True:
permission = takecommand()

if "wake up" in permission:


TaskExecution()
elif "small help" in permission:
smallhelp()
elif "goodbye" in permission:
speak("have a nice day sir")
sys.exit()

You might also like