Do You need an AI? Lets Make it in Python
Tags: python
Published: 2021-02-25 14:36:26

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:
<li>He can Tell the Time</li><li>He can Speak Jokes</li><li>He Also can Tell Temperature    
 </li><li>Retrieve Information on a Topic</li><li>Can Also Wish You</li><li>Play Videos On YouTube</li><li>Shutdown Computer</li>
<li>Sky is the limit of any AI it depends on you that how creatively you can make it.</li>

<h2>Firstly lets collect ingredients!</h2>
So guys for making this program we will need two table spoon of each module😁, just kidding don't take seriously
```python
pip install pyttsx3==2.71 #This will help in conversion of text into speech and stands for python text to speech.
```
```python
pip install speech_recognition # it will help us to convert speech into text.
```
```python
pip install pywhatkit # Its an awesome library & can do several tasks but we will be using it here for playing video on YouTube
```
```python
pip install wikipedia # it will help us in retrieving information about a particular topic 
```
```python
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 BTS or Billie Eilish, what would you prefer?

<h2>Now as we have all ingredients lets start!</h2>
<h4>1). The Speak Function:</h4>
```python
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.

<h4>2).The Listening Function</h4>
```python
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
```
<h3>3).The Wishing Function</h3>
```python
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")     
```

<h4>4).Making tell_temperature function:</h4>
For making it you need to use an API from [openweather](https://openweathermap.org). 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.
```python
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")
```
<h3>5).The Last Part</h3>
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.
```python
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 ("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)
```
<hr>
**I hope you loved the post❤️❤️**
Just combine all the parts and JARVIS is ready to use. Well what features would you like to add in JARVIS?