0% found this document useful (0 votes)
2K views4 pages

Jarvis AI Assistant Python Code Guide

This document provides the complete source code and setup guide for a Jarvis-like voice assistant built in Python. The assistant can execute voice commands for various tasks such as web searches, playing music, reading files, and system control functions. It is compatible with both PC and Android platforms using Pydroid3.

Uploaded by

rramp762008
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)
2K views4 pages

Jarvis AI Assistant Python Code Guide

This document provides the complete source code and setup guide for a Jarvis-like voice assistant built in Python. The assistant can execute voice commands for various tasks such as web searches, playing music, reading files, and system control functions. It is compatible with both PC and Android platforms using Pydroid3.

Uploaded by

rramp762008
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

Jarvis AI Assistant in Python - Full Code and Setup Guide

This document contains the full source code and explanation for a Jarvis-like voice assistant written
in Python. It supports:
- Voice commands
- Web and Wikipedia search
- Playing YouTube songs
- Reading files
- Opening folders and apps
- System control (shutdown, restart, lock)

Tested for both PC and Android (via Pydroid3).

import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import pyjokes
import pywhatkit
import webbrowser
import os
import subprocess

engine = [Link]()

def speak(text):
print("Jarvis:", text)
[Link](text)
[Link]()

def wish():
hour = [Link]().hour
if hour < 12:
speak("Good morning!")
elif hour < 18:
speak("Good afternoon!")
else:
speak("Good evening!")
speak("I am Jarvis. How may I help you?")
def take_command():
recognizer = [Link]()
with [Link]() as source:
print("Listening...")
audio = [Link](source)

try:
print("Recognizing...")
query = recognizer.recognize_google(audio, language="en-in")
print("You said:", query)
except Exception:
speak("Sorry, I didn't catch that. Say it again.")
return "None"
return [Link]()

def open_app(app_name):
paths = {
"chrome": "C:\\Program Files\\Google\\Chrome\\Application\\[Link]",
"notepad": "[Link]",
"word": "C:\\Program Files\\Microsoft Office\\root\\Office16\\[Link]"
}
if app_name in paths:
[Link](paths[app_name])
speak(f"Opening {app_name}")
else:
speak(f"I don't know how to open {app_name}")

def open_folder(folder_name):
folders = {
"downloads": "C:\\Users\\%USERNAME%\\Downloads",
"documents": "C:\\Users\\%USERNAME%\\Documents",
"desktop": "C:\\Users\\%USERNAME%\\Desktop"
}
if folder_name in folders:
[Link]([Link](folders[folder_name]))
speak(f"Opening {folder_name} folder")
else:
speak(f"Folder {folder_name} not configured")

def read_file():
file_path = "C:\\Users\\%USERNAME%\\Documents\\[Link]"
try:
with open([Link](file_path), 'r') as f:
content = [Link]()
speak("Reading your notes:")
speak(content)
except FileNotFoundError:
speak("Sorry, the notes file is missing.")

def system_control(command):
if command == "shutdown":
speak("Shutting down the system.")
[Link]("shutdown /s /t 1")
elif command == "restart":
speak("Restarting the system.")
[Link]("shutdown /r /t 1")
elif command == "lock":
speak("Locking the system.")
[Link]("[Link] [Link],LockWorkStation")

def run_jarvis():
wish()
while True:
query = take_command()

if 'time' in query:
time = [Link]().strftime("%I:%M %p")
speak(f"The time is {time}")

elif 'who is' in query:


person = [Link]("who is", "")
info = [Link](person, sentences=2)
speak(info)

elif 'joke' in query:


speak(pyjokes.get_joke())

elif 'play' in query:


song = [Link]("play", "")
speak(f"Playing {song}")
[Link](song)

elif 'open youtube' in query:


[Link]("[Link]
speak("Opening YouTube")

elif 'open google' in query:


[Link]("[Link]
speak("Opening Google")

elif 'open' in query and 'folder' in query:


for key in ['downloads', 'documents', 'desktop']:
if key in query:
open_folder(key)

elif 'open' in query and 'app' in query:


for key in ['chrome', 'notepad', 'word']:
if key in query:
open_app(key)

elif 'read file' in query or 'read notes' in query:


read_file()

elif 'shutdown' in query:


system_control("shutdown")

elif 'restart' in query:


system_control("restart")

elif 'lock' in query:


system_control("lock")

elif 'search for' in query or 'look up' in query:


search_term = [Link]("search for", "").replace("look up", "").strip()
speak(f"Searching Google for {search_term}")
[Link](search_term)

elif 'exit' in query or 'bye' in query:


speak("Goodbye!")
break

else:
speak("I didn't understand that command.")

run_jarvis()

Common questions

Powered by AI

Jarvis leverages several external libraries to enhance its functionality. pyttsx3 is used for text-to-speech conversion, speech_recognition for capturing and interpreting voice commands, wikipedia for fetching summaries, pyjokes for generating jokes, pywhatkit for playing YouTube songs and conducting web searches, webbrowser to open websites from voice commands, and os and subprocess for file and system operations. These libraries allow Jarvis to perform complex tasks by integrating various APIs and system commands seamlessly .

Jarvis handles media playback requests primarily through the 'play' keyword in user queries. It uses pywhatkit's playonyt function to open and play the requested song or video on YouTube. The function first extracts the song name from the user's query by replacing 'play' with an empty string. Then, it proceeds to play the song on YouTube and informs the user by saying 'Playing [song name].' This approach leverages the capabilities of pywhatkit to simplify media handling .

When the user query includes the keyword 'time', Jarvis retrieves the current time using datetime.datetime.now().strftime("%I:%M %p") to format it in a 12-hour clock notation, specifying hours and minutes with AM/PM. The assistant then verbalizes the time by saying 'The time is [current time'],' providing users with the information directly from the system's clock .

Jarvis uses the open_folder function to interact with the file system. This function checks a predefined dictionary that maps folder names to their directory paths. If a user requests a folder to open, the function verifies if the folder name is in the dictionary. If it is, it uses os.startfile to open the path. It communicates the folder opening by saying 'Opening [folder_name] folder,' or informs the user if the folder is not configured .

The open_app function uses a dictionary named paths that maps application names to their respective executable paths. When a user specifies an app to open, the function checks if the app name exists in the dictionary. If it does, it uses subprocess.Popen to launch the application. If the app is not in the dictionary, Jarvis informs the user that it doesn't know how to open the specified app .

When Jarvis encounters an unrecognized command, it defaults to a fallback mechanism where it communicates to the user 'I didn't understand that command.' This approach helps in gracefully handling unexpected input by prompting repetition or clarification, although it lacks intelligent feedback or self-learning capabilities to improve understanding of similar commands in the future .

Jarvis integrates system control capabilities such as shut down, restart, and lock, within the system_control function. This functionality is triggered by specific voice commands detected in take_command. Based on the command, the corresponding system action is executed: os.system("shutdown /s /t 1") for shutdown, os.system("shutdown /r /t 1") for restart, and os.system("rundll32.exe user32.dll,LockWorkStation") for locking the workstation. These commands are validated and executed only when the respective keywords are recognized .

Jarvis uses a try-except block to handle when the speech recognizer fails to understand a voice command. If an exception is raised in recognizing speech, Jarvis apologizes and prompts the user to repeat the command by saying 'Sorry, I didn't catch that. Say it again.' .

Using a voice assistant like Jarvis on a personal computer can raise several security and privacy concerns. Voice data could potentially be intercepted, misused, or accessed by unauthorized parties during transmission or processing. Moreover, if configured improperly or left without adequate security measures, the assistant could inadvertently execute malicious commands or expose sensitive data through voice commands or logs. Ensuring robust authentication, encrypted communication, and regular security updates are necessary measures to mitigate these risks .

The wish function first retrieves the current hour using datetime.datetime.now().hour. It then checks the hour and determines the appropriate greeting. If the hour is less than 12, it outputs 'Good morning!'; if it is between 12 and 18, 'Good afternoon!'; otherwise, it outputs 'Good evening!'. After the greeting, it introduces Jarvis with 'I am Jarvis. How may I help you?' .

You might also like