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

feat: Activity dataclass #87

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

juvilius
Copy link

@juvilius juvilius commented Dec 30, 2024

and ci: dependency group instead of optional dependency for linting

I've had some troubles pleasing mypy, so please check if I've made a mistake before considering to merge. :)

Also: your Data class is focused on there being one of "it" per day. I'm not sure how to best reconcile it with activities.

Summary by CodeRabbit

  • New Features

    • Added Activity class to data module, enabling retrieval and management of activity information
    • Introduced new utility functions for processing dictionary keys
  • Chores

    • Updated linting configuration with specific dependency versions
    • Refined project dependency management
  • Refactor

    • Improved type checking and code organization
    • Enhanced data handling utilities

and ci: dependency group instead of optional dependency for linting
Copy link
Contributor

coderabbitai bot commented Dec 30, 2024

Walkthrough

This pull request introduces enhancements to the project's data handling and utility functions, focusing on activity tracking and dependency management. The changes include adding a new Activity class in the data module, introducing utility functions for processing dictionary keys, and updating the project's configuration. The Makefile is modified to use a specific linting group, and the project's dependency management is refined with a new dependency group for linting tools.

Changes

File Change Summary
Makefile Modified lint target to use uv run --group linting mypy $(sources)
garth/data/__init__.py Added Activity to __all__ and imported from .activity
garth/data/activity.py Added new data classes: ActivityType, Summary, and Activity
Implemented methods for activity data retrieval and processing
garth/utils.py Added remove_dto and remove_dto_from_dict utility functions
pyproject.toml Added [dependency-groups] section with linting dependencies

Sequence Diagram

sequenceDiagram
    participant Client
    participant Activity
    participant HTTPClient
    
    Client->>Activity: list() or get(id)
    alt list activities
        Activity->>HTTPClient: Fetch activities
        HTTPClient-->>Activity: Return activity data
        Activity->>Activity: Sort activities
    else get specific activity
        Activity->>HTTPClient: Fetch activity by ID
        HTTPClient-->>Activity: Return activity details
        Activity->>Activity: Process and convert data
    end
    Activity-->>Client: Return Activity instance(s)
Loading

This sequence diagram illustrates the high-level interaction for retrieving activity data, showing how the Activity class interacts with an HTTP client to fetch and process activity information.

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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
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: 6

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 922f3c3 and 8fccc98.

📒 Files selected for processing (5)
  • Makefile (1 hunks)
  • garth/data/__init__.py (1 hunks)
  • garth/data/activity.py (1 hunks)
  • garth/utils.py (1 hunks)
  • pyproject.toml (1 hunks)
🔇 Additional comments (7)
garth/data/__init__.py (2)

1-1: Add 'Activity' to the module's public API
This change looks good and aligns with making the Activity class a first-class exported entity.


3-3: Importing Activity
No apparent issues, and consistency with the updated __all__ is maintained.

garth/utils.py (1)

36-43: Check for consistent suffix handling
The function correctly handles both "_dto" and "DTO" suffixes. The logic appears straightforward, and no issues are found with the slicing.

garth/data/activity.py (4)

9-13: Ensure consistent type usage
ActivityType is a minimal, frozen dataclass that correctly represents activity metadata. If you anticipate changes (e.g., additional fields), ensure future expansions remain consistent with Activity.


72-80: Check optional fields
The optional cadence/steps attributes help track running metrics. Ensure that downstream usage handles None values gracefully to avoid potential TypeErrors.


82-91: Revisit offset approach
The _get_localized_datetime method calculates the local offset and applies it to the GMT timestamp. Watch out for edge cases like daylight saving time transitions or historical offsets outside standard rules.


92-97: Exposing activity_start
This property elegantly exposes a localized start time. It provides clarity and ensures consistent usage with _get_localized_datetime.

Comment on lines +77 to +82
[dependency-groups]
linting = [
"mypy>=1.13.0",
"ruff>=0.8.2",
"types-requests>=2.32.0.20241016",
]
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

Consider consolidating dependency management approach

The new [dependency-groups] section introduces duplicate definitions for linting dependencies that are already defined in [project.optional-dependencies]. This could lead to:

  1. Version conflicts if different constraints are specified
  2. Maintenance overhead from managing dependencies in two places
  3. Confusion about which dependencies are being used

Consider one of these approaches:

  1. Remove the duplicate definitions and use only [dependency-groups]:
-[project.optional-dependencies]
-linting = [
-    "ruff",
-    "mypy",
-    "types-requests",
-]

[dependency-groups]
linting = [
    "mypy>=1.13.0",
    "ruff>=0.8.2",
    "types-requests>=2.32.0.20241016",
]
  1. Or, keep using [project.optional-dependencies] but with the specific versions:
[project.optional-dependencies]
linting = [
-    "ruff",
-    "mypy",
-    "types-requests",
+    "mypy>=1.13.0",
+    "ruff>=0.8.2",
+    "types-requests>=2.32.0.20241016",
]

-[dependency-groups]
-linting = [
-    "mypy>=1.13.0",
-    "ruff>=0.8.2",
-    "types-requests>=2.32.0.20241016",
-]

Committable suggestion skipped: line range outside the PR's diff.

@@ -30,7 +30,7 @@ format: .uv
lint: .uv
uv run ruff format --check $(sources)
uv run ruff check $(sources)
uv run mypy $(sources)
uv run --group linting mypy $(sources)
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

Ensure consistent usage of dependency groups

The lint target uses the new --group linting flag for mypy but not for ruff commands. This inconsistency could lead to confusion about how dependencies are managed.

Consider updating all linting commands to use the same approach:

.PHONY: lint  ## Lint python source files
lint: .uv
-	uv run ruff format --check $(sources)
-	uv run ruff check $(sources)
-	uv run --group linting mypy $(sources)
+	uv run --group linting ruff format --check $(sources)
+	uv run --group linting ruff check $(sources)
+	uv run --group linting mypy $(sources)

Also, the install target needs to be updated to match the new dependency management approach:

.PHONY: install
install: .uv .pre-commit
-	uv pip install -e ".[dev,linting,testing]"
+	uv pip install -e ".[dev,testing]" --group linting

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +45 to +63
def remove_dto_from_dict(input_dict: Dict[str, Any]) -> Dict[str, Any]:
"""
Removes `DTO` suffix from dictionary keys. Different API endpoints give
back different key names, e.g. "activityTypeDTO" instead of "activityType".
"""
output_dict: Dict[str, Any] = {}
for k, v in input_dict.items():
new_key = remove_dto(k)
if isinstance(v, dict):
output_dict[new_key] = remove_dto_from_dict(v)
elif isinstance(v, list):
output_dict[new_key] = [
remove_dto_from_dict(i) if isinstance(i, dict) else i
for i in v
]
else:
output_dict[new_key] = v
return output_dict

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider edge cases for nested structures
This function recursively removes DTO from keys in nested lists and dictionaries. It seems robust enough, but watch out for cases where internal structures might contain conflicting keys once DTO is removed.

Comment on lines +16 to +70
@dataclass(frozen=True)
class Summary:
distance: float
duration: float
moving_duration: float
average_speed: float
max_speed: float
calories: float
average_hr: float
max_hr: float
start_time_gmt: datetime
start_time_local: datetime
start_latitude: float
start_longitude: float
elapsed_duration: float
elevation_gain: float
elevation_loss: float
max_elevation: float
min_elevation: float
average_moving_speed: float
bmr_calories: float
average_run_cadence: float
max_run_cadence: float
average_temperature: float
max_temperature: float
min_temperature: float
average_power: float
max_power: float
min_power: float
normalized_power: float
total_work: float
ground_contact_time: float
stride_length: float
vertical_oscillation: float
training_effect: float
anaerobic_training_effect: float
aerobic_training_effect_message: str
anaerobic_training_effect_message: str
vertical_ratio: float
end_latitude: float
end_longitude: float
max_vertical_speed: float
water_estimated: float
training_effect_label: str
activity_training_load: float
min_activity_lap_duration: float
moderate_intensity_minutes: float
vigorous_intensity_minutes: float
steps: int
begin_potential_stamina: float
end_potential_stamina: float
min_available_stamina: float
avg_grade_adjusted_speed: float
difference_body_battery: float

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Validate wide-range numeric fields
Summary has many numeric fields (distances, durations, speeds, HR, etc.). Consider adding validation where necessary (e.g., non-negative checks) to safeguard against malformed input.

Comment on lines +98 to +113
@classmethod
def get(
cls,
id: int,
*,
client: http.Client | None = None,
):
client = client or http.client
path = f"/activity-service/activity/{id}"
activity_data = client.connectapi(path)
assert activity_data
activity_data = camel_to_snake_dict(activity_data)
activity_data = remove_dto_from_dict(activity_data)
assert isinstance(activity_data, dict)
return cls(**activity_data)

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Assert usage and error handling
Currently, the method asserts that activity_data is not None and is a dictionary. If either assertion fails, a more descriptive exception or graceful fallback might be helpful.

Comment on lines +114 to +117
@classmethod
def list(cls, *args, **kwargs):
data = super().list(*args, **kwargs)
return sorted(data, key=lambda x: x.activity_start)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Sorting approach
list returns a sorted list by activity_start. This is straightforward, but consider the performance impact if the dataset grows large. Paginating or lazily fetching might become necessary in the future.

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