C

JARVIS

by CHIRAG

JARVIS by CHIRAG

Advanced AI Voice Assistant for Windows

SYSTEM READY
đŸŽ€
Wake Word
"Jarvis"
đŸ€–
Gemini AI
Smart Fallback
🔊
Offline TTS
Microsoft David
⚡
System Control
Full Access

📩 Required Packages INSTALL FIRST

pip install SpeechRecognition pyttsx3 wikipedia pyautogui keyboard psutil AppOpener google-generativeai
jarvis_by_chirag.py
"""
╔══════════════════════════════════════════════════════════════╗
║                    JARVIS by CHIRAG                          ║
║         Advanced AI Voice Assistant for Windows              ║
║                                                              ║
║  GitHub: https://github.com/Chiragchoudhary26               ║
║  Instagram: @itz_chirag_xxvi                                 ║
║  Contact: kalilinux5488@gmail.com                           ║
╚══════════════════════════════════════════════════════════════╝
"""

import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import keyboard
import psutil
import os
import sys
from AppOpener import open as open_app, close as close_app
import google.generativeai as genai

# ============================================================
# CONFIGURATION
# ============================================================

GEMINI_API_KEY = "YOUR_GEMINI_API_KEY"  # Replace with your API key
WAKE_WORD = "jarvis"
LANGUAGE = "en-in"
VOICE_RATE = 175
CREATOR = "Chirag"
VERSION = "2.0"

# ============================================================
# INITIALIZE TTS ENGINE (Once - Optimized for Performance)
# ============================================================

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')

# Set Microsoft David voice (Male)
for voice in voices:
    if "david" in voice.name.lower():
        engine.setProperty('voice', voice.id)
        break

engine.setProperty('rate', VOICE_RATE)

# ============================================================
# CONFIGURE GEMINI AI
# ============================================================

genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel('gemini-1.5-flash-latest')

# ============================================================
# CORE FUNCTIONS
# ============================================================

def speak(text):
    """Text-to-speech output - Optimized single engine instance"""
    try:
        engine.say(text)
        engine.runAndWait()
    except:
        pass


def listen(timeout=5, phrase_limit=8):
    """Listen for voice input and return recognized text"""
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        recognizer.adjust_for_ambient_noise(source, duration=0.5)
        try:
            audio = recognizer.listen(source, timeout=timeout, phrase_time_limit=phrase_limit)
            query = recognizer.recognize_google(audio, language=LANGUAGE)
            return query.lower().strip()
        except (sr.UnknownValueError, sr.RequestError, sr.WaitTimeoutError):
            return ""


def listen_for_wake_word():
    """Continuously listen for wake word activation"""
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        recognizer.adjust_for_ambient_noise(source, duration=0.3)
        try:
            audio = recognizer.listen(source, timeout=None, phrase_time_limit=3)
            text = recognizer.recognize_google(audio, language=LANGUAGE)
            return WAKE_WORD in text.lower()
        except:
            return False


def greet():
    """Time-based greeting"""
    hour = datetime.datetime.now().hour
    
    if 5 <= hour < 12:
        greeting = "Good Morning"
    elif 12 <= hour < 17:
        greeting = "Good Afternoon"
    else:
        greeting = "Good Evening"
    
    speak(f"{greeting}! I am Jarvis, made by {CREATOR}. How can I assist you?")


def tell_time():
    """Tell current time"""
    current_time = datetime.datetime.now().strftime("%I:%M %p")
    speak(f"The time is {current_time}")


def tell_date():
    """Tell current date"""
    current_date = datetime.datetime.now().strftime("%B %d, %Y")
    speak(f"Today is {current_date}")


# ============================================================
# SEARCH FUNCTIONS
# ============================================================

def search_wikipedia(query):
    """Search Wikipedia and read 2-sentence summary"""
    try:
        search_term = query.replace("wikipedia", "").replace("search", "").replace("about", "").strip()
        wikipedia.set_lang("en")
        result = wikipedia.summary(search_term, sentences=2)
        speak(result)
    except wikipedia.exceptions.DisambiguationError:
        speak("Multiple results found. Please be more specific.")
    except wikipedia.exceptions.PageError:
        speak("No Wikipedia page found for that topic.")
    except:
        speak("Could not retrieve Wikipedia information.")


def search_google(query):
    """Search Google in default browser"""
    search_term = query.replace("google", "").replace("search", "").replace("for", "").strip()
    if search_term:
        url = f"https://www.google.com/search?q={search_term}"
        webbrowser.open(url)
        speak(f"Searching Google for {search_term}")
    else:
        speak("What would you like me to search for?")


def search_youtube(query):
    """Search YouTube in default browser"""
    search_term = query.replace("youtube", "").replace("search", "").replace("play", "").strip()
    if search_term:
        url = f"https://www.youtube.com/results?search_query={search_term}"
        webbrowser.open(url)
        speak(f"Searching YouTube for {search_term}")
    else:
        speak("What would you like me to search on YouTube?")


# ============================================================
# KEYBOARD AUTOMATION
# ============================================================

def keyboard_automation(command, text=""):
    """Handle keyboard automation tasks"""
    actions = {
        "type": lambda: keyboard.write(text, delay=0.02),
        "enter": lambda: keyboard.press_and_release('enter'),
        "save": lambda: keyboard.press_and_release('ctrl+s'),
        "new_tab": lambda: keyboard.press_and_release('ctrl+t'),
        "close_tab": lambda: keyboard.press_and_release('ctrl+w'),
        "copy": lambda: keyboard.press_and_release('ctrl+c'),
        "paste": lambda: keyboard.press_and_release('ctrl+v'),
        "undo": lambda: keyboard.press_and_release('ctrl+z'),
        "select_all": lambda: keyboard.press_and_release('ctrl+a'),
    }
    
    try:
        if command in actions:
            actions[command]()
            speak("Done")
        else:
            speak("Unknown keyboard command")
    except:
        speak("Keyboard action failed")


# ============================================================
# APPLICATION CONTROL
# ============================================================

def open_application(app_name):
    """Open application using AppOpener"""
    try:
        open_app(app_name, match_closest=True, throw_error=True)
        speak(f"Opening {app_name}")
    except:
        speak(f"Could not open {app_name}")


def close_application(app_name):
    """Close application with force close for specific apps"""
    force_close_map = {
        "chrome": "chrome.exe",
        "google chrome": "chrome.exe",
        "notepad": "notepad.exe",
        "vs code": "Code.exe",
        "vscode": "Code.exe",
        "visual studio code": "Code.exe",
        "code": "Code.exe",
        "firefox": "firefox.exe",
        "edge": "msedge.exe",
        "microsoft edge": "msedge.exe",
    }
    
    try:
        app_lower = app_name.lower()
        
        # Force close for specific apps
        if app_lower in force_close_map:
            process = force_close_map[app_lower]
            os.system(f"taskkill /f /im {process} >nul 2>&1")
            speak(f"Closed {app_name}")
        else:
            close_app(app_name, match_closest=True)
            speak(f"Closed {app_name}")
    except:
        speak(f"Could not close {app_name}")


# ============================================================
# SYSTEM COMMANDS
# ============================================================

def system_control(command):
    """Handle system shutdown, restart, and sleep"""
    commands = {
        "shutdown": ("Shutting down the system in 3 seconds", "shutdown /s /t 3"),
        "restart": ("Restarting the system in 3 seconds", "shutdown /r /t 3"),
        "sleep": ("Putting the system to sleep", "rundll32.exe powrprof.dll,SetSuspendState 0,1,0"),
        "lock": ("Locking the system", "rundll32.exe user32.dll,LockWorkStation"),
    }
    
    if command in commands:
        message, cmd = commands[command]
        speak(message)
        os.system(cmd)
    else:
        speak("Unknown system command")


def system_health():
    """Check and report CPU usage and battery status"""
    try:
        # CPU Usage
        cpu_percent = psutil.cpu_percent(interval=1)
        speak(f"CPU usage is at {cpu_percent} percent")
        
        # Memory Usage
        memory = psutil.virtual_memory()
        speak(f"Memory usage is at {memory.percent} percent")
        
        # Battery Status
        battery = psutil.sensors_battery()
        if battery:
            percent = battery.percent
            plugged = "and charging" if battery.power_plugged else ""
            speak(f"Battery is at {percent} percent {plugged}")
        else:
            speak("Battery information is not available")
    except:
        speak("Could not retrieve system health information")


# ============================================================
# AI CHAT (GEMINI)
# ============================================================

def ai_chat(query):
    """Use Gemini AI for general queries"""
    try:
        prompt = f"""You are Jarvis, an AI assistant created by Chirag. 
Answer the following question briefly and clearly in 1-2 sentences. 
Be helpful and conversational. Question: {query}"""
        
        response = model.generate_content(prompt)
        answer = response.text.strip()
        
        # Clean up response
        answer = answer.replace("*", "").replace("#", "")
        speak(answer)
    except:
        speak("I couldn't process that request. Please try again.")


# ============================================================
# COMMAND PROCESSOR
# ============================================================

def process_command(query):
    """Process and execute voice commands"""
    if not query:
        return True
    
    query_lower = query.lower()
    
    # Exit commands
    if any(word in query_lower for word in ["exit", "quit", "bye", "goodbye", "stop listening"]):
        speak(f"Goodbye! Jarvis by {CREATOR} signing off. Have a great day!")
        return False
    
    # Who made you / creator
    elif any(phrase in query_lower for phrase in ["who made you", "who created you", "who is your creator", "your creator", "who are you"]):
        speak(f"I am Jarvis, an AI voice assistant created by {CREATOR}. He is an amazing developer! You can find him on Instagram at itz_chirag_xxvi")
    
    # Time
    elif any(phrase in query_lower for phrase in ["what time", "tell time", "current time", "what's the time"]):
        tell_time()
    
    # Date
    elif any(phrase in query_lower for phrase in ["what date", "today's date", "current date", "what day"]):
        tell_date()
    
    # Wikipedia search
    elif "wikipedia" in query_lower:
        search_wikipedia(query)
    
    # YouTube search
    elif "youtube" in query_lower:
        search_youtube(query)
    
    # Google search
    elif "google" in query_lower or ("search" in query_lower and "wikipedia" not in query_lower and "youtube" not in query_lower):
        search_google(query)
    
    # Keyboard - Type
    elif query_lower.startswith("type "):
        text_to_type = query[5:].strip()
        keyboard_automation("type", text_to_type)
    
    # Keyboard - Enter
    elif "press enter" in query_lower or "hit enter" in query_lower:
        keyboard_automation("enter")
    
    # Keyboard - Save
    elif "save file" in query_lower or "save this" in query_lower or "save document" in query_lower:
        keyboard_automation("save")
    
    # Keyboard - New Tab
    elif "new tab" in query_lower or "open tab" in query_lower:
        keyboard_automation("new_tab")
    
    # Keyboard - Close Tab
    elif "close tab" in query_lower:
        keyboard_automation("close_tab")
    
    # Keyboard - Copy
    elif "copy this" in query_lower or "copy text" in query_lower:
        keyboard_automation("copy")
    
    # Keyboard - Paste
    elif "paste" in query_lower:
        keyboard_automation("paste")
    
    # Keyboard - Undo
    elif "undo" in query_lower:
        keyboard_automation("undo")
    
    # Keyboard - Select All
    elif "select all" in query_lower:
        keyboard_automation("select_all")
    
    # Open Application
    elif query_lower.startswith("open "):
        app_name = query[5:].strip()
        open_application(app_name)
    
    # Close Application
    elif query_lower.startswith("close "):
        app_name = query[6:].strip()
        close_application(app_name)
    
    # System - Shutdown
    elif "shutdown" in query_lower or "shut down" in query_lower:
        speak("Are you sure you want to shutdown?")
        confirm = listen(timeout=5)
        if "yes" in confirm:
            system_control("shutdown")
    
    # System - Restart
    elif "restart" in query_lower:
        speak("Are you sure you want to restart?")
        confirm = listen(timeout=5)
        if "yes" in confirm:
            system_control("restart")
    
    # System - Sleep
    elif "sleep mode" in query_lower or "go to sleep" in query_lower:
        system_control("sleep")
    
    # System - Lock
    elif "lock" in query_lower and ("system" in query_lower or "computer" in query_lower or "pc" in query_lower):
        system_control("lock")
    
    # System Health
    elif any(phrase in query_lower for phrase in ["system health", "cpu usage", "battery status", "battery level", "check health", "system status"]):
        system_health()
    
    # AI Fallback for everything else
    else:
        ai_chat(query)
    
    return True


# ============================================================
# MAIN FUNCTION
# ============================================================

def main():
    """Main entry point for Jarvis by Chirag"""
    
    # Startup greeting - "Hey! I am Jarvis, made by Chirag"
    speak(f"Hey! I am Jarvis, made by {CREATOR}.")
    speak("Say Jarvis to wake me up.")
    
    running = True
    while running:
        # Wait for wake word
        if listen_for_wake_word():
            greet()
            
            # Active listening mode
            active = True
            while active:
                speak("Listening...")
                query = listen()
                
                if query:
                    active = process_command(query)
                else:
                    speak("I didn't catch that. Say Jarvis to activate me again.")
                    active = False


if __name__ == "__main__":
    main()

🎯 Voice Commands

  • ‱ "What time is it?" - Get current time
  • ‱ "Who made you?" - Creator info
  • ‱ "Search Wikipedia for [topic]"
  • ‱ "Google [query]" - Web search
  • ‱ "YouTube [video]" - Video search
  • ‱ "Open Chrome/Notepad/VS Code"
  • ‱ "Close Chrome" - Force close apps
  • ‱ "Type [text]" - Keyboard automation
  • ‱ "Copy" / "Paste" / "Undo"
  • ‱ "System health" - CPU & battery
  • ‱ "Shutdown" / "Restart" / "Sleep"
  • ‱ Any question → AI chat

⚙ Setup Instructions

  1. Install Python 3.8+
  2. Install required packages (see above)
  3. Get a Gemini API key from Google AI Studio
  4. Replace "YOUR_GEMINI_API_KEY" in the code
  5. Run: python jarvis_by_chirag.py
  6. Jarvis says: "Hey! I am Jarvis, made by Chirag"
  7. Say "Jarvis" to activate
  8. Give voice commands

📬 Contact Me

⚡
Note: This code requires Windows OS, a working microphone, and administrator privileges for some system commands. Make sure Microsoft David voice is installed on your system. If you face any issues, contact me!