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

Add high level APIs #80

Merged
merged 8 commits into from
Apr 14, 2024
Merged

Add high level APIs #80

merged 8 commits into from
Apr 14, 2024

Conversation

talmo
Copy link
Contributor

@talmo talmo commented Apr 14, 2024

Summary by CodeRabbit

  • New Features
    • Introduced new functionalities to load and save video and label files, enhancing user interaction with media content.
  • Tests
    • Updated tests to cover new loading and saving functionalities, ensuring reliability and performance.

@talmo talmo changed the title Add High level APIs Add high level APIs Apr 14, 2024
Copy link
Contributor

coderabbitai bot commented Apr 14, 2024

Walkthrough

The latest update to the sleap_io library brings enhanced capabilities for handling video and file operations. New functions like load_video and load_file have been introduced to streamline file handling, enabling the loading of video files into Video objects and various files into appropriate Labels or Video objects. Additionally, a feature to save files based on their extensions has been integrated.

Changes

File Path Changes Summary
sleap_io/__init__.py Added load_video and load_file to exported functions.
sleap_io/io/main.py Added Video import, load_video, load_file, and save_file functions for file handling.
sleap_io/model/video.py Updated imports and introduced EXTS attribute for video extensions.
tests/io/test_main.py Added load_video and load_file functions, updated tests, and ensured correct object type returns.

🐇📜
In the realm of bytes and code so neat,
A rabbit danced to a new beat.
Loading videos and files with grace,
Ensuring tests cover every case.
Celebrating changes, a delightful feat! 🌟
🐇💾


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 3cb4193 and 9b56c31.
Files selected for processing (2)
  • sleap_io/io/main.py (3 hunks)
  • tests/io/test_main.py (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • tests/io/test_main.py
Additional comments not posted (1)
sleap_io/io/main.py (1)

116-125: Ensure robust error handling in Video.from_filename used in load_video.


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.

Copy link

codecov bot commented Apr 14, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.16%. Comparing base (12b15fa) to head (9b56c31).

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #80      +/-   ##
==========================================
+ Coverage   94.79%   95.16%   +0.37%     
==========================================
  Files          13       13              
  Lines        1498     1551      +53     
==========================================
+ Hits         1420     1476      +56     
+ Misses         78       75       -3     

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

@talmo talmo linked an issue Apr 14, 2024 that may be closed by this pull request
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Actionable comments outside the diff hunks (1)
sleap_io/model/video.py (1)

Line range hint 97-97: Avoid using a bare except statement. It's better to specify the exceptions you expect to handle to avoid masking other unexpected issues.

-        except:
+        except ExpectedExceptionType:

Comment on lines 24 to 29
save_labelstudio,
load_jabs,
save_jabs,
load_video,
load_file,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [7-28]

Several imports in this file are marked as unused. If these are not intended for external use, consider adding them to the __all__ list to explicitly define what is exported by this module, or remove them if they are not needed.

- from sleap_io.model.skeleton import Node, Edge, Skeleton, Symmetry
- from sleap_io.model.video import Video
- from sleap_io.model.instance import (
-     Point,
-     PredictedPoint,
-     Track,
-     Instance,
-     PredictedInstance,
- )
- from sleap_io.model.labeled_frame import LabeledFrame
- from sleap_io.model.labels import Labels
- from sleap_io.io.main import (
-     load_slp,
-     save_slp,
-     load_nwb,
-     save_nwb,
-     load_labelstudio,
-     save_labelstudio,
-     load_jabs,
-     save_jabs,
- )

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Comment on lines +128 to +209
def load_file(
filename: str | Path, format: Optional[str] = None, **kwargs
) -> Union[Labels, Video]:
"""Load a file and return the appropriate object.

Args:
filename: Path to a file.
format: Optional format to load as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio", "jabs"
and "video".

Returns:
A `Labels` or `Video` object.
"""
if isinstance(filename, Path):
filename = str(filename)

if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "json"
elif filename.endswith(".h5"):
format = "jabs"
else:
for vid_ext in Video.EXTS:
if filename.endswith(vid_ext):
format = "video"
break
if format is None:
raise ValueError(f"Could not infer format from filename: '{filename}'.")

if filename.endswith(".slp"):
return load_slp(filename, **kwargs)
elif filename.endswith(".nwb"):
return load_nwb(filename, **kwargs)
elif filename.endswith(".json"):
return load_labelstudio(filename, **kwargs)
elif filename.endswith(".h5"):
return load_jabs(filename, **kwargs)
elif format == "video":
return load_video(filename, **kwargs)


def save_file(
labels: Labels, filename: str | Path, format: Optional[str] = None, **kwargs
):
"""Save a file based on the extension.

Args:
labels: A SLEAP `Labels` object (see `load_slp`).
filename: Path to save labels to.
format: Optional format to save as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio" and
"jabs".
"""
if isinstance(filename, Path):
filename = str(filename)

if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "labelstudio"
elif "pose_version" in kwargs:
format = "jabs"

if format == "slp":
save_slp(labels, filename, **kwargs)
elif format == "nwb":
save_nwb(labels, filename, **kwargs)
elif format == "labelstudio":
save_labelstudio(labels, filename, **kwargs)
elif format == "jabs":
pose_version = kwargs.pop("pose_version", 5)
save_jabs(labels, pose_version, filename, **kwargs)
else:
raise ValueError(f"Unknown format '{format}' for filename: '{filename}'.")
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve the error message in load_file to list supported formats.

- raise ValueError(f"Could not infer format from filename: '{filename}'.")
+ raise ValueError(f"Could not infer format from filename: '{filename}'. Supported formats are: 'slp', 'nwb', 'labelstudio', 'jabs', 'video'.")

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
def load_file(
filename: str | Path, format: Optional[str] = None, **kwargs
) -> Union[Labels, Video]:
"""Load a file and return the appropriate object.
Args:
filename: Path to a file.
format: Optional format to load as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio", "jabs"
and "video".
Returns:
A `Labels` or `Video` object.
"""
if isinstance(filename, Path):
filename = str(filename)
if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "json"
elif filename.endswith(".h5"):
format = "jabs"
else:
for vid_ext in Video.EXTS:
if filename.endswith(vid_ext):
format = "video"
break
if format is None:
raise ValueError(f"Could not infer format from filename: '{filename}'.")
if filename.endswith(".slp"):
return load_slp(filename, **kwargs)
elif filename.endswith(".nwb"):
return load_nwb(filename, **kwargs)
elif filename.endswith(".json"):
return load_labelstudio(filename, **kwargs)
elif filename.endswith(".h5"):
return load_jabs(filename, **kwargs)
elif format == "video":
return load_video(filename, **kwargs)
def save_file(
labels: Labels, filename: str | Path, format: Optional[str] = None, **kwargs
):
"""Save a file based on the extension.
Args:
labels: A SLEAP `Labels` object (see `load_slp`).
filename: Path to save labels to.
format: Optional format to save as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio" and
"jabs".
"""
if isinstance(filename, Path):
filename = str(filename)
if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "labelstudio"
elif "pose_version" in kwargs:
format = "jabs"
if format == "slp":
save_slp(labels, filename, **kwargs)
elif format == "nwb":
save_nwb(labels, filename, **kwargs)
elif format == "labelstudio":
save_labelstudio(labels, filename, **kwargs)
elif format == "jabs":
pose_version = kwargs.pop("pose_version", 5)
save_jabs(labels, pose_version, filename, **kwargs)
else:
raise ValueError(f"Unknown format '{format}' for filename: '{filename}'.")
def load_file(
filename: str | Path, format: Optional[str] = None, **kwargs
) -> Union[Labels, Video]:
"""Load a file and return the appropriate object.
Args:
filename: Path to a file.
format: Optional format to load as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio", "jabs"
and "video".
Returns:
A `Labels` or `Video` object.
"""
if isinstance(filename, Path):
filename = str(filename)
if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "json"
elif filename.endswith(".h5"):
format = "jabs"
else:
for vid_ext in Video.EXTS:
if filename.endswith(vid_ext):
format = "video"
break
if format is None:
raise ValueError(f"Could not infer format from filename: '{filename}'. Supported formats are: 'slp', 'nwb', 'labelstudio', 'jabs', 'video'.")
if filename.endswith(".slp"):
return load_slp(filename, **kwargs)
elif filename.endswith(".nwb"):
return load_nwb(filename, **kwargs)
elif filename.endswith(".json"):
return load_labelstudio(filename, **kwargs)
elif filename.endswith(".h5"):
return load_jabs(filename, **kwargs)
elif format == "video":
return load_video(filename, **kwargs)
def save_file(
labels: Labels, filename: str | Path, format: Optional[str] = None, **kwargs
):
"""Save a file based on the extension.
Args:
labels: A SLEAP `Labels` object (see `load_slp`).
filename: Path to save labels to.
format: Optional format to save as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio" and
"jabs".
"""
if isinstance(filename, Path):
filename = str(filename)
if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "labelstudio"
elif "pose_version" in kwargs:
format = "jabs"
if format == "slp":
save_slp(labels, filename, **kwargs)
elif format == "nwb":
save_nwb(labels, filename, **kwargs)
elif format == "labelstudio":
save_labelstudio(labels, filename, **kwargs)
elif format == "jabs":
pose_version = kwargs.pop("pose_version", 5)
save_jabs(labels, pose_version, filename, **kwargs)
else:
raise ValueError(f"Unknown format '{format}' for filename: '{filename}'.")

Comment on lines +174 to +209
def save_file(
labels: Labels, filename: str | Path, format: Optional[str] = None, **kwargs
):
"""Save a file based on the extension.

Args:
labels: A SLEAP `Labels` object (see `load_slp`).
filename: Path to save labels to.
format: Optional format to save as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio" and
"jabs".
"""
if isinstance(filename, Path):
filename = str(filename)

if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "labelstudio"
elif "pose_version" in kwargs:
format = "jabs"

if format == "slp":
save_slp(labels, filename, **kwargs)
elif format == "nwb":
save_nwb(labels, filename, **kwargs)
elif format == "labelstudio":
save_labelstudio(labels, filename, **kwargs)
elif format == "jabs":
pose_version = kwargs.pop("pose_version", 5)
save_jabs(labels, pose_version, filename, **kwargs)
else:
raise ValueError(f"Unknown format '{format}' for filename: '{filename}'.")
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor save_file to handle pose_version more consistently.

- elif "pose_version" in kwargs:
-     format = "jabs"
+ # Move pose_version handling to the jabs-specific block

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
def save_file(
labels: Labels, filename: str | Path, format: Optional[str] = None, **kwargs
):
"""Save a file based on the extension.
Args:
labels: A SLEAP `Labels` object (see `load_slp`).
filename: Path to save labels to.
format: Optional format to save as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio" and
"jabs".
"""
if isinstance(filename, Path):
filename = str(filename)
if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "labelstudio"
elif "pose_version" in kwargs:
format = "jabs"
if format == "slp":
save_slp(labels, filename, **kwargs)
elif format == "nwb":
save_nwb(labels, filename, **kwargs)
elif format == "labelstudio":
save_labelstudio(labels, filename, **kwargs)
elif format == "jabs":
pose_version = kwargs.pop("pose_version", 5)
save_jabs(labels, pose_version, filename, **kwargs)
else:
raise ValueError(f"Unknown format '{format}' for filename: '{filename}'.")
def save_file(
labels: Labels, filename: str | Path, format: Optional[str] = None, **kwargs
):
"""Save a file based on the extension.
Args:
labels: A SLEAP `Labels` object (see `load_slp`).
filename: Path to save labels to.
format: Optional format to save as. If not provided, will be inferred from the
file extension. Available formats are: "slp", "nwb", "labelstudio" and
"jabs".
"""
if isinstance(filename, Path):
filename = str(filename)
if format is None:
if filename.endswith(".slp"):
format = "slp"
elif filename.endswith(".nwb"):
format = "nwb"
elif filename.endswith(".json"):
format = "labelstudio"
# Move pose_version handling to the jabs-specific block
if format == "slp":
save_slp(labels, filename, **kwargs)
elif format == "nwb":
save_nwb(labels, filename, **kwargs)
elif format == "labelstudio":
save_labelstudio(labels, filename, **kwargs)
elif format == "jabs":
pose_version = kwargs.pop("pose_version", 5)
save_jabs(labels, pose_version, filename, **kwargs)
else:
raise ValueError(f"Unknown format '{format}' for filename: '{filename}'.")

@talmo talmo merged commit 599b207 into main Apr 14, 2024
7 of 9 checks passed
@talmo talmo deleted the talmo/high-level-api branch April 14, 2024 06:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add high level file loading
1 participant