DEV Community

Cover image for AI CHATBOT (JARVIS)
Arish Sethi
Arish Sethi

Posted on

AI CHATBOT (JARVIS)

Building Jarvis: How I Created a Voice-Activated Python Assistant πŸš€

Ever since I started programming, I wanted to build something that felt like it belonged in a sci-fi movie. So, I decided to sit down and create my own virtual voice assistantβ€”Jarvis.

Using Python, I built an assistant that listens to my voice, speaks back to me, opens up my favorite websites, fetches live news headlines, and even plays my favorite tracks from a music dictionary.

Here is a breakdown of how I built it, how the code works, and what I learned along the way!


πŸ› οΈ The Tech Stack

To give Jarvis ears, a voice, and web powers, I used a few key Python libraries:

  • speech_recognition: For capturing audio from my microphone and converting it to text.

  • pyttsx3: A text-to-speech library that lets Jarvis talk back offline.

  • webbrowser: To trigger web automation directly from the terminal.

  • requests: To make API calls and fetch real-time data from the web.

πŸ’» The Full Code

Here is the complete Python script I wrote for Jarvis:

import speech_recognition as sr
import webbrowser
import pyttsx3
import requests

recognizer = sr.Recognizer()
engine = pyttsx3.init()
newsapi = "YOUR_API_KEY"  # Replace with your own key to use this code

# Function to speak a given text
def speak(text):
    engine.say(text)
    engine.runAndWait()

# Songs dictionary with song name and YouTube link
songs = {
    "who they": "[https://www.youtube.com/watch?v=wBw6Leb5F2U](https://www.youtube.com/watch?v=wBw6Leb5F2U)",
    "block": "[https://www.youtube.com/watch?v=e4c5i1fyW-4](https://www.youtube.com/watch?v=e4c5i1fyW-4)"
}

# Function to process recognized commands
def processword(c):
    if "open google" in c.lower():
        webbrowser.open("[https://google.com](https://google.com)")
    elif "open youtube" in c.lower():
        webbrowser.open("[https://youtube.com](https://youtube.com)")
    elif c.lower().startswith("play"):
        song = c.lower().split("play ")[1].strip()
        link = songs.get(song, None)
        if link:
            speak(f"Playing {song}")
            webbrowser.open(link)
        else:
            speak(f"Sorry, I don't have the song {song}.")
    elif "news" in c.lower():
        r = requests.get(f"[https://newsapi.org/v2/top-headlines?country=us&apiKey=](https://newsapi.org/v2/top-headlines?country=us&apiKey=){newsapi}")
        if r.status_code == 200:
            data = r.json()
            articles = data.get("articles", None)
            for article in articles:
                speak(article["title"])

# Main logic
if __name__ == "__main__":
    speak("Initializing Jarvis....")
    while True:
        try:
            # Obtain audio from the microphone
            with sr.Microphone() as source:
                print("Listening...")
                audio = recognizer.listen(source, timeout=3, phrase_time_limit=5)

            # Recognize the keyword 'Jarvis'
            word = recognizer.recognize_google(audio)
            if word.lower() == "jarvis":
                speak("Yes?")
                with sr.Microphone() as source:
                    print("Jarvis active...")
                    audio = recognizer.listen(source)
                    command = recognizer.recognize_google(audio)
                    processword(command)

        except Exception as e:
            print(f"Error: {str(e)}")





Enter fullscreen mode Exit fullscreen mode

πŸ“Έ See It In Action!

Here is what it looks like when Jarvis initializes and listens through the terminal:

[
 ]

πŸ’‘ What I Learned From This Project

  1. API Integration is Powerful: Working with requests to pull real-time news headlines opened my eyes to how modern web applications share data.

  2. Error Handling is Crucial: Wrapping the audio listener in a try/except block kept the program from constantly crashing when it couldn't understand a sentence.

  3. From Python to the Future: Building logic like this gives me a great foundation as I transition into learning lower-level, high-performance languages like C++.

πŸ›‘ Problems I Faced & How I Fixed Them

Building this wasn't smooth sailing! Here are the main roadblocks I had to smash:
The pyaudio Nightmare: Getting speech_recognition to work on Windows was tough because installing pyaudio kept throwing errors. I had to figure out how to manually install the correct wheel file via the terminal to get my microphone recognized.

API Security: At first, I accidentally left my live News API key visible in the code. I had to learn how to remove it and replace it with a placeholder so people wouldn't steal my API limits when I pushed it to GitHub.

Microphone Lag & Timeouts: Jarvis would either cut me off too early or hang forever waiting for me to speak. I had to tweak the timeout=3 and phrase_time_limit= 5 settings in the listening loop so he only processed active commands without lagging out.

"Since this is one of my major projects, I’d love to hear your thoughts! Please drop a comment below with any suggestions, improvements, or tips on what I did right or what I could do better."

🀝 Let’s Collaborate!

Are you working on something exciting in AI, web development, blockchain, or Python? I’d love to connect and collaborate. You can reach me out in comment section or you can message me on github-https://github.com/Arish2008/CodeSphere

Check out my GitHub repo for the full code and documentation and also for more interesting projects like this. I'd love to hear your feedback or ideas for improvement!" -https://github.com/Arish2008/CodeSphere

Thanks for reading! Let me know in the comments what features I should add to Jarvis next! πŸ€–πŸ”₯

Top comments (0)