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

(3a -> 3) Add method to match instances across views #1579

Conversation

roomrys
Copy link
Collaborator

@roomrys roomrys commented Oct 31, 2023

Description

This PR aims to add a method to match instances across views (without knowing Tracks).

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?

[list open issues here]

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

  • Refactor
    • Enhanced method logic in the delete.py file for improved frame removal handling.
    • Updated point handling logic in the instance.py file to improve point object creation.
    • Modified methods in the dataset.py file for better video and session management.
  • Tests
    • Added a new fixture for user-labeled data in the datasets.py file.
    • Updated test functions in the test_commands.py file to reflect changes in session handling.
    • Modified test declarations in the test_cameras.py file to align with entity imports.
    • Updated method calls in the test_dataset.py file for explicit parameter passing.

@roomrys roomrys added the MultiView Stack This PR is part of the MultView stacked PRs. label Oct 31, 2023
@coderabbitai
Copy link

coderabbitai bot commented Oct 31, 2023

Walkthrough

The recent changes across the codebase focused on enhancing the AddInstances class in sleap/gui/commands.py. These updates include method renaming, parameter adjustments, and return type refinements. Additionally, related test functions in tests/gui/test_commands.py have been modified to align with these class changes.

Changes

File Path Summary
sleap/gui/commands.py Various updates to the AddInstances class, including method renaming, parameter changes, and return type enhancements. The typing import statement has also been revised.
sleap/gui/dialogs/delete.py Logic change in the _delete method to call remove_frame instead of remove when no instances are left in a labeled frame.
sleap/instance.py Updates in handling points within the update_points method, skipping NaN values, extracting attributes, and updating the points dictionary.
sleap/io/dataset.py Additions like a new method remove_session_video, updated docstrings, and TODO comments for handling LabeledFrame removal in various methods.
tests/fixtures/datasets.py Addition of multiview_min_session_user_labels fixture for loading user-labeled data in a minimal session.
tests/gui/test_commands.py Removal of test functions related to triangulating sessions and verifying instances across views.
tests/io/test_cameras.py Modifications in declarations and tests for InstanceGroup and FrameGroup entities.
tests/io/test_dataset.py Modification in calling remove_session_video with explicit parameter naming.

Poem

🐇 Code changes dance like leaves in the wind, 🍃

Bringing clarity, a new path to find. 🛤️

Methods refactored, tests now aligned, 🛠️

In the realm of code, improvements designed. 🌌

A tale of updates, in lines and in tests, 📜

Progress whispers in the coder's quests. 🌠


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between d83ea64 and 176efb2.
Files selected for processing (9)
  • sleap/gui/commands.py (4 hunks)
  • sleap/gui/dialogs/delete.py (1 hunks)
  • sleap/instance.py (2 hunks)
  • sleap/io/cameras.py (8 hunks)
  • sleap/io/dataset.py (10 hunks)
  • tests/fixtures/datasets.py (1 hunks)
  • tests/gui/test_commands.py (2 hunks)
  • tests/io/test_cameras.py (3 hunks)
  • tests/io/test_dataset.py (1 hunks)
Files not summarized due to errors (1)
  • sleap/io/cameras.py: Error: Message exceeds token limit
Additional Context Used
Ruff (64)
sleap/gui/commands.py (10)

38-38: itertools.permutations imported but unused


38-38: itertools.product imported but unused


40-40: typing.cast imported but unused


196-196: Undefined name MainWindow


838-838: Local variable file_dir is assigned to but never used


1712-1712: Do not use bare except


1733-1733: Do not use bare except


2470-2470: f-string without any placeholders


2802-2802: f-string without any placeholders


3145-3145: Do not use bare except

sleap/instance.py (6)

89-89: Undefined name self


89-89: Undefined name self


411-411: Do not compare types, use isinstance()


449-449: Do not compare types, use isinstance()


503-503: Do not use bare except


1652-1652: Undefined name Labels

sleap/io/cameras.py (8)

6-6: typing.cast imported but unused


79-79: f-string without any placeholders


80-80: f-string without any placeholders


81-81: f-string without any placeholders


449-449: Undefined name Skeleton


602-602: Undefined name Skeleton


829-829: Do not use bare except


917-917: Undefined name Labels

sleap/io/dataset.py (16)

55-55: Redefinition of unused Callable from line 45


61-61: h5py imported but unused


69-69: Do not use bare except


70-70: typing._ForwardRef imported but unused


365-365: Do not assign a lambda expression, use a def


367-370: Do not assign a lambda expression, use a def


372-375: Do not assign a lambda expression, use a def


934-934: Do not compare types, use isinstance()


1454-1454: Do not compare types, use isinstance()


2355-2355: Undefined name glob


2450-2450: Avoid equality comparisons to False; use if not ret: for false checks


2538-2538: Avoid equality comparisons to False; use if not ret: for false checks


2553-2553: Undefined name sleap


2643-2643: Do not compare types, use isinstance()


2646-2646: Local variable e is assigned to but never used


2648-2648: f-string without any placeholders

tests/fixtures/datasets.py (1)

1-1: os imported but unused

tests/gui/test_commands.py (17)

5-5: typing.Dict imported but unused


7-7: numpy imported but unused


21-21: sleap.gui.commands.TriangulateSession imported but unused


25-25: sleap.io.cameras.Camcorder imported but unused


75-75: Ambiguous variable name: l


82-82: Ambiguous variable name: l


227-227: Avoid equality comparisons to True; use if okay: for truth checks


236-236: Avoid equality comparisons to True; use if okay: for truth checks


244-244: Avoid equality comparisons to True; use if okay: for truth checks


253-253: Avoid equality comparisons to True; use if okay: for truth checks


265-265: Avoid equality comparisons to True; use if okay: for truth checks


274-274: Avoid equality comparisons to True; use if okay: for truth checks


281-281: Avoid equality comparisons to True; use if okay: for truth checks


299-299: Avoid equality comparisons to True; use if okay: for truth checks


360-360: Local variable last_lf_frame is assigned to but never used


368-368: Avoid equality comparisons to True; use if video.backend.grayscale: for truth checks


528-528: f-string without any placeholders

tests/io/test_dataset.py (6)

119-119: Test for object identity should be is not


120-120: Test for membership should be not in


121-121: Test for object identity should be is not


692-692: Local variable new_labels_json is assigned to but never used


708-708: Local variable new_labels_json is assigned to but never used


1495-1495: Local variable track_insts is assigned to but never used

Learnings (1)
sleap/io/dataset.py (1)
User: roomrys"
PR: talmolab/sleap#1654
File: sleap/io/dataset.py:1717-1725
Timestamp: 2024-03-15T23:59:34.765Z
Learning: When removing a recording session using the `remove_recording_session` method in the `Labels` class, it's necessary to also update the `LabelsDataCache._session_by_video` dictionary to reflect the removal. This ensures that the mapping between videos and their corresponding recording sessions remains accurate.
Additional comments not posted (12)
sleap/gui/dialogs/delete.py (1)

219-219: Ensure proper handling when no instances are left in a labeled frame.

This change optimizes the removal process by directly removing the frame when it's empty, which is a logical improvement. Please ensure that remove_frame handles all necessary cleanup and state updates.

tests/fixtures/datasets.py (1)

283-288: New fixture for loading user-labeled data in a minimal session.

This fixture correctly loads the specified dataset and follows the established pattern for dataset fixtures in this file. Good job on maintaining consistency.

tests/io/test_cameras.py (2)

299-348: New function to create InstanceGroup objects.

This function is well-implemented and provides flexibility with the add_dummy parameter to test different scenarios. Ensure comprehensive tests cover all paths, including error handling and edge cases.


173-179: New method to create FrameGroup objects.

The method new_frame_group is correctly implemented and integrates well with the existing RecordingSession structure. Good use of assertions to validate the behavior.

tests/io/test_dataset.py (1)

1033-1033: Explicitly naming the video parameter in the function call enhances readability and reduces potential errors related to positional arguments. Good practice!

sleap/instance.py (1)

732-754: Consider handling NaN values more robustly in update_points.

The current implementation skips updating points if the new point is NaN or the old point is marked as complete. While this is generally a good approach, consider adding a mechanism to handle unexpected NaN values more gracefully, perhaps by logging or raising an exception if NaN values are not expected in this context.

sleap/io/dataset.py (1)

Line range hint 365-365: Avoid assigning lambda expressions directly to variables.

Consider defining a function with def instead of using a lambda expression for better readability and debuggability.

sleap/gui/commands.py (5)

Line range hint 1712-1712: Avoid using bare except statements as they can catch unexpected exceptions and hide bugs.

Consider specifying the exception types that you expect to handle.


Line range hint 1733-1733: Avoid using bare except statements as they can catch unexpected exceptions and hide bugs.

Consider specifying the exception types that you expect to handle.


Line range hint 2470-2470: The f-string does not contain any placeholders, which makes the use of f-string unnecessary.

Consider using a regular string if no formatting is needed.


Line range hint 2802-2802: The f-string does not contain any placeholders, which makes the use of f-string unnecessary.

Consider using a regular string if no formatting is needed.


Line range hint 3145-3145: Avoid using bare except statements as they can catch unexpected exceptions and hide bugs.

Consider specifying the exception types that you expect to handle.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@roomrys roomrys changed the base branch from develop to liezl/asc-initial-update-instances-across-views October 31, 2023 05:16
@codecov
Copy link

codecov bot commented Oct 31, 2023

Codecov Report

Attention: Patch coverage is 52.03837% with 200 lines in your changes are missing coverage. Please review.

Project coverage is 73.29%. Comparing base (a2326d3) to head (c3a8173).

❗ Current head c3a8173 differs from pull request most recent head 176efb2. Consider uploading reports for the commit 176efb2 to get more accurate results

Files Patch % Lines
sleap/io/cameras.py 54.23% 173 Missing ⚠️
sleap/gui/commands.py 16.12% 26 Missing ⚠️
sleap/instance.py 87.50% 1 Missing ⚠️
Additional details and impacted files
@@                                 Coverage Diff                                 @@
##           liezl/asc-initial-update-instances-across-views    #1579      +/-   ##
===================================================================================
- Coverage                                            73.71%   73.29%   -0.43%     
===================================================================================
  Files                                                  135      135              
  Lines                                                24502    24810     +308     
===================================================================================
+ Hits                                                 18062    18184     +122     
- Misses                                                6440     6626     +186     

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

@roomrys roomrys changed the title (-> 3) Add method to match instances across views (3a -> 3) Add method to match instances across views Nov 3, 2023
@roomrys
Copy link
Collaborator Author

roomrys commented Nov 3, 2023

@coderabbitai review

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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 4994f04 and d83ea64.
Files selected for processing (2)
  • sleap/gui/commands.py (12 hunks)
  • tests/gui/test_commands.py (8 hunks)
Additional comments: 13
tests/gui/test_commands.py (7)
  • 985-990: No issues found. The function signature and the initial setup look fine.

  • 1002-1006: No issues found. The assertions are checking the expected properties of the instances.

  • 1029-1033: No issues found. The assertions are checking the expected properties of the instances.

  • 1070-1108: No issues found. The function calls and assertions are checking the expected properties of the instances.

  • 1188-1202: No issues found. The function calls and assertions are checking the expected properties of the instances.

  • 1214-1227: No issues found. The function calls and assertions are checking the expected properties of the instances.

  • 1240-1258: No issues found. The function calls and assertions are checking the expected properties of the instances.

sleap/gui/commands.py (6)
  • 39-39: The cast function is imported but not used in the provided hunks. Ensure it is used elsewhere in the code or remove the import to maintain clean code.

  • 3429-3429: The ask method now has a return type annotation of bool. Ensure that all calls to this method throughout the codebase have been updated to handle the return type.

  • 3449-3449: The verify_views_and_instances method now has a return type annotation of bool. Ensure that all calls to this method throughout the codebase have been updated to handle the return type.

  • 3498-3498: The get_and_verify_enough_instances method has been renamed to get_instances_across_views_multiple_frames and now accepts a list of frame indices instead of a single frame index. Ensure that all calls to this method throughout the codebase have been updated to match the new signature.

  • 3516-3554: The get_and_verify_enough_instances method now returns a dictionary with frame identifier keys and values of another inner dictionary with Camcorder keys and List[Instance] values. Ensure that all calls to this method throughout the codebase have been updated to handle the return type.

  • 3643-3712: > Note: This review was outside of the patch, so it was mapped to the patch with the greatest overlap. Original lines [3606-3709]

The get_instances_across_views method has been renamed to get_instances_across_views_multiple_frames and now accepts a list of frame indices instead of a single frame index. Ensure that all calls to this method throughout the codebase have been updated to match the new signature.

tests/gui/test_commands.py Show resolved Hide resolved
@roomrys roomrys self-assigned this Jan 5, 2024
* Add method to get single instance permutations

* Append a dummy instance for missing instances

* Correct 'permutations' to 'products'

* (3c -> 3b) Add method to test instance grouping (#1599)

* (3d -> 3c) Add method for multi instance products (#1605)
* Add method to get single instance permutations

* Add method and (failing) test to get instance grouping

* Append a dummy instance for missing instances

* Update tests to accept a dummy instance

* Add initial InstanceGroup class

* Few extra tests for `InstanceGroup`

* Remember instance grouping after testing hypotheses

* Use reconsumable iterator for reprojected coords

* Only triangulate user instances, add fixture, update tests

* Normalize instance reprojection errors

* Add `locked`, `_dummy_instance`, `numpy`, and `update_points`

* Allow `PredictedPoint`s to be updated as well

* Add tests for new attributes and methods

* Add methods to create, add, replace, and remove instances

* Use PredictedInstance for new/dummy instances

* (3f -> 3e) Add `FrameGroup` class  (#1665)

* (3g -> 3f) Use frame group for triangulation (#1693)
@roomrys roomrys marked this pull request as ready for review April 18, 2024 19:54
@roomrys roomrys merged commit 2f56a1c into liezl/asc-initial-update-instances-across-views Apr 18, 2024
5 checks passed
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: 9

Actionable comments outside the diff hunks (25)
tests/fixtures/datasets.py (1)

Line range hint 1-1: Remove unused import to clean up the code.

- import os
tests/gui/test_commands.py (8)

Line range hint 5-5: Remove unused import Dict from typing.

- from typing import Dict, List
+ from typing import List

Line range hint 7-7: Remove unused import numpy.

- import numpy as np

Line range hint 21-21: Remove unused import TriangulateSession.

- from sleap.gui.commands import (
-     AddSession,
-     CommandContext,
-     ExportAnalysisFile,
-     ExportDatasetWithImages,
-     ImportDeepLabCutFolder,
-     OpenSkeleton,
-     RemoveVideo,
-     ReplaceVideo,
-     SaveProjectAs,
-     TriangulateSession,
-     get_new_version_filename,
- )
+ from sleap.gui.commands import (
+     AddSession,
+     CommandContext,
+     ExportAnalysisFile,
+     ExportDatasetWithImages,
+     ImportDeepLabCutFolder,
+     OpenSkeleton,
+     RemoveVideo,
+     ReplaceVideo,
+     SaveProjectAs,
+     get_new_version_filename,
+ )

Line range hint 25-25: Remove unused import Camcorder.

- from sleap.io.cameras import Camcorder

Line range hint 227-227: Replace equality comparison to True with a direct truth check.

- assert okay == True
+ assert okay

Line range hint 368-368: Use direct truth check instead of equality comparison to True.

- assert video.backend.grayscale == True
+ assert video.backend.grayscale

Line range hint 360-360: The local variable last_lf_frame is assigned but never used. Consider removing it if it's not needed.

- last_lf_frame = get_last_lf_in_video(labels, videos[0])

Line range hint 528-528: Remove unnecessary f-string as it contains no placeholders.

- default_name += f".{adaptor.default_ext}"
+ default_name += "." + adaptor.default_ext
sleap/instance.py (3)

Line range hint 411-411: Use isinstance() for type checks.

-        if from_predicted is not None and type(from_predicted) != PredictedInstance:
+        if from_predicted is not None and not isinstance(from_predicted, PredictedInstance):

Direct type comparisons using != can lead to issues, especially with inheritance. Use isinstance() for a more robust type check.


Line range hint 449-449: Use isinstance() for type checks.

-        if type(points) is dict:
+        if isinstance(points, dict):

Replace type comparison with isinstance() for consistency and to handle potential subclasses of dict.


Line range hint 1652-1652: Undefined name Labels in the method complex_merge_between.

It appears that the name Labels is used but not defined within this file or imported. Ensure that Labels is correctly imported from its module, or check if the name is incorrect or misspelled.

sleap/io/cameras.py (3)

Line range hint 79-79: Remove unnecessary f-string as it does not contain any placeholders.

- f"{self.name}, "
+ self.name + ", "

Line range hint 80-80: Remove unnecessary f-string as it does not contain any placeholders.

- f"{message[:-2]})"
+ message[:-2] + ")"

Line range hint 81-81: Remove unnecessary f-string as it does not contain any placeholders.

- f"{self.__class__.__name__}(name={self.name}, size={self.size})"
+ self.__class__.__name__ + "(name=" + self.name + ", size=" + self.size + ")"
sleap/io/dataset.py (8)

Line range hint 61-61: Unused import of h5py.

Please remove the unused import of h5py to maintain clean and efficient code.


Line range hint 69-69: Avoid using bare except.

Replace the bare except with a specific exception type to avoid catching unexpected exceptions, which can make debugging more difficult.


Line range hint 934-934: Use isinstance() for type checking.

Replace the type comparison using type() with isinstance() for a more robust and idiomatic check.

- if type(inst) == PredictedInstance:
+ if isinstance(inst, PredictedInstance):

Line range hint 2355-2355: Undefined name glob.

The function glob is used but not imported. Please add the necessary import statement:

from glob import glob

Line range hint 2450-2450: Avoid equality comparisons to False.

Use if not ret: instead of if ret == False: for a more Pythonic approach.

- if ret == False:
+ if not ret:

Line range hint 2553-2553: Undefined name sleap.

The module sleap is referenced but not imported. Ensure that the necessary import statement is added or correct the reference if it's a mistake.


Line range hint 2646-2646: Unused variable e.

The variable e is assigned in the except block but never used. Consider removing it if not needed.

- except IndexError as e:
+ except IndexError:

Line range hint 2648-2648: F-string without placeholders.

The f-string used does not contain any placeholders. Use a regular string instead if no formatting is needed.

- raise IndexError(f"There are no videos in this project. No points matrix to return.")
+ raise IndexError("There are no videos in this project. No points matrix to return.")
sleap/gui/commands.py (2)

Line range hint 196-196: Undefined name MainWindow may cause a runtime error if not handled properly.

Please ensure that MainWindow is defined or imported correctly in this context.


Line range hint 838-838: The local variable file_dir is assigned but never used, which is unnecessary.

Consider removing the assignment or using the variable appropriately.

import logging
import tempfile
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast, Set
Copy link

Choose a reason for hiding this comment

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

Remove unused import cast from typing.

- from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast, Set
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, Set

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.

Suggested change
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast, Set
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, Set

instance = self.instances[0]

# Use the example instance to create a dummy instance
skeleton: "Skeleton" = instance.skeleton
Copy link

Choose a reason for hiding this comment

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

Undefined name Skeleton used. Ensure that Skeleton is defined or imported in this file.

"""

# Get the `Skeleton`
skeleton: "Skeleton" = self.dummy_instance.skeleton
Copy link

Choose a reason for hiding this comment

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

Undefined name Skeleton used. Ensure that Skeleton is defined or imported in this file.

# isinstance(idx_or_key, Instance):
try:
return self.get_cam(idx_or_key)
except:
Copy link

Choose a reason for hiding this comment

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

Avoid using a bare except statement. Specify the exception type to handle specific exceptions appropriately.

- except:
+ except Exception as e:

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.

Suggested change
except:
except Exception as e:

@@ -35,8 +35,9 @@ class which inherits from `AppCommand` (or a more specialized class such as
import traceback
from enum import Enum
from glob import glob
from itertools import permutations, product
Copy link

Choose a reason for hiding this comment

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

Remove unused imports to clean up the code.

- from itertools import permutations, product

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.

Suggested change
from itertools import permutations, product

@@ -412,8 +914,9 @@
# TODO(LM): Consider implementing Observer pattern for `camera_cluster` and `labels`
camera_cluster: CameraCluster = field(factory=CameraCluster)
metadata: dict = field(factory=dict)
labels: Optional["Labels"] = field(default=None)
Copy link

Choose a reason for hiding this comment

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

Undefined name Labels used. Ensure that Labels is defined or imported in this file.

from pathlib import Path, PurePath
from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union
from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
Copy link

Choose a reason for hiding this comment

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

Remove unused import to clean up the code.

- from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
+ from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union

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.

Suggested change
from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union

Comment on lines +742 to +751
if type(self._points) == PredictedPointArray:
# TODO(LM): The point score is meant to rate the confidence of the
# prediction, but this method updates from triangulation.
score = points_old.score
point_obj = PredictedPoint(
x=x, y=y, visible=visible, complete=complete, score=score
)
else:
point_obj = Point(x=x, y=y, visible=visible, complete=complete)

Copy link

Choose a reason for hiding this comment

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

Ensure consistent handling of point types in update_points.

The method differentiates between PredictedPointArray and PointArray when creating new point objects. This is a good practice as it maintains the distinction between predicted and manually labeled points. However, ensure that this differentiation is consistently applied throughout your codebase to avoid type mismatches.

@@ -500,7 +500,6 @@
)
try:
parray[skeleton.node_to_index(node)] = point
# parray[skeleton.node_to_index(node.name)] = point
except:
Copy link

Choose a reason for hiding this comment

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

Avoid using a bare except statement.

-            except:
+            except Exception as e:
+                logger.error(f"Error setting point for node {node} in {skeleton} with point {point}: {str(e)}")

Using a bare except can catch unexpected exceptions and make debugging difficult. Specify the exception type or handle the general Exception and log the error for better error management.


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.

Suggested change
except:
except Exception as e:
logger.error(f"Error setting point for node {node} in {skeleton} with point {point}: {str(e)}")

@roomrys roomrys deleted the liezl/add-method-to-match-instances-across-views branch April 18, 2024 20:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
MultiView Stack This PR is part of the MultView stacked PRs.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant