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

Fix Frame Selection and Frame Count in GUI (Shift + Drag and Shift + Double Click) #2078

Open
wants to merge 24 commits into
base: develop
Choose a base branch
from

Conversation

ericleonardis
Copy link
Contributor

@ericleonardis ericleonardis commented Dec 21, 2024

Description

This PR addresses Issue #2074 Shift + Drag Frame Selection and Frame Count Not Matching Video. Previously, if a whole video using the Shift + Drag frame selection, the max selected frame range and frame count did not match the number of frames in the video listed in the Videos table. Shift + Double Click also did not matched in the Selection display but added 1 to the frame count.

Shift + Drag was fixed by changing the _slider_width function. Previously, self.handle.rect().width() was being subtracted from self.box_rect.width() to calculate _slider_width. If we remove this subtraction, and just set it to self.box_rect.width() the frame count bug appears to be fixed.

But why would subtracting it lead to an increase in frame count? That is because of the normalization by slider width which occurs in the _toVal function val /= self._slider_width. So that explains why we were getting the bug in the first place.

The Shift + Double Click issue of adding 1 to frame count when everything was selected was fixed by removing the +1 from the frame count display in app.py.

I added tests for the _toVal function and the _slider_width function to match expected output avoid this problem in the future.

I successfully tested this fix on Windows and Mac M1 Pro.

Types of changes

  • Bugfix
  • New feature
  • Refactor / Code style update (no logical changes)
  • Build / CI changes
  • Documentation Update
  • Other (explain)

Does this address any currently open issues?

#2074

Outside contributors checklist

  • Review the guidelines for contributing to this repository
  • Read and sign the CLA and add yourself to the authors list
  • Make sure you are making a pull request against the develop branch (not main). Also you should start your branch off develop
  • Add tests that prove your fix is effective or that your feature works
  • Add necessary documentation (if appropriate)

Thank you for contributing to SLEAP!

❤️

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Updated selection message in the status bar for accurate frame count display.
    • Enhanced VideoSlider functionality, including improved error handling and a new property for visible value range.
  • Bug Fixes

    • Adjusted calculations in the VideoSlider to ensure correct visual representation.
  • Tests

    • Added new tests for the _toVal method, _slider_width property, and error handling in the VideoSlider class, improving test coverage.

@ericleonardis ericleonardis added bug Something isn't working 2024-hackathon labels Dec 21, 2024
@ericleonardis ericleonardis self-assigned this Dec 21, 2024
Copy link

coderabbitai bot commented Dec 21, 2024

Warning

Rate limit exceeded

@ericleonardis has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1dda08c and d0e3558.

📒 Files selected for processing (1)
  • tests/gui/test_slider.py (2 hunks)

Walkthrough

The pull request introduces modifications to the sleap project, focusing on the VideoSlider class and its associated test suite. Changes include refining the slider's functionality in sleap/gui/widgets/slider.py, updating the status message calculation in sleap/gui/app.py, and expanding test coverage in tests/gui/test_slider.py. The modifications improve the precision of frame selection display, enhance slider interaction, and provide more comprehensive testing for the slider's behavior.

Changes

File Change Summary
sleap/gui/app.py Updated frame selection count calculation in status message
sleap/gui/widgets/slider.py - Enhanced _toVal method documentation
- Modified _slider_width property calculation
- Added slider_visible_value_range property
- Improved error handling in _toVal method
- Removed center parameter from _toVal method
tests/gui/test_slider.py - Added test_toVal function
- Added test_slider_width_property function
- Added test_toVal_invalid_input function
- Imported pytest

Sequence Diagram

sequenceDiagram
    participant User
    participant Slider
    participant App
    
    User->>Slider: Interact with slider
    Slider->>Slider: Transform mouse coordinates
    Slider->>App: Update selection
    App->>App: Calculate frame count
    App->>User: Display status message
Loading

Poem

🐰 A slider's dance, precise and neat,
Frames counted with mathematical beat
Mouse moves with grace, tooltips unfurl
Testing each pixel, each value's swirl
CodeRabbit's touch, a technical treat! 🖱️


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.

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

@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: 0

🧹 Nitpick comments (3)
sleap/gui/widgets/slider.py (2)

372-381: Improve docstring and add edge case handling.

The docstring improvement is good, but consider adding:

  • Example usage
  • Edge case handling for invalid inputs

Consider this implementation:

def _toVal(self, x: float, center=False) -> float:
    """
    Converts x position to slider value.

    Args:
        x: x position on the slider.
        center: Whether to offset by half the width of the handle.

    Returns:
        Slider value (frame index).

    Example:
        >>> slider._toVal(100)  # converts position 100 to frame index
        50  # (assuming slider range 0-100 and width 200)

    Raises:
        ValueError: If x is None or not a number.
    """
+   if x is None:
+       raise ValueError("x position cannot be None")
+   try:
+       val = float(x)
+   except (TypeError, ValueError):
+       raise ValueError("x position must be a number")
    val /= self._slider_width
    val *= max(1, self._val_max - self._val_min)
    val += self._val_min
    val = round(val)
    return val

392-392: LGTM! Consider adding validation.

The simplified implementation correctly fixes the frame count issue by returning the full width. However, consider adding validation to ensure the width is always positive.

Consider this implementation:

@property
def _slider_width(self) -> float:
    """Returns visual width of slider."""
    width = self.box_rect.width()
+   if width <= 0:
+       return 1.0  # Prevent division by zero in _toVal
    return width
tests/gui/test_slider.py (1)

44-85: Enhance test coverage for _toVal.

Good test coverage with parametrized tests. Consider adding:

  • Tests for center=True parameter
  • Tests for edge cases (None, non-numeric)

Add these test cases:

@pytest.mark.parametrize(
    "slider_width, x_value, min_value, max_value",
    [
        # Existing test cases...

+       # Test center=True parameter
+       (1000, 500, 0, 1000),  # Compare with center=True
+
+       # Edge cases
+       (1000, 0, 0, 1000),    # Minimum x position
+       (1000, 1000, 0, 1000), # Maximum x position
    ]
)
def test_toVal(qtbot, slider_width, x_value, min_value, max_value):
    slider = VideoSlider(min=0, max=1000, val=15, marks=(10, 15))
    slider.setMinimum(min_value)
    slider.setMaximum(max_value)
    slider.box_rect.setWidth(slider_width)

    # Test without center
    expected_value = round(
        (x_value / slider_width) * (max_value - min_value) + min_value
    )
    assert slider._toVal(x_value) == expected_value

+   # Test with center=True
+   expected_center_value = round(
+       ((x_value - slider.handle.rect().width() / 2.0) / slider_width) 
+       * (max_value - min_value) + min_value
+   )
+   assert slider._toVal(x_value, center=True) == expected_center_value

+@pytest.mark.parametrize(
+    "invalid_value",
+    [None, "invalid", [], {}]
+)
+def test_toVal_invalid_input(qtbot, invalid_value):
+    slider = VideoSlider(min=0, max=1000, val=15)
+    with pytest.raises(ValueError):
+        slider._toVal(invalid_value)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7785f66 and a06c954.

📒 Files selected for processing (3)
  • sleap/gui/app.py (1 hunks)
  • sleap/gui/widgets/slider.py (2 hunks)
  • tests/gui/test_slider.py (2 hunks)
🔇 Additional comments (2)
tests/gui/test_slider.py (1)

87-104: LGTM! Comprehensive test coverage.

The test coverage is thorough and includes:

  • Various box_rect widths
  • Edge cases (0 and large values)
sleap/gui/app.py (1)

1307-1307: LGTM! Frame count calculation fixed.

The removal of +1 from the frame count calculation correctly fixes the issue where Shift + Double Click was adding 1 to the frame count.

Copy link

codecov bot commented Dec 21, 2024

Codecov Report

Attention: Patch coverage is 71.42857% with 4 lines in your changes missing coverage. Please review.

Project coverage is 76.12%. Comparing base (7991f14) to head (d0e3558).
Report is 96 commits behind head on develop.

Files with missing lines Patch % Lines
sleap/gui/widgets/slider.py 76.92% 3 Missing ⚠️
sleap/gui/app.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2078      +/-   ##
===========================================
+ Coverage    75.43%   76.12%   +0.68%     
===========================================
  Files          134      134              
  Lines        24749    24788      +39     
===========================================
+ Hits         18670    18870     +200     
+ Misses        6079     5918     -161     

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

Copy link

@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: 0

🧹 Nitpick comments (1)
sleap/gui/widgets/slider.py (1)

375-377: Consider adding type hints to parameters.

For improved code maintainability and IDE support, consider adding type hints to the parameters:

-    x: x position on the slider.
-    center: Whether to offset by half the width of the handle.
+    x: float  # x position on the slider
+    center: bool  # Whether to offset by half the width of the handle
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fb35ff2 and ad57162.

📒 Files selected for processing (1)
  • sleap/gui/widgets/slider.py (2 hunks)
🔇 Additional comments (3)
sleap/gui/widgets/slider.py (3)

372-384: Improved documentation and error handling in _toVal method.

The added docstring and None check enhance the robustness and maintainability of the code.


395-398: Fixed frame selection bug by removing handle width subtraction.

The changes correctly address the frame count discrepancy issue mentioned in the PR objectives. The added check for non-positive width with a minimum return value of 1.0 prevents potential division by zero errors.


Line range hint 400-402: Well-designed property for accessing visible value range.

The new property provides a clean interface to get the visible value range, which is useful for UI calculations and zoom operations.

@ericleonardis
Copy link
Contributor Author

Actionable comments posted: 0

🧹 Nitpick comments (3)

sleap/gui/widgets/slider.py (2)> 372-381: Improve docstring and add edge case handling.

The docstring improvement is good, but consider adding:

  • Example usage
  • Edge case handling for invalid inputs

Consider this implementation:

def _toVal(self, x: float, center=False) -> float:
    """
    Converts x position to slider value.

    Args:
        x: x position on the slider.
        center: Whether to offset by half the width of the handle.

    Returns:
        Slider value (frame index).

    Example:
        >>> slider._toVal(100)  # converts position 100 to frame index
        50  # (assuming slider range 0-100 and width 200)

    Raises:
        ValueError: If x is None or not a number.
    """
+   if x is None:
+       raise ValueError("x position cannot be None")
+   try:
+       val = float(x)
+   except (TypeError, ValueError):
+       raise ValueError("x position must be a number")
    val /= self._slider_width
    val *= max(1, self._val_max - self._val_min)
    val += self._val_min
    val = round(val)
    return val

392-392: LGTM! Consider adding validation.
The simplified implementation correctly fixes the frame count issue by returning the full width. However, consider adding validation to ensure the width is always positive.
Consider this implementation:

@property
def _slider_width(self) -> float:
    """Returns visual width of slider."""
    width = self.box_rect.width()
+   if width <= 0:
+       return 1.0  # Prevent division by zero in _toVal
    return width

tests/gui/test_slider.py (1)> 44-85: Enhance test coverage for _toVal.

Good test coverage with parametrized tests. Consider adding:

  • Tests for center=True parameter
  • Tests for edge cases (None, non-numeric)

Add these test cases:

@pytest.mark.parametrize(
    "slider_width, x_value, min_value, max_value",
    [
        # Existing test cases...

+       # Test center=True parameter
+       (1000, 500, 0, 1000),  # Compare with center=True
+
+       # Edge cases
+       (1000, 0, 0, 1000),    # Minimum x position
+       (1000, 1000, 0, 1000), # Maximum x position
    ]
)
def test_toVal(qtbot, slider_width, x_value, min_value, max_value):
    slider = VideoSlider(min=0, max=1000, val=15, marks=(10, 15))
    slider.setMinimum(min_value)
    slider.setMaximum(max_value)
    slider.box_rect.setWidth(slider_width)

    # Test without center
    expected_value = round(
        (x_value / slider_width) * (max_value - min_value) + min_value
    )
    assert slider._toVal(x_value) == expected_value

+   # Test with center=True
+   expected_center_value = round(
+       ((x_value - slider.handle.rect().width() / 2.0) / slider_width) 
+       * (max_value - min_value) + min_value
+   )
+   assert slider._toVal(x_value, center=True) == expected_center_value

+@pytest.mark.parametrize(
+    "invalid_value",
+    [None, "invalid", [], {}]
+)
+def test_toVal_invalid_input(qtbot, invalid_value):
+    slider = VideoSlider(min=0, max=1000, val=15)
+    with pytest.raises(ValueError):
+        slider._toVal(invalid_value)

📜 Review details
Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

📥 Commits
📒 Files selected for processing (3)
🔇 Additional comments (2)
tests/gui/test_slider.py (1)
87-104: LGTM! Comprehensive test coverage.

The test coverage is thorough and includes:

  • Various box_rect widths
  • Edge cases (0 and large values)

sleap/gui/app.py (1)
1307-1307: LGTM! Frame count calculation fixed.

The removal of +1 from the frame count calculation correctly fixes the issue where Shift + Double Click was adding 1 to the frame count.

these are good suggestions I have made the suggested changes and added a test for the center=true case.

@ericleonardis
Copy link
Contributor Author

Actionable comments posted: 0
🧹 Nitpick comments (3)

sleap/gui/widgets/slider.py (2)> 372-381: Improve docstring and add edge case handling.

The docstring improvement is good, but consider adding:

  • Example usage
  • Edge case handling for invalid inputs

Consider this implementation:

def _toVal(self, x: float, center=False) -> float:
    """
    Converts x position to slider value.

    Args:
        x: x position on the slider.
        center: Whether to offset by half the width of the handle.

    Returns:
        Slider value (frame index).

    Example:
        >>> slider._toVal(100)  # converts position 100 to frame index
        50  # (assuming slider range 0-100 and width 200)

    Raises:
        ValueError: If x is None or not a number.
    """
+   if x is None:
+       raise ValueError("x position cannot be None")
+   try:
+       val = float(x)
+   except (TypeError, ValueError):
+       raise ValueError("x position must be a number")
    val /= self._slider_width
    val *= max(1, self._val_max - self._val_min)
    val += self._val_min
    val = round(val)
    return val

392-392: LGTM! Consider adding validation.
The simplified implementation correctly fixes the frame count issue by returning the full width. However, consider adding validation to ensure the width is always positive.
Consider this implementation:

@property
def _slider_width(self) -> float:
    """Returns visual width of slider."""
    width = self.box_rect.width()
+   if width <= 0:
+       return 1.0  # Prevent division by zero in _toVal
    return width

tests/gui/test_slider.py (1)> 44-85: Enhance test coverage for _toVal.

Good test coverage with parametrized tests. Consider adding:

  • Tests for center=True parameter
  • Tests for edge cases (None, non-numeric)

Add these test cases:

@pytest.mark.parametrize(
    "slider_width, x_value, min_value, max_value",
    [
        # Existing test cases...

+       # Test center=True parameter
+       (1000, 500, 0, 1000),  # Compare with center=True
+
+       # Edge cases
+       (1000, 0, 0, 1000),    # Minimum x position
+       (1000, 1000, 0, 1000), # Maximum x position
    ]
)
def test_toVal(qtbot, slider_width, x_value, min_value, max_value):
    slider = VideoSlider(min=0, max=1000, val=15, marks=(10, 15))
    slider.setMinimum(min_value)
    slider.setMaximum(max_value)
    slider.box_rect.setWidth(slider_width)

    # Test without center
    expected_value = round(
        (x_value / slider_width) * (max_value - min_value) + min_value
    )
    assert slider._toVal(x_value) == expected_value

+   # Test with center=True
+   expected_center_value = round(
+       ((x_value - slider.handle.rect().width() / 2.0) / slider_width) 
+       * (max_value - min_value) + min_value
+   )
+   assert slider._toVal(x_value, center=True) == expected_center_value

+@pytest.mark.parametrize(
+    "invalid_value",
+    [None, "invalid", [], {}]
+)
+def test_toVal_invalid_input(qtbot, invalid_value):
+    slider = VideoSlider(min=0, max=1000, val=15)
+    with pytest.raises(ValueError):
+        slider._toVal(invalid_value)

📜 Review details
Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro
📥 Commits
📒 Files selected for processing (3)
🔇 Additional comments (2)
tests/gui/test_slider.py (1)
87-104: LGTM! Comprehensive test coverage.
The test coverage is thorough and includes:

  • Various box_rect widths
  • Edge cases (0 and large values)

sleap/gui/app.py (1)
1307-1307: LGTM! Frame count calculation fixed.
The removal of +1 from the frame count calculation correctly fixes the issue where Shift + Double Click was adding 1 to the frame count.

these are good suggestions I have made the suggested changes and added a test for the center=true case.

actually i found that center=True is called but the logic is not different for true or false, so i got rid of the input variable and got rid of the variable from the tests

Copy link

@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: 0

🧹 Nitpick comments (6)
tests/gui/test_slider.py (3)

45-106: Add test case for zero width scenario.

The test cases are comprehensive but missing a critical edge case where the slider width is zero. This would help verify the division by zero protection in the _toVal method.

Add this test case to the parametrize decorator:

 @pytest.mark.parametrize(
     "slider_width, x_value, handle_width, min_value, max_value",
     [
+        (0, 0, 0, 0, 1000),  # Zero width edge case
         # ---- Cases from test_toVal (center=False) ----
         (1000, 500, 0, 0, 1000),  # Midpoint w/o centering

126-126: Fix incorrect assertion message.

The assertion message doesn't match the actual assertion. It states "Expected _slider_width to be 1" but the assertion checks for 0.

-    ), "Expected _slider_width to be 1 when box_rect width is 0"
+    ), "Expected _slider_width to be 0 when box_rect width is 0"

157-158: Remove unnecessary loop.

The loop with range(1) is unnecessary as it only executes once.

-    # We use tqdm to track progress across multiple invalid inputs (optional).
-    for _ in range(1):
-        slider = VideoSlider(min=0, max=1000, val=15)
+    slider = VideoSlider(min=0, max=1000, val=15)
sleap/gui/widgets/slider.py (3)

382-389: Improve error handling in _toVal method.

The error handling can be improved by:

  1. Using raise ... from err to preserve the exception chain
  2. Making the error messages more descriptive
     if x is None:
         raise ValueError("x position cannot be None")
 
     # Force conversion to float here.
     try:
         val = float(x)
     except (TypeError, ValueError) as err:
-        raise ValueError(f"x position must be a number, got {x}")
+        raise ValueError(f"x position must be a number, got {x!r}") from err
🧰 Tools
🪛 Ruff (0.8.2)

389-389: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


Line range hint 391-397: Consider adding input range validation.

The method could benefit from validating that the input x position is within the valid range of the slider's width.

     # Proceed with arithmetic only after we have a valid float.
     val = x
+    if not (0 <= val <= self._slider_width):
+        raise ValueError(f"x position {val} must be between 0 and {self._slider_width}")
     val /= self._slider_width
     val *= max(1, self._val_max - self._val_min)
     val += self._val_min
     val = round(val)
🧰 Tools
🪛 Ruff (0.8.2)

389-389: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


568-570: Consider caching the start value.

The _toVal calculation for x is performed twice, once for storing and once for comparison. Consider caching the result.

     if getattr(self, "_zoom_start_val", None) is None:
-        self._zoom_start_val = self._toVal(x)
+        current_val = self._toVal(x)
+        self._zoom_start_val = current_val
+    else:
+        current_val = self._toVal(x)
 
-    current_val = self._toVal(x)
     self._draw_zoom_box(current_val, self._zoom_start_val)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad57162 and 1dda08c.

📒 Files selected for processing (2)
  • sleap/gui/widgets/slider.py (5 hunks)
  • tests/gui/test_slider.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
sleap/gui/widgets/slider.py

389-389: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (1)
sleap/gui/widgets/slider.py (1)

402-403: LGTM! Good simplification of _slider_width.

The removal of handle width subtraction from _slider_width fixes the frame count issue by ensuring correct normalization in the _toVal function.

@ericleonardis ericleonardis requested a review from roomrys January 2, 2025 20:25
@ericleonardis
Copy link
Contributor Author

Actionable comments posted: 0

🧹 Nitpick comments (6)

tests/gui/test_slider.py (3)> 45-106: Add test case for zero width scenario.

The test cases are comprehensive but missing a critical edge case where the slider width is zero. This would help verify the division by zero protection in the _toVal method.
Add this test case to the parametrize decorator:

 @pytest.mark.parametrize(
     "slider_width, x_value, handle_width, min_value, max_value",
     [
+        (0, 0, 0, 0, 1000),  # Zero width edge case
         # ---- Cases from test_toVal (center=False) ----
         (1000, 500, 0, 0, 1000),  # Midpoint w/o centering

126-126: Fix incorrect assertion message.
The assertion message doesn't match the actual assertion. It states "Expected _slider_width to be 1" but the assertion checks for 0.

-    ), "Expected _slider_width to be 1 when box_rect width is 0"
+    ), "Expected _slider_width to be 0 when box_rect width is 0"

157-158: Remove unnecessary loop.
The loop with range(1) is unnecessary as it only executes once.

-    # We use tqdm to track progress across multiple invalid inputs (optional).
-    for _ in range(1):
-        slider = VideoSlider(min=0, max=1000, val=15)
+    slider = VideoSlider(min=0, max=1000, val=15)

sleap/gui/widgets/slider.py (3)> 382-389: Improve error handling in _toVal method.

The error handling can be improved by:

  1. Using raise ... from err to preserve the exception chain
  2. Making the error messages more descriptive
     if x is None:
         raise ValueError("x position cannot be None")
 
     # Force conversion to float here.
     try:
         val = float(x)
     except (TypeError, ValueError) as err:
-        raise ValueError(f"x position must be a number, got {x}")
+        raise ValueError(f"x position must be a number, got {x!r}") from err

🧰 Tools

🪛 Ruff (0.8.2)
389-389: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)

Line range hint 391-397: Consider adding input range validation.
The method could benefit from validating that the input x position is within the valid range of the slider's width.

     # Proceed with arithmetic only after we have a valid float.
     val = x
+    if not (0 <= val <= self._slider_width):
+        raise ValueError(f"x position {val} must be between 0 and {self._slider_width}")
     val /= self._slider_width
     val *= max(1, self._val_max - self._val_min)
     val += self._val_min
     val = round(val)

🧰 Tools

🪛 Ruff (0.8.2)
389-389: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)

568-570: Consider caching the start value.
The _toVal calculation for x is performed twice, once for storing and once for comparison. Consider caching the result.

     if getattr(self, "_zoom_start_val", None) is None:
-        self._zoom_start_val = self._toVal(x)
+        current_val = self._toVal(x)
+        self._zoom_start_val = current_val
+    else:
+        current_val = self._toVal(x)
 
-    current_val = self._toVal(x)
     self._draw_zoom_box(current_val, self._zoom_start_val)

📜 Review details

ok i fixed the incorrect comment and got rid of the unnecessary loop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2024-hackathon bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant