DEV Community

loading...
Cover image for Do You need an AI? Lets Make it in Python

Do You need an AI? Lets Make it in Python

krishan111 profile image Krishan111 Updated on ・4 min read

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:

  • He can Tell the Time
  • He can Speak Jokes
  • He Also can Tell Temperature
  • Retrieve Information on a Topic
  • Can Also Wish You
  • Play Videos On YouTube
  • Shutdown Computer

  • Sky is the limit of any AI it depends on you that how creatively you can make it.
  • 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.
    
    Enter fullscreen mode Exit fullscreen mode
    pip install speech_recognition # it will help us to convert speech into text.
    
    Enter fullscreen mode Exit fullscreen mode
    pip install pywhatkit # Its an awesome library & can do several tasks but we will be using it here for playing video on YouTube
    
    Enter fullscreen mode Exit fullscreen mode
    pip install wikipedia # it will help us in retrieving information about a particular topic 
    
    Enter fullscreen mode Exit fullscreen mode
    pip install pyjokes # with this JARVIS will be able to speak jokes
    
    Enter fullscreen mode Exit fullscreen mode

    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?

    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()
    
    Enter fullscreen mode Exit fullscreen mode

    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
    
    Enter fullscreen mode Exit fullscreen mode

    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")     
    
    Enter fullscreen mode Exit fullscreen mode

    4).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")
    
    Enter fullscreen mode Exit fullscreen mode

    5).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 ("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)
    
    Enter fullscreen mode Exit fullscreen mode



    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?

    Discussion (10)

    pic
    Editor guide
    Collapse
    iamcoderanddev profile image
    Nick Williams • Edited

    Nice post, integrating this AI with keylogger will be a cool stuff

    Collapse
    mariabailey profile image
    Maria Bailey • Edited

    I loved the post❤️❤️

    Collapse
    krishan111 profile image
    Collapse
    mariabailey profile image
    Maria Bailey

    Hi @krishan111 can we be friends

    Thread Thread
    krishan111 profile image
    Thread Thread
    mariabailey profile image
    Collapse
    radhikashrma profile image
    Radhika Sharma

    I was wishing to have a personal assistant which is coded in Python thanks krishan111

    Collapse
    krishan111 profile image
    Krishan111 Author

    I am glad it helped !

    Collapse
    jennawagnercode profile image
    Jenna Wagner • Edited

    The good thing is that the AI can search for queries❤️, Great Post!!

    Collapse
    krishan111 profile image
    Krishan111 Author

    Thanks 🙌