Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor:move_to_extras #315

Merged
merged 1 commit into from
Dec 4, 2024
Merged

refactor:move_to_extras #315

merged 1 commit into from
Dec 4, 2024

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Dec 4, 2024

package is too bloated for basic usage, timezonefinder, langcodes and oauth dependencies have been moved to extras

Summary by CodeRabbit

  • New Features

    • Added new dependencies: langcodes, timezonefinder, and oauthlib to enhance functionality.
    • Introduced orjson package for improved performance.
  • Bug Fixes

    • Improved error handling in get_timezone and standardize_lang_tag functions for better user feedback.
  • Refactor

    • Simplified the is_gui_running function for clearer application status checks.
    • Optimized import statements for better resource management in several functions.

package is too bloated for basic usage, timezonefinder, langcodes and oauth dependencies have been moved to extras
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Walkthrough

This pull request introduces several changes across multiple files, primarily focusing on improving the initialization and loading of variables and imports. Key modifications include the lazy loading of the TimezoneFinder class in the get_timezone function, enhancements to error handling in various functions, and the removal of deprecated checks in the is_gui_running function. Additionally, new dependencies are added to the requirements files, while existing packages remain unchanged.

Changes

File Change Summary
ovos_utils/geolocation.py - Changed _tz_finder initialization from type declaration to simple assignment.
- Moved TimezoneFinder import inside get_timezone function for lazy loading.
- Enhanced error handling in get_timezone.
ovos_utils/gui.py - Simplified is_gui_running function by removing deprecated checks and logging.
ovos_utils/lang/init.py - Moved standardize_tag and tag_distance imports inside their respective functions.
- Adjusted error handling in standardize_lang_tag for better fallback mechanism.
ovos_utils/oauth.py - Moved WebApplicationClient import inside refresh_oauth_token function for lazy loading.
requirements/extras.txt - Added new dependencies: langcodes, timezonefinder, and oauthlib with version constraint ~=3.2.
requirements/requirements.txt - Added new package: orjson.

Possibly related PRs

Poem

🐇 In the world of code, we hop and play,
With lazy loading, we save the day!
Errors caught, with care and grace,
A simpler path, we now embrace.
New friends in requirements, oh what a sight,
Let's code together, from morning till night! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Dec 4, 2024

Codecov Report

Attention: Patch coverage is 16.66667% with 5 lines in your changes missing coverage. Please review.

Project coverage is 44.86%. Comparing base (32b9fe1) to head (e45885f).
Report is 26 commits behind head on dev.

Files with missing lines Patch % Lines
ovos_utils/geolocation.py 0.00% 2 Missing ⚠️
ovos_utils/gui.py 0.00% 1 Missing ⚠️
ovos_utils/lang/__init__.py 50.00% 1 Missing ⚠️
ovos_utils/oauth.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #315      +/-   ##
==========================================
+ Coverage   44.74%   44.86%   +0.11%     
==========================================
  Files          33       33              
  Lines        3426     3415      -11     
==========================================
- Hits         1533     1532       -1     
+ Misses       1893     1883      -10     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@JarbasAl JarbasAl merged commit 5f49e08 into dev Dec 4, 2024
11 checks passed
@JarbasAl JarbasAl deleted the refactor/move_to_extras branch December 4, 2024 17:29
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
ovos_utils/gui.py (1)

Line range hint 1-99: Good architectural direction.

This change aligns well with the PR's objective of reducing package bloat. The removal of deprecated code paths and simplification of the GUI detection logic contributes to a more maintainable codebase. The utility functions maintain clear separation of concerns and follow the single responsibility principle.

ovos_utils/lang/__init__.py (2)

Line range hint 7-19: Improve error handling for missing optional dependency

The function handles missing langcodes gracefully, but we should log a warning to help users understand why the fallback is being used.

 def standardize_lang_tag(lang_code: str, macro=True) -> str:
     """https://langcodes-hickford.readthedocs.io/en/sphinx/index.html"""
     try:
         from langcodes import standardize_tag as std
         return str(std(lang_code, macro=macro))
-    except:
+    except ImportError:
+        LOG.debug("langcodes not installed, using fallback language standardization")
         if macro:
             return lang_code.split("-")[0].lower()
         if "-" in lang_code:
             a, b = lang_code.split("-", 2)
             return f"{a.lower()}-{b.upper()}"
         return lang_code.lower()
🧰 Tools
🪛 Ruff (0.8.0)

13-13: Do not use bare except

(E722)


Line range hint 22-41: Enhance error handling in get_language_dir

The function should distinguish between missing dependency and invalid language code errors.

     for f in listdir(base_path):
         if isdir(f"{base_path}/{f}"):
             try:
                 from langcodes import tag_distance
                 score = tag_distance(lang, f)
-            except:  # not a valid language code
+            except ImportError:
+                LOG.debug("langcodes not installed, skipping language distance calculation")
+                return None
+            except Exception:  # not a valid language code
                 continue
🧰 Tools
🪛 Ruff (0.8.0)

32-32: Do not use bare except

(E722)

ovos_utils/geolocation.py (2)

12-13: Add type hint to global variable

Restore the type hint for better code maintainability and IDE support.

-_tz_finder = None
+from typing import Optional
+_tz_finder: Optional['TimezoneFinder'] = None

Line range hint 43-47: Enhance error message clarity

The error messages should be more specific about the type of error encountered.

     except ValueError as e:
-        raise ValueError(f"Invalid coordinates: {str(e)}") from e
+        raise ValueError(f"Invalid coordinates (lat: {lat}, lon: {lon}): {str(e)}") from e
     except Exception as e:
-        raise RuntimeError(f"Timezone lookup failed: {str(e)}") from e
+        raise RuntimeError(f"Timezone lookup failed for coordinates (lat: {lat}, lon: {lon}): {str(e)}") from e
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e79d49a and e45885f.

📒 Files selected for processing (6)
  • ovos_utils/geolocation.py (2 hunks)
  • ovos_utils/gui.py (1 hunks)
  • ovos_utils/lang/__init__.py (2 hunks)
  • ovos_utils/oauth.py (1 hunks)
  • requirements/extras.txt (1 hunks)
  • requirements/requirements.txt (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • requirements/requirements.txt
  • requirements/extras.txt
🔇 Additional comments (2)
ovos_utils/gui.py (2)

37-37: LGTM! Clean and efficient implementation.

The simplified implementation is more maintainable and removes technical debt by eliminating deprecated checks. The use of a generator expression with any() is both Pythonic and efficient.


Line range hint 31-38: Verify impact and update documentation.

While the code changes look good, please ensure:

  1. The removal of deprecated GUI app checks is documented in the changelog
  2. Users are informed about this change if they're still using deprecated GUI applications

Let's verify the usage of deprecated GUI applications in the codebase:

Comment on lines +110 to 113
from oauthlib.oauth2 import WebApplicationClient
client = WebApplicationClient(client_id, refresh_token=refresh_token)
uri, headers, body = client.prepare_refresh_token_request(token_endpoint)
refresh_result = requests.post(uri, headers=headers, data=body,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for missing optional dependency

The function should gracefully handle missing oauthlib dependency and provide clear feedback to users.

-    from oauthlib.oauth2 import WebApplicationClient
-    client = WebApplicationClient(client_id, refresh_token=refresh_token)
+    try:
+        from oauthlib.oauth2 import WebApplicationClient
+        client = WebApplicationClient(client_id, refresh_token=refresh_token)
+    except ImportError:
+        LOG.error("oauthlib not installed. Please install 'ovos-utils[oauth]' to use OAuth functionality")
+        return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from oauthlib.oauth2 import WebApplicationClient
client = WebApplicationClient(client_id, refresh_token=refresh_token)
uri, headers, body = client.prepare_refresh_token_request(token_endpoint)
refresh_result = requests.post(uri, headers=headers, data=body,
try:
from oauthlib.oauth2 import WebApplicationClient
client = WebApplicationClient(client_id, refresh_token=refresh_token)
except ImportError:
LOG.error("oauthlib not installed. Please install 'ovos-utils[oauth]' to use OAuth functionality")
return None
uri, headers, body = client.prepare_refresh_token_request(token_endpoint)
refresh_result = requests.post(uri, headers=headers, data=body,

Comment on lines 31 to 34
if _tz_finder is None:
from timezonefinder import TimezoneFinder
# lazy loaded, resource intensive so we only want to do it once
_tz_finder = TimezoneFinder()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling for missing optional dependency

The function should provide clear feedback when timezonefinder is not installed.

     if _tz_finder is None:
-        from timezonefinder import TimezoneFinder
-        # lazy loaded, resource intensive so we only want to do it once
-        _tz_finder = TimezoneFinder()
+        try:
+            from timezonefinder import TimezoneFinder
+            # lazy loaded, resource intensive so we only want to do it once
+            _tz_finder = TimezoneFinder()
+        except ImportError:
+            LOG.error("timezonefinder not installed. Please install 'ovos-utils[location]' to use timezone functionality")
+            raise RuntimeError("timezonefinder package is required for timezone lookup")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if _tz_finder is None:
from timezonefinder import TimezoneFinder
# lazy loaded, resource intensive so we only want to do it once
_tz_finder = TimezoneFinder()
if _tz_finder is None:
try:
from timezonefinder import TimezoneFinder
# lazy loaded, resource intensive so we only want to do it once
_tz_finder = TimezoneFinder()
except ImportError:
LOG.error("timezonefinder not installed. Please install 'ovos-utils[location]' to use timezone functionality")
raise RuntimeError("timezonefinder package is required for timezone lookup")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant