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/.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/CONTRIBUTING.md b/CONTRIBUTING.md index c1c7b91..3e1f3b9 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 + - validate_query + - Single argument - query + - Validates query and returns true if query is a match for the action + - execute_query + - 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/pylint-score-check.sh b/pylint-score-check.sh new file mode 100644 index 0000000..3409697 --- /dev/null +++ b/pylint-score-check.sh @@ -0,0 +1,41 @@ +# Get the list of changed files and calculate the total pylint score for them + +# Get the list of changed files +{ # 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 +done +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 +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) +} || { # catch +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 +else +echo "Pylint score is acceptable: $pylint_score" +fi \ No newline at end of file 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/requirements.txt b/requirements.txt index c25bee3..c74e6bc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,51 +1,17 @@ -# -# 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 +pylint~=3.3.5 +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/shell.sh b/shell.sh deleted file mode 100644 index ff1d603..0000000 --- a/shell.sh +++ /dev/null @@ -1,41 +0,0 @@ -# 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="" - -# 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 -done -echo "Changed existing files: $changed_files" - -# Check if there are any changed Python files -if [ -z "$changed_files" ]; then - 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) -} || { # catch - 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 -else - echo "Pylint score is acceptable: $pylint_score" -fi \ No newline at end of file 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..160dacd --- /dev/null +++ b/src/command_registery.py @@ -0,0 +1,226 @@ +#!/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 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", +} + +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, validate_query: callable, execute_query: callable + ) -> None: + """ + Registers a command with the CommandRegistery. + + Args: + command (str): The command string to register. + 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] = (validate_query, execute_query) + + 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, 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]: + """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 + + return self.__registery.get(key=command, default=(None, None)) + + +INSTANCE = CommandRegistery(VoiceInterface()) + +INSTANCE.register_command( + GoogleSearch.command_name(), GoogleSearch.validate_query, GoogleSearch.execute_query +) +INSTANCE.register_command( + WikipediaSearch.command_name(), + WikipediaSearch.validate_query, + WikipediaSearch.execute_query, +) +INSTANCE.register_command( + OpenApplication.command_name(), + OpenApplication.validate_query, + OpenApplication.execute_query, +) +INSTANCE.register_command( + CurrentTime.command_name(), CurrentTime.validate_query, CurrentTime.execute_query +) +INSTANCE.register_command( + BrightnessControl.command_name(), + BrightnessControl.validate_query, + BrightnessControl.execute_query, +) +INSTANCE.register_command( + VolumeControl.command_name(), + VolumeControl.validate_query, + VolumeControl.execute_query, +) +INSTANCE.register_command( + ShutdownSystem.command_name(), + ShutdownSystem.validate_query, + ShutdownSystem.execute_query, +) +INSTANCE.register_command( + RestartSystem.command_name(), + RestartSystem.validate_query, + RestartSystem.execute_query, +) +INSTANCE.register_command( + WeatherReporter.command_name(), + WeatherReporter.validate_query, + WeatherReporter.execute_query, +) +INSTANCE.register_command( + FetchNews.command_name(), FetchNews.validate_query, FetchNews.execute_query +) +INSTANCE.register_command( + SendEmail.command_name(), SendEmail.validate_query, SendEmail.execute_query +) 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..db5baed --- /dev/null +++ b/src/commands/brightness_control.py @@ -0,0 +1,66 @@ +import re + +import wmi + +from voice_interface import VoiceInterface + + +class BrightnessControl: + + @staticmethod + def command_name() -> str: + return BrightnessControl.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return "brightness" in query + + @staticmethod + 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 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: + to_decrease = "decrease" in query or "reduce" in query + relative = "by" in query + brightness_control(value, relative, to_decrease) + + +def brightness_control(value: int, relative: bool, to_decrease: 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. + 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. + + 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 to_decrease + 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..3bba4aa --- /dev/null +++ b/src/commands/current_time.py @@ -0,0 +1,22 @@ +from datetime import datetime + +from voice_interface import VoiceInterface + + +class CurrentTime: + + @staticmethod + def command_name() -> str: + return CurrentTime.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return any(text in query for text in ["the time", "time please"]) + + @staticmethod + 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() + + 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..357cb8b --- /dev/null +++ b/src/commands/fetch_news.py @@ -0,0 +1,31 @@ +import feedparser + +from voice_interface import VoiceInterface + + +class FetchNews: + # 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 command_name() -> str: + return FetchNews.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return "news" in query + + @staticmethod + def execute_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..6014826 --- /dev/null +++ b/src/commands/google_search.py @@ -0,0 +1,26 @@ +import re + +import googlesearch + +from voice_interface import VoiceInterface + + +class GoogleSearch: + + @staticmethod + def command_name() -> str: + return GoogleSearch.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return re.search(r"search .* (in google)?", query) + + @staticmethod + 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: + 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..a490320 --- /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 as open_app + +import infra +from voice_interface import VoiceInterface + + +class OpenApplication: + + @staticmethod + def command_name() -> str: + return OpenApplication.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return re.search("open .*", query) + + @staticmethod + 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 ?") + 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..d126828 --- /dev/null +++ b/src/commands/restart_system.py @@ -0,0 +1,16 @@ +import subprocess + + +class RestartSystem: + + @staticmethod + def command_name(): + return RestartSystem.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return any(text in query for text in ["restart"]) + + @staticmethod + 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 new file mode 100644 index 0000000..3cec180 --- /dev/null +++ b/src/commands/send_email.py @@ -0,0 +1,120 @@ +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 command_name() -> str: + return SendEmail.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return "email" in query + + @staticmethod + def execute_query(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 + 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) + valid_email = True + elif re.match( + r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", receiver + ): + valid_email = 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 + max_attempts_for_body = 3 + while body is None and max_attempts_for_body > 0: + max_attempts_for_body -= 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(*args): + """ + 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. + """ + + vi, server, port, from_email, to_email, subject, body = args + + context = ssl.create_default_context() + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = from_email + msg["To"] = [to_email] + msg.set_content(body) + server = smtplib.SMTP_SSL(server, port, context=context) + server.login(from_email, __ENV__.get(__SMTP_PASS__)) + server.send_message(msg) + server.quit() + vi.speak(f"Email sent to {to_email}") diff --git a/src/commands/shutdown_system.py b/src/commands/shutdown_system.py new file mode 100644 index 0000000..f5c72df --- /dev/null +++ b/src/commands/shutdown_system.py @@ -0,0 +1,16 @@ +import subprocess + + +class ShutdownSystem: + + @staticmethod + def command_name(): + return ShutdownSystem.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return any(text in query for text in ["shutdown", "shut down"]) + + @staticmethod + def execute_query(*_): + subprocess.run(["shutdown", "-s", "/t", "1"], check=True) diff --git a/src/commands/volume_control.py b/src/commands/volume_control.py new file mode 100644 index 0000000..0ee5c0a --- /dev/null +++ b/src/commands/volume_control.py @@ -0,0 +1,67 @@ +import re + +from comtypes import CLSCTX_ALL +from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume + +from voice_interface import VoiceInterface + + +class VolumeControl: + + @staticmethod + def command_name() -> str: + return VolumeControl.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return any(text in query for text in ["volume", "sound"]) + + @staticmethod + 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 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: + to_decrease = "decrease" in query or "reduce" in query + relative = "by" in query + volume_control(value, relative, to_decrease) + + +def volume_control(value: int, relative: bool, to_decrease: 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. + 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. + + 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 to_decrease 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..74e6dff --- /dev/null +++ b/src/commands/weather_reporter.py @@ -0,0 +1,73 @@ +import re + +import requests + +from voice_interface import VoiceInterface + + +class WeatherReporter: + + @staticmethod + def command_name() -> str: + return WeatherReporter.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return "weather" in query + + @staticmethod + 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: + # 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"}, + timeout=60, # 60 second timeout + ).json() + + 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( + "https://api.open-meteo.com/v1/forecast", params=query_params, timeout=60 + ).json() + + data = weather_data_response.get("current") + unit = weather_data_response.get("current_units") + + vi.speak( + 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 data.get("rain") == 0: + vi.speak("The skies will be clear, with no chance of rain.") + else: + cloud_cover = data.get("cloud_cover") + vi.speak( + 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 {wind_speed_mag}{wind_speed_unit}, " + "so plan accordingly." + ) diff --git a/src/commands/wikipedia_search.py b/src/commands/wikipedia_search.py new file mode 100644 index 0000000..7a2c6c4 --- /dev/null +++ b/src/commands/wikipedia_search.py @@ -0,0 +1,38 @@ +import wikipedia + +from voice_interface import VoiceInterface + + +class WikipediaSearch: + + sentence_count = 3 + + @staticmethod + def command_name() -> str: + return WikipediaSearch.__name__ + + @staticmethod + def validate_query(query: str) -> bool: + return "wikipedia" in query + + @staticmethod + def execute_query(query: str, vi: VoiceInterface) -> None: + 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..28b85c4 100644 --- a/src/infra.py +++ b/src/infra.py @@ -8,33 +8,71 @@ """ +import json import os import sys +from voice_interface import VoiceInterface -def __is_windows() -> bool: +__CONFIG_DIR = os.path.join(os.path.abspath(__file__), "config") + + +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") + + +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("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 {} + + with open(config_path, "r", encoding="UTF-8") 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)