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

Refactor video writer to use imageio instead of skvideo #1900

Conversation

eberrigan
Copy link
Contributor

@eberrigan eberrigan commented Aug 9, 2024

Description

  • skvideo is no longer supported and results in a syntax error with newer versions of python (>3.7). We are updating all of our dependencies--see Update python versions and dependencies #1841.
  • We use imageio.v2 with an ffmpeg backend instead.
  • VideoWriter is re-written and tested to use imageio.v2.
  • VideoWriter.safe_builder checks if ffmpeg is available. It should be since now we install imageio-ffmpeg in the environment.
  • A test has been added for the VideoWriterImageio. This test should always pass since imageio-ffmpeg is now in the test environment.
  • The safe_builder method is tested. It should always use imageio now that imageio-ffmpeg is in the environment.
  • The render clip from the GUI using different settings was tested manually.
                "-vf",
                "scale=trunc(iw/2)*2:trunc(ih/2)*2",  # Ensure even dimensions

was removed from output_params since imagio-ffmpeg already resizes : "WARNING:imageio_ffmpeg:IMAGEIO FFMPEG_WRITER WARNING: input image is not divisible by macro_block_size=16, resizing from (406, 720) to (416, 720) to ensure video compatibility with most codecs and players. To prevent resizing, make your input image divisible by the macro_block_size or set the macro_block_size to 1 (risking incompatibility)."

  • An additional test was made for videos with odd sizes since that has been an issue in the past. imagio-ffmpeg resizes automatically correctly for videos with odd number of pixels for height and width.
  • This PR is relevant for the parameters used when writing the video: Add one-line fix to VideoWriterSkyvideo #1082.

imagio.v2 full documentation is not easy to find.

The writing parameters are here for convenience from "\miniforge\pkgs\imageio-2.34.2-pyh12aca89_0\site-packages\imageio\plugins"
"""
Parameters for writing

fps : scalar
The number of frames per second. Default 10.
codec : str
the video codec to use. Default 'libx264', which represents the
widely available mpeg4. Except when saving .wmv files, then the
defaults is 'msmpeg4' which is more commonly supported for windows
quality : float | None
Video output quality. Default is 5. Uses variable bit rate. Highest
quality is 10, lowest is 0. Set to None to prevent variable bitrate
flags to FFMPEG so you can manually specify them using output_params
instead. Specifying a fixed bitrate using 'bitrate' disables this
parameter.
bitrate : int | None
Set a constant bitrate for the video encoding. Default is None causing
'quality' parameter to be used instead. Better quality videos with
smaller file sizes will result from using the 'quality' variable
bitrate parameter rather than specifying a fixed bitrate with this
parameter.
pixelformat: str
The output video pixel format. Default is 'yuv420p' which most widely
supported by video players.
input_params : list
List additional arguments to ffmpeg for input file options (i.e. the
stream that imageio provides).
output_params : list
List additional arguments to ffmpeg for output file options.
(Can also be provided as ffmpeg_params for backwards compatibility)
Example ffmpeg arguments to use only intra frames and set aspect ratio:
['-intra', '-aspect', '16:9']
ffmpeg_log_level: str
Sets ffmpeg output log level. Default is "warning".
Values can be "quiet", "panic", "fatal", "error", "warning", "info"
"verbose", or "debug". Also prints the FFMPEG command being used by
imageio if "info", "verbose", or "debug".
macro_block_size: int
Size constraint for video. Width and height, must be divisible by this
number. If not divisible by this number imageio will tell ffmpeg to
scale the image up to the next closest size
divisible by this number. Most codecs are compatible with a macroblock
size of 16 (default), some can go smaller (4, 8). To disable this
automatic feature set it to None or 1, however be warned many players
can't decode videos that are odd in size and some codecs will produce
poor results or fail. See https://en.wikipedia.org/wiki/Macroblock.
audio_path : str | None
Audio path of any audio that needs to be written. Defaults to nothing,
so no audio will be written. Please note, when writing shorter video
than the original, ffmpeg will not truncate the audio track; it
will maintain its original length and be longer than the video.
audio_codec : str | None
The audio codec to use. Defaults to nothing, but if an audio_path has
been provided ffmpeg will attempt to set a default codec.

ffmpeg version 4.2.2 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 9.2.1 (GCC) 20200122
  configuration: --disable-static --enable-shared --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
Encoder libx264 [libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10]:
    General capabilities: delay threads
    Threading capabilities: auto
    Supported pixel formats: yuv420p yuvj420p yuv422p yuvj422p yuv444p yuvj444p nv12 nv16 nv21 yuv420p10le yuv422p10le yuv444p10le nv20le gray gray10le
libx264 AVOptions:
  -preset            <string>     E..V..... Set the encoding preset (cf. x264 --fullhelp) (default "medium")
  -tune              <string>     E..V..... Tune the encoding params (cf. x264 --fullhelp)
  -profile           <string>     E..V..... Set profile restrictions (cf. x264 --fullhelp)
  -fastfirstpass     <boolean>    E..V..... Use fast settings when encoding first pass (default true)
  -level             <string>     E..V..... Specify level (as defined by Annex A)
  -passlogfile       <string>     E..V..... Filename for 2 pass stats
  -wpredp            <string>     E..V..... Weighted prediction for P-frames
  -a53cc             <boolean>    E..V..... Use A53 Closed Captions (if available) (default true)
  -x264opts          <string>     E..V..... x264 options
  -crf               <float>      E..V..... Select the quality for constant quality mode (from -1 to FLT_MAX) (default -1)
  -crf_max           <float>      E..V..... In CRF mode, prevents VBV from lowering quality beyond this point. (from -1 to FLT_MAX) (default -1)
  -qp                <int>        E..V..... Constant quantization parameter rate control method (from -1 to INT_MAX) (default -1)
  -aq-mode           <int>        E..V..... AQ method (from -1 to INT_MAX) (default -1)
     none                         E..V.....
     variance                     E..V..... Variance AQ (complexity mask)
     autovariance                 E..V..... Auto-variance AQ
     autovariance-biased              E..V..... Auto-variance AQ with bias to dark scenes
  -aq-strength       <float>      E..V..... AQ strength. Reduces blocking and blurring in flat and textured areas. (from -1 to FLT_MAX) (default -1)
  -psy               <boolean>    E..V..... Use psychovisual optimizations. (default auto)
  -psy-rd            <string>     E..V..... Strength of psychovisual optimization, in <psy-rd>:<psy-trellis> format.
  -rc-lookahead      <int>        E..V..... Number of frames to look ahead for frametype and ratecontrol (from -1 to INT_MAX) (default -1)
  -weightb           <boolean>    E..V..... Weighted prediction for B-frames. (default auto)
  -weightp           <int>        E..V..... Weighted prediction analysis method. (from -1 to INT_MAX) (default -1)
     none                         E..V.....
     simple                       E..V.....
     smart                        E..V.....
  -ssim              <boolean>    E..V..... Calculate and print SSIM stats. (default auto)
  -intra-refresh     <boolean>    E..V..... Use Periodic Intra Refresh instead of IDR frames. (default auto)
  -bluray-compat     <boolean>    E..V..... Bluray compatibility workarounds. (default auto)
  -b-bias            <int>        E..V..... Influences how often B-frames are used (from INT_MIN to INT_MAX) (default INT_MIN)
  -b-pyramid         <int>        E..V..... Keep some B-frames as references. (from -1 to INT_MAX) (default -1)
     none                         E..V.....
     strict                       E..V..... Strictly hierarchical pyramid
     normal                       E..V..... Non-strict (not Blu-ray compatible)
  -mixed-refs        <boolean>    E..V..... One reference per partition, as opposed to one reference per macroblock (default auto)
  -8x8dct            <boolean>    E..V..... High profile 8x8 transform. (default auto)
  -fast-pskip        <boolean>    E..V..... (default auto)
  -aud               <boolean>    E..V..... Use access unit delimiters. (default auto)
  -mbtree            <boolean>    E..V..... Use macroblock tree ratecontrol. (default auto)
  -deblock           <string>     E..V..... Loop filter parameters, in <alpha:beta> form.
  -cplxblur          <float>      E..V..... Reduce fluctuations in QP (before curve compression) (from -1 to FLT_MAX) (default -1)
  -partitions        <string>     E..V..... A comma-separated list of partitions to consider. Possible values: p8x8, p4x4, b8x8, i8x8, i4x4, none, all
  -direct-pred       <int>        E..V..... Direct MV prediction mode (from -1 to INT_MAX) (default -1)
     none                         E..V.....
     spatial                      E..V.....
     temporal                     E..V.....
     auto                         E..V.....
  -slice-max-size    <int>        E..V..... Limit the size of each slice in bytes (from -1 to INT_MAX) (default -1)
  -stats             <string>     E..V..... Filename for 2 pass stats
  -nal-hrd           <int>        E..V..... Signal HRD information (requires vbv-bufsize; cbr not allowed in .mp4) (from -1 to INT_MAX) (default -1)
     none                         E..V.....
     vbr                          E..V.....
     cbr                          E..V.....
  -avcintra-class    <int>        E..V..... AVC-Intra class 50/100/200 (from -1 to 200) (default -1)
  -me_method         <int>        E..V..... Set motion estimation method (from -1 to 4) (default -1)
     dia                          E..V.....
     hex                          E..V.....
     umh                          E..V.....
     esa                          E..V.....
     tesa                         E..V.....
  -motion-est        <int>        E..V..... Set motion estimation method (from -1 to 4) (default -1)
     dia                          E..V.....
     hex                          E..V.....
     umh                          E..V.....
     esa                          E..V.....
     tesa                         E..V.....
  -forced-idr        <boolean>    E..V..... If forcing keyframes, force them as IDR frames. (default false)
  -coder             <int>        E..V..... Coder type (from -1 to 1) (default default)
     default                      E..V.....
     cavlc                        E..V.....
     cabac                        E..V.....
     vlc                          E..V.....
     ac                           E..V.....
  -b_strategy        <int>        E..V..... Strategy to choose between I/P/B-frames (from -1 to 2) (default -1)
  -chromaoffset      <int>        E..V..... QP difference between chroma and luma (from INT_MIN to INT_MAX) (default -1)
  -sc_threshold      <int>        E..V..... Scene change threshold (from INT_MIN to INT_MAX) (default -1)
  -noise_reduction   <int>        E..V..... Noise reduction (from INT_MIN to INT_MAX) (default -1)
  -x264-params       <string>     E..V..... Override the x264 configuration using a :-separated list of key=value parameters

Types of changes

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

Does this address any currently open issues?

[list open issues here]

Outside contributors checklist

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

Thank you for contributing to SLEAP!

❤️

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced video encoding capabilities by integrating imageio for AVI file support.
    • Introduced a new VideoWriterImageio class to improve video writing functionality.
  • Bug Fixes

    • Updated user feedback messages based on the availability of ffmpeg, clarifying encoding options.
  • Tests

    • Added new test functions to verify the functionality of the VideoWriterImageio class, ensuring robustness in video writing processes.

Copy link

coderabbitai bot commented Aug 9, 2024

Walkthrough

The recent changes enhance video handling in the application by replacing the skvideo library with imageio, ensuring better compatibility and flexibility. Key files have been updated to reflect this new dependency, particularly in user feedback and internal logic. This transition improves encoding processes and overall robustness in managing video writing functionalities.

Changes

Files Change Summary
sleap/gui/dialogs/export_clip.py, sleap/io/videowriter.py, tests/io/test_videowriter.py Transitioned from skvideo to imageio for video encoding; updated checks for ffmpeg availability, modified user feedback, and introduced a new VideoWriterImageio class for improved video writing capabilities. The VideoWriterSkvideo class was replaced, and method names were adapted to align with the new library. New tests ensure functionality.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ExportClip
    participant VideoWriter

    User->>ExportClip: Initiate export
    ExportClip->>VideoWriter: Check for ffmpeg availability
    VideoWriter-->>ExportClip: Return availability status
    alt ffmpeg available
        ExportClip->>VideoWriter: Encode video with imageio
    else ffmpeg not available
        ExportClip->>User: Fallback to AVI using OpenCV
    end
    VideoWriter->>ExportClip: Confirm encoding completion
    ExportClip-->>User: Export finished
Loading

Poem

In the garden of code, a rabbit hops free,
With imageio's magic, as bright as can be!
No more skvideo clutter, just smooth, swift grace,
Encoding our dreams in a new, happy space.
🐇✨ Let’s dance in the light of our video streams!


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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 076f3dd and b80ee45.

Files selected for processing (2)
  • sleap/gui/dialogs/export_clip.py (1 hunks)
  • sleap/io/videowriter.py (4 hunks)
Additional context used
Ruff
sleap/io/videowriter.py

144-144: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (4)
sleap/gui/dialogs/export_clip.py (1)

14-23: LGTM! Transition to ffmpeg via imageio is clear.

The changes correctly update the logic and user messages to reflect the use of ffmpeg through imageio, aligning with the PR objectives.

sleap/io/videowriter.py (3)

15-15: Import imageio.v2 is necessary for new functionality.

The import of imageio.v2 is required for the updated video writing functionality.


36-55: Robust transition to imageio for ffmpeg checks.

The safe_builder and can_use_ffmpeg methods correctly transition the dependency check from skvideo to imageio, ensuring robust functionality.


Line range hint 120-173: VideoWriterImageio class implementation is sound.

The class effectively utilizes imageio for video writing, aligning with the refactor objectives. The methods are correctly implemented.

Tools
Ruff

144-144: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

sleap/io/videowriter.py Show resolved Hide resolved
Copy link

codecov bot commented Aug 9, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 5 lines in your changes missing coverage. Please review.

Project coverage is 74.47%. Comparing base (7ed1229) to head (8def1c8).
Report is 30 commits behind head on develop.

Files Patch % Lines
sleap/gui/dialogs/export_clip.py 0.00% 2 Missing ⚠️
sleap/io/videowriter.py 90.90% 2 Missing ⚠️
sleap/gui/commands.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1900      +/-   ##
===========================================
+ Coverage    73.30%   74.47%   +1.16%     
===========================================
  Files          134      135       +1     
  Lines        24087    24791     +704     
===========================================
+ Hits         17658    18462     +804     
+ Misses        6429     6329     -100     

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b80ee45 and a080f55.

Files selected for processing (7)
  • environment.yml (1 hunks)
  • environment_mac.yml (1 hunks)
  • environment_no_cuda.yml (1 hunks)
  • sleap/gui/commands.py (1 hunks)
  • sleap/gui/dialogs/export_clip.py (1 hunks)
  • sleap/io/videowriter.py (4 hunks)
  • tests/io/test_videowriter.py (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • sleap/gui/dialogs/export_clip.py
Additional context used
Ruff
sleap/io/videowriter.py

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (11)
environment_mac.yml (1)

15-15: Add imageio-ffmpeg dependency for video processing.

The addition of imageio-ffmpeg is appropriate for enabling video processing with imageio. This aligns with the PR objectives to transition from skvideo to imageio.

environment_no_cuda.yml (1)

16-16: Add imageio-ffmpeg dependency for video processing.

The addition of imageio-ffmpeg is consistent with the changes in other environment files, supporting video processing with imageio.

environment.yml (1)

15-15: Add imageio-ffmpeg dependency for video processing.

The addition of imageio-ffmpeg is necessary for video processing with imageio, aligning with the PR objectives to replace skvideo.

tests/io/test_videowriter.py (3)

Line range hint 5-19: Test function test_video_writer is well-structured.

The function correctly tests the VideoWriter by ensuring it writes a video file successfully.


Line range hint 22-36: Test function test_cv_video_writer is well-structured.

The function correctly tests the VideoWriterOpenCV by ensuring it writes a video file successfully.


44-67: Comprehensive test for VideoWriterImageio.

The function thoroughly tests video writing and verifies attributes like height, width, fps, filename, crf, and preset.

sleap/io/videowriter.py (4)

36-37: Update to safe_builder method is appropriate.

The method now correctly uses VideoWriterImageio when ffmpeg is available, aligning with the refactoring objectives.


Line range hint 76-120: Initialization logic for VideoWriterImageio is well-structured.

The constructor initializes necessary attributes and sets up the imageio writer with appropriate parameters.

Tools
Ruff

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)


126-129: Methods add_frame and close are correctly implemented.

The add_frame method uses append_data, and the close method ensures proper closure of the writer.


42-55: Verify can_use_ffmpeg method functionality.

The method attempts to import imageio_ffmpeg and check its version, which is a valid approach to determine ffmpeg availability.

Verification successful

can_use_ffmpeg method is functioning correctly and integrated properly.

The method is used to check for ffmpeg availability and conditionally adjust functionality, such as user messages, video writer selection, and file naming. The codebase uses it appropriately to ensure smooth operations based on ffmpeg presence.

  • sleap/gui/dialogs/export_clip.py: Determines the message about video encoding.
  • sleap/io/videowriter.py: Chooses between VideoWriterImageio and VideoWriterOpenCV.
  • sleap/gui/commands.py: Influences default output filename.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the `can_use_ffmpeg` method functionality by checking for `imageio_ffmpeg` usage.

# Test: Search for usage of `can_use_ffmpeg` across the codebase.
ast-grep --lang python --pattern $'VideoWriter.can_use_ffmpeg()'

Length of output: 291


Script:

#!/bin/bash
# Description: Gather context around the usage of `can_use_ffmpeg` in the identified files.

# Get context around the usage in sleap/gui/dialogs/export_clip.py
rg -A 5 -B 5 'VideoWriter.can_use_ffmpeg()' sleap/gui/dialogs/export_clip.py

# Get context around the usage in sleap/io/videowriter.py
rg -A 5 -B 5 'VideoWriter.can_use_ffmpeg()' sleap/io/videowriter.py

# Get context around the usage in sleap/gui/commands.py
rg -A 5 -B 5 'VideoWriter.can_use_ffmpeg()' sleap/gui/commands.py

Length of output: 1365

sleap/gui/commands.py (1)

1332-1333: Update to ask function logic is appropriate.

The function now defaults to .avi when ffmpeg is available, aligning with the transition from skvideo.

Also applies to: 1335-1335

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a080f55 and 3a03cee.

Files selected for processing (1)
  • sleap/io/videowriter.py (4 hunks)
Additional context used
Ruff
sleap/io/videowriter.py

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (6)
sleap/io/videowriter.py (6)

15-15: Import statement for imageio.v2 is necessary.

The addition of imageio.v2 is appropriate for replacing skvideo with imageio.


36-37: Changes to safe_builder method are appropriate.

The method now correctly checks for ffmpeg availability and uses VideoWriterImageio if available.


42-55: Changes to can_use_ffmpeg method are correct.

The method now checks for imageio_ffmpeg availability, which is essential for using imageio.


Line range hint 76-120:
Introduction of VideoWriterImageio class is well-implemented.

The class effectively uses imageio to handle video writing, replacing the deprecated skvideo.

Tools
Ruff

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)


125-126: add_frame method implementation is correct.

The method uses append_data to add frames, which aligns with imageio usage.


129-129: close method implementation is appropriate.

The method ensures the writer is properly closed, which is crucial for resource management.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (1)
sleap/io/videowriter.py (1)

36-38: Use logging instead of print.

Replace print with a logging library for better control over logging levels and outputs.

-            print("USING IMAGEIO")
+            import logging
+            logging.info("USING IMAGEIO")
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3a03cee and 107abe2.

Files selected for processing (2)
  • sleap/gui/commands.py (1 hunks)
  • sleap/io/videowriter.py (4 hunks)
Additional context used
Ruff
sleap/io/videowriter.py

101-101: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (4)
sleap/io/videowriter.py (3)

15-15: Import Approved: imageio.v2.

The import of imageio.v2 is necessary for the transition from skvideo to imageio.


Line range hint 77-130: Implementation Approved: VideoWriterImageio.

The VideoWriterImageio class is well-implemented, leveraging imageio for video writing.

Tools
Ruff

101-101: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)


43-56: Remove unused import imageio_ffmpeg.

The import statement for imageio_ffmpeg is not used in the code and should be removed to clean up the imports.

-        import imageio_ffmpeg as ffmpeg

Likely invalid or redundant comment.

sleap/gui/commands.py (1)

1332-1335: Logic and Comment Change Approved.

The logic for determining the default output filename is appropriate, and the comment change improves readability.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 107abe2 and 2d1b265.

Files selected for processing (1)
  • sleap/gui/dialogs/export_clip.py (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • sleap/gui/dialogs/export_clip.py

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2d1b265 and 38359e7.

Files selected for processing (1)
  • tests/io/test_videowriter.py (2 hunks)
Additional context used
Ruff
tests/io/test_videowriter.py

2-2: cv2 imported but unused

Remove unused import: cv2

(F401)

Additional comments not posted (3)
tests/io/test_videowriter.py (3)

Line range hint 6-19:
LGTM!

The test for VideoWriter is well-structured and ensures functionality.

Tools
Ruff

2-2: cv2 imported but unused

Remove unused import: cv2

(F401)


Line range hint 22-35:
LGTM!

The test for VideoWriterOpenCV is well-structured and ensures functionality.

Tools
Ruff

2-2: cv2 imported but unused

Remove unused import: cv2

(F401)


45-68: LGTM!

The test for VideoWriterImageio is comprehensive and ensures both functionality and attribute verification.

tests/io/test_videowriter.py Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 38359e7 and e04743b.

Files selected for processing (2)
  • sleap/io/videowriter.py (4 hunks)
  • tests/io/test_videowriter.py (2 hunks)
Additional context used
Ruff
sleap/io/videowriter.py

101-101: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (5)
tests/io/test_videowriter.py (2)

45-69: LGTM! Comprehensive test for AVI writing.

The test function effectively verifies the functionality of VideoWriterImageio for AVI format, ensuring all critical attributes are checked.


71-101: LGTM! Effective test for handling odd-sized frames.

The test function ensures that VideoWriterImageio correctly processes frames with non-standard dimensions, maintaining expected attributes.

sleap/io/videowriter.py (3)

Line range hint 77-119:
Ensure correct initialization and parameter usage.

The VideoWriterImageio class is well-implemented, leveraging imageio for video writing. Ensure that all parameters, such as crf and preset, are correctly utilized and documented.

Tools
Ruff

101-101: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)


101-101: Remove unused import: imageio_ffmpeg.

The import statement for imageio_ffmpeg is not used directly in the code and should be removed to clean up the imports.

-        import imageio_ffmpeg as ffmpeg

Likely invalid or redundant comment.

Tools
Ruff

101-101: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)


36-38: Ensure ffmpeg availability check is robust.

The safe_builder method now uses can_use_ffmpeg to decide on the writer implementation. Ensure that ffmpeg is correctly detected in all environments.

Verification successful

can_use_ffmpeg function is robustly implemented.

The can_use_ffmpeg function in sleap/io/videowriter.py correctly handles ImportError and checks for the ffmpeg version, ensuring reliable detection of ffmpeg availability.

  • Located in sleap/io/videowriter.py
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `can_use_ffmpeg` correctly detects `ffmpeg` availability.

# Test: Check for `ffmpeg` detection logic in the codebase. Expect: Correct handling of `ImportError` and version check.
ast-grep --lang python --pattern $'def can_use_ffmpeg() {
  try {
    import imageio_ffmpeg as ffmpeg
  } catch ImportError {
    return False
  }
  try {
    $_ = ffmpeg.get_ffmpeg_version()
    if $_ {
      return True
    }
  } catch Exception {
    return False
  }
  return False
}'

Length of output: 964


Script:

#!/bin/bash
# Description: Verify that `can_use_ffmpeg` correctly detects `ffmpeg` availability.

# Corrected Test: Check for `ffmpeg` detection logic in the codebase. Expect: Correct handling of `ImportError` and version check.
ast-grep --lang python --pattern $'def can_use_ffmpeg():\n    try:\n        import imageio_ffmpeg as ffmpeg\n    except ImportError:\n        return False\n    try:\n        version = ffmpeg.get_ffmpeg_version()\n        if version:\n            return True\n    except Exception:\n        return False\n    return False\n'

Length of output: 312


Script:

#!/bin/bash
# Description: Search for the `can_use_ffmpeg` function in the codebase.

# Use `rg` to search for the function definition across the repository.
rg 'def can_use_ffmpeg' -A 10

Length of output: 654

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e04743b and eac1d89.

Files selected for processing (1)
  • tests/io/test_videowriter.py (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • tests/io/test_videowriter.py

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Outside diff range, codebase verification and nitpick comments (1)
sleap/io/videowriter.py (1)

102-102: Clarify the necessity of the imageio_ffmpeg import.

The import statement for imageio_ffmpeg is flagged as unused, but it is necessary for checking the ffmpeg version. Ensure this is documented to avoid confusion.

# Import necessary for checking ffmpeg version
import imageio_ffmpeg as ffmpeg
Tools
Ruff

102-102: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between eac1d89 and 9f488e3.

Files selected for processing (1)
  • sleap/io/videowriter.py (4 hunks)
Additional context used
Ruff
sleap/io/videowriter.py

102-102: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (2)
sleap/io/videowriter.py (2)

129-129: LGTM! Ensure proper resource management in close.

The close method correctly closes the writer. Ensure that this is called in all code paths to prevent resource leaks.


126-126: Ensure color conversion consistency in add_frame.

The add_frame method converts BGR to RGB if specified. Ensure that this behavior aligns with the expected input format for imageio.

sleap/io/videowriter.py Show resolved Hide resolved
sleap/io/videowriter.py Show resolved Hide resolved
Copy link
Collaborator

@talmo talmo left a comment

Choose a reason for hiding this comment

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

LGTM! Just remove one logging statement

sleap/io/videowriter.py Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9f488e3 and 8def1c8.

Files selected for processing (1)
  • sleap/io/videowriter.py (4 hunks)
Additional context used
Ruff
sleap/io/videowriter.py

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

Additional comments not posted (6)
sleap/io/videowriter.py (6)

36-37: LGTM! Safe builder logic is sound.

The safe_builder method correctly checks for ffmpeg availability and defaults to VideoWriterOpenCV if not available.


42-55: Ensure robust exception handling in can_use_ffmpeg.

The current implementation uses a broad Exception catch, which can obscure specific errors. Consider catching more specific exceptions to improve error handling.

-        except Exception:
+        except (ImportError, AttributeError):

93-118: Consider parameter validation in __init__.

The constructor of VideoWriterImageio initializes several parameters. Adding validation for these parameters (e.g., non-negative dimensions, valid FPS) could prevent runtime errors.

if height <= 0 or width <= 0:
    raise ValueError("Height and width must be positive integers.")
if fps <= 0:
    raise ValueError("FPS must be a positive number.")
Tools
Ruff

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)


123-124: LGTM! Frame addition logic is correct.

The add_frame method correctly handles BGR to RGB conversion and appends frames using imageio.


127-127: LGTM! Writer closure is correctly implemented.

The close method correctly closes the imageio writer.


100-100: Retain necessary import imageio_ffmpeg.

The import statement for imageio_ffmpeg is necessary for checking ffmpeg availability in the can_use_ffmpeg method.

Tools
Ruff

100-100: imageio_ffmpeg imported but unused

Remove unused import: imageio_ffmpeg

(F401)

@eberrigan eberrigan merged commit efdf3fa into develop Aug 15, 2024
8 checks passed
@eberrigan eberrigan deleted the elizabeth/Refactor-VideoWriter-to-use-imageio-instead-of-skvideo branch August 15, 2024 17:24
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.

2 participants