This content originally appeared on DEV Community and was authored by Krishan111
Hello World!, I am Krishan and in this blog we are going to make an AI. We are going to name this AI JARVIS bcoz I got the idea to make it from the Iron Man, moreover I like Tony Stark and he is my favorite fictional character, I guess you too like him.
Lets get started,
Before Going ahead lets take a look at the things JARVIS can do:
Firstly lets collect ingredients!
So guys for making this program we will need two table spoon of each module?, just kidding don't take seriously
pip install pyttsx3==2.71 #This will help in conversion of text into speech and stands for python text to speech.
pip install speech_recognition # it will help us to convert speech into text.
pip install pywhatkit # Its an awesome library & can do several tasks but we will be using it here for playing video on YouTube
pip install wikipedia # it will help us in retrieving information about a particular topic
pip install pyjokes # with this JARVIS will be able to speak jokes
One more thing, we also need to install PyAudio but PyAudio cannot be installed from pip command directly. For installing it you have type in your browser unofficial Python Binaries open the first website and search for PyAudio. Click on that Pyaudio wheel which supports you computer i.e, if you have 32-bit PC go for 32-bit version and if you have 64-bit PC than go ahead for it. After installing open the installed file in file explorer and open Command Prompt in that directory, and in CMD type pip install path_of_installed_PyAudio_file, hit Enter and enjoy listening music until its installed
Pretty Long but easy!
By the way I would prefer listening to Dua Lipa or Billie Eilish, what would you prefer?
Now as we have all ingredients lets start!
1). The Speak Function:
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
You can also put voices[1].id in place of voices[0].id if you want female voice. But as we are making JARVIS I am using voices[0].id.
2).The Listening Function
import speech_recognition as spr
def voice_command_inp():
r = spr.Recognizer()
with spr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-us')
print(f"You Said: {query}\n")
except Exception as e:
# print(e)
print("Can You Say That Again Please...")
return "**None**"
return query
3).The Wishing Function
import datetime
def wish():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
voice_output("Good Morning")
elif hour>=12 and hour<15:
voice_output("Good Afternoon")
elif (hour>=15 and hour<18):
voice_output("Hello! How are you doing")
else:
voice_output("Good Evening")
4).Website opening part
def open_in_browser(argumentz):
webbrowser.register('chrome',
None,
webbrowser.BackgroundBrowser("C://Program Files (x86)//Google//Chrome//Application//chrome.exe"))
webbrowser.get('chrome').open(f'{argumentz}')
You can simply use open function of webbrowser module but in that case it will be opening websites in Internet Explorer. If you are using this method, replace the path in argument of webbrowser.BackgroundBrowser() with the chrome path in your PC.
5).Making tell_temperature function:
For making it you need to use an API from openweather. You can get this API by logging in to your account and request for an API key.
After we got the API key lets make tell_temperature() function.
def tell_temperature(city_name):
city_name_inp = city_name
complete_url = base_url + "appid=" + weather_api_key + "&q=" + city_name_inp
response_for_location = requests.get(complete_url)
var_1 = response_for_location.json()
if var_2["cod"] != "404" :
var_3 = var_2["main"]
current_temperature = var_3["temp"]
print(f"Tempreature In {city_name_inp}: ", str(int(current_temperature-273.15)),"°C")
speak(f"Today Tempreture in {city_name_inp}" + str(int(current_temperature-273.15)) + "degree celsius")
else:
print(f"Sorry I could not find the specified palce")
speak(f"Sorry I could not find the specified palce")
6).The Last Part
Now we just need to execute all the functions we made with some additional features and we can try JARVIS for the first time.
And Yes don't put wish() function inside while loop here otherwise JARVIS will wish you non-stop.
if __name__ == "__main__":
wish()
while True:
query = voice_command_inp().lower()==> ")
elif("hello jarvis" in query):
speak("Oh Hello Sir/Mam/anything u wish to listen...")
elif("joke" in query):
var_joke = pyjokes.get_joke()
print(f"{var_joke}, XD")
speak(var_joke)
elif("temperature" in query):
try:
var_1 = query.split(' ')
var_2 = var_1.index("of")
name_of_city = str(var_1[var_2+1])
tell_temperature(name_of_city)
except Exception as e:
print("Try Saying Tempreature Of")
speak("Try Saying Tempreature Of")
elif('who are you' in query):
speak("I m JARVIS the AI made by Krishan/Your Name, I Am still being made better than before, the full form of my name is Just A Rather Very Intelligent System")
# Logic for executing tasks based on query
elif 'search' in query:
speak('Searching Query...')
print('Searching Query...')
query = query.replace("search", "")
try:
results = wikipedia.summary(query, sentences=2)
speak("According to My Search...")
print("According to My Search...")
print(f"=> {results}")
speak(results)
except Exception as e:
print("Sorry! I could not find results")
speak("Sorry! I could not find results")
elif 'play' in query:
var_a = query.split(' ')
var_b = var_a.index("play")
var_c = str(var_a[var_b+1:])
print(f"Playing {var_c}...")
speak(f"Playing {var_c}...")
pywhatkit.playonyt(var_c)
elif 'shut down computer' in query:
speak("Please type the password")
pcshtdwn_paswrd_inp = input("Type In the Password: ")
if (pcshtdwn_paswrd_inp == 'password of your wish'):
speak("Shutting Down PC Thanks For Your Time Sir!")
os.system("shutdown /s /t 7")
else:
print("Password Is Incorrect")
elif 'open' in query:
var1 = query.split(' ')
var2 = var1.index("open")
var3 = var1[var2+1]
print(f"Opening {x} Sir...")
speak(f"Opening {x} Sir...")
open_in_browser(f"{x}")
elif ("ok GoodBye" in query):
print("Thanks For Your Time, GoodBye!")
speak("Thanks For Your Time, Good Bye!")
sys.exit()
elif 'the time' in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"Sir/Mam/anything you would prefer listening, the time is {strTime}")
elif 'start visual studio' in query:
speak("Starting Visual Studio Code...")
vscodePath = (Replace this path with yours) "C:\\Users\\Krishan verma\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
os.startfile(vscodePath)
I hope you loved the post❤️❤️
Just combine all the parts and JARVIS is ready to use. Well what features would you want to add in JARVIS?
This content originally appeared on DEV Community and was authored by Krishan111
Krishan111 | Sciencx (2021-02-25T14:36:26+00:00) Do You need an AI? Lets Make it in Python. Retrieved from https://www.scien.cx/2021/02/25/do-you-need-an-ai-lets-make-it-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.