-
Notifications
You must be signed in to change notification settings - Fork 100
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
Add menu item for deleting instances beyond frame limit #1797
Add menu item for deleting instances beyond frame limit #1797
Conversation
WalkthroughA new feature has been introduced to the SLEAP GUI application, allowing users to delete predicted instances beyond a specified frame limit. This involves adding a new menu item, creating a command to handle the deletion, and implementing tests to ensure functionality. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant GUI
participant Commands
participant DataHandler
User->>GUI: Clicks "Delete Predictions beyond Frame Limit..."
GUI->>Commands: Trigger deleteFrameLimitPredictions()
Commands->>DataHandler: Identify and delete instances beyond frame limit
DataHandler->>Commands: Confirm deletion
Commands->>GUI: Update display
GUI->>User: Show updated predictions
Possibly related PRs
Poem
Tip CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command 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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 (6)
sleap/gui/app.py (1)
Line range hint
261-261
: Remove the unused variablefilename
to clean up the code.- filename = event.mimeData().data(mime_format).data().decode()
sleap/gui/commands.py (5)
Line range hint
193-193
: Undefined reference toMainWindow
.The reference to
MainWindow
in theexecute
method ofNewProject
class is undefined within this file. Ensure thatMainWindow
is correctly imported or defined to avoid runtime errors.
Line range hint
817-817
: Unused variablefile_dir
.The variable
file_dir
in theask
method ofImportNWB
is assigned but never used. Consider removing it if it's not needed.
Line range hint
1691-1691
: Avoid using bareexcept
.Using a bare
except
is not recommended as it can catch unexpected exceptions and hide programming errors. Specify the exception types that you expect to handle.Also applies to: 1712-1712
Line range hint
2418-2418
: Remove unnecessary f-string.The f-string in this line does not contain any placeholders, making the use of an f-string unnecessary. Consider using a regular string instead.
Also applies to: 2787-2787
Line range hint
3149-3149
: Avoid using bareexcept
.Using a bare
except
is not recommended as it can catch unexpected exceptions and hide programming errors. Specify the exception types that you expect to handle.
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (2)
- sleap/gui/app.py (1 hunks)
- sleap/gui/commands.py (2 hunks)
Additional context used
Ruff
sleap/gui/app.py
261-261: Local variable
filename
is assigned to but never used (F841)sleap/gui/commands.py
193-193: Undefined name
MainWindow
(F821)
817-817: Local variable
file_dir
is assigned to but never used (F841)
1691-1691: Do not use bare
except
(E722)
1712-1712: Do not use bare
except
(E722)
2418-2418: f-string without any placeholders (F541)
2787-2787: f-string without any placeholders (F541)
3149-3149: Do not use bare
except
(E722)
Additional comments not posted (1)
sleap/gui/app.py (1)
793-795
: The addition of the new menu item "Delete Predictions beyond Frame Limit new item..." is correctly implemented and linked to the appropriate command.
def deleteFrameLimitPredictions(self): | ||
"""Gui for deleting instances beyond some frame number.""" | ||
self.execute(DeleteFrameLimitPredictions) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add method documentation for deleteFrameLimitPredictions
.
Consider adding a detailed docstring for the deleteFrameLimitPredictions
method to explain its parameters, return type, and any exceptions it might raise. This will enhance code maintainability and readability.
sleap/gui/commands.py
Outdated
class DeleteFrameLimitPredictions(InstanceDeleteCommand): | ||
@staticmethod | ||
def get_frame_instance_list(context: CommandContext, params: Dict): | ||
predicted_instances = [] | ||
# Select the instances to be deleted | ||
for lf in context.labels.find(context.state["video"]): | ||
if lf.frame_idx >= params["frame_idx_threshold"]: | ||
predicted_instances.extend( | ||
[(lf, inst) for inst in lf.predicted_instances] | ||
) | ||
return predicted_instances | ||
|
||
@classmethod | ||
def ask(cls, context: CommandContext, params: Dict) -> bool: | ||
current_video = context.state["video"] | ||
frame_idx_thresh, okay = QtWidgets.QInputDialog.getInt( | ||
context.app, | ||
"Delete Instance beyond Frame Number...", | ||
"Frame number after which instances to be deleted:", | ||
1, | ||
1, | ||
len(current_video), | ||
) | ||
if okay: | ||
params["frame_idx_threshold"] = frame_idx_thresh | ||
return super().ask(context, params) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure proper validation and error handling in DeleteFrameLimitPredictions
.
- if okay:
+ if okay and frame_idx_thresh > 0:
It's crucial to validate the frame_idx_threshold
to ensure it's a positive integer. This prevents logical errors where a negative frame index could potentially delete all instances.
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.
class DeleteFrameLimitPredictions(InstanceDeleteCommand): | |
@staticmethod | |
def get_frame_instance_list(context: CommandContext, params: Dict): | |
predicted_instances = [] | |
# Select the instances to be deleted | |
for lf in context.labels.find(context.state["video"]): | |
if lf.frame_idx >= params["frame_idx_threshold"]: | |
predicted_instances.extend( | |
[(lf, inst) for inst in lf.predicted_instances] | |
) | |
return predicted_instances | |
@classmethod | |
def ask(cls, context: CommandContext, params: Dict) -> bool: | |
current_video = context.state["video"] | |
frame_idx_thresh, okay = QtWidgets.QInputDialog.getInt( | |
context.app, | |
"Delete Instance beyond Frame Number...", | |
"Frame number after which instances to be deleted:", | |
1, | |
1, | |
len(current_video), | |
) | |
if okay: | |
params["frame_idx_threshold"] = frame_idx_thresh | |
return super().ask(context, params) | |
class DeleteFrameLimitPredictions(InstanceDeleteCommand): | |
@staticmethod | |
def get_frame_instance_list(context: CommandContext, params: Dict): | |
predicted_instances = [] | |
# Select the instances to be deleted | |
for lf in context.labels.find(context.state["video"]): | |
if lf.frame_idx >= params["frame_idx_threshold"]: | |
predicted_instances.extend( | |
[(lf, inst) for inst in lf.predicted_instances] | |
) | |
return predicted_instances | |
@classmethod | |
def ask(cls, context: CommandContext, params: Dict) -> bool: | |
current_video = context.state["video"] | |
frame_idx_thresh, okay = QtWidgets.QInputDialog.getInt( | |
context.app, | |
"Delete Instance beyond Frame Number...", | |
"Frame number after which instances to be deleted:", | |
1, | |
1, | |
len(current_video), | |
) | |
if okay and frame_idx_thresh > 0: | |
params["frame_idx_threshold"] = frame_idx_thresh | |
return super().ask(context, params) |
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #1797 +/- ##
===========================================
+ Coverage 73.30% 75.51% +2.20%
===========================================
Files 134 133 -1
Lines 24087 24666 +579
===========================================
+ Hits 17658 18627 +969
+ Misses 6429 6039 -390 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this 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
Outside diff range and nitpick comments (22)
tests/gui/test_commands.py (6)
Line range hint
76-76
: Remove duplicate items from sets to ensure data integrity.- "tests/data/dlc_multiple_datasets/video1/img000.jpg", - "tests/data/dlc_multiple_datasets/video1/img000.jpg", + "tests/data/dlc_multiple_datasets/video1/img000.jpg",- {0, 0, 1} + {0, 1}Also applies to: 79-79
Line range hint
134-137
: Simplify the assignment ofcsv
using a ternary operator.- if out_suffix == "csv": - csv = True - else: - csv = False + csv = True if out_suffix == "csv" else False
Line range hint
225-225
: Replace equality comparisons toTrue
with direct truth checks.- assert okay == True + assert okayAlso applies to: 234-234, 242-242, 251-251, 263-263, 272-272, 279-279, 297-297
Line range hint
358-358
: Remove the unused variablelast_lf_frame
to clean up the code.- last_lf_frame = get_last_lf_in_video(labels, videos[0])
Line range hint
366-366
: Use direct truth checks instead of comparing toTrue
.- assert video.backend.grayscale == True + assert video.backend.grayscale
Line range hint
526-526
: Remove the extraneousf
prefix from the string since there are no placeholders.- default_name += f".{adaptor.default_ext}" + default_name += ".{adaptor.default_ext}"sleap/gui/app.py (6)
Line range hint
123-123
: Usesuper()
instead ofsuper(__class__, self)
.- super(MainWindow, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs)
Line range hint
194-194
: Usesuper()
instead ofsuper(__class__, self)
.- super(MainWindow, self).setWindowTitle(f"{value} - SLEAP v{sleap.version.__version__}") + super().setWindowTitle(f"{value} - SLEAP v{sleap.version.__version__}")
Line range hint
209-210
: Combine nestedif
statements usingand
.- if e.type() == QEvent.StatusTip: - if e.tip() == "": + if e.type() == QEvent.StatusTip and e.tip() == "":
Line range hint
261-261
: Local variablefilename
is assigned to but never used.- filename = event.mimeData().data(mime_format).data().decode()
Line range hint
1087-1087
: Remove extraneous parentheses.- if (n_instances > 0) and not self.state["show instances"]: + if n_instances > 0 and not self.state["show instances"]:
Line range hint
1148-1151
: Use a more concise expression withany()
.- def _has_topic(topic_list): - if UpdateTopic.all in what: - return True - for topic in topic_list: - if topic in what: - return True - return False + def _has_topic(topic_list): + return UpdateTopic.all in what or any(topic in what for topic in topic_list)sleap/gui/commands.py (10)
Line range hint
193-193
: Undefined reference toMainWindow
.Please ensure that
MainWindow
is defined or imported in this file, as it is referenced in theCommandContext
class.
Line range hint
653-653
: Simplify dictionary access.- params.get("filename", None) + params.get("filename")
Line range hint
756-756
: Simplify dictionary access.- video_path = params["video_path"] if "video_path" in params else None + video_path = params.get("video_path", None)
Line range hint
817-817
: Remove unused variable.- file_dir = os.path.dirname(filename)
The variable
file_dir
is assigned but never used. Consider removing it to clean up the code.
Line range hint
1691-1691
: Avoid using bareexcept
.Using bare
except
can catch unexpected exceptions and hide programming errors. Specify the exception type or useexcept Exception
to catch all standard errors.Also applies to: 1712-1712
Line range hint
1972-1972
: Improve exception chaining.- except Exception as e: + except Exception as e: + raise RuntimeError("Failed to save project.") from eUse
raise ... from
to provide context for the exception and help with debugging.
Line range hint
2101-2101
: Simplify dictionary key check.- if node not in instance.nodes.keys(): + if node not in instance.nodes:You can directly check for the existence of a key in a dictionary without using
.keys()
.Also applies to: 2116-2116
Line range hint
2418-2418
: Remove unnecessary f-string prefix.- f"This video type {type(video.backend)} for video at index {idx} " + "This video type {type(video.backend)} for video at index {idx} "The f-string is used without placeholders, so the prefix can be removed.
Also applies to: 2789-2789
Line range hint
2887-2887
: Simplify dictionary access.- params.get("copy_instance", None) + params.get("copy_instance") - params.get("location", None) + params.get("location")Also applies to: 2889-2889
Line range hint
3151-3151
: Avoid using bareexcept
.Using bare
except
can catch unexpected exceptions and hide programming errors. Specify the exception type or useexcept Exception
to catch all standard errors.
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (3)
- sleap/gui/app.py (1 hunks)
- sleap/gui/commands.py (2 hunks)
- tests/gui/test_commands.py (2 hunks)
Additional context used
Ruff
tests/gui/test_commands.py
72-72: Ambiguous variable name:
l
(E741)
76-76: Sets should not contain duplicate item
"tests/data/dlc_multiple_datasets/video1/img000.jpg"
(B033)Remove duplicate item
79-79: Ambiguous variable name:
l
(E741)
79-79: Sets should not contain duplicate item
0
(B033)Remove duplicate item
134-137: Use ternary operator
csv = True if out_suffix == "csv" else False
instead ofif
-else
-block (SIM108)Replace
if
-else
-block withcsv = True if out_suffix == "csv" else False
200-200: Loop control variable
video
not used within loop body (B007)Rename unused
video
to_video
225-225: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
234-234: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
242-242: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
251-251: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
263-263: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
272-272: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
279-279: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
297-297: Avoid equality comparisons to
True
; useif okay:
for truth checks (E712)Replace with
okay
303-303: Loop control variable
video
not used within loop body (B007)Rename unused
video
to_video
358-358: Local variable
last_lf_frame
is assigned to but never used (F841)Remove assignment to unused variable
last_lf_frame
366-366: Avoid equality comparisons to
True
; useif video.backend.grayscale:
for truth checks (E712)Replace with
video.backend.grayscale
526-526: f-string without any placeholders (F541)
Remove extraneous
f
prefixsleap/gui/app.py
123-123: Use
super()
instead ofsuper(__class__, self)
(UP008)Remove
__super__
parameters
194-194: Use
super()
instead ofsuper(__class__, self)
(UP008)Remove
__super__
parameters
209-210: Use a single
if
statement instead of nestedif
statements (SIM102)Combine
if
statements usingand
261-261: Local variable
filename
is assigned to but never used (F841)Remove assignment to unused variable
filename
1087-1087: Avoid extraneous parentheses (UP034)
Remove extraneous parentheses
1148-1151: Use
return any(topic in what for topic in topic_list)
instead offor
loop (SIM110)Replace with
return any(topic in what for topic in topic_list)
sleap/gui/commands.py
193-193: Undefined name
MainWindow
(F821)
653-653: Use
params.get("filename")
instead ofparams.get("filename", None)
(SIM910)Replace
params.get("filename", None)
withparams.get("filename")
756-756: Use
params.get("video_path", None)
instead of anif
block (SIM401)Replace with
params.get("video_path", None)
817-817: Local variable
file_dir
is assigned to but never used (F841)Remove assignment to unused variable
file_dir
1691-1691: Do not use bare
except
(E722)
1712-1712: Do not use bare
except
(E722)
1972-1972: Within an
except
clause, raise exceptions withraise ... from err
orraise ... from None
to distinguish them from errors in exception handling (B904)
2101-2101: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2116-2116: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2418-2418: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2789-2789: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2887-2887: Use
params.get("copy_instance")
instead ofparams.get("copy_instance", None)
(SIM910)Replace
params.get("copy_instance", None)
withparams.get("copy_instance")
2889-2889: Use
params.get("location")
instead ofparams.get("location", None)
(SIM910)Replace
params.get("location", None)
withparams.get("location")
3151-3151: Do not use bare
except
(E722)
Additional comments not posted (3)
tests/gui/test_commands.py (2)
19-19
: The import ofDeleteFrameLimitPredictions
is correctly placed in the import section. Ensure that all necessary methods from this class are covered by unit tests.
851-871
: The new test functiontest_DeleteFrameLimitPredictions
is well-structured and tests the functionality as described in the PR. Ensure that theexpected_instances
value is derived from a reliable source or calculation to maintain test accuracy.sleap/gui/app.py (1)
791-796
: Ensure the new menu item "Delete Predictions beyond Frame Limit..." is correctly integrated and accessible.This addition aligns with the PR's objective to enhance usability by allowing users to delete predictions beyond a specified frame limit. Please ensure that this new menu item is tested thoroughly to confirm its functionality.
There was a problem hiding this 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
Outside diff range and nitpick comments (10)
sleap/gui/commands.py (10)
Line range hint
193-193
: Undefined reference toMainWindow
.The reference to
MainWindow
in the methodexecute
of theAppCommand
class is undefined within this file. Ensure thatMainWindow
is properly imported or defined, or use a different existing reference.- MainWindow + [Correct reference or import statement]
Line range hint
653-653
: Simplify dictionary access.Use
params.get("filename")
instead ofparams.get("filename", None)
for simplicity and readability.- params.get("filename", None) + params.get("filename")
Line range hint
756-756
: Simplify dictionary access.Use
params.get("video_path", None)
instead of anif
block for simplicity and readability.- video_path = params["video_path"] if "video_path" in params else None + video_path = params.get("video_path", None)
Line range hint
817-817
: Remove unused variable.The local variable
file_dir
is assigned but never used. Consider removing it to clean up the code.- file_dir = os.path.dirname(filename)
Line range hint
1691-1691
: Avoid using bareexcept
.Using a bare
except
can catch unexpected exceptions and hide programming errors. Specify the exception type to improve error handling.- except: + except Exception as e:Also applies to: 1712-1712
Line range hint
1972-1972
: Improve exception chaining.Within an
except
clause, raise exceptions withraise ... from err
orraise ... from None
to distinguish them from errors in exception handling.- raise TypeError("Importing videos with different extensions is not supported.") + raise TypeError("Importing videos with different extensions is not supported.") from None
Line range hint
2101-2101
: Usekey in dict
instead ofkey in dict.keys()
.For checking if a key is in a dictionary, it's more idiomatic and slightly faster to use
key in dict
instead ofkey in dict.keys()
.- if node not in instance.nodes.keys(): + if node not in instance.nodes:Also applies to: 2116-2116
Line range hint
2418-2418
: Remove extraneousf
prefix from strings.The
f
prefix is used for formatted strings in Python, but it's unnecessary when the string does not contain any placeholders.- f"This video type {type(video.backend)} for video at index {idx} does not support grayscale yet." + "This video type does not support grayscale yet."Also applies to: 2789-2789
Line range hint
2887-2887
: Simplify dictionary access.Use
params.get("copy_instance")
andparams.get("location")
instead ofparams.get("copy_instance", None)
andparams.get("location", None)
for simplicity and readability.- params.get("copy_instance", None) + params.get("copy_instance") - params.get("location", None) + params.get("location")Also applies to: 2889-2889
Line range hint
3151-3151
: Avoid using bareexcept
.Using a bare
except
can catch unexpected exceptions and hide programming errors. Specify the exception type to improve error handling.- except: + except Exception as e:
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- sleap/gui/commands.py (2 hunks)
Additional context used
Ruff
sleap/gui/commands.py
193-193: Undefined name
MainWindow
(F821)
653-653: Use
params.get("filename")
instead ofparams.get("filename", None)
(SIM910)Replace
params.get("filename", None)
withparams.get("filename")
756-756: Use
params.get("video_path", None)
instead of anif
block (SIM401)Replace with
params.get("video_path", None)
817-817: Local variable
file_dir
is assigned to but never used (F841)Remove assignment to unused variable
file_dir
1691-1691: Do not use bare
except
(E722)
1712-1712: Do not use bare
except
(E722)
1972-1972: Within an
except
clause, raise exceptions withraise ... from err
orraise ... from None
to distinguish them from errors in exception handling (B904)
2101-2101: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2116-2116: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2418-2418: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2789-2789: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2887-2887: Use
params.get("copy_instance")
instead ofparams.get("copy_instance", None)
(SIM910)Replace
params.get("copy_instance", None)
withparams.get("copy_instance")
2889-2889: Use
params.get("location")
instead ofparams.get("location", None)
(SIM910)Replace
params.get("location", None)
withparams.get("location")
3151-3151: Do not use bare
except
(E722)
Additional comments not posted (2)
sleap/gui/commands.py (2)
497-500
: Add method documentation fordeleteFrameLimitPredictions
.Consider adding a detailed docstring for the
deleteFrameLimitPredictions
method to explain its parameters, return type, and any exceptions it might raise. This will enhance code maintainability and readability.
2476-2487
: Add a comment that this is used in theInstanceDeleteCommand.ask
method.
sleap/gui/commands.py
Outdated
"""Called from the parent `InstanceDeleteCommand.ask` class. Returns a list of | ||
instances to be deleted.""" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Have a single line summary docstring followed by Args and Returns if needed.
…ps://github.com/talmolab/sleap into shrivaths/delete-predictions-beyond-frame-limit
There was a problem hiding this 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
Outside diff range and nitpick comments (10)
sleap/gui/commands.py (10)
Line range hint
193-193
: Undefined reference toMainWindow
.- """Entry point for running command. + """Entry point for running command in `MainWindow`.Ensure that
MainWindow
is correctly imported or defined within the scope where it's referenced.
Line range hint
653-653
: Simplify theget
method for dictionary access.- filename = params.get("filename", None) # If called with just a Labels object + filename = params.get("filename") # If called with just a Labels object
Line range hint
756-756
: Use theget
method with a default value directly.- video_path = params["video_path"] if "video_path" in params else None + video_path = params.get("video_path", None)
Line range hint
817-817
: Remove assignment to unused variablefile_dir
.- file_dir = os.path.dirname(filename)
Line range hint
1691-1691
: Avoid using bareexcept
statements. Specify exception types to handle specific exceptions appropriately.- except: + except Exception as e:Also applies to: 1712-1712
Line range hint
1972-1972
: When re-raising exceptions, useraise ... from err
to provide context.- raise e + raise Exception("Error during save operation.") from e
Line range hint
2101-2101
: Usekey in dict
instead ofkey in dict.keys()
.- if node not in instance.nodes.keys(): + if node not in instance.nodes:Also applies to: 2116-2116
Line range hint
2418-2418
: Remove extraneousf
prefix from strings that do not contain placeholders.- f"This video type {type(video.backend)} for video at index {idx} " + "This video type {type(video.backend)} for video at index {idx} "Also applies to: 2792-2792
Line range hint
2890-2890
: Simplify theget
method for dictionary access.- copy_instance = params.get("copy_instance", None) + copy_instance = params.get("copy_instance") - location = params.get("location", None) + location = params.get("location")Also applies to: 2892-2892
Line range hint
3154-3154
: Avoid using bareexcept
statements. Specify exception types to handle specific exceptions appropriately.- except: + except Exception as e:
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- sleap/gui/commands.py (2 hunks)
Additional context used
Ruff
sleap/gui/commands.py
193-193: Undefined name
MainWindow
(F821)
653-653: Use
params.get("filename")
instead ofparams.get("filename", None)
(SIM910)Replace
params.get("filename", None)
withparams.get("filename")
756-756: Use
params.get("video_path", None)
instead of anif
block (SIM401)Replace with
params.get("video_path", None)
817-817: Local variable
file_dir
is assigned to but never used (F841)Remove assignment to unused variable
file_dir
1691-1691: Do not use bare
except
(E722)
1712-1712: Do not use bare
except
(E722)
1972-1972: Within an
except
clause, raise exceptions withraise ... from err
orraise ... from None
to distinguish them from errors in exception handling (B904)
2101-2101: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2116-2116: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2418-2418: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2792-2792: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2890-2890: Use
params.get("copy_instance")
instead ofparams.get("copy_instance", None)
(SIM910)Replace
params.get("copy_instance", None)
withparams.get("copy_instance")
2892-2892: Use
params.get("location")
instead ofparams.get("location", None)
(SIM910)Replace
params.get("location", None)
withparams.get("location")
3154-3154: Do not use bare
except
(E722)
Additional comments not posted (2)
sleap/gui/commands.py (2)
497-500
: Consider adding a detailed docstring for thedeleteFrameLimitPredictions
method to explain its parameters, return type, and any exceptions it might raise. This will enhance code maintainability and readability.
2476-2477
: Add a comment that this is used in theInstanceDeleteCommand.ask
method.
There was a problem hiding this 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
Outside diff range and nitpick comments (10)
sleap/gui/commands.py (10)
Line range hint
193-193
: Specify correct type hint forMainWindow
.The type hint for
MainWindow
is missing, causing an undefined name issue. Please importMainWindow
or define it if it's a custom class.+ from sleap.gui.mainwindow import MainWindow
Line range hint
653-653
: Simplify dictionary access.Directly use
params.get("filename")
instead ofparams.get("filename", None)
asNone
is the default return value for theget
method.- filename = params.get("filename", None) # If called with just a Labels object + filename = params.get("filename") # If called with just a Labels object
Line range hint
756-756
: Simplify dictionary access.Replace the
if
block withparams.get("video_path", None)
for cleaner and more efficient code.- video_path = params["video_path"] if "video_path" in params else None + video_path = params.get("video_path", None)
Line range hint
817-817
: Remove unused variable.The variable
file_dir
is assigned but never used. Consider removing it to clean up the code.- file_dir = os.path.dirname(filename)
Line range hint
1691-1691
: Avoid using bareexcept
statements.Using bare
except
statements can catch unexpected exceptions and hide programming errors. Specify the exception type or useexcept Exception
to catch all standard exceptions.- except: + except Exception:Also applies to: 1712-1712
Line range hint
1972-1972
: Improve exception chaining for clarity.When re-raising exceptions, use the
from
keyword to clarify whether the new exception was directly caused by the previous one.- except Exception as e: + except Exception as e: + raise RuntimeError("Failed to save") from e
Line range hint
2101-2101
: Simplify dictionary key check.Use
key in dict
instead ofkey in dict.keys()
for more concise and pythonic code.- if node in instance.nodes.keys(): + if node in instance.nodes:Also applies to: 2116-2116
Line range hint
2420-2420
: Remove unnecessary f-string prefix.The f-string syntax is used without placeholders, which is unnecessary. Remove the
f
prefix.- f"This video type {type(video.backend)} for video at index {idx} " + "This video type {type(video.backend)} for video at index {idx} "Also applies to: 2796-2796
Line range hint
2894-2894
: Simplify dictionary access.Use
params.get("key")
directly as it is cleaner and the default return isNone
.- copy_instance = params.get("copy_instance", None) + copy_instance = params.get("copy_instance") - location = params.get("location", None) + location = params.get("location")Also applies to: 2896-2896
Line range hint
3158-3158
: Avoid using bareexcept
statements.Replace bare
except
withexcept Exception
to avoid catching unexpected exceptions.- except: + except Exception:
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- sleap/gui/commands.py (2 hunks)
Additional context used
Ruff
sleap/gui/commands.py
193-193: Undefined name
MainWindow
(F821)
653-653: Use
params.get("filename")
instead ofparams.get("filename", None)
(SIM910)Replace
params.get("filename", None)
withparams.get("filename")
756-756: Use
params.get("video_path", None)
instead of anif
block (SIM401)Replace with
params.get("video_path", None)
817-817: Local variable
file_dir
is assigned to but never used (F841)Remove assignment to unused variable
file_dir
1691-1691: Do not use bare
except
(E722)
1712-1712: Do not use bare
except
(E722)
1972-1972: Within an
except
clause, raise exceptions withraise ... from err
orraise ... from None
to distinguish them from errors in exception handling (B904)
2101-2101: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2116-2116: Use
key in dict
instead ofkey in dict.keys()
(SIM118)Remove
.keys()
2420-2420: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2796-2796: f-string without any placeholders (F541)
Remove extraneous
f
prefix
2894-2894: Use
params.get("copy_instance")
instead ofparams.get("copy_instance", None)
(SIM910)Replace
params.get("copy_instance", None)
withparams.get("copy_instance")
2896-2896: Use
params.get("location")
instead ofparams.get("location", None)
(SIM910)Replace
params.get("location", None)
withparams.get("location")
3158-3158: Do not use bare
except
(E722)
Additional comments not posted (2)
sleap/gui/commands.py (2)
497-500
: Add method documentation fordeleteFrameLimitPredictions
.Consider adding a detailed docstring for the
deleteFrameLimitPredictions
method to explain its parameters, return type, and any exceptions it might raise. This will enhance code maintainability and readability.
2478-2479
: Add a comment that this is used in theInstanceDeleteCommand.ask
method.This comment helps clarify the relationship between the
DeleteFrameLimitPredictions
class and its superclass, making the code easier to understand.
There was a problem hiding this 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
♻️ Duplicate comments (1)
sleap/gui/commands.py (1)
2479-2511
: 🛠️ Refactor suggestionAdd method documentation and input validation.
The command implementation is good but needs:
- Docstring for the
get_frame_instance_list
method- Validation of the frame threshold value
Apply this diff to add validation:
@classmethod def ask(cls, context: CommandContext, params: Dict) -> bool: current_video = context.state["video"] frame_idx_thresh, okay = QtWidgets.QInputDialog.getInt( context.app, "Delete Instance beyond Frame Number...", "Frame number after which instances to be deleted:", 1, 1, len(current_video), ) - if okay: + if okay and frame_idx_thresh > 0: params["frame_idx_threshold"] = frame_idx_thresh return super().ask(context, params)
🧹 Nitpick comments (1)
tests/gui/test_commands.py (1)
855-874
: Test implementation looks good but could be more comprehensive.The test verifies the basic functionality of deleting instances beyond a frame limit. However, consider adding more test cases to cover:
- Edge cases (frame_idx_threshold = 0, negative values)
- Boundary conditions (frame_idx_threshold = video length)
- Cases where no instances are deleted
@pytest.mark.parametrize("frame_idx_threshold,expected_count", [ (900, 423), # Current test case (0, 0), # Edge case: no instances deleted (-1, 0), # Invalid input (1000000, 423), # Beyond video length ]) def test_DeleteFrameLimitPredictions( centered_pair_predictions: Labels, centered_pair_vid: Video, frame_idx_threshold: int, expected_count: int ): """Test deleting instances beyond a frame limit.""" labels = centered_pair_predictions context = CommandContext.from_labels(labels) context.state["video"] = centered_pair_vid params = {"frame_idx_threshold": frame_idx_threshold} predicted_instances = DeleteFrameLimitPredictions.get_frame_instance_list( context, params ) assert len(predicted_instances) == expected_count
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
sleap/gui/app.py
(1 hunks)sleap/gui/commands.py
(2 hunks)tests/gui/test_commands.py
(2 hunks)
🔇 Additional comments (1)
sleap/gui/app.py (1)
807-812
: LGTM! Menu item is well-integrated.
The menu item for deleting predictions beyond frame limit is properly placed in the Labels menu alongside other prediction deletion options, follows consistent naming patterns, and correctly links to the command handler.
There was a problem hiding this 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
🧹 Nitpick comments (3)
sleap/config/frame_range_form.yaml (1)
13-13
: Add newline at end of file.Add a newline character at the end of the file to follow YAML best practices.
default: 1000 +
🧰 Tools
🪛 yamllint (1.35.1)
[error] 13-13: no new line character at the end of file
(new-line-at-end-of-file)
sleap/gui/dialogs/frame_range.py (1)
39-42
: Document the test code in the main block.Add a comment explaining that this is test code for manual testing of the dialog.
if __name__ == "__main__": + # Manual test code for the frame range dialog app = QtWidgets.QApplication([]) dialog = FrameRangeDialog(max_frame_idx=100) print(dialog.get_results())
sleap/gui/commands.py (1)
2480-2509
: LGTM! The DeleteFrameLimitPredictions implementation is solid.The implementation correctly:
- Inherits from InstanceDeleteCommand
- Uses FrameRangeDialog for user input
- Handles frame range selection and instance deletion
However, consider adding frame index validation:
@classmethod def ask(cls, context: CommandContext, params: Dict) -> bool: current_video = context.state["video"] dialog = FrameRangeDialog( title="Delete Instances in Frame Range...", max_frame_idx=len(current_video) ) results = dialog.get_results() if results: + min_frame_idx = results["min_frame_idx"] + max_frame_idx = results["max_frame_idx"] + if min_frame_idx > max_frame_idx: + QtWidgets.QMessageBox.warning( + context.app, + "Invalid Frame Range", + "Minimum frame index cannot be greater than maximum frame index." + ) + return False params["min_frame_idx"] = results["min_frame_idx"] params["max_frame_idx"] = results["max_frame_idx"] return super().ask(context, params)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
sleap/config/frame_range_form.yaml
(1 hunks)sleap/gui/commands.py
(3 hunks)sleap/gui/dialogs/frame_range.py
(1 hunks)
🧰 Additional context used
🪛 yamllint (1.35.1)
sleap/config/frame_range_form.yaml
[error] 13-13: no new line character at the end of file
(new-line-at-end-of-file)
🪛 Ruff (0.8.2)
sleap/gui/dialogs/frame_range.py
27-27: Local variable min_frame_idx_field
is assigned to but never used
Remove assignment to unused variable min_frame_idx_field
(F841)
34-34: Local variable max_frame_idx_field
is assigned to but never used
Remove assignment to unused variable max_frame_idx_field
(F841)
🔇 Additional comments (4)
sleap/config/frame_range_form.yaml (1)
1-13
: LGTM! The frame range configuration looks good.
The parameter ranges and default values are well-chosen for frame indexing:
- Range of 1 to 1,000,000 provides good flexibility
- Default values (min=1, max=1000) are sensible starting points
🧰 Tools
🪛 yamllint (1.35.1)
[error] 13-13: no new line character at the end of file
(new-line-at-end-of-file)
sleap/gui/dialogs/frame_range.py (2)
1-5
: LGTM! The imports and module docstring are appropriate.
The imports are correctly organized and the module has a clear docstring.
7-25
: LGTM! The dialog initialization is well-implemented.
The constructor properly initializes the form and sets up field ranges based on the provided max_frame_idx.
sleap/gui/commands.py (1)
498-501
: Add docstring to deleteFrameLimitPredictions method.
Add a docstring to explain the method's purpose and behavior.
def deleteFrameLimitPredictions(self):
+ """Shows GUI for deleting instances beyond a specified frame range.
+
+ This method opens a frame range dialog that allows users to specify minimum and
+ maximum frame indices. Any instances outside this range will be deleted.
+ """
self.execute(DeleteFrameLimitPredictions)
def _update_max_frame_range(self, value): | ||
min_frame_idx_field = self.form_widget.fields["min_frame_idx"] | ||
max_frame_idx_field = self.form_widget.fields["max_frame_idx"] | ||
|
||
max_frame_idx_field.setRange(value, max_frame_idx_field.maximum()) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unused variable in _update_max_frame_range method.
The min_frame_idx_field
variable is assigned but never used.
def _update_max_frame_range(self, value):
- min_frame_idx_field = self.form_widget.fields["min_frame_idx"]
max_frame_idx_field = self.form_widget.fields["max_frame_idx"]
max_frame_idx_field.setRange(value, max_frame_idx_field.maximum())
📝 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.
def _update_max_frame_range(self, value): | |
min_frame_idx_field = self.form_widget.fields["min_frame_idx"] | |
max_frame_idx_field = self.form_widget.fields["max_frame_idx"] | |
max_frame_idx_field.setRange(value, max_frame_idx_field.maximum()) | |
def _update_max_frame_range(self, value): | |
max_frame_idx_field = self.form_widget.fields["max_frame_idx"] | |
max_frame_idx_field.setRange(value, max_frame_idx_field.maximum()) | |
🧰 Tools
🪛 Ruff (0.8.2)
27-27: Local variable min_frame_idx_field
is assigned to but never used
Remove assignment to unused variable min_frame_idx_field
(F841)
def _update_min_frame_range(self, value): | ||
min_frame_idx_field = self.form_widget.fields["min_frame_idx"] | ||
max_frame_idx_field = self.form_widget.fields["max_frame_idx"] | ||
|
||
min_frame_idx_field.setRange(min_frame_idx_field.minimum(), value) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unused variable in _update_min_frame_range method.
The max_frame_idx_field
variable is assigned but never used.
def _update_min_frame_range(self, value):
min_frame_idx_field = self.form_widget.fields["min_frame_idx"]
- max_frame_idx_field = self.form_widget.fields["max_frame_idx"]
min_frame_idx_field.setRange(min_frame_idx_field.minimum(), value)
📝 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.
def _update_min_frame_range(self, value): | |
min_frame_idx_field = self.form_widget.fields["min_frame_idx"] | |
max_frame_idx_field = self.form_widget.fields["max_frame_idx"] | |
min_frame_idx_field.setRange(min_frame_idx_field.minimum(), value) | |
def _update_min_frame_range(self, value): | |
min_frame_idx_field = self.form_widget.fields["min_frame_idx"] | |
min_frame_idx_field.setRange(min_frame_idx_field.minimum(), value) |
🧰 Tools
🪛 Ruff (0.8.2)
34-34: Local variable max_frame_idx_field
is assigned to but never used
Remove assignment to unused variable max_frame_idx_field
(F841)
* Remove no-op code from #1498 * Add options to set background color when exporting video (#1328) * implement #921 * simplified form / refractor * Add test function and update cli docs * Improve test function to check background color * Improve comments * Change background options to lowercase * Use coderabbitai suggested `fill` --------- Co-authored-by: Shrivaths Shyam <[email protected]> Co-authored-by: Liezl Maree <[email protected]> * Increase range on batch size (#1513) * Increase range on batch size * Set maximum to a factor of 2 * Set default callable for `match_lists_function` (#1520) * Set default for `match_lists_function` * Move test code to official tests * Check using expected values * Allow passing in `Labels` to `app.main` (#1524) * Allow passing in `Labels` to `app.main` * Load the labels object through command * Add warning when unable to switch back to CPU mode * Replace (broken) `--unrag` with `--ragged` (#1539) * Fix unrag always set to true in sleap-export * Replace unrag with ragged * Fix typos * Add function to create app (#1546) * Refactor `AddInstance` command (#1561) * Refactor AddInstance command * Add staticmethod wrappers * Return early from set_visible_nodes * Import DLC with uniquebodyparts, add Tracks (#1562) * Import DLC with uniquebodyparts, add Tracks * add tests * correct tests * Make the hdf5 videos store as int8 format (#1559) * make the hdf5 video dataset type as proper int8 by padding with zeros * add gzip compression * Scale new instances to new frame size (#1568) * Fix typehinting in `AddInstance` * brought over changes from my own branch * added suggestions * Ensured google style comments --------- Co-authored-by: roomrys <[email protected]> Co-authored-by: sidharth srinath <[email protected]> * Fix package export (#1619) Add check for empty videos * Add resize/scroll to training GUI (#1565) * Make resizable training GUI and add adaptive scroll bar * Set a maximum window size --------- Co-authored-by: Liezl Maree <[email protected]> * support loading slp files with non-compound types and str in metadata (#1566) Co-authored-by: Liezl Maree <[email protected]> * change inference pipeline option to tracking-only (#1666) change inference pipeline none option to tracking-only * Add ABL:AOC 2023 Workshop link (#1673) * Add ABL:AOC 2023 Workshop link * Trigger website build * Graceful failing with seeking errors (#1712) * Don't try to seek to faulty last frame on provider initialization * Catch seeking errors and pass * Lint * Fix IndexError for hdf5 file import for single instance analysis files (#1695) * Fix hdf5 read for single instance analysis files * Add test * Small test files * removing unneccessary fixtures * Replace imgaug with albumentations (#1623) What's the worst that could happen? * Initial commit * Fix augmentation * Update more deps requirements * Use pip for installing albumentations and avoid reinstalling OpenCV * Update other conda envs * Fix out of bounds albumentations issues and update dependencies (#1724) * Install albumentations using conda-forge in environment file * Conda install albumentations * Add ndx-pose to pypi requirements * Keep out of bounds points * Black * Add ndx-pose to conda install in environment file * Match environment file without cuda * Ordered dependencies * Add test * Delete comments * Add conda packages to mac environment file * Order dependencies in pypi requirements * Add tests with zeroes and NaNs for augmentation * Back * Black * Make comment one line * Add todo for later * Black * Update to new TensorFlow conda package (#1726) * Build conda package locally * Try 2.8.4 * Merge develop into branch to fix dependencies * Change tensorflow version to 2.7.4 in where conda packages are used * Make tensorflow requirements in pypi looser * Conda package has TensorFlow 2.7.0 and h5py and numpy installed via conda * Change tensorflow version in `environment_no_cuda.yml` to test using CI * Test new sleap/tensorflow package * Reset build number * Bump version * Update mac deps * Update to Arm64 Mac runners * pin `importlib-metadata` * Pin more stuff on mac * constrain `opencv` version due to new qt dependencies * Update more mac stuff * Patches to get to green * More mac skipping --------- Co-authored-by: Talmo Pereira <[email protected]> Co-authored-by: Talmo Pereira <[email protected]> * Fix CI on macosx-arm64 (#1734) * Build conda package locally * Try 2.8.4 * Merge develop into branch to fix dependencies * Change tensorflow version to 2.7.4 in where conda packages are used * Make tensorflow requirements in pypi looser * Conda package has TensorFlow 2.7.0 and h5py and numpy installed via conda * Change tensorflow version in `environment_no_cuda.yml` to test using CI * Test new sleap/tensorflow package * Reset build number * Bump version * Update mac deps * Update to Arm64 Mac runners * pin `importlib-metadata` * Pin more stuff on mac * constrain `opencv` version due to new qt dependencies * Update more mac stuff * Patches to get to green * More mac skipping * Re-enable mac tests * Handle GPU re-init * Fix mac build CI * Widen tolerance for movenet correctness test * Fix build ci * Try for manual build without upload * Try to reduce training CI time * Rework actions * Fix miniforge usage * Tweaks * Fix build ci * Disable manual build * Try merging CI coverage * GPU/CPU usage in tests * Lint * Clean up * Fix test skip condition * Remove scratch test --------- Co-authored-by: eberrigan <[email protected]> * Add option to export to CSV via sleap-convert and API (#1730) * Add csv as a format option * Add analysis to format * Add csv suffix to output path * Add condition for csv analysis file * Add export function to Labels class * delete print statement * lint * Add `analysis.csv` as parametrize input for `sleap-convert` tests * test `export_csv` method added to `Labels` class * black formatting * use `Path` to construct filename * add `analysis.csv` to cli guide for `sleap-convert` --------- Co-authored-by: Talmo Pereira <[email protected]> * Only propagate Transpose Tracks when propagate is checked (#1748) Fix always-propagate transpose tracks issue * View Hyperparameter nonetype fix (#1766) Pass config getter argument to fetch hyperparameters * Adding ragged metadata to `info.json` (#1765) Add ragged metadata to info.json file * Add batch size to GUI for inference (#1771) * Fix conda builds (#1776) * test conda packages in a test environment as part of CI * do not test sleap import using conda build * use github environment variables to define build path for each OS in the matrix and add print statements for testing * figure out paths one OS at a time * github environment variables work in subsequent steps not current step * use local builds first * print env info * try simple environment creation * try conda instead of mamba * fix windows build path * fix windows build path * add comment to reference pull request * remove test stage from conda build for macs and test instead by creating the environment in a workflow * test workflow by pushing to current branch * test conda package on macos runner * Mac build does not need nvidia channel * qudida and albumentations are conda installed now * add comment with original issue * use python 3.9 * use conda match specifications syntax * make print statements more readable for troubleshooting python versioning * clean up build file * update version for pre-release * add TODO * add tests for conda packages before uploading * update ci comments and branches * remove macos test of pip wheel since python 3.9 is not supported by setup-python action * Upgrade build actions for release (#1779) * update `build.yml` so it matches updates from `build_manual.yml` * test `build.yml` without uploading * test again using build_manual.yml * build pip wheel with Ubuntu and turn off caching so build.yml exactly matches build_manual.yml * `build.yml` on release only and upload * testing caching * `use-only-tar-bz2: true` makes environment unsolvable, change it back * Update .github/workflows/build_manual.yml Co-authored-by: Liezl Maree <[email protected]> * Update .github/workflows/build.yml Co-authored-by: Liezl Maree <[email protected]> * bump pre-release version * fix version for pre-release * run build and upload on release! * try setting `CACHE_NUMBER` to 1 with `use-only-tar-bz2` set to true * increasing the cache number to reset the cache does work when `use-only-tar-bz2` is set to true * publish and upload on release only --------- Co-authored-by: Liezl Maree <[email protected]> * Add ZMQ support via GUI and CLI (#1780) * Add ZMQ support via GUI and CLI, automatic port handler, separate utils module for the functions * Change menu name to match deleting predictions beyond max instance (#1790) Change menu and function names * Fix website build and remove build cache across workflows (#1786) * test with build_manual on push * comment out caching in build manual * remove cache step from builad manual since environment resolves when this is commented out * comment out cache in build ci * remove cache from build on release * remove cache from website build * test website build on push * add name to checkout step * update checkout to v4 * update checkout to v4 in build ci * remove cache since build ci works without it * update upload-artifact to v4 in build ci * update second chechout to v4 in build ci * update setup-python to v5 in build ci * update download-artifact to v4 in build ci * update checkout to v4 in build ci * update checkout to v4 in website build * update setup-miniconda to v3.0.3 in website build * update actions-gh-pages to v4 in website build * update actions checkout and setup-python in ci * update checkout action in ci to v4 * pip install lxml[html_clean] because of error message during action * add error message to website to explain why pip install lxml[html_clean] * remove my branch for pull request * Bump to 1.4.1a1 (#1791) * bump versions to 1.4.1a1 * we can change the version on the installation page since this will be merged into the develop branch and not main * Fix windows conda package upload and build ci (#1792) * windows OS is 2022 not 2019 on runner * upload windows conda build manually but not pypi build * remove comment and run build ci * change build manual back so that it doesn't upload * remove branch from build manual * update installation docs for 1.4.1a1 * Fix zmq inference (#1800) * Ensure that we always pass in the zmq_port dict to LossViewer * Ensure zmq_ports has correct keys inside LossViewer * Use specified controller and publish ports for first attempted addresses * Add test for ports being set in LossViewer * Add max attempts to find unused port * Fix find free port loop and add for controller port also * Improve code readablility and reuse * Improve error message when unable to find free port * Set selected instance to None after removal (#1808) * Add test that selected instance set to None after removal * Set selected instance to None after removal * Add `InstancesList` class to handle backref to `LabeledFrame` (#1807) * Add InstancesList class to handle backref to LabeledFrame * Register structure/unstructure hooks for InstancesList * Add tests for the InstanceList class * Handle case where instance are passed in but labeled_frame is None * Add tests relevant methods in LabeledFrame * Delegate setting frame to InstancesList * Add test for PredictedInstance.frame after complex merge * Add todo comment to not use Instance.frame * Add rtest for InstasnceList.remove * Use normal list for informative `merged_instances` * Add test for copy and clear * Add copy and clear methods, use normal lists in merge method * Bump to v1.4.1a2 (#1835) bump to 1.4.1a2 * Updated trail length viewing options (#1822) * updated trail length optptions * Updated trail length options in the view menu * Updated `prefs` to include length info from `preferences.yaml` * Added trail length as method of `MainWindow` * Updated trail length documentation * black formatting --------- Co-authored-by: Keya Loding <[email protected]> * Handle case when no frame selection for trail overlay (#1832) * Menu option to open preferences directory and update to util functions to pathlib (#1843) * Add menu to view preferences directory and update to pathlib * text formatting * Add `Keep visualizations` checkbox to training GUI (#1824) * Renamed save_visualizations to view_visualizations for clarity * Added Delete Visualizations button to the training pipeline gui, exposed del_viz_predictions config option to the user * Reverted view_ back to save_ and changed new training checkbox to Keep visualization images after training. * Fixed keep_viz config option state override bug and updated keep_viz doc description * Added test case for reading training CLI argument correctly * Removed unnecessary testing code * Creating test case to check for viz folder * Finished tests to check CLI argument reading and viz directory existence * Use empty string instead of None in cli args test * Use keep_viz_images false in most all test configs (except test to override config) --------- Co-authored-by: roomrys <[email protected]> * Allowing inference on multiple videos via `sleap-track` (#1784) * implementing proposed code changes from issue #1777 * comments * configuring output_path to support multiple video inputs * fixing errors from preexisting test cases * Test case / code fixes * extending test cases for mp4 folders * test case for output directory * black and code rabbit fixes * code rabbit fixes * as_posix errors resolved * syntax error * adding test data * black * output error resolved * edited for push to dev branch * black * errors fixed, test cases implemented * invalid output test and invalid input test * deleting debugging statements * deleting print statements * black * deleting unnecessary test case * implemented tmpdir * deleting extraneous file * fixing broken test case * fixing test_sleap_track_invalid_output * removing support for multiple slp files * implementing talmo's comments * adding comments * Add object keypoint similarity method (#1003) * Add object keypoint similarity method * fix max_tracking * correct off-by-one error * correct off-by-one error * Generate suggestions using max point displacement threshold (#1862) * create function max_point_displacement, _max_point_displacement_video. Add to yaml file. Create test for new function . . . will need to edit * remove unnecessary for loop, calculate proper displacement, adjusted tests accordingly * Increase range for displacement threshold * Fix frames not found bug * Return the latter frame index * Lint --------- Co-authored-by: roomrys <[email protected]> * Added Three Different Cases for Adding a New Instance (#1859) * implemented paste with offset * right click and then default will paste the new instance at the location of the cursor * modified the logics for creating new instance * refined the logic * fixed the logic for right click * refined logics for adding new instance at a specific location * Remove print statements * Comment code * Ensure that we choose a non nan reference node * Move OOB nodes to closest in-bounds position --------- Co-authored-by: roomrys <[email protected]> * Allow csv and text file support on sleap track (#1875) * initial changes * csv support and test case * increased code coverage * Error fixing, black, deletion of (self-written) unused code * final edits * black * documentation changes * documentation changes * Fix GUI crash on scroll (#1883) * Only pass wheelEvent to children that can handle it * Add test for wheelEvent * Fix typo to allow rendering videos with mp4 (Mac) (#1892) Fix typo to allow rendering videos with mp4 * Do not apply offset when double clicking a `PredictedInstance` (#1888) * Add offset argument to newInstance and AddInstance * Apply offset of 10 for Add Instance menu button (Ctrl + I) * Add offset for docks Add Instance button * Make the QtVideoPlayer context menu unit-testable * Add test for creating a new instance * Add test for "New Instance" button in `InstancesDock` * Fix typo in docstring * Add docstrings and typehinting * Remove unused imports and sort imports * Refactor video writer to use imageio instead of skvideo (#1900) * modify `VideoWriter` to use imageio with ffmpeg backend * check to see if ffmpeg is present * use the new check for ffmpeg * import imageio.v2 * add imageio-ffmpeg to environments to test * using avi format for now * remove SKvideo videowriter * test `VideoWriterImageio` minimally * add more documentation for ffmpeg * default mp4 for ffmpeg should be mp4 * print using `IMAGEIO` when using ffmpeg * mp4 for ffmpeg * use mp4 ending in test * test `VideoWriterImageio` with avi file extension * test video with odd size * remove redundant filter since imageio-ffmpeg resizes automatically * black * remove unused import * use logging instead of print statement * import cv2 is needed for resize * remove logging * Use `Video.from_filename` when structuring videos (#1905) * Use Video.from_filename when structuring videos * Modify removal_test_labels to have extension in filename * Use | instead of + in key commands (#1907) * Use | instead of + in key commands * Lint * Replace QtDesktop widget in preparation for PySide6 (#1908) * Replace to-be-depreciated QDesktopWidget * Remove unused imports and sort remaining imports * Remove unsupported |= operand to prepare for PySide6 (#1910) Fixes TypeError: unsupported operand type(s) for |=: 'int' and 'Option' * Use positional argument for exception type (#1912) traceback.format_exception has changed it's first positional argument's name from etype to exc in python 3.7 to 3.10 * Replace all Video structuring with Video.cattr() (#1911) * Remove unused AsyncVideo class (#1917) Remove unused AsyncVideo * Refactor `LossViewer` to use matplotlib (#1899) * use updated syntax for QtAgg backend of matplotlib * start add features to `MplCanvas` to replace QtCharts features in `LossViewer` (untested) * remove QtCharts imports and replace with MplCanvas * remove QtCharts imports and replace with MplCanvas * start using MplCanvas in LossViwer instead of QtCharts (untested) * use updated syntax * Uncomment all commented out QtChart * Add debug code * Refactor monitor to use LossViewer._init_series method * Add monitor only debug code * Add methods for setting up axes and legend * Add the matplotlib canvas to the widget * Resize axis with data (no log support yet) * Try using PathCollection for "batch" * Get "batch" plotting with ax.scatter (no log support yet) * Add log support * Add a _resize_axis method * Modify init_series to work for ax.plot as well * Use matplotlib to plot epoch_loss line * Add method _add_data_to_scatter * Add _add_data_to_plot method * Add docstring to _resize_axes * Add matplotlib plot for val_loss * Add matplotlib scatter for val_loss_best * Avoid errors with setting log scale before any positive values * Add x and y axes labels * Set title (removing html tags) * Add legend * Adjust positioning of plot * Lint * Leave MplCanvas unchanged * Removed unused training_monitor.LossViewer * Resize fonts * Move legend outside of plot * Add debug code for montitor aesthetics * Use latex formatting to bold parts of title * Make axes aesthetic * Add midpoint grid lines * Set initial limits on x and y axes to be 0+ * Ensure x axis minimum is always resized to 0+ * Adjust plot to account for plateau patience title * Add debug code for plateau patience title line * Lint * Set thicker line width * Remove unused import * Set log axis on initialization * Make tick labels smaller * Move plot down a smidge * Move ylabel left a bit * Lint * Add class LossPlot * Refactor LossViewer to use LossPlot * Remove QtCharts code * Remove debug codes * Allocate space for figure items based on item's size * Refactor LossPlot to use underscores for internal methods * Ensure y_min, y_max not equal Otherwise we get an unnecessary teminal message: UserWarning: Attempting to set identical bottom == top == 3.0 results in singular transformations; automatically expanding. self.axes.set_ylim(y_min, y_max) --------- Co-authored-by: roomrys <[email protected]> Co-authored-by: roomrys <[email protected]> * Refactor `LossViewer` to use underscores for internal method names (#1919) Refactor LossViewer to use underscores for internal method names * Manually handle `Instance.from_predicted` structuring when not `None` (#1930) * Use `tf.math.mod` instead of `%` (#1931) * Option for Max Stride to be 128 (#1941) Co-authored-by: Max Weinberg <[email protected]> * Add discussion comment workflow (#1945) * Add a bot to autocomment on workflow * Use github markdown warning syntax * Add a multiline warning * Change happy coding to happy SLEAPing Co-authored-by: Talmo Pereira <[email protected]> --------- Co-authored-by: roomrys <[email protected]> Co-authored-by: Talmo Pereira <[email protected]> * Add comment on issue workflow (#1946) * Add workflow to test conda packages (#1935) * Add missing imageio-ffmpeg to meta.ymls (#1943) * Update installation docs 1.4.1 (#1810) * [wip] Updated installation docs * Add tabs for different OS installations * Move installation methods to tabs * Use tabs.css * FIx styling error (line under last tab in terminal hint) * Add installation instructions before TOC * Replace mamba with conda * Lint * Find good light colors not switching when change dark/light themes * Get color scheme switching with dark/light toggle button * Upgrade website build dependencies * Remove seemingly unneeded dependencies from workflow * Add myst-nb>=0.16.0 lower bound * Trigger dev website build * Fix minor typo in css * Add miniforge and one-liner installs for package managers --------- Co-authored-by: roomrys <[email protected]> Co-authored-by: Talmo Pereira <[email protected]> * Add imageio dependencies for pypi wheel (#1950) Add imagio dependencies for pypi wheel Co-authored-by: roomrys <[email protected]> * Do not always color skeletons table black (#1952) Co-authored-by: roomrys <[email protected]> * Remove no module named work error (#1956) * Do not always color skeletons table black * Remove offending (possibly unneeded) line that causes the no module named work error to print in terminal * Remove offending (possibly unneeded) line that causes the no module named work error to print in terminal * Remove accidentally added changes * Add (failing) test to ensure menu-item updates with state change * Reconnect callback for menu-item (using lambda) * Add (failing) test to ensure menu-item updates with state change Do not assume inital state * Reconnect callback for menu-item (using lambda) --------- Co-authored-by: roomrys <[email protected]> * Add `normalized_instance_similarity` method (#1939) * Add normalize function * Expose normalization function * Fix tests * Expose object keypoint sim function * Fix tests * Handle skeleton decoding internally (#1961) * Reorganize (and add) imports * Add (and reorganize) imports * Modify decode_preview_image to return bytes if specified * Implement (minimally tested) replace_jsonpickle_decode * Add support for using idx_to_node map i.e. loading from Labels (slp file) * Ignore None items in reduce_list * Convert large function to SkeletonDecoder class * Update SkeletonDecoder.decode docstring * Move decode_preview_image to SkeletonDecoder * Use SkeletonDecoder instead of jsonpickle in tests * Remove unused imports * Add test for decoding dict vs tuple pystates * Handle skeleton encoding internally (#1970) * start class `SkeletonEncoder` * _encoded_objects need to be a dict to add to * add notebook for testing * format * fix type in docstring * finish classmethod for encoding Skeleton as a json string * test encoded Skeleton as json string by decoding it * add test for decoded encoded skeleton * update jupyter notebook for easy testing * constraining attrs in dev environment to make sure decode format is always the same locally * encode links first then encode source then target then type * save first enconding statically as an input to _get_or_assign_id so that we do not always get py/id * save first encoding statically * first encoding is passed to _get_or_assign_id * use first_encoding variable to determine if we should assign a py/id * add print statements for debugging * update notebook for easy testing * black * remove comment * adding attrs constraint to show this passes for certain attrs version only * add import * switch out jsonpickle.encode * oops remove import * can attrs be unconstrained? * forgot comma * pin attrs for testing * test Skeleton from json, template, with symmetries, and template * use SkeletonEncoder.encode * black * try removing None values in EdgeType reduced * Handle case when nodes are replaced by integer indices from caller * Remove prototyping notebook * Remove attrs pins * Remove sort keys (which flips the neccessary ordering of our py/ids) * Do not add extra indents to encoded file * Only append links after fully encoded (fat-finger) * Remove outdated comment * Lint --------- Co-authored-by: Talmo Pereira <[email protected]> Co-authored-by: roomrys <[email protected]> * Pin ndx-pose<0.2.0 (#1978) * Pin ndx-pose<0.2.0 * Typo * Sort encoded `Skeleton` dictionary for backwards compatibility (#1975) * Add failing test to check that encoded Skeleton is sorted * Sort Skeleton dictionary before encoding * Remove unused import * Disable comment bot for now * Fix COCO Dataset Loading for Invisible Keypoints (#2035) Update coco.py # Fix COCO Dataset Loading for Invisible Keypoints ## Issue When loading COCO datasets, keypoints marked as invisible (flag=0) are currently skipped and later placed randomly within the instance's bounding box. However, in COCO format, these keypoints may still have valid coordinate information that should be preserved (see toy_dataset for expected vs. current behavior). ## Changes Modified the COCO dataset loading logic to: - Check if invisible keypoints (flag=0) have non-zero coordinates - If coordinates are (0,0), skip the point (existing behavior) - If coordinates are not (0,0), create the point at those coordinates but mark it as not visible - Maintain existing behavior for visible (flag=2) and labeled * Lint * Add tracking score as seekbar header options (#2047) * Add `tracking_score` as a constructor arg for `PredictedInstance` * Add `tracking_score` to ID models * Add fixture with tracking scores * Add tracking score to seekbar header * Add bonsai guide for sleap docs (#2050) * [WIP] Add bonsai guide page * Add more information to the guide with images * add branch for website build * Typos * fix links * Include suggestions * Add more screenshots and refine the doc * Remove branch from website workflow * Completed documentation edits from PR made by reviewer + review bot. --------- Co-authored-by: Shrivaths Shyam <[email protected]> Co-authored-by: Liezl Maree <[email protected]> * Don't mark complete on instance scaling (#2049) * Add check for instances with track assigned before training ID models (#2053) * Add menu item for deleting instances beyond frame limit (#1797) * Add menu item for deleting instances beyond frame limit * Add test function to test the instances returned * typos * Update docstring * Add frame range form * Extend command to use frame range --------- Co-authored-by: Talmo Pereira <[email protected]> * Highlight instance box on hover (#2055) * Make node marker and label sizes configurable via preferences (#2057) * Make node marker and label sizes configurable via preferences * Fix test * Enable touchpad pinch to zoom (#2058) * Fix import PySide2 -> qtpy (#2065) * Fix import PySide2 -> qtpy * Remove unnecessary print statements. * Add channels for pip conda env (#2067) * Add channels for pypi conda env * Trigger dev website build * Separate the video name and its filepath columns in `VideoTablesModel` (#2052) * add option to show video names with filepath * add doc * new feature added successfully * delete unnecessary code * remove attributes from video object * Update dataviews.py * remove all properties * delete toggle option * remove video show * fix the order of the columns * remove options * Update sleap/gui/dataviews.py Co-authored-by: Liezl Maree <[email protected]> * Update sleap/gui/dataviews.py Co-authored-by: Liezl Maree <[email protected]> * use pathlib instead of substrings * Update dataviews.py Co-authored-by: Liezl Maree <[email protected]> * Use Path instead of pathlib.Path and sort imports and remove unused imports * Use item.filename instead of getattr --------- Co-authored-by: Liezl Maree <[email protected]> * Make status bar dependent on UI mode (#2063) * remove bug for dark mode * fix toggle case --------- Co-authored-by: Liezl Maree <[email protected]> * Bump version to 1.4.1 (#2062) * Bump version to 1.4.1 * Trigger conda/pypi builds (no upload) * Trigger website build * Add dev channel to installation instructions --------- Co-authored-by: Talmo Pereira <[email protected]> * Add -c sleap/label/dev channel for win/linux - also trigger website build --------- Co-authored-by: Scott Yang <[email protected]> Co-authored-by: Shrivaths Shyam <[email protected]> Co-authored-by: getzze <[email protected]> Co-authored-by: Lili Karashchuk <[email protected]> Co-authored-by: Sidharth Srinath <[email protected]> Co-authored-by: sidharth srinath <[email protected]> Co-authored-by: Talmo Pereira <[email protected]> Co-authored-by: KevinZ0217 <[email protected]> Co-authored-by: Elizabeth <[email protected]> Co-authored-by: Talmo Pereira <[email protected]> Co-authored-by: eberrigan <[email protected]> Co-authored-by: vaibhavtrip29 <[email protected]> Co-authored-by: Keya Loding <[email protected]> Co-authored-by: Keya Loding <[email protected]> Co-authored-by: Hajin Park <[email protected]> Co-authored-by: Elise Davis <[email protected]> Co-authored-by: gqcpm <[email protected]> Co-authored-by: Andrew Park <[email protected]> Co-authored-by: roomrys <[email protected]> Co-authored-by: MweinbergUmass <[email protected]> Co-authored-by: Max Weinberg <[email protected]> Co-authored-by: DivyaSesh <[email protected]> Co-authored-by: Felipe Parodi <[email protected]> Co-authored-by: croblesMed <[email protected]>
Description
Currently there is no menu option to delete predictions beyond a certain frame number. This would add some ease of use when trying to delete predictions and then re-labeling to train the model again to get different/better predictions.
This came in as a suggestion in #1762
Types of changes
Does this address any currently open issues?
[list open issues here]
Outside contributors checklist
Thank you for contributing to SLEAP!
❤️
Summary by CodeRabbit
New Features
Configuration
Tests