From bb98f49e6b21323a9098d08ab813ad0fb4c1199a Mon Sep 17 00:00:00 2001 From: Vihar Shah Date: Sun, 3 Nov 2024 15:57:42 +0530 Subject: [PATCH 1/5] backing up 1.0.0 --- backups/1.0.0/README.md | 45 ++++ backups/1.0.0/requirements.txt | 34 +++ backups/1.0.0/setupProject.sh | 62 ++++++ backups/1.0.0/src/assistant.py | 161 +++++++++++++++ backups/1.0.0/src/commands.py | 295 +++++++++++++++++++++++++++ backups/1.0.0/src/infra.py | 40 ++++ backups/1.0.0/src/voice_interface.py | 123 +++++++++++ 7 files changed, 760 insertions(+) create mode 100644 backups/1.0.0/README.md create mode 100644 backups/1.0.0/requirements.txt create mode 100644 backups/1.0.0/setupProject.sh create mode 100755 backups/1.0.0/src/assistant.py create mode 100644 backups/1.0.0/src/commands.py create mode 100644 backups/1.0.0/src/infra.py create mode 100644 backups/1.0.0/src/voice_interface.py diff --git a/backups/1.0.0/README.md b/backups/1.0.0/README.md new file mode 100644 index 0000000..6a2d208 --- /dev/null +++ b/backups/1.0.0/README.md @@ -0,0 +1,45 @@ +# 🗂️ Backups Module - Version 1.0.0 + +This module contains the backup implementation of the Desktop Assistant project. + +![Version](https://img.shields.io/badge/Version-1.0.0-green.svg) + +## 📁 Version Structure + +The `backups/1.0.0` directory contains the following files and directories: + +- `README.md`: This file, containing details about the module. +- `src/`: Source code directory for the backup implementation. +- `setupProject.sh`: Script to set up the project environment. +- `requirements.txt`: File containing the required Python packages for the project. + +## 🛠️ Setup + +To set up the project, follow these steps: + +1. **Clone the repository**: + ```bash + git clone https://github.com/vihar-s1/Desktop-Assistant + ``` + +2. **Navigate to the backup directory**: + ```bash + cd Desktop-Assistant/backups/1.0.0 + ``` + +3. **Run the setup script**: + ```bash + bash setupProject.sh + ``` + +4. **Activate the virtual environment**: + ```bash + source .venv/bin/activate + ``` + +## ▶️ How to Run the Project + +After setting up the project, you can run the assistant using the following command: + +```bash +python3 assistant.py \ No newline at end of file diff --git a/backups/1.0.0/requirements.txt b/backups/1.0.0/requirements.txt new file mode 100644 index 0000000..d4e73e2 --- /dev/null +++ b/backups/1.0.0/requirements.txt @@ -0,0 +1,34 @@ +# +# This file is autogenerated by pip-compile with Python 3.11 +# by the following command: +# +# pip-compile --no-annotate --output-file=requirements_temp.txt requirements.txt +# +appopener~=1.6 +beautifulsoup4~=4.12.2 +build~=1.0.3 +certifi~=2024.7.4 +charset-normalizer~=3.2.0 +click~=8.1.7 +colorama~=0.4.6 +comtypes~=1.2.0 +googlesearch-python~=1.2.3 +idna~=3.4 +packaging~=23.1 +pillow~=11.0.0 +pip-tools~=7.3.0 +pipdeptree~=2.13.0 +pyaudio~=0.2.13 +pyautogui~=0.9.54 +pyproject-hooks~=1.0.0 +pyttsx3~=2.90 +requests~=2.32.0 +soupsieve~=2.5 +speechrecognition~=3.10.0 +urllib3~=2.2.2 +wheel~=0.41.2 +wikipedia~=1.4.0 + +# The following packages are considered to be unsafe in a requirements file: +# pip +# setuptools diff --git a/backups/1.0.0/setupProject.sh b/backups/1.0.0/setupProject.sh new file mode 100644 index 0000000..5436d66 --- /dev/null +++ b/backups/1.0.0/setupProject.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash + +# This script is used to setup the project for the first time. + +echo "Starting project setup..." + +# Check if the system is macOS or Linux and install portaudio using brew +if [[ "$OSTYPE" == "darwin"* || "$OSTYPE" == "linux-gnu"* ]]; then + echo "MacOS detected, installing portaudio using brew..." + brew install portaudio +fi + +VENV_DIR="" +if [ -x ".venv" ]; then + VENV_DIR=".venv" + echo "Found existing virtual environment directory: .venv" +elif [ -x "venv" ]; then + VENV_DIR="venv" + echo "Found existing virtual environment directory: venv" +fi + +# Create a virtual environment +if [ -z "${VENV_DIR}" ]; then + if [ -x "*.iml" ]; then + # intelliJ system so use "venv" + VENV_DIR="venv" + echo "IntelliJ system detected, setting virtual environment directory to: venv" + else + VENV_DIR=".venv" + echo "Setting virtual environment directory to: .venv" + fi + echo "Creating virtual environment in directory: ${VENV_DIR}" + python3 -m venv "${VENV_DIR}" +fi + +# Activate the virtual environment if inactive +# VIRTUAL_ENV will be set if virtual env is active +if [ -z "${VIRTUAL_ENV}" ]; then + echo "Activating virtual environment..." + source "${VENV_DIR}/bin/activate" +else + echo "Active virtual environment found: ${VIRTUAL_ENV}" +fi + +# attempt to upgrade pip in case it is not latest version +echo "Upgrading pip..." +pip install --upgrade pip + +# Install the required packages +echo "Installing required packages from requirements.txt..." +pip3 install -r requirements.txt + +# Installing pre-commit hooks +echo "Installing pre-commit hooks..." +pip3 install pre-commit +pre-commit install + +# Deactivate the virtual environment +echo "Deactivating virtual environment..." +deactivate + +echo "Project setup complete." \ No newline at end of file diff --git a/backups/1.0.0/src/assistant.py b/backups/1.0.0/src/assistant.py new file mode 100755 index 0000000..b83f810 --- /dev/null +++ b/backups/1.0.0/src/assistant.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Assistant +=============== + +This module contains the Assistant class, which listens to user queries and responds accordingly. + +""" + +import re +from datetime import datetime + +import commands +from infra import clear_screen +from voice_interface import VoiceInterface + +LISTENING_ERROR = "Say that again please..." + + +class Assistant: + """ + Assistant class containing implementation of the Assistant to listen and respond to user queries + """ + + def __init__(self): + """Creates an Assistant instance consisting of a VoiceInterface instance""" + self.__voice_interface = VoiceInterface() + self.__scrolling_thread = None + self.__stop_scrolling_event = None + + def wish_user(self): + """Wishes user based on the hour of the day""" + hour = int(datetime.now().hour) + if 0 <= hour < 12: + self.__voice_interface.speak("Good Morning!") + elif 12 <= hour < 18: + self.__voice_interface.speak("Good Afternoon!") + else: + self.__voice_interface.speak("Good Evening!") + + def listen_for_query(self) -> str: + """Listens for microphone input and return string of the input + + Returns: + str: the query string obtained from the speech input + """ + query = self.__voice_interface.listen(True) + if query: + print(f"User:\n{query}\n") + self.__voice_interface.speak(query) + else: + print(LISTENING_ERROR) + self.__voice_interface.speak(LISTENING_ERROR) + return query + + def execute_query(self, query: str) -> None: + """Processes the query string and runs the corresponding tasks + Args: + query (str): the query string obtained from speech input + """ + if query is None: + print("No query detected. Please provide an input.") + + elif "what can you do" in query: + commands.explain_features(self.__voice_interface) + + elif re.search(r"search .* (in google)?", query): + # to convert to a generalized format + query = query.replace(" in google", "") + search_query = re.findall(r"search (.*)", query)[0] + commands.run_search_query(self.__voice_interface, search_query) + + elif "wikipedia" in query: + # replace it only once to prevent changing the query + query = query.replace("wikipedia", "", 1) + search_query = query.replace("search", "", 1) + commands.wikipedia_search(self.__voice_interface, search_query, 3) + + elif re.search("open .*", query): + application = re.findall(r"open (.*)", query) + if len(application) == 0: + self.__voice_interface.speak("Which Application Should I Open ?") + return + application = application[0] + try: + commands.open_application_website(self.__voice_interface, application) + except ValueError as ve: + print( + f"Error occurred while opening {application}: {ve.__class__.__name__}: {ve}" + ) + self.__voice_interface.speak( + f"Failed to open {application}. Please try again." + ) + + elif any(text in query for text in ["the time", "time please"]): + commands.tell_time(self.__voice_interface) + + elif "scroll" in query: + direction = re.search(r"(up|down|left|right|top|bottom)", query) + if direction is None: + print("Scroll direction not recognized") + return + direction = direction.group(0) + + if re.search(r"start scrolling (up|down|left|right|top|bottom)", query): + if ( + self.__scrolling_thread is None + ): # Only start if not already scrolling + self.__scrolling_thread, self.__stop_scrolling_event = ( + commands.start_scrolling(direction) + ) + elif "stop scrolling" in query: + if self.__scrolling_thread is None: # Only stop if already scrolling + return + commands.stop_scrolling( + self.__scrolling_thread, self.__stop_scrolling_event + ) + del self.__scrolling_thread + self.__scrolling_thread = None + elif re.search(r"scroll to (up|down|left|right|top|bottom)", query): + commands.scroll_to(direction) + elif re.search(r"scroll (up|down|left|right)", query): + commands.simple_scroll(direction) + else: + print("Scroll command not recognized") + + else: + self.__voice_interface.speak("could not interpret the query") + + def close(self): + """Close the VoiceInterface instance and delete other variables""" + self.__voice_interface.close() + del self.__voice_interface + if self.__scrolling_thread: + commands.stop_scrolling( + self.__scrolling_thread, self.__stop_scrolling_event + ) + del self.__scrolling_thread + if self.__stop_scrolling_event: + del self.__stop_scrolling_event + + def reset(self): + """Re-instantiate VoiceInterface instance and other variables""" + self.close() + self.__voice_interface = VoiceInterface() + self.__scrolling_thread = None + self.__stop_scrolling_event = None + + +def __main__(): + assistant = Assistant() + assistant.wish_user() + clear_screen() + while True: + query = assistant.listen_for_query() + assistant.execute_query(query) + + +if __name__ == "__main__": + __main__() diff --git a/backups/1.0.0/src/commands.py b/backups/1.0.0/src/commands.py new file mode 100644 index 0000000..8084f0c --- /dev/null +++ b/backups/1.0.0/src/commands.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Features +=============== + +This module contains all the functions pertaining to implementing the +individual features of the Assistant. + +""" + +import subprocess +import threading +import time +from datetime import datetime +from subprocess import CalledProcessError, TimeoutExpired + +import googlesearch +import pyautogui as pag +import pygetwindow +import wikipedia +from PIL import ImageGrab + +from infra import __is_darwin, __is_posix, __is_windows, __system_os +from voice_interface import VoiceInterface + +SUPPORTED_FEATURES = { + "search your query in google and return upto 10 results", + "get a wikipedia search summary of upto 3 sentences", + "open applications or websites", + "tell you the time of the day", + "scroll the screen with active cursor", +} + +########## Conditional Imports ########## +if __is_windows(): + from AppOpener import open as open_app +########## Conditional Imports ########## + + +def explain_features(vi: VoiceInterface) -> None: + """Explains the features available + + Args: + vi (VoiceInterface): The voice interface instance used to speak the text + """ + vi.speak("Here's what I can do...\n") + for feature in SUPPORTED_FEATURES: + vi.speak(f"--> {feature}") + + +def run_search_query(vi: VoiceInterface, search_query: str) -> None: + """Performs google search based on some terms + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak + search_query (str): the query term to be searched in google + """ + if not search_query: + vi.speak("Invalid Google Search Query Found!!") + return + + results = googlesearch.search(term=search_query) + if not results: + vi.speak("No Search Result Found!!") + else: + results = list(results) + vi.speak("Found Following Results: ") + for i, result in enumerate(results): + print(i + 1, ")", result.title) + + +def wikipedia_search( + vi: VoiceInterface, search_query: str, sentence_count: int = 3 +) -> None: + """Searches wikipedia for the given query and returns fixed number of statements in response. + Disambiguation Error due to multiple similar results is handled. + Speaks the options in this case. + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The query term to search in wikipedia + sentence_count (int, optional): The number of sentences to speak in case of direct match. + Default is 3. + """ + try: + vi.speak("Searching Wikipedia...") + results = wikipedia.summary(search_query, sentences=sentence_count) + + vi.speak("According to wikipedia...") + vi.speak(results) + except wikipedia.DisambiguationError as de: + vi.speak(f"\n{de.__class__.__name__}") + options = str(de).split("\n") + if len(options) < 7: + for option in options: + vi.speak(option) + else: + for option in options[0:6]: + vi.speak(option) + vi.speak("... and more") + + +def open_application_website(vi: VoiceInterface, search_query: str) -> None: + """ + open the application/website using a matching path from AppPath/WebPath dictionaries. + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + vi.speak(f"Attempting to open {search_query}...") + + search_query = search_query.strip().lower() + + # use appopener to open the application only if os is windows + if __is_windows(): + __open_application_website_windows(vi, search_query) + if __is_darwin(): + __open_application_website_darwin(vi, search_query) + elif __is_posix(): + __open_application_website_posix(vi, search_query) + else: + raise ValueError(f"Unsupported OS: {__system_os()}") + + +def __open_application_website_windows(vi: VoiceInterface, search_query: str) -> None: + """handle the opening of application/website for Windows OS + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + try: + open_app(search_query, match_closest=True) # attempt to open as application + except Exception as error: + vi.speak(f"Error: {error}: Failed to open {search_query}") + + +def __open_application_website_darwin(vi: VoiceInterface, search_query: str) -> None: + """handle the opening of application/website for Darwin OS + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + try: + subprocess.run( + ["open", "-a", search_query], capture_output=True, check=True + ) # attempt to open as application + except CalledProcessError: + try: + subprocess.run( + ["open", search_query], capture_output=True, check=True + ) # attempt to open as website + except CalledProcessError as error: + return_code = error.returncode + stdout_text = error.stdout.decode("utf-8") + stderr_text = error.stderr.decode("utf-8") + vi.speak( + f"Error: {error}: Failed to open {search_query}: error code {return_code}" + ) + if stdout_text: + print("stdout:", stdout_text) + if stderr_text: + print("stderr:", stderr_text) + except TimeoutExpired as error: + vi.speak(f"Error: {error}: Call to open {search_query} timed out.") + + except TimeoutExpired as error: + vi.speak(f"Error: {error}: Call to open {search_query} timed out.") + + +def __open_application_website_posix(vi: VoiceInterface, search_query: str) -> None: + """handle the opening of application/website for POSIX OS + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + try: + subprocess.run( + ["xdg-open", search_query], capture_output=True, check=True + ) # attempt to open website/application + except CalledProcessError as error: + vi.speak( + f"Error: {error}: Failed to open {search_query}: error code {error.returncode}" + ) + stdout_text = error.stdout.decode("utf-8") + stderr_text = error.stderr.decode("utf-8") + if stdout_text: + print("stdout:", stdout_text) + if stderr_text: + print("stderr:", stderr_text) + + except TimeoutExpired as error: + vi.speak(f"Error: {error}: Call to open {search_query} timed out.") + + +def tell_time(vi: VoiceInterface) -> None: + """Tells the time of the day with timezone + + Args: + vi (VoiceInterface): Voice interface instance used to speak + """ + date_time = datetime.now() + hour, minute, second = date_time.hour, date_time.minute, date_time.second + tmz = date_time.tzname() + + vi.speak(f"Current time is {hour}:{minute}:{second} {tmz}") + + +def start_gradual_scroll(direction: str, stop_event: threading.Event) -> None: + """Gradually scroll in the given direction until stop_event is set.""" + active_window = pygetwindow.getActiveWindow() + if not active_window: + return + + # Capture a portion of the window to ensure scrolling + left, top, right, bottom = 0, 0, 100, 100 + width = right - left + height = bottom - top + previous_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) + while not stop_event.is_set(): + pag.scroll(clicks=1) + current_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) + + if current_image.getdata() == previous_image.getdata(): + print("Reached to extreme") + stop_event.set() + break + previous_image = current_image + + print(f"Stopped scrolling {direction}.") + + +def start_scrolling(direction: str) -> tuple[threading.Thread, threading.Event]: + """Start a new scroll thread.""" + stop_scrolling_event = threading.Event() + scrolling_thread = threading.Thread( + target=start_gradual_scroll, args=(direction, stop_scrolling_event) + ) + scrolling_thread.start() + return scrolling_thread, stop_scrolling_event + + +def stop_scrolling( + scrolling_thread: threading.Thread, scrolling_thread_event: threading.Event +) -> None: + """Stop the scrolling thread if not already stopped.""" + if scrolling_thread is not None: + scrolling_thread_event.set() + scrolling_thread.join() + + +def scroll_to(direction: str) -> None: + """Scroll to the extreme in the given direction.""" + active_window = pygetwindow.getActiveWindow() + if not active_window: + return + time.sleep(0.5) + if direction == "top": + pag.press("home") + elif direction == "bottom": + pag.press("end") + elif direction == "right": + pag.press("right", presses=9999) + elif direction == "left": + pag.press("left", presses=9999) + else: + print("Invalid Command") + + +def simple_scroll(direction: str) -> None: + """Simple scroll in the given direction by a fixed number of steps.""" + active_window = pygetwindow.getActiveWindow() + if not active_window: + return + time.sleep(0.5) + if direction in ["up", "down", "left", "right"]: + pag.press(keys=direction, presses=25) + else: + print("Invalid direction") diff --git a/backups/1.0.0/src/infra.py b/backups/1.0.0/src/infra.py new file mode 100644 index 0000000..4d5beef --- /dev/null +++ b/backups/1.0.0/src/infra.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Infra +=============== + +This module contains implementations for various support functions and features of the Assistant. + +""" + +import os +import sys + + +def __is_windows() -> bool: + """Returns True if the operating system is Windows""" + return sys.platform in ["win32", "cygwin"] + + +def __is_darwin() -> bool: + """Returns True if the operating system is Darwin""" + return sys.platform in ["darwin", "ios"] + + +def __is_posix() -> bool: + """Returns True if the operating system is POSIX""" + return sys.platform in ["aix", "android", "emscripten", "linux", "darwin", "wasi"] + + +def __system_os() -> str: + """Returns the name of the operating system""" + return sys.platform + + +def clear_screen() -> None: + """Clears the screen based on the operating system""" + if __is_windows(): + os.system("cls") + else: + os.system("clear") diff --git a/backups/1.0.0/src/voice_interface.py b/backups/1.0.0/src/voice_interface.py new file mode 100644 index 0000000..485fd91 --- /dev/null +++ b/backups/1.0.0/src/voice_interface.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Voice Interface +=============== + +This module contains the VoiceInterface class which provides functions +that allow speech-to-text and text-to-speech conversions. + +""" + +import platform +import random +from typing import Any + +import pyttsx3 +import speech_recognition as sr +from pyttsx3 import voice + + +def __get_driver_name__() -> str: + """Returns the driver name for the pyttsx3 engine based on operating system""" + os_name = platform.system() + if os_name == "Windows": + return "sapi5" + if os_name == "Darwin": # macOS + return "nsss" + return "espeak" # default for other systems + + +class VoiceInterface: + """ + Class consisting of functions that allow speech-to-text + and text-to-speech conversions. + """ + + def __init__(self) -> None: + """ + Creates VoiceInterface instance consisting of a voice engine, + sets the voice of the engine, and creates a voice recognizer instance. + """ + self.__engine = pyttsx3.init(__get_driver_name__()) + voices = self.__engine.getProperty("voices") + self.__engine.setProperty("voice", random.choice(voices).id) + + self.__recognizer = sr.Recognizer() + self.__recognizer.energy_threshold = 150 + self.__recognizer.pause_threshold = 1 + self.__recognizer.phrase_threshold = 0.3 + self.__recognizer.non_speaking_duration = 0.5 + + def speak(self, text: str) -> None: + """Tells Assistant to speak the given 'text' and also prints on the console.""" + self.__engine.say(text) + print(text) + self.__engine.runAndWait() + + def listen(self, print_statement: bool = False) -> Any | None: + """ + Listens for Microphone input, converts to string using + google recognitions engine,and returns the string on success. + """ + with sr.Microphone() as source: + if print_statement: + print("\nListening...") + audio = self.__recognizer.listen(source) + try: + # language = English(en)-India(in) + if print_statement: + print("Recognizing...\n") + query = self.__recognizer.recognize_google( + audio_data=audio, language="en-in" + ) + return query + except sr.UnknownValueError: + print("Sorry, I did not get that.") + return None + except sr.RequestError: + print("Sorry, My speech service is down.") + return None + + def set_properties( + self, + energy_threshold: int | None = None, + pause_threshold: float | None = None, + phrase_threshold: float | None = None, + non_speaking_duration: float | None = None, + ) -> None: + """Set properties of the (voice) recognizer instance + + Args: + energy_threshold (int | None, optional): + Min audio energy for recording. Default value is 150. + pause_threshold (float | None, optional): + Silence after a phrase to conclude recording. Default value is 1. + phrase_threshold (float | None, optional): + Min audio time to be considered for recording. Default value is 0.3. + non_speaking_duration (float | None, optional): + Empty Audio buffer on start and end of audio. Default value is 0.5. + """ + if energy_threshold: + self.__recognizer.energy_threshold = energy_threshold + if pause_threshold: + self.__recognizer.pause_threshold = pause_threshold + if phrase_threshold: + self.__recognizer.phrase_threshold = phrase_threshold + if non_speaking_duration: + self.__recognizer.non_speaking_duration = non_speaking_duration + + def get_available_voices(self) -> list[voice.Voice]: + """Returns a list of available voices for the pyttsx3 engine""" + return self.__engine.getProperty("voices") + + def set_voice(self, voice_instance: voice.Voice) -> None: + """Sets the voice of the pyttsx3 engine to the given voice instance""" + if isinstance(voice_instance, voice.Voice): + self.__engine.setProperty("voice", voice_instance.id) + + def close(self) -> None: + """Deletes the Voice Engine and Recognizer instances""" + self.speak("Have a Good Day !!!") + del self.__engine + del self.__recognizer From fdda9ff9442b9e95e9e5a0b967730e12fffed958 Mon Sep 17 00:00:00 2001 From: Vihar Shah Date: Thu, 13 Mar 2025 00:07:53 +0530 Subject: [PATCH 2/5] refactored commands --- .env.sample | 2 +- CONTRIBUTING.md | 33 +- README.md | 17 +- backups/1.0.0/README.md | 45 -- backups/1.0.0/requirements.txt | 34 -- backups/1.0.0/setupProject.sh | 62 --- backups/1.0.0/src/assistant.py | 161 ------ backups/1.0.0/src/commands.py | 295 ----------- backups/1.0.0/src/infra.py | 40 -- backups/1.0.0/src/voice_interface.py | 123 ----- requirements.txt | 67 +-- src/assistant.py | 188 +------ src/command_registery.py | 228 ++++++++ src/commands.py | 490 ------------------ src/commands/brightness_control.py | 65 +++ src/commands/current_time.py | 27 + src/commands/fetch_news.py | 43 ++ src/commands/google_search.py | 35 ++ src/commands/open_application.py | 142 +++++ src/commands/restart_system.py | 18 + src/commands/send_email.py | 126 +++++ src/commands/shutdown_system.py | 18 + src/commands/volume_control.py | 66 +++ src/commands/weather_reporter.py | 78 +++ src/commands/wikipedia_search.py | 50 ++ .../{email_config.json => mail_server.json} | 2 +- src/infra.py | 38 ++ src/utils.py | 11 - 28 files changed, 998 insertions(+), 1506 deletions(-) delete mode 100644 backups/1.0.0/README.md delete mode 100644 backups/1.0.0/requirements.txt delete mode 100644 backups/1.0.0/setupProject.sh delete mode 100755 backups/1.0.0/src/assistant.py delete mode 100644 backups/1.0.0/src/commands.py delete mode 100644 backups/1.0.0/src/infra.py delete mode 100644 backups/1.0.0/src/voice_interface.py create mode 100644 src/command_registery.py delete mode 100644 src/commands.py create mode 100644 src/commands/brightness_control.py create mode 100644 src/commands/current_time.py create mode 100644 src/commands/fetch_news.py create mode 100644 src/commands/google_search.py create mode 100644 src/commands/open_application.py create mode 100644 src/commands/restart_system.py create mode 100644 src/commands/send_email.py create mode 100644 src/commands/shutdown_system.py create mode 100644 src/commands/volume_control.py create mode 100644 src/commands/weather_reporter.py create mode 100644 src/commands/wikipedia_search.py rename src/config/{email_config.json => mail_server.json} (81%) delete mode 100644 src/utils.py diff --git a/.env.sample b/.env.sample index 9cc86b6..d3532a8 100644 --- a/.env.sample +++ b/.env.sample @@ -1 +1 @@ -DESKTOP_ASSISTANT_SMTP_PWD=YOUR_EMAIL_PASSWORD \ No newline at end of file +SMTP_PASSWORD=YOUR_EMAIL_PASSWORD \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c1c7b91..6c3e8ba 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,12 +25,35 @@ Welcome to the open-source Voice-Assisted Desktop Assistant project! Contributio ``` 5. **_Make Changes:_** Work on the issue you're assigned to or the feature you want to add. Make sure to test your changes. - - Any new command added should be implemented via a function in the `commands.py` file. - - Any additional functionality should be added in the `infra.py` file. - - DO NOT DEFINE ANY GLOBAL VARIABLES IN THE `infra.py` or `commands.py`. Define a class variable inside `__init__(self)` method of `Assistant` class if you have to. - - All the functions implemented in the `infra.py` and `commnds.py` file should be python equivalent of _static_ methods. + - Any new command added should be implemented via a class defined in the `commands` directory. + - Any additional generic utility should be added in the `infra.py` file. + - DO NOT DEFINE ANY GLOBAL VARIABLES IN THE `infra.py`. Define a class variable inside `__init__(self)` method of `Assistant` class if you have to. + - All the functions implemented in the `infra.py` file should be python equivalent of _static_ methods. -6. **_Run the Pre-commit hooks:_** The pre-commit hooks are set up to ensure that the code is formatted correctly and passes the linting checks. They are already set up in the project and configured via the `.pre-commit-config.yaml` file. To run the pre-commit hooks, use the following command: + ``` + # class structure + - static methods + - commandName + - No arguements + - the `__name__` field of class as return value + - validateQuery + - Single argument - query + - Validates query and returns true if query is a match for the action + - executeQuery + - Two arguments - query and voice-interface instance + - executes the query and announces the result via the voice interface instance + ``` + +6. **_Registering Command:_** Once the command is implemented, register the command in the `command_registery.py` file via the `register_command(command_name, validate_query, execute_query)` method of the `CommandRegistery` class. + +7. **_Requirements:_** If you are adding any new libraries or dependencies, make sure to update the `requirements.txt` file. To generate the updated `requirements.txt` file, run the following command: + + ```bash + pipdeptree --warn silence | grep -E '^[a-zA-Z0-9]' | sed 's/==/~=/g' > requirements.txt + ``` + - The above command will generate the `requirements.txt` file with the appropriate versions of the libraries used in the project without the nested depedencies and metadata. + +8. **_Run the Pre-commit hooks:_** The pre-commit hooks are set up to ensure that the code is formatted correctly and passes the linting checks. They are already set up in the project and configured via the `.pre-commit-config.yaml` file. To run the pre-commit hooks, use the following command: ```bash pre-commit run --all-files ``` diff --git a/README.md b/README.md index 993c7dd..fcbaaad 100644 --- a/README.md +++ b/README.md @@ -26,18 +26,11 @@ A simple Python-based desktop assistant that can perform basic tasks like search ## 🚀 Introduction - The project is a simple Python-based desktop assistant that can perform basic tasks like searching on Google, opening applications, telling the time, and more. -- The assistant is still in the development phase, and more features will be added in the future. -- The assistant is built using Python and does not use any Machine Learning (ML) or Artificial Intelligence (AI) models. +- The assistant is always under the development phase waiting for more features to be added. +- It is built using Python and does not use any Machine Learning (ML) or Artificial Intelligence (AI) models. - The assistant is built using the `pyttsx3` library for text-to-speech conversion and the `speech_recognition` library for speech recognition. - The project is open-source and contributions and/or feature requests are always welcome. -## ✨ Features - -- Google and Wikipedia searches 🌐 -- Open applications and websites 🚀 -- Tell time of the day in _hour **:** minute **:** second_ format ⏰ -- Scroll the screen up and down, left and right. 📜 - ## 🚀 Getting Started To get started with the project, follow the instructions below. @@ -106,14 +99,14 @@ objc.super(NSSpeechDriver, self).init() ## 🤝 Contributing - If you want to contribute, follow the contribution guidelines - here: [Contributing Guidelines](https://github.com/vihar-s1/Desktop-Assistant/blob/main/CONTRIBUTING.md). + here: [Contributing Guidelines](CONTRIBUTING.md). ## 🐞 Bug Reports and Feature Requests - If you encounter an issue or want to report a bug, following is - the [Bug Report Template](https://github.com/vihar-s1/Desktop-Assistant/blob/main/.github/ISSUE_TEMPLATE/bug_report.md) + the [Bug Report Template](.github/ISSUE_TEMPLATE/bug_report.yml) you will be asked to follow. -- Any new feature requests will also be appreciated if it follows the predefined [Feature Request Template](https://github.com/vihar-s1/Desktop-Assistant/blob/main/.github/ISSUE_TEMPLATE/feature_request.md). +- Any new feature requests will also be appreciated if it follows the predefined [Feature Request Template](.github/ISSUE_TEMPLATE/feature_request.yml). > **NOTE:** The templates are predefined and integrated in the repository so you can go to > the [Issues Tab](https://github.com/vihar-s1/Desktop-Assistant/issues) and start writing your bug report, or feature diff --git a/backups/1.0.0/README.md b/backups/1.0.0/README.md deleted file mode 100644 index 6a2d208..0000000 --- a/backups/1.0.0/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# 🗂️ Backups Module - Version 1.0.0 - -This module contains the backup implementation of the Desktop Assistant project. - -![Version](https://img.shields.io/badge/Version-1.0.0-green.svg) - -## 📁 Version Structure - -The `backups/1.0.0` directory contains the following files and directories: - -- `README.md`: This file, containing details about the module. -- `src/`: Source code directory for the backup implementation. -- `setupProject.sh`: Script to set up the project environment. -- `requirements.txt`: File containing the required Python packages for the project. - -## 🛠️ Setup - -To set up the project, follow these steps: - -1. **Clone the repository**: - ```bash - git clone https://github.com/vihar-s1/Desktop-Assistant - ``` - -2. **Navigate to the backup directory**: - ```bash - cd Desktop-Assistant/backups/1.0.0 - ``` - -3. **Run the setup script**: - ```bash - bash setupProject.sh - ``` - -4. **Activate the virtual environment**: - ```bash - source .venv/bin/activate - ``` - -## ▶️ How to Run the Project - -After setting up the project, you can run the assistant using the following command: - -```bash -python3 assistant.py \ No newline at end of file diff --git a/backups/1.0.0/requirements.txt b/backups/1.0.0/requirements.txt deleted file mode 100644 index d4e73e2..0000000 --- a/backups/1.0.0/requirements.txt +++ /dev/null @@ -1,34 +0,0 @@ -# -# This file is autogenerated by pip-compile with Python 3.11 -# by the following command: -# -# pip-compile --no-annotate --output-file=requirements_temp.txt requirements.txt -# -appopener~=1.6 -beautifulsoup4~=4.12.2 -build~=1.0.3 -certifi~=2024.7.4 -charset-normalizer~=3.2.0 -click~=8.1.7 -colorama~=0.4.6 -comtypes~=1.2.0 -googlesearch-python~=1.2.3 -idna~=3.4 -packaging~=23.1 -pillow~=11.0.0 -pip-tools~=7.3.0 -pipdeptree~=2.13.0 -pyaudio~=0.2.13 -pyautogui~=0.9.54 -pyproject-hooks~=1.0.0 -pyttsx3~=2.90 -requests~=2.32.0 -soupsieve~=2.5 -speechrecognition~=3.10.0 -urllib3~=2.2.2 -wheel~=0.41.2 -wikipedia~=1.4.0 - -# The following packages are considered to be unsafe in a requirements file: -# pip -# setuptools diff --git a/backups/1.0.0/setupProject.sh b/backups/1.0.0/setupProject.sh deleted file mode 100644 index 5436d66..0000000 --- a/backups/1.0.0/setupProject.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env bash - -# This script is used to setup the project for the first time. - -echo "Starting project setup..." - -# Check if the system is macOS or Linux and install portaudio using brew -if [[ "$OSTYPE" == "darwin"* || "$OSTYPE" == "linux-gnu"* ]]; then - echo "MacOS detected, installing portaudio using brew..." - brew install portaudio -fi - -VENV_DIR="" -if [ -x ".venv" ]; then - VENV_DIR=".venv" - echo "Found existing virtual environment directory: .venv" -elif [ -x "venv" ]; then - VENV_DIR="venv" - echo "Found existing virtual environment directory: venv" -fi - -# Create a virtual environment -if [ -z "${VENV_DIR}" ]; then - if [ -x "*.iml" ]; then - # intelliJ system so use "venv" - VENV_DIR="venv" - echo "IntelliJ system detected, setting virtual environment directory to: venv" - else - VENV_DIR=".venv" - echo "Setting virtual environment directory to: .venv" - fi - echo "Creating virtual environment in directory: ${VENV_DIR}" - python3 -m venv "${VENV_DIR}" -fi - -# Activate the virtual environment if inactive -# VIRTUAL_ENV will be set if virtual env is active -if [ -z "${VIRTUAL_ENV}" ]; then - echo "Activating virtual environment..." - source "${VENV_DIR}/bin/activate" -else - echo "Active virtual environment found: ${VIRTUAL_ENV}" -fi - -# attempt to upgrade pip in case it is not latest version -echo "Upgrading pip..." -pip install --upgrade pip - -# Install the required packages -echo "Installing required packages from requirements.txt..." -pip3 install -r requirements.txt - -# Installing pre-commit hooks -echo "Installing pre-commit hooks..." -pip3 install pre-commit -pre-commit install - -# Deactivate the virtual environment -echo "Deactivating virtual environment..." -deactivate - -echo "Project setup complete." \ No newline at end of file diff --git a/backups/1.0.0/src/assistant.py b/backups/1.0.0/src/assistant.py deleted file mode 100755 index b83f810..0000000 --- a/backups/1.0.0/src/assistant.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Assistant -=============== - -This module contains the Assistant class, which listens to user queries and responds accordingly. - -""" - -import re -from datetime import datetime - -import commands -from infra import clear_screen -from voice_interface import VoiceInterface - -LISTENING_ERROR = "Say that again please..." - - -class Assistant: - """ - Assistant class containing implementation of the Assistant to listen and respond to user queries - """ - - def __init__(self): - """Creates an Assistant instance consisting of a VoiceInterface instance""" - self.__voice_interface = VoiceInterface() - self.__scrolling_thread = None - self.__stop_scrolling_event = None - - def wish_user(self): - """Wishes user based on the hour of the day""" - hour = int(datetime.now().hour) - if 0 <= hour < 12: - self.__voice_interface.speak("Good Morning!") - elif 12 <= hour < 18: - self.__voice_interface.speak("Good Afternoon!") - else: - self.__voice_interface.speak("Good Evening!") - - def listen_for_query(self) -> str: - """Listens for microphone input and return string of the input - - Returns: - str: the query string obtained from the speech input - """ - query = self.__voice_interface.listen(True) - if query: - print(f"User:\n{query}\n") - self.__voice_interface.speak(query) - else: - print(LISTENING_ERROR) - self.__voice_interface.speak(LISTENING_ERROR) - return query - - def execute_query(self, query: str) -> None: - """Processes the query string and runs the corresponding tasks - Args: - query (str): the query string obtained from speech input - """ - if query is None: - print("No query detected. Please provide an input.") - - elif "what can you do" in query: - commands.explain_features(self.__voice_interface) - - elif re.search(r"search .* (in google)?", query): - # to convert to a generalized format - query = query.replace(" in google", "") - search_query = re.findall(r"search (.*)", query)[0] - commands.run_search_query(self.__voice_interface, search_query) - - elif "wikipedia" in query: - # replace it only once to prevent changing the query - query = query.replace("wikipedia", "", 1) - search_query = query.replace("search", "", 1) - commands.wikipedia_search(self.__voice_interface, search_query, 3) - - elif re.search("open .*", query): - application = re.findall(r"open (.*)", query) - if len(application) == 0: - self.__voice_interface.speak("Which Application Should I Open ?") - return - application = application[0] - try: - commands.open_application_website(self.__voice_interface, application) - except ValueError as ve: - print( - f"Error occurred while opening {application}: {ve.__class__.__name__}: {ve}" - ) - self.__voice_interface.speak( - f"Failed to open {application}. Please try again." - ) - - elif any(text in query for text in ["the time", "time please"]): - commands.tell_time(self.__voice_interface) - - elif "scroll" in query: - direction = re.search(r"(up|down|left|right|top|bottom)", query) - if direction is None: - print("Scroll direction not recognized") - return - direction = direction.group(0) - - if re.search(r"start scrolling (up|down|left|right|top|bottom)", query): - if ( - self.__scrolling_thread is None - ): # Only start if not already scrolling - self.__scrolling_thread, self.__stop_scrolling_event = ( - commands.start_scrolling(direction) - ) - elif "stop scrolling" in query: - if self.__scrolling_thread is None: # Only stop if already scrolling - return - commands.stop_scrolling( - self.__scrolling_thread, self.__stop_scrolling_event - ) - del self.__scrolling_thread - self.__scrolling_thread = None - elif re.search(r"scroll to (up|down|left|right|top|bottom)", query): - commands.scroll_to(direction) - elif re.search(r"scroll (up|down|left|right)", query): - commands.simple_scroll(direction) - else: - print("Scroll command not recognized") - - else: - self.__voice_interface.speak("could not interpret the query") - - def close(self): - """Close the VoiceInterface instance and delete other variables""" - self.__voice_interface.close() - del self.__voice_interface - if self.__scrolling_thread: - commands.stop_scrolling( - self.__scrolling_thread, self.__stop_scrolling_event - ) - del self.__scrolling_thread - if self.__stop_scrolling_event: - del self.__stop_scrolling_event - - def reset(self): - """Re-instantiate VoiceInterface instance and other variables""" - self.close() - self.__voice_interface = VoiceInterface() - self.__scrolling_thread = None - self.__stop_scrolling_event = None - - -def __main__(): - assistant = Assistant() - assistant.wish_user() - clear_screen() - while True: - query = assistant.listen_for_query() - assistant.execute_query(query) - - -if __name__ == "__main__": - __main__() diff --git a/backups/1.0.0/src/commands.py b/backups/1.0.0/src/commands.py deleted file mode 100644 index 8084f0c..0000000 --- a/backups/1.0.0/src/commands.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Features -=============== - -This module contains all the functions pertaining to implementing the -individual features of the Assistant. - -""" - -import subprocess -import threading -import time -from datetime import datetime -from subprocess import CalledProcessError, TimeoutExpired - -import googlesearch -import pyautogui as pag -import pygetwindow -import wikipedia -from PIL import ImageGrab - -from infra import __is_darwin, __is_posix, __is_windows, __system_os -from voice_interface import VoiceInterface - -SUPPORTED_FEATURES = { - "search your query in google and return upto 10 results", - "get a wikipedia search summary of upto 3 sentences", - "open applications or websites", - "tell you the time of the day", - "scroll the screen with active cursor", -} - -########## Conditional Imports ########## -if __is_windows(): - from AppOpener import open as open_app -########## Conditional Imports ########## - - -def explain_features(vi: VoiceInterface) -> None: - """Explains the features available - - Args: - vi (VoiceInterface): The voice interface instance used to speak the text - """ - vi.speak("Here's what I can do...\n") - for feature in SUPPORTED_FEATURES: - vi.speak(f"--> {feature}") - - -def run_search_query(vi: VoiceInterface, search_query: str) -> None: - """Performs google search based on some terms - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak - search_query (str): the query term to be searched in google - """ - if not search_query: - vi.speak("Invalid Google Search Query Found!!") - return - - results = googlesearch.search(term=search_query) - if not results: - vi.speak("No Search Result Found!!") - else: - results = list(results) - vi.speak("Found Following Results: ") - for i, result in enumerate(results): - print(i + 1, ")", result.title) - - -def wikipedia_search( - vi: VoiceInterface, search_query: str, sentence_count: int = 3 -) -> None: - """Searches wikipedia for the given query and returns fixed number of statements in response. - Disambiguation Error due to multiple similar results is handled. - Speaks the options in this case. - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The query term to search in wikipedia - sentence_count (int, optional): The number of sentences to speak in case of direct match. - Default is 3. - """ - try: - vi.speak("Searching Wikipedia...") - results = wikipedia.summary(search_query, sentences=sentence_count) - - vi.speak("According to wikipedia...") - vi.speak(results) - except wikipedia.DisambiguationError as de: - vi.speak(f"\n{de.__class__.__name__}") - options = str(de).split("\n") - if len(options) < 7: - for option in options: - vi.speak(option) - else: - for option in options[0:6]: - vi.speak(option) - vi.speak("... and more") - - -def open_application_website(vi: VoiceInterface, search_query: str) -> None: - """ - open the application/website using a matching path from AppPath/WebPath dictionaries. - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - vi.speak(f"Attempting to open {search_query}...") - - search_query = search_query.strip().lower() - - # use appopener to open the application only if os is windows - if __is_windows(): - __open_application_website_windows(vi, search_query) - if __is_darwin(): - __open_application_website_darwin(vi, search_query) - elif __is_posix(): - __open_application_website_posix(vi, search_query) - else: - raise ValueError(f"Unsupported OS: {__system_os()}") - - -def __open_application_website_windows(vi: VoiceInterface, search_query: str) -> None: - """handle the opening of application/website for Windows OS - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - try: - open_app(search_query, match_closest=True) # attempt to open as application - except Exception as error: - vi.speak(f"Error: {error}: Failed to open {search_query}") - - -def __open_application_website_darwin(vi: VoiceInterface, search_query: str) -> None: - """handle the opening of application/website for Darwin OS - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - try: - subprocess.run( - ["open", "-a", search_query], capture_output=True, check=True - ) # attempt to open as application - except CalledProcessError: - try: - subprocess.run( - ["open", search_query], capture_output=True, check=True - ) # attempt to open as website - except CalledProcessError as error: - return_code = error.returncode - stdout_text = error.stdout.decode("utf-8") - stderr_text = error.stderr.decode("utf-8") - vi.speak( - f"Error: {error}: Failed to open {search_query}: error code {return_code}" - ) - if stdout_text: - print("stdout:", stdout_text) - if stderr_text: - print("stderr:", stderr_text) - except TimeoutExpired as error: - vi.speak(f"Error: {error}: Call to open {search_query} timed out.") - - except TimeoutExpired as error: - vi.speak(f"Error: {error}: Call to open {search_query} timed out.") - - -def __open_application_website_posix(vi: VoiceInterface, search_query: str) -> None: - """handle the opening of application/website for POSIX OS - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - try: - subprocess.run( - ["xdg-open", search_query], capture_output=True, check=True - ) # attempt to open website/application - except CalledProcessError as error: - vi.speak( - f"Error: {error}: Failed to open {search_query}: error code {error.returncode}" - ) - stdout_text = error.stdout.decode("utf-8") - stderr_text = error.stderr.decode("utf-8") - if stdout_text: - print("stdout:", stdout_text) - if stderr_text: - print("stderr:", stderr_text) - - except TimeoutExpired as error: - vi.speak(f"Error: {error}: Call to open {search_query} timed out.") - - -def tell_time(vi: VoiceInterface) -> None: - """Tells the time of the day with timezone - - Args: - vi (VoiceInterface): Voice interface instance used to speak - """ - date_time = datetime.now() - hour, minute, second = date_time.hour, date_time.minute, date_time.second - tmz = date_time.tzname() - - vi.speak(f"Current time is {hour}:{minute}:{second} {tmz}") - - -def start_gradual_scroll(direction: str, stop_event: threading.Event) -> None: - """Gradually scroll in the given direction until stop_event is set.""" - active_window = pygetwindow.getActiveWindow() - if not active_window: - return - - # Capture a portion of the window to ensure scrolling - left, top, right, bottom = 0, 0, 100, 100 - width = right - left - height = bottom - top - previous_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) - while not stop_event.is_set(): - pag.scroll(clicks=1) - current_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) - - if current_image.getdata() == previous_image.getdata(): - print("Reached to extreme") - stop_event.set() - break - previous_image = current_image - - print(f"Stopped scrolling {direction}.") - - -def start_scrolling(direction: str) -> tuple[threading.Thread, threading.Event]: - """Start a new scroll thread.""" - stop_scrolling_event = threading.Event() - scrolling_thread = threading.Thread( - target=start_gradual_scroll, args=(direction, stop_scrolling_event) - ) - scrolling_thread.start() - return scrolling_thread, stop_scrolling_event - - -def stop_scrolling( - scrolling_thread: threading.Thread, scrolling_thread_event: threading.Event -) -> None: - """Stop the scrolling thread if not already stopped.""" - if scrolling_thread is not None: - scrolling_thread_event.set() - scrolling_thread.join() - - -def scroll_to(direction: str) -> None: - """Scroll to the extreme in the given direction.""" - active_window = pygetwindow.getActiveWindow() - if not active_window: - return - time.sleep(0.5) - if direction == "top": - pag.press("home") - elif direction == "bottom": - pag.press("end") - elif direction == "right": - pag.press("right", presses=9999) - elif direction == "left": - pag.press("left", presses=9999) - else: - print("Invalid Command") - - -def simple_scroll(direction: str) -> None: - """Simple scroll in the given direction by a fixed number of steps.""" - active_window = pygetwindow.getActiveWindow() - if not active_window: - return - time.sleep(0.5) - if direction in ["up", "down", "left", "right"]: - pag.press(keys=direction, presses=25) - else: - print("Invalid direction") diff --git a/backups/1.0.0/src/infra.py b/backups/1.0.0/src/infra.py deleted file mode 100644 index 4d5beef..0000000 --- a/backups/1.0.0/src/infra.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Infra -=============== - -This module contains implementations for various support functions and features of the Assistant. - -""" - -import os -import sys - - -def __is_windows() -> bool: - """Returns True if the operating system is Windows""" - return sys.platform in ["win32", "cygwin"] - - -def __is_darwin() -> bool: - """Returns True if the operating system is Darwin""" - return sys.platform in ["darwin", "ios"] - - -def __is_posix() -> bool: - """Returns True if the operating system is POSIX""" - return sys.platform in ["aix", "android", "emscripten", "linux", "darwin", "wasi"] - - -def __system_os() -> str: - """Returns the name of the operating system""" - return sys.platform - - -def clear_screen() -> None: - """Clears the screen based on the operating system""" - if __is_windows(): - os.system("cls") - else: - os.system("clear") diff --git a/backups/1.0.0/src/voice_interface.py b/backups/1.0.0/src/voice_interface.py deleted file mode 100644 index 485fd91..0000000 --- a/backups/1.0.0/src/voice_interface.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Voice Interface -=============== - -This module contains the VoiceInterface class which provides functions -that allow speech-to-text and text-to-speech conversions. - -""" - -import platform -import random -from typing import Any - -import pyttsx3 -import speech_recognition as sr -from pyttsx3 import voice - - -def __get_driver_name__() -> str: - """Returns the driver name for the pyttsx3 engine based on operating system""" - os_name = platform.system() - if os_name == "Windows": - return "sapi5" - if os_name == "Darwin": # macOS - return "nsss" - return "espeak" # default for other systems - - -class VoiceInterface: - """ - Class consisting of functions that allow speech-to-text - and text-to-speech conversions. - """ - - def __init__(self) -> None: - """ - Creates VoiceInterface instance consisting of a voice engine, - sets the voice of the engine, and creates a voice recognizer instance. - """ - self.__engine = pyttsx3.init(__get_driver_name__()) - voices = self.__engine.getProperty("voices") - self.__engine.setProperty("voice", random.choice(voices).id) - - self.__recognizer = sr.Recognizer() - self.__recognizer.energy_threshold = 150 - self.__recognizer.pause_threshold = 1 - self.__recognizer.phrase_threshold = 0.3 - self.__recognizer.non_speaking_duration = 0.5 - - def speak(self, text: str) -> None: - """Tells Assistant to speak the given 'text' and also prints on the console.""" - self.__engine.say(text) - print(text) - self.__engine.runAndWait() - - def listen(self, print_statement: bool = False) -> Any | None: - """ - Listens for Microphone input, converts to string using - google recognitions engine,and returns the string on success. - """ - with sr.Microphone() as source: - if print_statement: - print("\nListening...") - audio = self.__recognizer.listen(source) - try: - # language = English(en)-India(in) - if print_statement: - print("Recognizing...\n") - query = self.__recognizer.recognize_google( - audio_data=audio, language="en-in" - ) - return query - except sr.UnknownValueError: - print("Sorry, I did not get that.") - return None - except sr.RequestError: - print("Sorry, My speech service is down.") - return None - - def set_properties( - self, - energy_threshold: int | None = None, - pause_threshold: float | None = None, - phrase_threshold: float | None = None, - non_speaking_duration: float | None = None, - ) -> None: - """Set properties of the (voice) recognizer instance - - Args: - energy_threshold (int | None, optional): - Min audio energy for recording. Default value is 150. - pause_threshold (float | None, optional): - Silence after a phrase to conclude recording. Default value is 1. - phrase_threshold (float | None, optional): - Min audio time to be considered for recording. Default value is 0.3. - non_speaking_duration (float | None, optional): - Empty Audio buffer on start and end of audio. Default value is 0.5. - """ - if energy_threshold: - self.__recognizer.energy_threshold = energy_threshold - if pause_threshold: - self.__recognizer.pause_threshold = pause_threshold - if phrase_threshold: - self.__recognizer.phrase_threshold = phrase_threshold - if non_speaking_duration: - self.__recognizer.non_speaking_duration = non_speaking_duration - - def get_available_voices(self) -> list[voice.Voice]: - """Returns a list of available voices for the pyttsx3 engine""" - return self.__engine.getProperty("voices") - - def set_voice(self, voice_instance: voice.Voice) -> None: - """Sets the voice of the pyttsx3 engine to the given voice instance""" - if isinstance(voice_instance, voice.Voice): - self.__engine.setProperty("voice", voice_instance.id) - - def close(self) -> None: - """Deletes the Voice Engine and Recognizer instances""" - self.speak("Have a Good Day !!!") - del self.__engine - del self.__recognizer diff --git a/requirements.txt b/requirements.txt index c25bee3..942ddb8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,51 +1,16 @@ -# -# This file is autogenerated by pip-compile with Python 3.11 -# by the following command: -# -# pip-compile --no-annotate --output-file=requirements_temp.txt requirements.txt -# -appopener==1.7 -beautifulsoup4==4.12.3 -build==1.0.3 -certifi==2024.7.4 -charset-normalizer==3.2.0 -click==8.1.8 -colorama==0.4.6 -comtypes==1.2.1 -feedparser==6.0.11 -googlesearch-python==1.2.5 -idna==3.10 -mouseinfo==0.1.3 -packaging==23.2 -pillow==11.0.0 -pip-tools==7.3.0 -pipdeptree==2.13.2 -psutil==6.1.1 -pyaudio==0.2.14 -pyautogui==0.9.54 -pycaw==20240210 -pygetwindow==0.0.9 -pymsgbox==1.0.9 -pyperclip==1.9.0 -pypiwin32==223 -pyproject-hooks==1.0.0 -pyrect==0.2.0 -pyscreeze==1.0.1 -python-dotenv==1.0.1 -pyttsx3==2.98 -pytweening==1.2.0 -pywin32==308 -regex==2024.11.6 -requests==2.32.3 -sgmllib3k==1.0.0 -soupsieve==2.6 -speechrecognition==3.10.4 -typing-extensions==4.12.2 -urllib3==2.2.3 -wheel==0.41.3 -wikipedia==1.4.0 -wmi==1.5.1 - -# The following packages are considered to be unsafe in a requirements file: -# pip -# setuptools +appopener~=1.6 +colorama~=0.4.6 +feedparser~=6.0.11 +googlesearch-python~=1.3.0 +pillow~=11.1.0 +pip-tools~=7.4.1 +pipdeptree~=2.25.0 +PyAudio~=0.2.14 +PyAutoGUI~=0.9.54 +pycaw~=20240210 +python-dotenv~=1.0.1 +pyttsx3~=2.98 +regex~=2024.11.6 +SpeechRecognition~=3.14.1 +wikipedia~=1.4.0 +WMI~=1.4.9 diff --git a/src/assistant.py b/src/assistant.py index d36922c..e0b5482 100755 --- a/src/assistant.py +++ b/src/assistant.py @@ -8,21 +8,13 @@ """ -import json import re -import subprocess from datetime import datetime -import commands -from infra import clear_screen -from utils import load_email_config +import command_registery +from infra import clear_screen, listen from voice_interface import VoiceInterface -LISTENING_ERROR = "Say that again please..." -MAX_FETCHED_HEADLINES = ( - 10 # Maximum number of news headlines to fetch when news function is called -) - class Assistant: """ @@ -51,14 +43,7 @@ def listen_for_query(self) -> str: Returns: str: the query string obtained from the speech input """ - query = self.__voice_interface.listen(True) - if query: - print(f"User:\n{query}\n") - self.__voice_interface.speak(query) - else: - print(LISTENING_ERROR) - self.__voice_interface.speak(LISTENING_ERROR) - return query + return listen def execute_query(self, query: str) -> None: """Processes the query string and runs the corresponding tasks @@ -68,40 +53,6 @@ def execute_query(self, query: str) -> None: if query is None: print("No query detected. Please provide an input.") - elif "what can you do" in query: - commands.explain_features(self.__voice_interface) - - elif re.search(r"search .* (in google)?", query): - # to convert to a generalized format - query = query.replace(" in google", "") - search_query = re.findall(r"search (.*)", query)[0] - commands.run_search_query(self.__voice_interface, search_query) - - elif "wikipedia" in query: - # replace it only once to prevent changing the query - query = query.replace("wikipedia", "", 1) - search_query = query.replace("search", "", 1) - commands.wikipedia_search(self.__voice_interface, search_query, 3) - - elif re.search("open .*", query): - application = re.findall(r"open (.*)", query) - if len(application) == 0: - self.__voice_interface.speak("Which Application Should I Open ?") - return - application = application[0] - try: - commands.open_application_website(self.__voice_interface, application) - except ValueError as ve: - print( - f"Error occurred while opening {application}: {ve.__class__.__name__}: {ve}" - ) - self.__voice_interface.speak( - f"Failed to open {application}. Please try again." - ) - - elif any(text in query for text in ["the time", "time please"]): - commands.tell_time(self.__voice_interface) - elif "scroll" in query: direction = re.search(r"(up|down|left|right|top|bottom)", query) if direction is None: @@ -114,150 +65,37 @@ def execute_query(self, query: str) -> None: self.__scrolling_thread is None ): # Only start if not already scrolling self.__scrolling_thread, self.__stop_scrolling_event = ( - commands.start_scrolling(direction) + command_registery.start_scrolling(direction) ) elif "stop scrolling" in query: if self.__scrolling_thread is None: # Only stop if already scrolling return - commands.stop_scrolling( + command_registery.stop_scrolling( self.__scrolling_thread, self.__stop_scrolling_event ) del self.__scrolling_thread self.__scrolling_thread = None elif re.search(r"scroll to (up|down|left|right|top|bottom)", query): - commands.scroll_to(direction) + command_registery.scroll_to(direction) elif re.search(r"scroll (up|down|left|right)", query): - commands.simple_scroll(direction) + command_registery.simple_scroll(direction) else: print("Scroll command not recognized") - elif "weather" in query: - cities = re.findall( - r"\b(?:of|in|at)\s+(\w+)", query - ) # Extract the city name just after the word 'of' - commands.weather_reporter(self.__voice_interface, cities[0]) - elif "email" in query: - query = query.lower() - - data = load_email_config() - - if data.get("server") == "smtp.example.com": - self.__voice_interface.speak( - "Please setup email config file before sending mail." - ) - else: - self.__voice_interface.speak("who do you want to send email to?") - receiver = None - validEmail = False - while not validEmail: - receiver = self.listen_for_query() - if receiver in data.get("contacts").keys(): - print( - f"Receiver selected from contacts: {data.get("contacts").get(receiver)}" - ) - receiver = data.get("contacts").get(receiver) - validEmail = True - elif re.match( - r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", receiver - ): - validEmail = True - else: - self.__voice_interface.speak( - "Valid Email not provided or contact does not exists" - ) - - self.__voice_interface.speak( - "What would be the subject of the message? " - ) - subject = None - while subject is None: - subject = self.listen_for_query() - - self.__voice_interface.speak("What would be the body of the email?") - body = None - while body is None: - body = self.listen_for_query() - - print( - f"Sender Address: {data.get("username")}\n" - f"Receiver address: {receiver}\n" - f"Subject: {subject}\n" - f"Body: {body}\n" - ) - - self.__voice_interface.speak("Do You Want to send this email?") - response = None - while response is None: - response = self.listen_for_query() - if "yes" in response.lower() or "sure" in response.lower(): - self.__voice_interface.speak("Sending the email") - commands.send_email(self.__voice_interface, receiver, subject, body) - else: - self.__voice_interface.speak("Request aborted by user") - - elif "brightness" in query: - query = query.lower() - - value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) - if len(value) == 0: - print("Please provide a value or input is out of range") - else: - value = min(max(0, int(value[0])), 100) - if "set" in query: - commands.brightness_control(value, False, False) - else: - toDecrease = "decrease" in query or "reduce" in query - relative = "by" in query - commands.brightness_control(value, relative, toDecrease) - - elif "volume" in query: - query = query.lower() - - value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) - if len(value) == 0: - print("Please provide a value or input is out of range") - else: - value = min(max(0, int(value[0])), 100) - if "set" in query: - commands.volume_control(value, False, False) - else: - toDecrease = "decrease" in query or "reduce" in query - relative = "by" in query - commands.volume_control(value, relative, toDecrease) - - elif "shutdown" in query or "shut down" in query: - self.__voice_interface.speak("Are you sure you want to shut down your PC?") - response = None - while response is None: - response = self.listen_for_query() - if "yes" in response.lower() or "sure" in response.lower(): - self.__voice_interface.speak("Shutting Down your PC") - subprocess.run(["shutdown", "-s", "/t", "1"]) - else: - self.__voice_interface.speak("Request aborted by user") + else: + command, executor = command_registery.INSTANCE.get_executor(query=query) - elif "restart" in query: - self.__voice_interface.speak("Are you sure you want to restart your PC?") - response = None - while response is None: - response = self.listen_for_query() - if "yes" in response.lower() or "sure" in response.lower(): - self.__voice_interface.speak("Restarting your PC") - subprocess.run(["shutdown", "/r", "/t", "1"]) + if command is None: + self.__voice_interface.speak("could not interpret the query") else: - self.__voice_interface.speak("Request aborted by user") - elif "news" in query: - commands.fetch_news(self.__voice_interface, MAX_FETCHED_HEADLINES) - - else: - self.__voice_interface.speak("could not interpret the query") + executor(query, self.__voice_interface) def close(self): """Close the VoiceInterface instance and delete other variables""" self.__voice_interface.close() del self.__voice_interface if self.__scrolling_thread: - commands.stop_scrolling( + command_registery.stop_scrolling( self.__scrolling_thread, self.__stop_scrolling_event ) del self.__scrolling_thread diff --git a/src/command_registery.py b/src/command_registery.py new file mode 100644 index 0000000..9e185cc --- /dev/null +++ b/src/command_registery.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Features +=============== + +This module contains all the functions pertaining to implementing the +individual features of the Assistant. + +""" + +import threading +import time + +import pyautogui as pag +import pygetwindow +from dotenv import dotenv_values +from PIL import ImageGrab + +from commands.brightness_control import BrightnessControl +from commands.current_time import CurrentTime +from commands.fetch_news import FetchNews +from commands.google_search import GoogleSearch +from commands.open_application import OpenApplication +from commands.restart_system import RestartSystem +from commands.send_email import SendEmail +from commands.shutdown_system import ShutdownSystem +from commands.volume_control import VolumeControl +from commands.weather_reporter import WeatherReporter +from commands.wikipedia_search import WikipediaSearch +from infra import __is_windows +from voice_interface import VoiceInterface + +SUPPORTED_FEATURES = { + "search your query in google and return upto 10 results", + "get a wikipedia search summary of upto 3 sentences", + "open applications or websites", + "tell you the time of the day", + "scroll the screen with active cursor", +} + +########## Conditional Imports ########## +if __is_windows(): + from AppOpener import open as open_app +########## Conditional Imports ########## + +ENVIRONMENT_VARIABLES = dotenv_values(".env") + + +def explain_features(vi: VoiceInterface) -> None: + """Explains the features available + + Args: + vi (VoiceInterface): The voice interface instance used to speak the text + """ + vi.speak("Here's what I can do...\n") + for feature in SUPPORTED_FEATURES: + vi.speak(f"--> {feature}") + + +def start_gradual_scroll(direction: str, stop_event: threading.Event) -> None: + """Gradually scroll in the given direction until stop_event is set.""" + active_window = pygetwindow.getActiveWindow() + if not active_window: + return + + # Capture a portion of the window to ensure scrolling + left, top, right, bottom = 0, 0, 100, 100 + width = right - left + height = bottom - top + previous_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) + while not stop_event.is_set(): + pag.scroll(clicks=1) + current_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) + + if current_image.getdata() == previous_image.getdata(): + print("Reached to extreme") + stop_event.set() + break + previous_image = current_image + + print(f"Stopped scrolling {direction}.") + + +def start_scrolling(direction: str) -> tuple[threading.Thread, threading.Event]: + """Start a new scroll thread.""" + stop_scrolling_event = threading.Event() + scrolling_thread = threading.Thread( + target=start_gradual_scroll, args=(direction, stop_scrolling_event) + ) + scrolling_thread.start() + return scrolling_thread, stop_scrolling_event + + +def stop_scrolling( + scrolling_thread: threading.Thread, scrolling_thread_event: threading.Event +) -> None: + """Stop the scrolling thread if not already stopped.""" + if scrolling_thread is not None: + scrolling_thread_event.set() + scrolling_thread.join() + + +def scroll_to(direction: str) -> None: + """Scroll to the extreme in the given direction.""" + active_window = pygetwindow.getActiveWindow() + if not active_window: + return + time.sleep(0.5) + if direction == "top": + pag.press("home") + elif direction == "bottom": + pag.press("end") + elif direction == "right": + pag.press("right", presses=9999) + elif direction == "left": + pag.press("left", presses=9999) + else: + print("Invalid Command") + + +def simple_scroll(direction: str) -> None: + """Simple scroll in the given direction by a fixed number of steps.""" + active_window = pygetwindow.getActiveWindow() + if not active_window: + return + time.sleep(0.5) + if direction in ["up", "down", "left", "right"]: + pag.press(keys=direction, presses=25) + else: + print("Invalid direction") + + +class CommandRegistery: + """Class to register and execute commands based on the query""" + + def __init__(self, vi: VoiceInterface) -> None: + self.vi = vi + self.__registery = dict[str, tuple[callable, callable]]() + + def register_command( + self, command: str, validateQuery: callable, executeQuery: callable + ) -> None: + """ + Registers a command with the CommandRegistery. + + Args: + command (str): The command string to register. + validateQuery (callable): The function to validate the query for the command. + executeQuery (callable): The function to execute the query for the command. + """ + self.__registery[command] = (validateQuery, executeQuery) + + def get_executor(self, query: str) -> tuple[str, callable]: + """ + Returns the executor function for the given query. + + Args: + query (str): The query to find the executor for. + + Returns: + tuple[str, callable]: The command string and the executor function for the query. + """ + for command, validateQuery, executeQuery in self.__registery: + if validateQuery.__call__(query): + return command, executeQuery + return None, None + + def get_command(self, command: str) -> tuple[callable, callable]: + """Get the query validator and query executor for given command name + + Args: + command (str): name of the command to fetch + + Returns: + tuple[callable, callable]: Tuple of Query Validator and Query Executor if found + """ + if self.__registery is None: + return None, None + + self.__registery.get(key=command, default=(None, None)) + + +INSTANCE = CommandRegistery(VoiceInterface()) + +INSTANCE.register_command( + GoogleSearch.commandName(), GoogleSearch.validateQuery, GoogleSearch.executeQuery +) +INSTANCE.register_command( + WikipediaSearch.commandName(), + WikipediaSearch.validateQuery, + WikipediaSearch.executeQuery, +) +INSTANCE.register_command( + OpenApplication.commandName(), + OpenApplication.validateQuery, + OpenApplication.executeQuery, +) +INSTANCE.register_command( + CurrentTime.commandName(), CurrentTime.validateQuery, CurrentTime.executeQuery +) +INSTANCE.register_command( + BrightnessControl.commandName(), + BrightnessControl.validateQuery, + BrightnessControl.executeQuery, +) +INSTANCE.register_command( + VolumeControl.commandName(), VolumeControl.validateQuery, VolumeControl.executeQuery +) +INSTANCE.register_command( + ShutdownSystem.commandName(), + ShutdownSystem.validateQuery, + ShutdownSystem.executeQuery, +) +INSTANCE.register_command( + RestartSystem.commandName(), RestartSystem.validateQuery, RestartSystem.executeQuery +) +INSTANCE.register_command( + WeatherReporter.commandName(), + WeatherReporter.validateQuery, + WeatherReporter.executeQuery, +) +INSTANCE.register_command( + FetchNews.commandName(), FetchNews.validateQuery, FetchNews.executeQuery +) +INSTANCE.register_command( + SendEmail.commandName(), SendEmail.validateQuery, SendEmail.executeQuery +) diff --git a/src/commands.py b/src/commands.py deleted file mode 100644 index 96b7321..0000000 --- a/src/commands.py +++ /dev/null @@ -1,490 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Features -=============== - -This module contains all the functions pertaining to implementing the -individual features of the Assistant. - -""" - -import smtplib -import ssl -import subprocess -import threading -import time -from datetime import datetime -from email.message import EmailMessage -from subprocess import CalledProcessError, TimeoutExpired - -import feedparser -import googlesearch -import pyautogui as pag -import pygetwindow -import requests -import wikipedia -import wmi -from comtypes import CLSCTX_ALL -from dotenv import dotenv_values -from PIL import ImageGrab -from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume - -from infra import __is_darwin, __is_posix, __is_windows, __system_os -from utils import load_email_config -from voice_interface import VoiceInterface - -SUPPORTED_FEATURES = { - "search your query in google and return upto 10 results", - "get a wikipedia search summary of upto 3 sentences", - "open applications or websites", - "tell you the time of the day", - "scroll the screen with active cursor", -} - -########## Conditional Imports ########## -if __is_windows(): - from AppOpener import open as open_app -########## Conditional Imports ########## - -ENVIRONMENT_VARIABLES = dotenv_values(".env") - - -def explain_features(vi: VoiceInterface) -> None: - """Explains the features available - - Args: - vi (VoiceInterface): The voice interface instance used to speak the text - """ - vi.speak("Here's what I can do...\n") - for feature in SUPPORTED_FEATURES: - vi.speak(f"--> {feature}") - - -def run_search_query(vi: VoiceInterface, search_query: str) -> None: - """Performs google search based on some terms - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak - search_query (str): the query term to be searched in google - """ - if not search_query: - vi.speak("Invalid Google Search Query Found!!") - return - - results = googlesearch.search(term=search_query) - if not results: - vi.speak("No Search Result Found!!") - else: - results = list(results) - vi.speak("Found Following Results: ") - for i, result in enumerate(results): - print(i + 1, ")", result.title) - - -def wikipedia_search( - vi: VoiceInterface, search_query: str, sentence_count: int = 3 -) -> None: - """Searches wikipedia for the given query and returns fixed number of statements in response. - Disambiguation Error due to multiple similar results is handled. - Speaks the options in this case. - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The query term to search in wikipedia - sentence_count (int, optional): The number of sentences to speak in case of direct match. - Default is 3. - """ - try: - vi.speak("Searching Wikipedia...") - results = wikipedia.summary(search_query, sentences=sentence_count) - - vi.speak("According to wikipedia...") - vi.speak(results) - except wikipedia.DisambiguationError as de: - vi.speak(f"\n{de.__class__.__name__}") - options = str(de).split("\n") - if len(options) < 7: - for option in options: - vi.speak(option) - else: - for option in options[0:6]: - vi.speak(option) - vi.speak("... and more") - - -def open_application_website(vi: VoiceInterface, search_query: str) -> None: - """ - open the application/website using a matching path from AppPath/WebPath dictionaries. - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - vi.speak(f"Attempting to open {search_query}...") - - search_query = search_query.strip().lower() - - # use appopener to open the application only if os is windows - if __is_windows(): - __open_application_website_windows(vi, search_query) - if __is_darwin(): - __open_application_website_darwin(vi, search_query) - elif __is_posix(): - __open_application_website_posix(vi, search_query) - else: - raise ValueError(f"Unsupported OS: {__system_os()}") - - -def __open_application_website_windows(vi: VoiceInterface, search_query: str) -> None: - """handle the opening of application/website for Windows OS - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - try: - open_app(search_query, match_closest=True) # attempt to open as application - except Exception as error: - vi.speak(f"Error: {error}: Failed to open {search_query}") - - -def __open_application_website_darwin(vi: VoiceInterface, search_query: str) -> None: - """handle the opening of application/website for Darwin OS - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - try: - subprocess.run( - ["open", "-a", search_query], capture_output=True, check=True - ) # attempt to open as application - except CalledProcessError: - try: - subprocess.run( - ["open", search_query], capture_output=True, check=True - ) # attempt to open as website - except CalledProcessError as error: - return_code = error.returncode - stdout_text = error.stdout.decode("utf-8") - stderr_text = error.stderr.decode("utf-8") - vi.speak( - f"Error: {error}: Failed to open {search_query}: error code {return_code}" - ) - if stdout_text: - print("stdout:", stdout_text) - if stderr_text: - print("stderr:", stderr_text) - except TimeoutExpired as error: - vi.speak(f"Error: {error}: Call to open {search_query} timed out.") - - except TimeoutExpired as error: - vi.speak(f"Error: {error}: Call to open {search_query} timed out.") - - -def __open_application_website_posix(vi: VoiceInterface, search_query: str) -> None: - """handle the opening of application/website for POSIX OS - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - search_query (str): The website or application name - - Raises: - ValueError: Throws exception in case neither app nor web access-point is present. - """ - try: - subprocess.run( - ["xdg-open", search_query], capture_output=True, check=True - ) # attempt to open website/application - except CalledProcessError as error: - vi.speak( - f"Error: {error}: Failed to open {search_query}: error code {error.returncode}" - ) - stdout_text = error.stdout.decode("utf-8") - stderr_text = error.stderr.decode("utf-8") - if stdout_text: - print("stdout:", stdout_text) - if stderr_text: - print("stderr:", stderr_text) - - except TimeoutExpired as error: - vi.speak(f"Error: {error}: Call to open {search_query} timed out.") - - -def tell_time(vi: VoiceInterface) -> None: - """Tells the time of the day with timezone - - Args: - vi (VoiceInterface): Voice interface instance used to speak - """ - date_time = datetime.now() - hour, minute, second = date_time.hour, date_time.minute, date_time.second - tmz = date_time.tzname() - - vi.speak(f"Current time is {hour}:{minute}:{second} {tmz}") - - -def start_gradual_scroll(direction: str, stop_event: threading.Event) -> None: - """Gradually scroll in the given direction until stop_event is set.""" - active_window = pygetwindow.getActiveWindow() - if not active_window: - return - - # Capture a portion of the window to ensure scrolling - left, top, right, bottom = 0, 0, 100, 100 - width = right - left - height = bottom - top - previous_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) - while not stop_event.is_set(): - pag.scroll(clicks=1) - current_image = ImageGrab.grab(bbox=(left, top, left + width, top + height)) - - if current_image.getdata() == previous_image.getdata(): - print("Reached to extreme") - stop_event.set() - break - previous_image = current_image - - print(f"Stopped scrolling {direction}.") - - -def start_scrolling(direction: str) -> tuple[threading.Thread, threading.Event]: - """Start a new scroll thread.""" - stop_scrolling_event = threading.Event() - scrolling_thread = threading.Thread( - target=start_gradual_scroll, args=(direction, stop_scrolling_event) - ) - scrolling_thread.start() - return scrolling_thread, stop_scrolling_event - - -def stop_scrolling( - scrolling_thread: threading.Thread, scrolling_thread_event: threading.Event -) -> None: - """Stop the scrolling thread if not already stopped.""" - if scrolling_thread is not None: - scrolling_thread_event.set() - scrolling_thread.join() - - -def scroll_to(direction: str) -> None: - """Scroll to the extreme in the given direction.""" - active_window = pygetwindow.getActiveWindow() - if not active_window: - return - time.sleep(0.5) - if direction == "top": - pag.press("home") - elif direction == "bottom": - pag.press("end") - elif direction == "right": - pag.press("right", presses=9999) - elif direction == "left": - pag.press("left", presses=9999) - else: - print("Invalid Command") - - -def simple_scroll(direction: str) -> None: - """Simple scroll in the given direction by a fixed number of steps.""" - active_window = pygetwindow.getActiveWindow() - if not active_window: - return - time.sleep(0.5) - if direction in ["up", "down", "left", "right"]: - pag.press(keys=direction, presses=25) - else: - print("Invalid direction") - - -def brightness_control(value: int, relative: bool, toDecrease: bool): - """ - Adjusts the brightness of the monitor. - - Args: - value (int): The brightness level to set or adjust by. Should be between 0 and 100. - relative (bool): If True, the brightness change is relative to the current brightness. - If False, the brightness is set to the specified value. - toDecrease (bool): If True, decreases the brightness by the specified value. - If False, increases the brightness by the specified value. Only applicable when `relative` is True. - - Raises: - RuntimeError: If there is an issue with accessing the brightness control methods. - - Returns: - None - """ - - brightness_ctrl = wmi.WMI(namespace="root\\wmi") - methods = brightness_ctrl.WmiMonitorBrightnessMethods()[0] - - if relative: - current_brightness = brightness_ctrl.WmiMonitorBrightness()[0].CurrentBrightness - set_brightnes = ( - current_brightness - int(value) - if toDecrease - else current_brightness + int(value) - ) - methods.WmiSetBrightness(set_brightnes, 0) - else: - methods.WmiSetBrightness(value, 0) - - -def volume_control(value: int, relative: bool, toDecrease: bool): - """ - Adjusts the master volume of the system. - - Args: - value (int): The volume level to set or adjust by. Should be between 0 and 100. - relative (bool): If True, the volume change is relative to the current volume. - If False, the volume is set to the specified value. - toDecrease (bool): If True, decreases the volume by the specified value. - If False, increases the volume by the specified value. Only applicable when `relative` is True. - - Raises: - RuntimeError: If there is an issue with accessing the audio endpoint. - - Returns: - None - """ - - devices = AudioUtilities.GetSpeakers() - interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) - volume = interface.QueryInterface(IAudioEndpointVolume) - - if relative: - current_volume = volume.GetMasterVolumeLevelScalar() * 100 - set_volume = ( - current_volume - int(value) if toDecrease else current_volume + int(value) - ) - print(set_volume) - volume.SetMasterVolumeLevelScalar(min(max(0, set_volume), 100) / 100, None) - else: - volume.SetMasterVolumeLevelScalar(min(max(0, value), 100) / 100, None) - - -def fetch_news(vi: VoiceInterface, max_fetched_headlines: int) -> None: - """ - Fetches and reads out the top 5 headlines from the Google News RSS feed. - - This function fetches news headlines from the Google News RSS feed (specific to India in English). - It then reads out the top 5 headlines using the provided VoiceInterface instance. If the feed fetch is successful, - it reads the headlines one by one. If the fetch fails, it informs the user that the news couldn't be fetched. - - Args: - vi (VoiceInterface): The VoiceInterface instance used to speak the news headlines. - - Raises: - requests.exceptions.RequestException: If there is an issue while fetching the RSS feed. - AttributeError: If the feed does not contain expected attributes or entries. - """ - - feed_url = "https://news.google.com/rss?hl=en-IN&gl=IN&ceid=IN:en" - - vi.speak("Fetching news from servers.") - feed = feedparser.parse(feed_url) - if feed.status == 200: - headlines_list = [] - for entry in feed.entries[:max_fetched_headlines]: - headlines_list.append((entry.title).split(" -")[0]) - vi.speak("Here are some recent news headlines.") - for headline in headlines_list: - vi.speak(headline) - else: - vi.speak("Failed to fetch the news.") - - -def weather_reporter(vi: VoiceInterface, city_name: str) -> None: - """ - Fetches and reports the weather conditions for a given city. - - This function retrieves the latitude and longitude of the specified city using the API Ninjas City API. - It then fetches the current weather data from the Open-Meteo API and reports the temperature, humidity, - apparent temperature, rain probability, cloud cover, and wind speed using the VoiceInterface instance. - - Args: - vi (VoiceInterface): The VoiceInterface instance used to speak the weather report. - city_name (str): The name of the city for which to fetch weather data. - - Raises: - requests.exceptions.RequestException: If there is an issue with the API request. - IndexError: If the city name is not found in the API response. - KeyError: If expected weather data fields are missing from the response. - """ - # Fetch latitude and longitude for the given city to be used by open-metro api - params = { - "name": city_name, - } - geo_codes = requests.get( - "https://api.api-ninjas.com/v1/city", - params=params, - headers={"origin": "https://www.api-ninjas.com"}, - ).json() - - # Fetch weather data from Open-Meteo using the obtained coordinates - weather_data_response = requests.get( - f'https://api.open-meteo.com/v1/forecast?latitude={geo_codes[0].get("latitude")}&longitude={geo_codes[0].get("longitude")}¤t=temperature_2m,relative_humidity_2m,apparent_temperature,rain,showers,cloud_cover,wind_speed_10m&forecast_days=1' - ).json() - - weather_data = weather_data_response.get("current") - weather_units = weather_data_response.get("current_units") - - vi.speak( - f"The current temperature in {city_name} is {weather_data.get('temperature_2m')}{weather_units.get('temperature_2m')}. " - f"However, due to a relative humidity of {weather_data.get('relative_humidity_2m')}{weather_units.get('relative_humidity_2m')}, " - f"it feels like {weather_data.get('apparent_temperature')}{weather_units.get('apparent_temperature')}." - ) - - if weather_data.get("rain") == 0: - vi.speak("The skies will be clear, with no chance of rain.") - else: - cloud_cover = weather_data.get("cloud_cover") - vi.speak( - f"The sky will be {cloud_cover}{weather_units.get('cloud_cover')} cloudy, " - f"and there's a predicted rainfall of {weather_data.get('rain')}{weather_units.get('rain')}." - ) - - vi.speak( - f"The wind speed is expected to be {weather_data.get('wind_speed_10m')}{weather_units.get('wind_speed_10m')}, " - "so plan accordingly." - ) - - -def send_email(vi: VoiceInterface, toEmail: str, subject: str, body: str): - """ - Send an email to the specified recipient. - - Args: - vi (VoiceInterface): VoiceInterface instance used to speak. - toEmail (str): The recipient's email address. - subject (str): The subject of the email. - body (str): The body content of the email. - - Raises: - ValueError: If any required parameters are missing or invalid. - """ - - data = load_email_config() - CONTEXT = ssl.create_default_context() - msg = EmailMessage() - msg["Subject"] = subject - msg["From"] = data.get("username") - msg["To"] = [toEmail] - msg.set_content(body) - server = smtplib.SMTP_SSL(data.get("server"), data.get("port"), context=CONTEXT) - server.login( - data.get("username"), ENVIRONMENT_VARIABLES.get("DESKTOP_ASSISTANT_SMTP_PWD") - ) - server.send_message(msg) - server.quit() - vi.speak(f"Email sent to {toEmail}") diff --git a/src/commands/brightness_control.py b/src/commands/brightness_control.py new file mode 100644 index 0000000..0b884e0 --- /dev/null +++ b/src/commands/brightness_control.py @@ -0,0 +1,65 @@ +import re + +import wmi + +from voice_interface import VoiceInterface + + +class BrightnessControl: + + @staticmethod + def commandName() -> str: + return BrightnessControl.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return "brightness" in query + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + query = query.lower() + + value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) + if len(value) == 0 or str(value).isnumeric() == False: + vi.speak("Please provide a valid brightness value between 0 and 100") + else: + value = min(max(0, int(value[0])), 100) + if "set" in query: + brightness_control(value, False, False) + else: + toDecrease = "decrease" in query or "reduce" in query + relative = "by" in query + brightness_control(value, relative, toDecrease) + + +def brightness_control(value: int, relative: bool, toDecrease: bool): + """ + Adjusts the brightness of the monitor. + + Args: + value (int): The brightness level to set or adjust by. Should be between 0 and 100. + relative (bool): If True, the brightness change is relative to the current brightness. + If False, the brightness is set to the specified value. + toDecrease (bool): If True, decreases the brightness by the specified value. + If False, increases the brightness by the specified value. Only applicable when `relative` is True. + + Raises: + RuntimeError: If there is an issue with accessing the brightness control methods. + + Returns: + None + """ + + brightness_ctrl = wmi.WMI(namespace="root\\wmi") + methods = brightness_ctrl.WmiMonitorBrightnessMethods()[0] + + if relative: + current_brightness = brightness_ctrl.WmiMonitorBrightness()[0].CurrentBrightness + set_brightness = ( + current_brightness - int(value) + if toDecrease + else current_brightness + int(value) + ) + methods.WmiSetBrightness(set_brightness, 0) + else: + methods.WmiSetBrightness(value, 0) diff --git a/src/commands/current_time.py b/src/commands/current_time.py new file mode 100644 index 0000000..9b3d678 --- /dev/null +++ b/src/commands/current_time.py @@ -0,0 +1,27 @@ +from datetime import datetime + +from voice_interface import VoiceInterface + + +class CurrentTime: + """Tells the time of the day with timezone""" + + @staticmethod + def commandName() -> str: + return CurrentTime.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return any(text in query for text in ["the time", "time please"]) + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + """ + Args: + vi (VoiceInterface): Voice interface instance used to speak + """ + date_time = datetime.now() + hour, minute, second = date_time.hour, date_time.minute, date_time.second + tmz = date_time.tzname() + + vi.speak(f"Current time is {hour}:{minute}:{second} {tmz}") diff --git a/src/commands/fetch_news.py b/src/commands/fetch_news.py new file mode 100644 index 0000000..4d16769 --- /dev/null +++ b/src/commands/fetch_news.py @@ -0,0 +1,43 @@ +import feedparser + +from voice_interface import VoiceInterface + + +class FetchNews: + """ + Fetches and reads out the top 5 headlines from the Google News RSS feed. + + This function fetches news headlines from the Google News RSS feed (specific to India in English). + It then reads out the top 5 headlines using the provided VoiceInterface instance. If the feed fetch is successful, + it reads the headlines one by one. If the fetch fails, it informs the user that the news couldn't be fetched. + + Raises: + requests.exceptions.RequestException: If there is an issue while fetching the RSS feed. + AttributeError: If the feed does not contain expected attributes or entries. + """ + + # Maximum number of news headlines to fetch when news function is called + MAX_FETCHED_HEADLINES = 10 + FEED_URL = "https://news.google.com/rss?hl=en-IN&gl=IN&ceid=IN:en" + + @staticmethod + def commandName() -> str: + return FetchNews.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return "news" in query + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + vi.speak("Fetching news from servers.") + feed = feedparser.parse(FetchNews.FEED_URL) + if feed.status == 200: + headlines_list = [] + for entry in feed.entries[: FetchNews.MAX_FETCHED_HEADLINES]: + headlines_list.append((entry.title).split(" -")[0]) + vi.speak("Here are some recent news headlines.") + for headline in headlines_list: + vi.speak(headline) + else: + vi.speak("Failed to fetch the news.") diff --git a/src/commands/google_search.py b/src/commands/google_search.py new file mode 100644 index 0000000..5a5a1d3 --- /dev/null +++ b/src/commands/google_search.py @@ -0,0 +1,35 @@ +import re + +import googlesearch + +from voice_interface import VoiceInterface + + +class GoogleSearch: + """Performs google search based on some terms""" + + @staticmethod + def commandName() -> str: + return GoogleSearch.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return re.search(r"search .* (in google)?", query) + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + """ + Args: + search_query (str): the query term to be searched in google + """ + if not GoogleSearch.validQuery(query): + vi.speak("Invalid Google Search Query Found!!") + return + + search_query = re.findall(r"search (.*)", query.replace("in google", ""))[0] + results = googlesearch.search(term=search_query) + if not results: + vi.speak("No Search Result Found!!") + else: + results = list(results) + vi.speak("Found Following Results: ") diff --git a/src/commands/open_application.py b/src/commands/open_application.py new file mode 100644 index 0000000..76d75dc --- /dev/null +++ b/src/commands/open_application.py @@ -0,0 +1,142 @@ +import re +import subprocess +from subprocess import CalledProcessError, TimeoutExpired + +from AppOpener import open_app + +import infra +from voice_interface import VoiceInterface + + +class OpenApplication: + + @staticmethod + def commandName() -> str: + return OpenApplication.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return re.search("open .*", query) + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + application = re.findall(r"open (.*)", query) + if len(application) == 0: + vi.speak("Which Application Should I Open ?") + return + application = application[0] + try: + open_application_website(vi, application) + except ValueError as ve: + print( + f"Error occurred while opening {application}: {ve.__class__.__name__}: {ve}" + ) + vi.speak(f"Failed to open {application}. Please try again.") + + +def open_application_website(vi: VoiceInterface, search_query: str) -> None: + """ + open the application/website using a matching path from AppPath/WebPath dictionaries. + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + vi.speak(f"Attempting to open {search_query}...") + + search_query = search_query.strip().lower() + + # use appopener to open the application only if os is windows + if infra.__is_windows(): + __open_application_website_windows(vi, search_query) + if infra.__is_darwin(): + __open_application_website_darwin(vi, search_query) + elif infra.__is_posix(): + __open_application_website_posix(vi, search_query) + else: + raise ValueError(f"Unsupported OS: {infra.__system_os()}") + + +def __open_application_website_windows(vi: VoiceInterface, search_query: str) -> None: + """handle the opening of application/website for Windows OS + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + try: + open_app(search_query, match_closest=True) # attempt to open as application + except Exception as error: + vi.speak(f"Error: {error}: Failed to open {search_query}") + + +def __open_application_website_darwin(vi: VoiceInterface, search_query: str) -> None: + """handle the opening of application/website for Darwin OS + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + try: + subprocess.run( + ["open", "-a", search_query], capture_output=True, check=True + ) # attempt to open as application + except CalledProcessError: + try: + subprocess.run( + ["open", search_query], capture_output=True, check=True + ) # attempt to open as website + except CalledProcessError as error: + return_code = error.returncode + stdout_text = error.stdout.decode("utf-8") + stderr_text = error.stderr.decode("utf-8") + vi.speak( + f"Error: {error}: Failed to open {search_query}: error code {return_code}" + ) + if stdout_text: + print("stdout:", stdout_text) + if stderr_text: + print("stderr:", stderr_text) + except TimeoutExpired as error: + vi.speak(f"Error: {error}: Call to open {search_query} timed out.") + + except TimeoutExpired as error: + vi.speak(f"Error: {error}: Call to open {search_query} timed out.") + + +def __open_application_website_posix(vi: VoiceInterface, search_query: str) -> None: + """handle the opening of application/website for POSIX OS + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + search_query (str): The website or application name + + Raises: + ValueError: Throws exception in case neither app nor web access-point is present. + """ + try: + subprocess.run( + ["xdg-open", search_query], capture_output=True, check=True + ) # attempt to open website/application + except CalledProcessError as error: + vi.speak( + f"Error: {error}: Failed to open {search_query}: error code {error.returncode}" + ) + stdout_text = error.stdout.decode("utf-8") + stderr_text = error.stderr.decode("utf-8") + if stdout_text: + print("stdout:", stdout_text) + if stderr_text: + print("stderr:", stderr_text) + + except TimeoutExpired as error: + vi.speak(f"Error: {error}: Call to open {search_query} timed out.") diff --git a/src/commands/restart_system.py b/src/commands/restart_system.py new file mode 100644 index 0000000..c14243d --- /dev/null +++ b/src/commands/restart_system.py @@ -0,0 +1,18 @@ +import subprocess + +from voice_interface import VoiceInterface + + +class RestartSystem: + + @staticmethod + def commandName(): + return RestartSystem.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return any(text in query for text in ["restart"]) + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface): + subprocess.run(["shutdown", "/r", "/t", "1"]) diff --git a/src/commands/send_email.py b/src/commands/send_email.py new file mode 100644 index 0000000..7c0293d --- /dev/null +++ b/src/commands/send_email.py @@ -0,0 +1,126 @@ +import re +import smtplib +import ssl +from email.message import EmailMessage + +from dotenv import dotenv_values + +from infra import listen, load_json_config +from voice_interface import VoiceInterface + +CONFIG_FILE = "mail_server.json" +SERVER = "server" +PORT = "port" +EMAIL_CONTACTS = "contacts" +SENDER = "username" +SMTP_PASS = "SMTP_PASSWORD" + +ENV = dotenv_values(".env") + + +class SendEmail: + + @staticmethod + def commandName() -> str: + return SendEmail.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return "email" in query + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + query = query.lower() + + data = load_json_config(CONFIG_FILE) + + server = data.get(SERVER) + port = data.get(PORT) + sender = data.get(SENDER) + contacts = data.get(EMAIL_CONTACTS) + + if data.get("server") is None: + vi.speak("Please setup email config file before sending mail.") + else: + vi.speak("who do you want to send email to?") + receiver = None + validEmail = False + maxAttempts = 3 + while not validEmail and maxAttempts > 0: + maxAttempts -= 1 + receiver = listen(vi).strip() + + if receiver in contacts.keys(): + print(f"Receiver selected from contacts: {contacts.get(receiver)}") + receiver = contacts.get(receiver) + validEmail = True + elif re.match( + r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", receiver + ): + validEmail = True + else: + vi.speak("Valid Email not provided or contact does not exists") + + vi.speak("What would be the subject of the message? ") + subject = listen(vi) + + vi.speak("What would be the body of the email?") + body = None + maxAttemptsForBody = 3 + while body is None and maxAttemptsForBody > 0: + maxAttemptsForBody -= 1 + body = listen(vi) + + print( + f"Sender Address: {sender}\n" + + f"Receiver address: {receiver}\n" + + f"Subject: {subject}\n" + + f"Body: {body}\n" + ) + + vi.speak("Do You Want to send this email?") + response = None + while response is None: + response = listen(vi) + if "yes" in response.lower() or "sure" in response.lower(): + vi.speak("Sending the email") + SendEmail.__send_email( + vi, server, port, sender, receiver, subject, body + ) + else: + vi.speak("Request aborted by user") + + @staticmethod + def __send_email( + vi: VoiceInterface, + server: str, + port: str, + fromEmail: str, + toEmail: str, + subject: str, + body: str, + ): + """ + Send an email to the specified recipient. + + Args: + vi (VoiceInterface): VoiceInterface instance used to speak. + toEmail (str): The recipient's email address. + subject (str): The subject of the email. + body (str): The body content of the email. + + Raises: + ValueError: If any required parameters are missing or invalid. + """ + + context = ssl.create_default_context() + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = fromEmail + msg["To"] = [toEmail] + msg.set_content(body) + server = smtplib.SMTP_SSL(server, port, context=context) + server.login(fromEmail, ENV.get(SMTP_PASS)) + server.send_message(msg) + server.quit() + vi.speak(f"Email sent to {toEmail}") diff --git a/src/commands/shutdown_system.py b/src/commands/shutdown_system.py new file mode 100644 index 0000000..1aa9979 --- /dev/null +++ b/src/commands/shutdown_system.py @@ -0,0 +1,18 @@ +import subprocess + +from voice_interface import VoiceInterface + + +class ShutdownSystem: + + @staticmethod + def commandName(): + return ShutdownSystem.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return any(text in query for text in ["shutdown", "shut down"]) + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface): + subprocess.run(["shutdown", "-s", "/t", "1"]) diff --git a/src/commands/volume_control.py b/src/commands/volume_control.py new file mode 100644 index 0000000..8420bf4 --- /dev/null +++ b/src/commands/volume_control.py @@ -0,0 +1,66 @@ +import re + +from comtypes import CLSCTX_ALL +from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume + +from voice_interface import VoiceInterface + + +class VolumeControl: + + @staticmethod + def commandName() -> str: + return VolumeControl.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return any(text in query for text in ["volume", "sound"]) + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + query = query.lower() + value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) + + if len(value) == 0 or str(value).isnumeric() == False: + vi.speak("Please provide a value or input is out of range") + else: + value = min(max(0, int(value[0])), 100) + if "set" in query: + volume_control(value, False, False) + else: + toDecrease = "decrease" in query or "reduce" in query + relative = "by" in query + volume_control(value, relative, toDecrease) + + +def volume_control(value: int, relative: bool, toDecrease: bool): + """ + Adjusts the master volume of the system. + + Args: + value (int): The volume level to set or adjust by. Should be between 0 and 100. + relative (bool): If True, the volume change is relative to the current volume. + If False, the volume is set to the specified value. + toDecrease (bool): If True, decreases the volume by the specified value. + If False, increases the volume by the specified value. Only applicable when `relative` is True. + + Raises: + RuntimeError: If there is an issue with accessing the audio endpoint. + + Returns: + None + """ + + devices = AudioUtilities.GetSpeakers() + interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) + volume = interface.QueryInterface(IAudioEndpointVolume) + + if relative: + current_volume = volume.GetMasterVolumeLevelScalar() * 100 + set_volume = ( + current_volume - int(value) if toDecrease else current_volume + int(value) + ) + print(set_volume) + volume.SetMasterVolumeLevelScalar(min(max(0, set_volume), 100) / 100, None) + else: + volume.SetMasterVolumeLevelScalar(min(max(0, value), 100) / 100, None) diff --git a/src/commands/weather_reporter.py b/src/commands/weather_reporter.py new file mode 100644 index 0000000..6b1832c --- /dev/null +++ b/src/commands/weather_reporter.py @@ -0,0 +1,78 @@ +import re + +import requests + +from voice_interface import VoiceInterface + + +class WeatherReporter: + + @staticmethod + def commandName() -> str: + return WeatherReporter.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return "weather" in query + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + # Extract the city name just after the word 'of' + cities = re.findall(r"\b(?:of|in|at)\s+(\w+)", query) + weather_reporter(vi, cities[0]) + + +def weather_reporter(vi: VoiceInterface, city_name: str) -> None: + """ + Fetches and reports the weather conditions for a given city. + + Retrieve the latitude and longitude of the specified city using the API Ninjas City API. + Then fetch the current weather data from the Open-Meteo API and then report the temperature, humidity, + apparent temperature, rain probability, cloud cover, and wind speed + + Args: + vi (VoiceInterface): The VoiceInterface instance used to speak the weather report. + city_name (str): The name of the city for which to fetch weather data. + + Raises: + requests.exceptions.RequestException: If there is an issue with the API request. + IndexError: If the city name is not found in the API response. + KeyError: If expected weather data fields are missing from the response. + """ + # Fetch latitude and longitude for the given city to be used by open-metro api + params = { + "name": city_name, + } + geo_codes = requests.get( + "https://api.api-ninjas.com/v1/city", + params=params, + headers={"origin": "https://www.api-ninjas.com"}, + ).json() + + # Fetch weather data from Open-Meteo using the obtained coordinates + weather_data_response = requests.get( + f'https://api.open-meteo.com/v1/forecast?latitude={geo_codes[0].get("latitude")}&longitude={geo_codes[0].get("longitude")}¤t=temperature_2m,relative_humidity_2m,apparent_temperature,rain,showers,cloud_cover,wind_speed_10m&forecast_days=1' + ).json() + + weather_data = weather_data_response.get("current") + weather_units = weather_data_response.get("current_units") + + vi.speak( + f"The current temperature in {city_name} is {weather_data.get('temperature_2m')}{weather_units.get('temperature_2m')}. " + f"However, due to a relative humidity of {weather_data.get('relative_humidity_2m')}{weather_units.get('relative_humidity_2m')}, " + f"it feels like {weather_data.get('apparent_temperature')}{weather_units.get('apparent_temperature')}." + ) + + if weather_data.get("rain") == 0: + vi.speak("The skies will be clear, with no chance of rain.") + else: + cloud_cover = weather_data.get("cloud_cover") + vi.speak( + f"The sky will be {cloud_cover}{weather_units.get('cloud_cover')} cloudy, " + f"and there's a predicted rainfall of {weather_data.get('rain')}{weather_units.get('rain')}." + ) + + vi.speak( + f"The wind speed is expected to be {weather_data.get('wind_speed_10m')}{weather_units.get('wind_speed_10m')}, " + "so plan accordingly." + ) diff --git a/src/commands/wikipedia_search.py b/src/commands/wikipedia_search.py new file mode 100644 index 0000000..cd4415c --- /dev/null +++ b/src/commands/wikipedia_search.py @@ -0,0 +1,50 @@ +import wikipedia + +from voice_interface import VoiceInterface + + +class WikipediaSearch: + """Searches wikipedia for the given query and returns fixed number of statements in response. + Disambiguation Error due to multiple similar results is handled. + Speaks the options in this case. + """ + + sentence_count = 3 + + @staticmethod + def commandName() -> str: + return WikipediaSearch.__name__ + + @staticmethod + def validateQuery(query: str) -> bool: + return "wikipedia" in query + + @staticmethod + def executeQuery(query: str, vi: VoiceInterface) -> None: + """ + Args: + search_query (str): the query term to be searched in google + """ + if not WikipediaSearch.validQuery(query): + vi.speak("Invalid Wikipedia Search Query Found!!") + return + + search_query = query.replace("wikipedia", "", 1).replace("search", "", 1) + try: + vi.speak("Searching Wikipedia...") + results = wikipedia.summary( + search_query, sentences=WikipediaSearch.sentence_count + ) + + vi.speak("According to wikipedia...") + vi.speak(results) + except wikipedia.DisambiguationError as de: + vi.speak(f"\n{de.__class__.__name__}") + options = str(de).split("\n") + if len(options) < 7: + for option in options: + vi.speak(option) + else: + for option in options[0:6]: + vi.speak(option) + vi.speak("... and more") diff --git a/src/config/email_config.json b/src/config/mail_server.json similarity index 81% rename from src/config/email_config.json rename to src/config/mail_server.json index add5924..2580dd3 100644 --- a/src/config/email_config.json +++ b/src/config/mail_server.json @@ -1,5 +1,5 @@ { - "server": "smtp.example.com", + "server": "smtp.gmail.com", "port": 465, "username":"no-reply@gmail.com", "contacts": { diff --git a/src/infra.py b/src/infra.py index 4d5beef..12dc435 100644 --- a/src/infra.py +++ b/src/infra.py @@ -8,9 +8,14 @@ """ +import json import os import sys +from voice_interface import VoiceInterface + +__CONFIG_DIR = os.path.join(os.path.abspath(__file__), "config") + def __is_windows() -> bool: """Returns True if the operating system is Windows""" @@ -38,3 +43,36 @@ def clear_screen() -> None: os.system("cls") else: os.system("clear") + + +def listen(vi: VoiceInterface) -> str: + """Listens for microphone input and return string of the input + + Returns: + str: the query string obtained from the speech input + """ + query = vi.listen(True) + if query: + print(f"User:") + vi.speak(query) + else: + vi.speak("Say that again please...") + return query + + +def load_json_config(config_path: str) -> dict: + """Load Json from the configs folder + + Args: + file_path (str): json doc path relative to config folder + + Returns: + dict: json document deserialized as dictionary + """ + file_path = os.path.join(__CONFIG_DIR, config_path) + + if not os.path.isfile(file_path): + return dict() + + with open(config_path, "r") as json_doc: + return json.load(json_doc) diff --git a/src/utils.py b/src/utils.py deleted file mode 100644 index 09cbd27..0000000 --- a/src/utils.py +++ /dev/null @@ -1,11 +0,0 @@ -import json -import os - -BASE_DIR = os.path.dirname(os.path.abspath(__file__)) - -CONFIG_PATH = os.path.join(BASE_DIR, "config", "email_config.json") - - -def load_email_config(): - with open(CONFIG_PATH, "r") as f: - return json.load(f) From 8b0eed1847abd9d57c54d2099e76dd70515d6f7a Mon Sep 17 00:00:00 2001 From: Vihar Shah Date: Wed, 19 Mar 2025 15:38:40 +0530 Subject: [PATCH 3/5] resolving pylint errors - 1 --- CONTRIBUTING.md | 4 +- shell.sh => pylint-score-check.sh | 12 +++--- requirements.txt | 1 + src/command_registery.py | 68 +++++++++++++++--------------- src/commands/brightness_control.py | 9 ++-- src/commands/current_time.py | 11 ++--- src/commands/fetch_news.py | 18 ++------ src/commands/google_search.py | 15 ++----- src/commands/open_application.py | 28 ++++++++---- src/commands/restart_system.py | 6 +-- src/commands/send_email.py | 68 +++++++++++++++--------------- src/commands/shutdown_system.py | 13 ++++-- src/commands/volume_control.py | 21 ++++----- src/commands/weather_reporter.py | 33 ++++++--------- src/commands/wikipedia_search.py | 18 ++------ src/infra.py | 16 +++---- 16 files changed, 157 insertions(+), 184 deletions(-) rename shell.sh => pylint-score-check.sh (80%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6c3e8ba..3e1f3b9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,10 +36,10 @@ Welcome to the open-source Voice-Assisted Desktop Assistant project! Contributio - commandName - No arguements - the `__name__` field of class as return value - - validateQuery + - validate_query - Single argument - query - Validates query and returns true if query is a match for the action - - executeQuery + - execute_query - Two arguments - query and voice-interface instance - executes the query and announces the result via the voice interface instance ``` diff --git a/shell.sh b/pylint-score-check.sh similarity index 80% rename from shell.sh rename to pylint-score-check.sh index ff1d603..4cb9c37 100644 --- a/shell.sh +++ b/pylint-score-check.sh @@ -1,12 +1,12 @@ # Get the list of changed files and calculate the total pylint score for them -# Setup the project and activate the virtual environment -bash setupProject.sh -source .venv/bin/activate -echo "Active Virtual Environment: ${VIRTUAL_ENV}" +# # Setup the project and activate the virtual environment +# bash setupProject.sh +# source .venv/bin/activate +# echo "Active Virtual Environment: ${VIRTUAL_ENV}" -# get the list of installed python modules -pip freeze +# # get the list of installed python modules +# pip freeze # Get the list of changed files changes="" diff --git a/requirements.txt b/requirements.txt index 942ddb8..c74e6bc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,6 +8,7 @@ pipdeptree~=2.25.0 PyAudio~=0.2.14 PyAutoGUI~=0.9.54 pycaw~=20240210 +pylint~=3.3.5 python-dotenv~=1.0.1 pyttsx3~=2.98 regex~=2024.11.6 diff --git a/src/command_registery.py b/src/command_registery.py index 9e185cc..160dacd 100644 --- a/src/command_registery.py +++ b/src/command_registery.py @@ -28,7 +28,6 @@ from commands.volume_control import VolumeControl from commands.weather_reporter import WeatherReporter from commands.wikipedia_search import WikipediaSearch -from infra import __is_windows from voice_interface import VoiceInterface SUPPORTED_FEATURES = { @@ -39,11 +38,6 @@ "scroll the screen with active cursor", } -########## Conditional Imports ########## -if __is_windows(): - from AppOpener import open as open_app -########## Conditional Imports ########## - ENVIRONMENT_VARIABLES = dotenv_values(".env") @@ -139,17 +133,17 @@ def __init__(self, vi: VoiceInterface) -> None: self.__registery = dict[str, tuple[callable, callable]]() def register_command( - self, command: str, validateQuery: callable, executeQuery: callable + self, command: str, validate_query: callable, execute_query: callable ) -> None: """ Registers a command with the CommandRegistery. Args: command (str): The command string to register. - validateQuery (callable): The function to validate the query for the command. - executeQuery (callable): The function to execute the query for the command. + validate_query (callable): The function to validate the query for the command. + execute_query (callable): The function to execute the query for the command. """ - self.__registery[command] = (validateQuery, executeQuery) + self.__registery[command] = (validate_query, execute_query) def get_executor(self, query: str) -> tuple[str, callable]: """ @@ -161,9 +155,9 @@ def get_executor(self, query: str) -> tuple[str, callable]: Returns: tuple[str, callable]: The command string and the executor function for the query. """ - for command, validateQuery, executeQuery in self.__registery: - if validateQuery.__call__(query): - return command, executeQuery + for command, validate_query, execute_query in self.__registery: + if validate_query(query): + return command, execute_query return None, None def get_command(self, command: str) -> tuple[callable, callable]: @@ -178,51 +172,55 @@ def get_command(self, command: str) -> tuple[callable, callable]: if self.__registery is None: return None, None - self.__registery.get(key=command, default=(None, None)) + return self.__registery.get(key=command, default=(None, None)) INSTANCE = CommandRegistery(VoiceInterface()) INSTANCE.register_command( - GoogleSearch.commandName(), GoogleSearch.validateQuery, GoogleSearch.executeQuery + GoogleSearch.command_name(), GoogleSearch.validate_query, GoogleSearch.execute_query ) INSTANCE.register_command( - WikipediaSearch.commandName(), - WikipediaSearch.validateQuery, - WikipediaSearch.executeQuery, + WikipediaSearch.command_name(), + WikipediaSearch.validate_query, + WikipediaSearch.execute_query, ) INSTANCE.register_command( - OpenApplication.commandName(), - OpenApplication.validateQuery, - OpenApplication.executeQuery, + OpenApplication.command_name(), + OpenApplication.validate_query, + OpenApplication.execute_query, ) INSTANCE.register_command( - CurrentTime.commandName(), CurrentTime.validateQuery, CurrentTime.executeQuery + CurrentTime.command_name(), CurrentTime.validate_query, CurrentTime.execute_query ) INSTANCE.register_command( - BrightnessControl.commandName(), - BrightnessControl.validateQuery, - BrightnessControl.executeQuery, + BrightnessControl.command_name(), + BrightnessControl.validate_query, + BrightnessControl.execute_query, ) INSTANCE.register_command( - VolumeControl.commandName(), VolumeControl.validateQuery, VolumeControl.executeQuery + VolumeControl.command_name(), + VolumeControl.validate_query, + VolumeControl.execute_query, ) INSTANCE.register_command( - ShutdownSystem.commandName(), - ShutdownSystem.validateQuery, - ShutdownSystem.executeQuery, + ShutdownSystem.command_name(), + ShutdownSystem.validate_query, + ShutdownSystem.execute_query, ) INSTANCE.register_command( - RestartSystem.commandName(), RestartSystem.validateQuery, RestartSystem.executeQuery + RestartSystem.command_name(), + RestartSystem.validate_query, + RestartSystem.execute_query, ) INSTANCE.register_command( - WeatherReporter.commandName(), - WeatherReporter.validateQuery, - WeatherReporter.executeQuery, + WeatherReporter.command_name(), + WeatherReporter.validate_query, + WeatherReporter.execute_query, ) INSTANCE.register_command( - FetchNews.commandName(), FetchNews.validateQuery, FetchNews.executeQuery + FetchNews.command_name(), FetchNews.validate_query, FetchNews.execute_query ) INSTANCE.register_command( - SendEmail.commandName(), SendEmail.validateQuery, SendEmail.executeQuery + SendEmail.command_name(), SendEmail.validate_query, SendEmail.execute_query ) diff --git a/src/commands/brightness_control.py b/src/commands/brightness_control.py index 0b884e0..5a5bc90 100644 --- a/src/commands/brightness_control.py +++ b/src/commands/brightness_control.py @@ -8,15 +8,15 @@ class BrightnessControl: @staticmethod - def commandName() -> str: + def command_name() -> str: return BrightnessControl.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return "brightness" in query @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: + def execute_query(query: str, vi: VoiceInterface) -> None: query = query.lower() value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) @@ -41,7 +41,8 @@ def brightness_control(value: int, relative: bool, toDecrease: bool): relative (bool): If True, the brightness change is relative to the current brightness. If False, the brightness is set to the specified value. toDecrease (bool): If True, decreases the brightness by the specified value. - If False, increases the brightness by the specified value. Only applicable when `relative` is True. + If False, increases the brightness by the specified value. + Only applicable when `relative` is True. Raises: RuntimeError: If there is an issue with accessing the brightness control methods. diff --git a/src/commands/current_time.py b/src/commands/current_time.py index 9b3d678..3bba4aa 100644 --- a/src/commands/current_time.py +++ b/src/commands/current_time.py @@ -4,22 +4,17 @@ class CurrentTime: - """Tells the time of the day with timezone""" @staticmethod - def commandName() -> str: + def command_name() -> str: return CurrentTime.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return any(text in query for text in ["the time", "time please"]) @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: - """ - Args: - vi (VoiceInterface): Voice interface instance used to speak - """ + def execute_query(_: str, vi: VoiceInterface) -> None: date_time = datetime.now() hour, minute, second = date_time.hour, date_time.minute, date_time.second tmz = date_time.tzname() diff --git a/src/commands/fetch_news.py b/src/commands/fetch_news.py index 4d16769..51f664c 100644 --- a/src/commands/fetch_news.py +++ b/src/commands/fetch_news.py @@ -4,32 +4,20 @@ class FetchNews: - """ - Fetches and reads out the top 5 headlines from the Google News RSS feed. - - This function fetches news headlines from the Google News RSS feed (specific to India in English). - It then reads out the top 5 headlines using the provided VoiceInterface instance. If the feed fetch is successful, - it reads the headlines one by one. If the fetch fails, it informs the user that the news couldn't be fetched. - - Raises: - requests.exceptions.RequestException: If there is an issue while fetching the RSS feed. - AttributeError: If the feed does not contain expected attributes or entries. - """ - # Maximum number of news headlines to fetch when news function is called MAX_FETCHED_HEADLINES = 10 FEED_URL = "https://news.google.com/rss?hl=en-IN&gl=IN&ceid=IN:en" @staticmethod - def commandName() -> str: + def command_name() -> str: return FetchNews.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return "news" in query @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: + def execute_query(query: str, vi: VoiceInterface) -> None: vi.speak("Fetching news from servers.") feed = feedparser.parse(FetchNews.FEED_URL) if feed.status == 200: diff --git a/src/commands/google_search.py b/src/commands/google_search.py index 5a5a1d3..6014826 100644 --- a/src/commands/google_search.py +++ b/src/commands/google_search.py @@ -6,26 +6,17 @@ class GoogleSearch: - """Performs google search based on some terms""" @staticmethod - def commandName() -> str: + def command_name() -> str: return GoogleSearch.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return re.search(r"search .* (in google)?", query) @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: - """ - Args: - search_query (str): the query term to be searched in google - """ - if not GoogleSearch.validQuery(query): - vi.speak("Invalid Google Search Query Found!!") - return - + def execute_query(query: str, vi: VoiceInterface) -> None: search_query = re.findall(r"search (.*)", query.replace("in google", ""))[0] results = googlesearch.search(term=search_query) if not results: diff --git a/src/commands/open_application.py b/src/commands/open_application.py index 76d75dc..32e65bb 100644 --- a/src/commands/open_application.py +++ b/src/commands/open_application.py @@ -1,8 +1,20 @@ +""" +This module provides functionality to handle voice commands for opening applications or websites. +It includes the `OpenApplication` class, which validates and executes user queries to open +applications, and helper functions to handle platform-specific operations for opening applications +or websites. + +Classes: + OpenApplication: + - Handles voice commands for opening applications. + - Validates queries and executes commands to open specified applications. +""" + import re import subprocess from subprocess import CalledProcessError, TimeoutExpired -from AppOpener import open_app +from AppOpener import open as open_app import infra from voice_interface import VoiceInterface @@ -11,15 +23,15 @@ class OpenApplication: @staticmethod - def commandName() -> str: + def command_name() -> str: return OpenApplication.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return re.search("open .*", query) @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: + def execute_query(query: str, vi: VoiceInterface) -> None: application = re.findall(r"open (.*)", query) if len(application) == 0: vi.speak("Which Application Should I Open ?") @@ -50,14 +62,14 @@ def open_application_website(vi: VoiceInterface, search_query: str) -> None: search_query = search_query.strip().lower() # use appopener to open the application only if os is windows - if infra.__is_windows(): + if infra.is_windows(): __open_application_website_windows(vi, search_query) - if infra.__is_darwin(): + if infra.is_darwin(): __open_application_website_darwin(vi, search_query) - elif infra.__is_posix(): + elif infra.is_posix(): __open_application_website_posix(vi, search_query) else: - raise ValueError(f"Unsupported OS: {infra.__system_os()}") + raise ValueError(f"Unsupported OS: {infra.system_os()}") def __open_application_website_windows(vi: VoiceInterface, search_query: str) -> None: diff --git a/src/commands/restart_system.py b/src/commands/restart_system.py index c14243d..e15ed85 100644 --- a/src/commands/restart_system.py +++ b/src/commands/restart_system.py @@ -6,13 +6,13 @@ class RestartSystem: @staticmethod - def commandName(): + def command_name(): return RestartSystem.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return any(text in query for text in ["restart"]) @staticmethod - def executeQuery(query: str, vi: VoiceInterface): + def execute_query(query: str, vi: VoiceInterface): subprocess.run(["shutdown", "/r", "/t", "1"]) diff --git a/src/commands/send_email.py b/src/commands/send_email.py index 7c0293d..f89d150 100644 --- a/src/commands/send_email.py +++ b/src/commands/send_email.py @@ -8,56 +8,56 @@ from infra import listen, load_json_config from voice_interface import VoiceInterface -CONFIG_FILE = "mail_server.json" -SERVER = "server" -PORT = "port" -EMAIL_CONTACTS = "contacts" -SENDER = "username" -SMTP_PASS = "SMTP_PASSWORD" +__CONFIG_FILE__ = "mail_server.json" +__SERVER__ = "server" +__PORT__ = "port" +__EMAIL_CONTACTS__ = "contacts" +__SENDER__ = "username" +__SMTP_PASS__ = "SMTP_PASSWORD" -ENV = dotenv_values(".env") +__ENV__ = dotenv_values(".env") class SendEmail: @staticmethod - def commandName() -> str: + def command_name() -> str: return SendEmail.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return "email" in query @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: + def execute_query(query: str, vi: VoiceInterface) -> None: query = query.lower() - data = load_json_config(CONFIG_FILE) + data = load_json_config(__CONFIG_FILE__) - server = data.get(SERVER) - port = data.get(PORT) - sender = data.get(SENDER) - contacts = data.get(EMAIL_CONTACTS) + server = data.get(__SERVER__) + port = data.get(__PORT__) + sender = data.get(__SENDER__) + contacts = data.get(__EMAIL_CONTACTS__) if data.get("server") is None: vi.speak("Please setup email config file before sending mail.") else: vi.speak("who do you want to send email to?") receiver = None - validEmail = False - maxAttempts = 3 - while not validEmail and maxAttempts > 0: - maxAttempts -= 1 + valid_email = False + max_attempts = 3 + while not valid_email and max_attempts > 0: + max_attempts -= 1 receiver = listen(vi).strip() if receiver in contacts.keys(): print(f"Receiver selected from contacts: {contacts.get(receiver)}") receiver = contacts.get(receiver) - validEmail = True + valid_email = True elif re.match( r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", receiver ): - validEmail = True + valid_email = True else: vi.speak("Valid Email not provided or contact does not exists") @@ -66,9 +66,9 @@ def executeQuery(query: str, vi: VoiceInterface) -> None: vi.speak("What would be the body of the email?") body = None - maxAttemptsForBody = 3 - while body is None and maxAttemptsForBody > 0: - maxAttemptsForBody -= 1 + max_attempts_for_body = 3 + while body is None and max_attempts_for_body > 0: + max_attempts_for_body -= 1 body = listen(vi) print( @@ -93,12 +93,12 @@ def executeQuery(query: str, vi: VoiceInterface) -> None: @staticmethod def __send_email( vi: VoiceInterface, - server: str, - port: str, - fromEmail: str, - toEmail: str, - subject: str, - body: str, + server: str = None, + port: str = None, + from_email: str = None, + to_email: str = None, + subject: str = None, + body: str = None, ): """ Send an email to the specified recipient. @@ -116,11 +116,11 @@ def __send_email( context = ssl.create_default_context() msg = EmailMessage() msg["Subject"] = subject - msg["From"] = fromEmail - msg["To"] = [toEmail] + msg["From"] = from_email + msg["To"] = [to_email] msg.set_content(body) server = smtplib.SMTP_SSL(server, port, context=context) - server.login(fromEmail, ENV.get(SMTP_PASS)) + server.login(from_email, __ENV__.get(__SMTP_PASS__)) server.send_message(msg) server.quit() - vi.speak(f"Email sent to {toEmail}") + vi.speak(f"Email sent to {to_email}") diff --git a/src/commands/shutdown_system.py b/src/commands/shutdown_system.py index 1aa9979..fffab50 100644 --- a/src/commands/shutdown_system.py +++ b/src/commands/shutdown_system.py @@ -1,3 +1,10 @@ +""" +This module defines the `ShutdownSystem` class, which provides functionality to handle system shutdown commands. +It includes methods to validate user queries for shutdown-related keywords and execute the shutdown command. +Classes: + ShutdownSystem: A class to validate and execute system shutdown commands. +""" + import subprocess from voice_interface import VoiceInterface @@ -6,13 +13,13 @@ class ShutdownSystem: @staticmethod - def commandName(): + def command_name(): return ShutdownSystem.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return any(text in query for text in ["shutdown", "shut down"]) @staticmethod - def executeQuery(query: str, vi: VoiceInterface): + def execute_query(query: str, vi: VoiceInterface): subprocess.run(["shutdown", "-s", "/t", "1"]) diff --git a/src/commands/volume_control.py b/src/commands/volume_control.py index 8420bf4..0ee5c0a 100644 --- a/src/commands/volume_control.py +++ b/src/commands/volume_control.py @@ -9,31 +9,31 @@ class VolumeControl: @staticmethod - def commandName() -> str: + def command_name() -> str: return VolumeControl.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return any(text in query for text in ["volume", "sound"]) @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: + def execute_query(query: str, vi: VoiceInterface) -> None: query = query.lower() value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) - if len(value) == 0 or str(value).isnumeric() == False: + if len(value) == 0 or not str(value).isnumeric(): vi.speak("Please provide a value or input is out of range") else: value = min(max(0, int(value[0])), 100) if "set" in query: volume_control(value, False, False) else: - toDecrease = "decrease" in query or "reduce" in query + to_decrease = "decrease" in query or "reduce" in query relative = "by" in query - volume_control(value, relative, toDecrease) + volume_control(value, relative, to_decrease) -def volume_control(value: int, relative: bool, toDecrease: bool): +def volume_control(value: int, relative: bool, to_decrease: bool): """ Adjusts the master volume of the system. @@ -41,8 +41,9 @@ def volume_control(value: int, relative: bool, toDecrease: bool): value (int): The volume level to set or adjust by. Should be between 0 and 100. relative (bool): If True, the volume change is relative to the current volume. If False, the volume is set to the specified value. - toDecrease (bool): If True, decreases the volume by the specified value. - If False, increases the volume by the specified value. Only applicable when `relative` is True. + to_decrease (bool): If True, decreases the volume by the specified value. + If False, increases the volume by the specified value. + Only applicable when `relative` is True. Raises: RuntimeError: If there is an issue with accessing the audio endpoint. @@ -58,7 +59,7 @@ def volume_control(value: int, relative: bool, toDecrease: bool): if relative: current_volume = volume.GetMasterVolumeLevelScalar() * 100 set_volume = ( - current_volume - int(value) if toDecrease else current_volume + int(value) + current_volume - int(value) if to_decrease else current_volume + int(value) ) print(set_volume) volume.SetMasterVolumeLevelScalar(min(max(0, set_volume), 100) / 100, None) diff --git a/src/commands/weather_reporter.py b/src/commands/weather_reporter.py index 6b1832c..e58bec7 100644 --- a/src/commands/weather_reporter.py +++ b/src/commands/weather_reporter.py @@ -8,37 +8,21 @@ class WeatherReporter: @staticmethod - def commandName() -> str: + def command_name() -> str: return WeatherReporter.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return "weather" in query @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: + def execute_query(query: str, vi: VoiceInterface) -> None: # Extract the city name just after the word 'of' cities = re.findall(r"\b(?:of|in|at)\s+(\w+)", query) weather_reporter(vi, cities[0]) def weather_reporter(vi: VoiceInterface, city_name: str) -> None: - """ - Fetches and reports the weather conditions for a given city. - - Retrieve the latitude and longitude of the specified city using the API Ninjas City API. - Then fetch the current weather data from the Open-Meteo API and then report the temperature, humidity, - apparent temperature, rain probability, cloud cover, and wind speed - - Args: - vi (VoiceInterface): The VoiceInterface instance used to speak the weather report. - city_name (str): The name of the city for which to fetch weather data. - - Raises: - requests.exceptions.RequestException: If there is an issue with the API request. - IndexError: If the city name is not found in the API response. - KeyError: If expected weather data fields are missing from the response. - """ # Fetch latitude and longitude for the given city to be used by open-metro api params = { "name": city_name, @@ -49,9 +33,16 @@ def weather_reporter(vi: VoiceInterface, city_name: str) -> None: headers={"origin": "https://www.api-ninjas.com"}, ).json() - # Fetch weather data from Open-Meteo using the obtained coordinates + query_params = { + "latitude": geo_codes[0].get("latitude"), + "longitude": geo_codes[0].get("longitude"), + "current": "temperature_2m,relative_humidity_2m,apparent_temperature,rain,showers,cloud_cover,wind_speed_10m", + "forecast_days": 1, + } + + # Fetch weather data from Open-Meteo using the obtained coordinates. Time out after 60 seeconds of no response weather_data_response = requests.get( - f'https://api.open-meteo.com/v1/forecast?latitude={geo_codes[0].get("latitude")}&longitude={geo_codes[0].get("longitude")}¤t=temperature_2m,relative_humidity_2m,apparent_temperature,rain,showers,cloud_cover,wind_speed_10m&forecast_days=1' + "https://api.open-meteo.com/v1/forecast", params=query_params, timeout=60 ).json() weather_data = weather_data_response.get("current") diff --git a/src/commands/wikipedia_search.py b/src/commands/wikipedia_search.py index cd4415c..7a2c6c4 100644 --- a/src/commands/wikipedia_search.py +++ b/src/commands/wikipedia_search.py @@ -4,31 +4,19 @@ class WikipediaSearch: - """Searches wikipedia for the given query and returns fixed number of statements in response. - Disambiguation Error due to multiple similar results is handled. - Speaks the options in this case. - """ sentence_count = 3 @staticmethod - def commandName() -> str: + def command_name() -> str: return WikipediaSearch.__name__ @staticmethod - def validateQuery(query: str) -> bool: + def validate_query(query: str) -> bool: return "wikipedia" in query @staticmethod - def executeQuery(query: str, vi: VoiceInterface) -> None: - """ - Args: - search_query (str): the query term to be searched in google - """ - if not WikipediaSearch.validQuery(query): - vi.speak("Invalid Wikipedia Search Query Found!!") - return - + def execute_query(query: str, vi: VoiceInterface) -> None: search_query = query.replace("wikipedia", "", 1).replace("search", "", 1) try: vi.speak("Searching Wikipedia...") diff --git a/src/infra.py b/src/infra.py index 12dc435..28b85c4 100644 --- a/src/infra.py +++ b/src/infra.py @@ -17,29 +17,29 @@ __CONFIG_DIR = os.path.join(os.path.abspath(__file__), "config") -def __is_windows() -> bool: +def is_windows() -> bool: """Returns True if the operating system is Windows""" return sys.platform in ["win32", "cygwin"] -def __is_darwin() -> bool: +def is_darwin() -> bool: """Returns True if the operating system is Darwin""" return sys.platform in ["darwin", "ios"] -def __is_posix() -> bool: +def is_posix() -> bool: """Returns True if the operating system is POSIX""" return sys.platform in ["aix", "android", "emscripten", "linux", "darwin", "wasi"] -def __system_os() -> str: +def system_os() -> str: """Returns the name of the operating system""" return sys.platform def clear_screen() -> None: """Clears the screen based on the operating system""" - if __is_windows(): + if is_windows(): os.system("cls") else: os.system("clear") @@ -53,7 +53,7 @@ def listen(vi: VoiceInterface) -> str: """ query = vi.listen(True) if query: - print(f"User:") + print("User:") vi.speak(query) else: vi.speak("Say that again please...") @@ -72,7 +72,7 @@ def load_json_config(config_path: str) -> dict: file_path = os.path.join(__CONFIG_DIR, config_path) if not os.path.isfile(file_path): - return dict() + return {} - with open(config_path, "r") as json_doc: + with open(config_path, "r", encoding="UTF-8") as json_doc: return json.load(json_doc) From 4c2fbde138bfc1dccf023ee1ba6a10b8b6fdeb1a Mon Sep 17 00:00:00 2001 From: Vihar Shah Date: Sun, 23 Mar 2025 18:06:28 +0530 Subject: [PATCH 4/5] pylint fixes --- pylintrc | 649 +++++++++++++++++++++++++++++ src/commands/brightness_control.py | 12 +- src/commands/fetch_news.py | 2 +- src/commands/open_application.py | 12 - src/commands/restart_system.py | 6 +- src/commands/send_email.py | 12 +- src/commands/shutdown_system.py | 13 +- src/commands/weather_reporter.py | 26 +- 8 files changed, 678 insertions(+), 54 deletions(-) create mode 100644 pylintrc diff --git a/pylintrc b/pylintrc new file mode 100644 index 0000000..611eedc --- /dev/null +++ b/pylintrc @@ -0,0 +1,649 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked and +# will not be imported (useful for modules/projects where namespaces are +# manipulated during runtime and thus existing member attributes cannot be +# deduced by static analysis). It supports qualified module names, as well as +# Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Resolve imports to .pyi stubs if available. May reduce no-member messages and +# increase not-an-iterable messages. +prefer-stubs=no + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.13 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=.* + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of positional arguments for function / method. +max-positional-arguments=5 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero, + missing-module-docstring, + line-too-long + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + +# Let 'consider-using-join' be raised when the separator to join on would be +# non-empty (resulting in expected fixes of the type: ``"- " + " - +# ".join(items)``) +suggest-join-with-non-empty-separator=yes + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are: text, parseable, colorized, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/src/commands/brightness_control.py b/src/commands/brightness_control.py index 5a5bc90..db5baed 100644 --- a/src/commands/brightness_control.py +++ b/src/commands/brightness_control.py @@ -20,19 +20,19 @@ def execute_query(query: str, vi: VoiceInterface) -> None: query = query.lower() value = re.findall(r"\b(100|[1-9]?[0-9])\b", query) - if len(value) == 0 or str(value).isnumeric() == False: + if len(value) == 0 or not str(value).isnumeric(): vi.speak("Please provide a valid brightness value between 0 and 100") else: value = min(max(0, int(value[0])), 100) if "set" in query: brightness_control(value, False, False) else: - toDecrease = "decrease" in query or "reduce" in query + to_decrease = "decrease" in query or "reduce" in query relative = "by" in query - brightness_control(value, relative, toDecrease) + brightness_control(value, relative, to_decrease) -def brightness_control(value: int, relative: bool, toDecrease: bool): +def brightness_control(value: int, relative: bool, to_decrease: bool): """ Adjusts the brightness of the monitor. @@ -40,7 +40,7 @@ def brightness_control(value: int, relative: bool, toDecrease: bool): value (int): The brightness level to set or adjust by. Should be between 0 and 100. relative (bool): If True, the brightness change is relative to the current brightness. If False, the brightness is set to the specified value. - toDecrease (bool): If True, decreases the brightness by the specified value. + to_decrease (bool): If True, decreases the brightness by the specified value. If False, increases the brightness by the specified value. Only applicable when `relative` is True. @@ -58,7 +58,7 @@ def brightness_control(value: int, relative: bool, toDecrease: bool): current_brightness = brightness_ctrl.WmiMonitorBrightness()[0].CurrentBrightness set_brightness = ( current_brightness - int(value) - if toDecrease + if to_decrease else current_brightness + int(value) ) methods.WmiSetBrightness(set_brightness, 0) diff --git a/src/commands/fetch_news.py b/src/commands/fetch_news.py index 51f664c..357cb8b 100644 --- a/src/commands/fetch_news.py +++ b/src/commands/fetch_news.py @@ -17,7 +17,7 @@ def validate_query(query: str) -> bool: return "news" in query @staticmethod - def execute_query(query: str, vi: VoiceInterface) -> None: + def execute_query(_: str, vi: VoiceInterface) -> None: vi.speak("Fetching news from servers.") feed = feedparser.parse(FetchNews.FEED_URL) if feed.status == 200: diff --git a/src/commands/open_application.py b/src/commands/open_application.py index 32e65bb..a490320 100644 --- a/src/commands/open_application.py +++ b/src/commands/open_application.py @@ -1,15 +1,3 @@ -""" -This module provides functionality to handle voice commands for opening applications or websites. -It includes the `OpenApplication` class, which validates and executes user queries to open -applications, and helper functions to handle platform-specific operations for opening applications -or websites. - -Classes: - OpenApplication: - - Handles voice commands for opening applications. - - Validates queries and executes commands to open specified applications. -""" - import re import subprocess from subprocess import CalledProcessError, TimeoutExpired diff --git a/src/commands/restart_system.py b/src/commands/restart_system.py index e15ed85..d126828 100644 --- a/src/commands/restart_system.py +++ b/src/commands/restart_system.py @@ -1,7 +1,5 @@ import subprocess -from voice_interface import VoiceInterface - class RestartSystem: @@ -14,5 +12,5 @@ def validate_query(query: str) -> bool: return any(text in query for text in ["restart"]) @staticmethod - def execute_query(query: str, vi: VoiceInterface): - subprocess.run(["shutdown", "/r", "/t", "1"]) + def execute_query(*_): + subprocess.run(["shutdown", "/r", "/t", "1"], check=True) diff --git a/src/commands/send_email.py b/src/commands/send_email.py index f89d150..3cec180 100644 --- a/src/commands/send_email.py +++ b/src/commands/send_email.py @@ -91,15 +91,7 @@ def execute_query(query: str, vi: VoiceInterface) -> None: vi.speak("Request aborted by user") @staticmethod - def __send_email( - vi: VoiceInterface, - server: str = None, - port: str = None, - from_email: str = None, - to_email: str = None, - subject: str = None, - body: str = None, - ): + def __send_email(*args): """ Send an email to the specified recipient. @@ -113,6 +105,8 @@ def __send_email( ValueError: If any required parameters are missing or invalid. """ + vi, server, port, from_email, to_email, subject, body = args + context = ssl.create_default_context() msg = EmailMessage() msg["Subject"] = subject diff --git a/src/commands/shutdown_system.py b/src/commands/shutdown_system.py index fffab50..f5c72df 100644 --- a/src/commands/shutdown_system.py +++ b/src/commands/shutdown_system.py @@ -1,14 +1,5 @@ -""" -This module defines the `ShutdownSystem` class, which provides functionality to handle system shutdown commands. -It includes methods to validate user queries for shutdown-related keywords and execute the shutdown command. -Classes: - ShutdownSystem: A class to validate and execute system shutdown commands. -""" - import subprocess -from voice_interface import VoiceInterface - class ShutdownSystem: @@ -21,5 +12,5 @@ def validate_query(query: str) -> bool: return any(text in query for text in ["shutdown", "shut down"]) @staticmethod - def execute_query(query: str, vi: VoiceInterface): - subprocess.run(["shutdown", "-s", "/t", "1"]) + def execute_query(*_): + subprocess.run(["shutdown", "-s", "/t", "1"], check=True) diff --git a/src/commands/weather_reporter.py b/src/commands/weather_reporter.py index e58bec7..74e6dff 100644 --- a/src/commands/weather_reporter.py +++ b/src/commands/weather_reporter.py @@ -31,6 +31,7 @@ def weather_reporter(vi: VoiceInterface, city_name: str) -> None: "https://api.api-ninjas.com/v1/city", params=params, headers={"origin": "https://www.api-ninjas.com"}, + timeout=60, # 60 second timeout ).json() query_params = { @@ -40,30 +41,33 @@ def weather_reporter(vi: VoiceInterface, city_name: str) -> None: "forecast_days": 1, } - # Fetch weather data from Open-Meteo using the obtained coordinates. Time out after 60 seeconds of no response + # Fetch weather data from Open-Meteo using the obtained coordinates. + # Time out after 60 seeconds of no response weather_data_response = requests.get( "https://api.open-meteo.com/v1/forecast", params=query_params, timeout=60 ).json() - weather_data = weather_data_response.get("current") - weather_units = weather_data_response.get("current_units") + data = weather_data_response.get("current") + unit = weather_data_response.get("current_units") vi.speak( - f"The current temperature in {city_name} is {weather_data.get('temperature_2m')}{weather_units.get('temperature_2m')}. " - f"However, due to a relative humidity of {weather_data.get('relative_humidity_2m')}{weather_units.get('relative_humidity_2m')}, " - f"it feels like {weather_data.get('apparent_temperature')}{weather_units.get('apparent_temperature')}." + f"The current temperature in {city_name} is {data.get('temperature_2m')}{unit.get('temperature_2m')}. " + f"However, due to a relative humidity of {data.get('relative_humidity_2m')}{unit.get('relative_humidity_2m')}, " + f"it feels like {data.get('apparent_temperature')}{unit.get('apparent_temperature')}." ) - if weather_data.get("rain") == 0: + if data.get("rain") == 0: vi.speak("The skies will be clear, with no chance of rain.") else: - cloud_cover = weather_data.get("cloud_cover") + cloud_cover = data.get("cloud_cover") vi.speak( - f"The sky will be {cloud_cover}{weather_units.get('cloud_cover')} cloudy, " - f"and there's a predicted rainfall of {weather_data.get('rain')}{weather_units.get('rain')}." + f"The sky will be {cloud_cover}{unit.get('cloud_cover')} cloudy, " + f"and there's a predicted rainfall of {data.get('rain')}{unit.get('rain')}." ) + wind_speed_mag = data.get("wind_speed_10m") + wind_speed_unit = unit.get("wind_speed_10m") vi.speak( - f"The wind speed is expected to be {weather_data.get('wind_speed_10m')}{weather_units.get('wind_speed_10m')}, " + f"The wind speed is expected to be {wind_speed_mag}{wind_speed_unit}, " "so plan accordingly." ) From ca2cd260a5ec7d587817bf840c78e70338a55600 Mon Sep 17 00:00:00 2001 From: Vihar Shah Date: Sun, 23 Mar 2025 23:03:38 +0530 Subject: [PATCH 5/5] pylint score check fix --- .github/workflows/pylint-checks.yaml | 2 +- pylint-score-check.sh | 40 ++++++++++++++-------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/.github/workflows/pylint-checks.yaml b/.github/workflows/pylint-checks.yaml index 5bea921..52c0424 100644 --- a/.github/workflows/pylint-checks.yaml +++ b/.github/workflows/pylint-checks.yaml @@ -58,7 +58,7 @@ jobs: # Run pylint on the changed files and capture the score { # try - pylint_score=$(pylint $changed_files | grep 'Your code has been rated at' | awk '{print $7}' | cut -d '/' -f 1) + pylint_score=$(pylint --rcfile pylintrc $changed_files | grep 'Your code has been rated at' | awk '{print $7}' | cut -d '/' -f 1) } || { # catch echo "Pylint failed to run with exit code: $?" } diff --git a/pylint-score-check.sh b/pylint-score-check.sh index 4cb9c37..3409697 100644 --- a/pylint-score-check.sh +++ b/pylint-score-check.sh @@ -1,41 +1,41 @@ # Get the list of changed files and calculate the total pylint score for them -# # Setup the project and activate the virtual environment -# bash setupProject.sh -# source .venv/bin/activate -# echo "Active Virtual Environment: ${VIRTUAL_ENV}" - -# # get the list of installed python modules -# pip freeze - # Get the list of changed files -changes="" +{ # try +changes=$(git diff --name-only HEAD main | grep '\.py$') +} || { # catch +if [ $? -eq 1 ]; then + echo "No python file changes found in the pull request." + exit 0 +fi +} +echo -e "changes:\n$changes\n" # Make sure to include only the files that exist changed_files="" for file in $changes; do - if [ -f "$file" ]; then - changed_files="$changed_files $file" - fi +if [ -f "$file" ]; then + changed_files="$changed_files $file" +fi done -echo "Changed existing files: $changed_files" +echo -e "Changed existing files:\n$changed_files\n" # Check if there are any changed Python files if [ -z "$changed_files" ]; then - echo "No Python files changed." - exit 0 +echo "No Python files changed." +exit 0 fi # Run pylint on the changed files and capture the score { # try - pylint_score=$(pylint $changed_files | grep 'Your code has been rated at' | awk '{print $7}' | cut -d '/' -f 1) +pylint_score=$(pylint $changed_files | grep 'Your code has been rated at' | awk '{print $7}' | cut -d '/' -f 1) } || { # catch - echo "Pylint failed to run with exit code: $?" +echo "Pylint failed to run with exit code: $?" } # Check if the score is below 9 if (( $(echo "$pylint_score < 9" | bc -l) )); then - echo "Pylint score is below 9: $pylint_score" - exit 1 +echo "Pylint score is below 9: $pylint_score" +exit 1 else - echo "Pylint score is acceptable: $pylint_score" +echo "Pylint score is acceptable: $pylint_score" fi \ No newline at end of file