Advertisement
xosski

Jarvis AI assistant

Jan 1st, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.18 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import smtplib
  4. import pyautogui
  5. import requests
  6. import json
  7. import random
  8. import pywhatkit as pwk
  9. import psutil
  10. from pywikihow import search_wikihow
  11. from win10toast import ToastNotifier
  12. from time import sleep
  13. from fuzzywuzzy import process
  14. import winshell
  15. import wolframalpha
  16. import datetime
  17. import pyttsx3
  18. import speech_recognition as sr
  19. import webbrowser
  20.  
  21. # External Libraries
  22. import screen_brightness_control as sbc
  23.  
  24. # Initialize Speech Engine
  25. class SpeechRecognitionEngine:
  26. def __init__(self):
  27. self.recognizer = sr.Recognizer()
  28. self.microphone = sr.Microphone()
  29.  
  30. def listen(self):
  31. with self.microphone as source:
  32. self.recognizer.adjust_for_ambient_noise(source)
  33. print("Listening...")
  34. audio = self.recognizer.listen(source)
  35. return audio
  36.  
  37. def recognize_speech(self, audio):
  38. try:
  39. return self.recognizer.recognize_google(audio).lower()
  40. except sr.UnknownValueError:
  41. return None
  42. except sr.RequestError:
  43. return None
  44.  
  45. # Initialize Text-to-Speech Engine
  46. class TTSEngine:
  47. def __init__(self):
  48. self.engine = pyttsx3.init()
  49.  
  50. def speak(self, text):
  51. self.engine.say(text)
  52. self.engine.runAndWait()
  53.  
  54. # Initialize the Search Engine for web and media
  55. class SearchEngine:
  56. @staticmethod
  57. def perform_search(query):
  58. if "google" in query:
  59. search_query = query.replace("google", "").strip()
  60. webbrowser.open(f"https://www.google.com/search?q={search_query}")
  61. elif "youtube" in query:
  62. search_query = query.replace("youtube", "").strip()
  63. webbrowser.open(f"https://www.youtube.com/results?search_query={search_query}")
  64. elif "wikipedia" in query:
  65. search_query = query.replace("wikipedia", "").strip()
  66. webbrowser.open(f"https://en.wikipedia.org/wiki/{search_query}")
  67. else:
  68. print("Unknown search query.")
  69.  
  70. # Manage Resources
  71. class ResourceManager:
  72. def __init__(self):
  73. self._wolfram_client = None
  74. self._wiki = None
  75. self._pywhatkit = None
  76.  
  77. def get_wolfram(self):
  78. if not self._wolfram_client:
  79. self._wolfram_client = wolframalpha.Client("YOUR_WOLFRAM_API_KEY")
  80. return self._wolfram_client
  81.  
  82. def get_wiki(self):
  83. if not self._wiki:
  84. import wikipedia
  85. self._wiki = wikipedia
  86. return self._wiki
  87.  
  88. def get_pywhatkit(self):
  89. if not self._pywhatkit:
  90. self._pywhatkit = pywhatkit
  91. return self._pywhatkit
  92.  
  93. # Email Management
  94. class EmailManager:
  95. def __init__(self, username, password):
  96. self.username = username
  97. self.password = password
  98.  
  99. def send_email(self, to, subject, content):
  100. try:
  101. server = smtplib.SMTP('smtp.gmail.com', 587)
  102. server.starttls()
  103. server.login(self.username, self.password)
  104. message = f"Subject: {subject}\n\n{content}"
  105. server.sendmail(self.username, to, message)
  106. server.close()
  107. return True
  108. except Exception as e:
  109. print(f"Error sending email: {e}")
  110. return False
  111.  
  112. # App Launcher
  113. class AppLauncher:
  114. def __init__(self, app_paths):
  115. self.app_paths = app_paths
  116.  
  117. def launch_app(self, query):
  118. query = query.lower()
  119. app, location = self.find_app(query)
  120. if location:
  121. try:
  122. subprocess.Popen(location)
  123. speak(f"{app} opened successfully.")
  124. except FileNotFoundError:
  125. speak(f"Sorry, {app} not found.")
  126. else:
  127. speak(f"Sorry, {query} is not in my list.")
  128.  
  129. def find_app(self, query):
  130. for app, path in self.app_paths.items():
  131. if query == app.lower():
  132. return app, path
  133. best_match = process.extractOne(query, self.app_paths.keys())
  134. if best_match and best_match[1] >= 80:
  135. return best_match[0], self.app_paths[best_match[0]]
  136. return None, None
  137.  
  138. # Main logic for interaction
  139. def main():
  140. # Initialize classes
  141. tts_engine = TTSEngine()
  142. speech_engine = SpeechRecognitionEngine()
  143. email_manager = EmailManager('your_email@gmail.com', 'your_app_password')
  144. app_paths = {
  145. 'notepad': 'C:\\Windows\\System32\\notepad.exe',
  146. 'chrome': 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
  147. }
  148. app_launcher = AppLauncher(app_paths)
  149. resources = ResourceManager()
  150.  
  151. # Greet the user
  152. greet_msg = wish()
  153. speak(greet_msg)
  154.  
  155. while True:
  156. audio = speech_engine.listen()
  157. query = speech_engine.recognize_speech(audio)
  158.  
  159. if query is None:
  160. continue
  161.  
  162. print(f"Received: {query}")
  163.  
  164. if "open notepad" in query:
  165. speak("Opening Notepad")
  166. subprocess.Popen("notepad.exe")
  167. elif "play music" in query:
  168. play_music()
  169. elif "weather" in query:
  170. weather_report()
  171. elif "search" in query:
  172. search_engine.perform_search(query)
  173. elif "send email" in query:
  174. to = 'recipient@example.com'
  175. subject = 'Test Email'
  176. content = 'This is a test email from the assistant.'
  177. email_manager.send_email(to, subject, content)
  178. speak(f"Email sent to {to}")
  179. elif "shutdown" in query:
  180. speak("Shutting down the system.")
  181. os.system("shutdown /s /t 1")
  182. elif "restart" in query:
  183. speak("Restarting the system.")
  184. os.system("shutdown /r /t 1")
  185. else:
  186. speak("Sorry, I didn't understand that.")
  187.  
  188. # Function to generate the greeting
  189. def wish():
  190. hour = datetime.datetime.now().hour
  191. if 0 <= hour < 12:
  192. return "Good Morning!"
  193. elif 12 <= hour < 18:
  194. return "Good Afternoon!"
  195. else:
  196. return "Good Evening!"
  197.  
  198. # Function to speak text
  199. def speak(text):
  200. tts_engine.speak(text)
  201.  
  202. # Function to play music
  203. def play_music():
  204. speak("Playing music to freshen up your mood.")
  205. music_dir = "C:\\Users\\Admin\\Music"
  206. songs = os.listdir(music_dir)
  207. song = random.choice(songs)
  208. os.startfile(os.path.join(music_dir, song))
  209.  
  210. # Function to get weather
  211. def weather_report():
  212. api_key = "YOUR_WEATHER_API_KEY"
  213. base_url = "http://api.openweathermap.org/data/2.5/weather?"
  214. city_name = input("Enter city name: ")
  215. complete_url = f"{base_url}appid={api_key}&q={city_name}"
  216.  
  217. response = requests.get(complete_url)
  218. data = response.json()
  219.  
  220. if data["cod"] != "404":
  221. main_data = data["main"]
  222. current_temperature = main_data["temp"] - 273.15
  223. current_humidity = main_data["humidity"]
  224. weather_description = data["weather"][0]["description"]
  225.  
  226. speak(f"Temperature: {current_temperature:.2f}°C, Humidity: {current_humidity}%, Weather: {weather_description}")
  227. else:
  228. speak("City not found.")
  229.  
  230. if __name__ == '__main__':
  231. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement