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

Lazy import libraries in src/transformers/image_utils.py #36435

Merged
merged 3 commits into from
Feb 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions src/transformers/image_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,6 @@
PILImageResampling.LANCZOS: InterpolationMode.LANCZOS,
}

if is_decord_available():
from decord import VideoReader, cpu

if is_av_available():
import av

if is_cv2_available():
import cv2

if is_yt_dlp_available():
from yt_dlp import YoutubeDL

if TYPE_CHECKING:
if is_torch_available():
Expand Down Expand Up @@ -608,6 +597,10 @@ def sample_indices_fn(metadata, **kwargs):
- Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
- `VideoMetadata` object.
"""
# Lazy import cv2
requires_backends(read_video_opencv, ["cv2"])
import cv2

video = cv2.VideoCapture(video_path)
total_num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
video_fps = video.get(cv2.CAP_PROP_FPS)
Expand Down Expand Up @@ -661,6 +654,10 @@ def sample_indices_fn(metadata, **kwargs):
- Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
- `VideoMetadata` object.
"""
# Lazy import from decord
requires_backends(read_video_decord, ["decord"])
from decord import VideoReader, cpu

vr = VideoReader(uri=video_path, ctx=cpu(0)) # decord has problems with gpu
video_fps = vr.get_avg_fps()
total_num_frames = len(vr)
Expand Down Expand Up @@ -700,6 +697,10 @@ def sample_indices_fn(metadata, **kwargs):
- Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
- `VideoMetadata` object.
"""
# Lazy import av
requires_backends(read_video_pyav, ["av"])
import av

container = av.open(video_path)
total_num_frames = container.streams.video[0].frames
video_fps = container.streams.video[0].average_rate # should we better use `av_guess_frame_rate`?
Expand Down Expand Up @@ -834,6 +835,10 @@ def sample_indices_fn_func(metadata, **fn_kwargs):
if video.startswith("https://www.youtube.com") or video.startswith("http://www.youtube.com"):
if not is_yt_dlp_available():
raise ImportError("To load a video from YouTube url you have to install `yt_dlp` first.")
# Lazy import from yt_dlp
requires_backends(load_video, ["yt_dlp"])
from yt_dlp import YoutubeDL

buffer = BytesIO()
with redirect_stdout(buffer), YoutubeDL() as f:
f.download([video])
Expand Down