0% found this document useful (0 votes)
26 views8 pages

Jarvis

The document outlines a Python program that functions as a personal assistant, capable of performing various tasks such as fetching smartphone details, providing news updates, translating text, and managing system applications. It utilizes libraries like Google Translate, text-to-speech, and web scraping to enhance its functionality. The program also includes features for voice recognition, weather updates, and multimedia control, making it a comprehensive assistant tool.

Uploaded by

adityanawale200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views8 pages

Jarvis

The document outlines a Python program that functions as a personal assistant, capable of performing various tasks such as fetching smartphone details, providing news updates, translating text, and managing system applications. It utilizes libraries like Google Translate, text-to-speech, and web scraping to enhance its functionality. The program also includes features for voice recognition, weather updates, and multimedia control, making it a comprehensive assistant tool.

Uploaded by

adityanawale200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

import datetime

import os
import random
import time
import webbrowser
from googletrans import Translator
from gtts import gTTS
import cap
import cv2
import googleapiclient.discovery
import psutil
import pyttsx3
import pywhatkit
import speech_recognition as sr
import wikipedia
from requests import get
import subprocess
import pygame
import sys
import time
import geocoder
import psutil

import pyautogui
import winsound
import pyjokes
import requests
from bs4 import BeautifulSoup
from win10toast import ToastNotifier

smartphone_details = {
"iphone 12": {
"brand": "Apple",
"price": "$699",
"display_size": "6.1 inches",
"camera": "Dual 12 MP",
"storage": "64GB/128GB/256GB",
"availability": "Available on Apple Store"
},

"samsung galaxy m01": {


"brand": "Samsung",
"price": "$99",
"display_size": "5.71 inches",
"camera": "Dual 13 MP",
"storage": "32GB",
"availability": "Available on Samsung Store"
},
"galaxy s21": {
"brand": "Samsung",
"price": "$799",
"display_size": "6.2 inches",
"camera": "Triple 12 MP",
"storage": "128GB/256GB",
"availability": "Available on Samsung Online Store"
},
"pixel 6": {
"brand": "Google",
"price": "$699",
"display_size": "6.4 inches",
"camera": "Dual 50 MP",
"storage": "128GB/256GB",
"availability": "Available on Google Store"
},
"oneplus 9": {
"brand": "OnePlus",
"price": "$729",
"display_size": "6.55 inches",
"camera": "Triple 48 MP",
"storage": "128GB/256GB",
"availability": "Available on OnePlus Website"
},

def get_smartphone_details(smartphone_name):
if smartphone_name in smartphone_details:
return smartphone_details[smartphone_name]
else:
return "Smartphone details not found for {}".format(smartphone_name)

API_KEY = 'Y83abe34985994044801c95a92b9b5449'
NEWS_API_ENDPOINT = 'https://newsapi.org/v2/everything?q=tesla&from=2023-07-
18&sortBy=publishedAt&apiKey=83abe34985994044801c95a92b9b5449'
PARAMS = {'apiKey': API_KEY , 'country': 'us'}

def get_news ():


response = requests.get(NEWS_API_ENDPOINT , params=PARAMS)

if response.status_code == 200:
news_data = response.json()
articles = news_data.get('articles' , [])

if articles:
news_text = "Top news headlines:\n"
for index , article in enumerate(articles , start=1):
title = article.get('title' , 'N/A')
source = article.get('source' , {}).get('name' , 'N/A')
news_text += f"{index}. {title} - {source}\n"

speak(news_text)
else:
speak("No news articles available.")
else:
speak("Error fetching news. Please check your API key or try again later.")

YOUTUBE_API_KEY = "AIzaSyBwkb4V6znFaYCX80x3YSPOMI7BPWwxBS4"

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice' , voices[0].id)

def speak (audio):


engine.say(audio)
print(audio)
engine.runAndWait()

def get_location():
location = geocoder.ip('me')
return location.address

def monitor_notifications ():


toaster = ToastNotifier()
previous_notification = None

def translate_text (text , target_lang):


translator = Translator()
translated_text = translator.translate(text , dest=target_lang)
return translated_text.text

def get_time ():


now = datetime.datetime.now()
time_str = now.strftime("%I:%M %p")
return time_str

def get_weather ():


city = "New York" # Replace with your desired city
url = f"https://www.google.com/search?q=weather+in+{city}"
headers = {}
response = requests.get(url , headers=headers)
soup = BeautifulSoup(response.text , "html.parser")
weather_info = soup.find("div" , class_="BNeawe").text
return weather_info

def close_app_by_name (app_name):


for proc in psutil.process_iter(['pid' , 'name']):
if app_name.lower() in proc.info['name'].lower():
os.kill(proc.info['pid'] , 9)
print(f"Closed {proc.info['name']} (PID: {proc.info['pid']})")

def take_photo ():


cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH , 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT , 480)

ret , img = cap.read()


if ret:
cv2.imwrite('photo.jpg' , img)
print("Photo captured and saved as 'captured_photo.jpg'")
speak("Photo captured and saved as 'captured_photo.jpg'")
else:
print("Failed to capture photo.")
speak("Sorry, I couldn't capture the photo.")

cap.release()
cv2.destroyAllWindows()

listening_enabled = True

def is_video_playing(video_process_name):
for process in psutil.process_iter(['pid', 'name']):
if video_process_name.lower() in process.info['name'].lower():
return True
return False

def take_command():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)

try:
print("Recognizing...")
query = recognizer.recognize_google(audio).lower()
print("You said:", query)

except Exception as e:
speak("")
return "none"
return query

def wish ():


hour = int(datetime.datetime.now().hour)

if hour >= 0 and hour <= 11:


speak("good morning sir")
elif hour > 11 and hour < 18:
speak("good afternoon sir")
else:
speak("good evening sir")

current_time = datetime.datetime.now().strftime("%I:%M %p")


speak(f"The current time is {current_time}.")

speak(" i am jarvis aadi sir's persnal assistant, how can i help you sir ")

def play_youtube_video(query):
try:
speak(f"Searching for {query} on YouTube.")
youtube_url = f"https://www.youtube.com/results?search_query={query}"
webbrowser.open(youtube_url)

# Simulate a click on a random video link (adjust the delay as needed)


delay_seconds = 5
time.sleep(delay_seconds)
pyautogui.click(x=500, y=500) # Adjust the coordinates based on your
screen resolution

except Exception as e:
print(f"Error playing video: {e}")
speak("Sorry, I couldn't play the video.")

if __name__ == "__main__":
wish()
while True:
query = take_command()
global listening_enabled
location = get_location()

if "open notepad" in query:


npath = "C:\\Windows\\System32\\notepad.exe"
os.startfile(npath)

if "monitor notifications" in query:


speak("Monitoring notifications. I will notify you about new
messages.")
monitor_notifications()

if "translate" in query:
parts = query.replace("translate" , "").strip().split(" in ")
if len(parts) == 2:
text , target_lang = parts
translated_text = translate_text(text , target_lang)
print(f"Translated: {translated_text}")
speak(f"The translation is: {translated_text}")
else:
speak("Invalid translation format. Please use 'translate <text> to
<target_language>'")

elif "open command prompt" in query:


os.system("start cmd")

if "open camera" in query:


speak("Sure, Sir. Would you like me to take a photo?")
while True:
query = take_command().lower()

if "yes" in query:
take_photo()
break
elif "no" in query:
speak("Okay, closing the camera.")
break
else:
speak("Sorry, I didn't catch that. Please say 'yes' or 'no'.")

elif "play music" in query:


music_dir = "C:\\Users\\Dell\\Music\\Playlists"
songs = os.listdir(music_dir)
rd = random.choice(songs)
os.startfile(os.path.join(music_dir , rd))

elif "tell me news" in query:


get_news()

if "tell me details about" in query:


smartphone_name = query.replace("tell me details about" , "").strip()
details = get_smartphone_details(smartphone_name)
print(details)
speak(details)

elif "what is my ip address" in query:


ip = get('https://api.ipify.org').text
speak(f"your IP address is {ip}")

elif "say hello to everyone" in query:


speak("ok sir, hello everyone nice to meet you all.")

elif "tell me time" in query:


time_str = get_time()
speak(f"The current time is {time_str}.")

elif "tell me weather" in query:


speak(f"The weather in osmanabad is {get_weather()}.")

elif "wikipedia" in query:


speak("searching wikipedia...")
query = query.replace("wikipedia" , "")
results = wikipedia.summary(query , sentences=10)
speak("according to wikipedia")
speak(results)
print(results)

elif "open youtube" in query:


webbrowser.open("www.youtube.com")

elif "open instagram" in query:


speak("ok sir, opening instagram")
webbrowser.open("www.instagram.com")
elif "open google" in query:
speak("sir, what should i search on google")
cm = take_command().lower()
webbrowser.open(f"(cm)")
elif "send message" in query:
speak("To whom you want to send the message?")
recipient_number = input("Enter recipient's phone number: ")
speak("What is the message, sir?")
message = take_command().lower()
now = datetime.datetime.now()
current_hour = now.hour
current_minute = now.minute
pywhatkit.sendwhatmsg(recipient_number , message , current_hour ,
current_minute)
speak("Message sent successfully!")

elif "set alarm" in query:


nn = int(datetime.datetime.now().hour)
if nn == 22:
music_dir = 'C:\\Users\\Dell\\Music\\Playlists'
songs = os.startfile(music_dir)
os.startfile(os.path.join(music_dir , songs[0]))

elif "tell me a jok" in query:


joke = pyjokes.get_joke()
speak(joke)

elif "shutdown the system" in query:


os.system("shutdown /s /t 5")

elif "restart the system" in query:


os.system("shutdown /r /t 5")

elif "switch the wimdow" in query:


pyautogui.keyDown("alt")
pyautogui.press("tab")
time.sleep(1)
pyautogui.keyUp("alt")

elif "play video" in query:


speak("What video would you like to watch?")
search_query = take_command().lower()
play_youtube_video(search_query)

elif "take screenshot" in query or "take a screenshot" in query:


speak("sir, please tell me the name for this screenshot file")
name = take_command().lower()
speak("sir, please hold the screen for few seconds, i am taking
screenshot")
time.sleep(3)
img = pyautogui.screenshot()
img.save(f"{name}.png")
speak("i am done sir, screenshot is saved in our main folder. now i am
ready for the next command")
if "where we are" in query:

speak("Sir, your current location is approximately " + location)


break

elif "no thanks" in query:


speak("thanks for using me sir, have a good day")
sys.exit()

speak("sir, do you have any other work for me")

You might also like