Skip to content

close GIF file handle after frame extraction in load_video#13854

Open
gagandhakrey wants to merge 2 commits into
huggingface:mainfrom
gagandhakrey:fix/gif-file-handle-leak
Open

close GIF file handle after frame extraction in load_video#13854
gagandhakrey wants to merge 2 commits into
huggingface:mainfrom
gagandhakrey:fix/gif-file-handle-leak

Conversation

@gagandhakrey
Copy link
Copy Markdown
Contributor

Fix: Close GIF File Handle in load_video

Problem

In load_video, PIL.Image.open() is called on a GIF file, but the underlying file handle is never explicitly closed after all frames are extracted.

gif = PIL.Image.open(video)  # file handle opened
try:
    while True:
        pil_images.append(gif.copy())
        gif.seek(gif.tell() + 1)
except EOFError:
    pass
# gif.close() never called

Impact

PIL.Image.open() keeps the underlying OS file descriptor open for the lifetime of the image object. Without an explicit close(), the descriptor is only released when Python's garbage collector destroys the object, which is non-deterministic.

Under repeated calls to load_video with GIF inputs, file descriptors can accumulate and eventually exhaust the process limit, resulting in:

OSError: [Errno 24] Too many open files

Fix

Wrap PIL.Image.open() in a context manager so the file handle is deterministically closed once all frames have been copied.

with PIL.Image.open(video) as gif:
    try:
        while True:
            pil_images.append(gif.copy())
            gif.seek(gif.tell() + 1)
    except EOFError:
        pass

This change is safe because gif.copy() creates independent in-memory PIL.Image objects. Once the frames are copied, the underlying GIF file can be closed without affecting the returned images.

Signed-off-by: Gagan Dhakrey <gagandhakrey@gmail.com>
@github-actions github-actions Bot added size/S PR with diff < 50 LOC utils and removed size/S PR with diff < 50 LOC labels Jun 2, 2026
@gagandhakrey
Copy link
Copy Markdown
Contributor Author

Hi @sayakpaul, could you please take a quick look at this small GIF file handle fix ? thanks

@github-actions github-actions Bot added the size/S PR with diff < 50 LOC label Jun 2, 2026
@gagandhakrey
Copy link
Copy Markdown
Contributor Author

Bumping it again
Hi @sayakpaul, could you please take a quick look at this pr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/S PR with diff < 50 LOC utils

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant