Loads `video` to a list of PIL Image. Args: video (`str`): A URL or Path to a video to convert to a list of PIL Image format. convert_method (Callable[[list[PIL.Image.Image]], list[PIL.Image.Image]], *optional*): A conversion method to apply to the v
(
video: str,
convert_method: Callable[[list[PIL.Image.Image]], list[PIL.Image.Image]] | None = None,
)
| 55 | |
| 56 | |
| 57 | def load_video( |
| 58 | video: str, |
| 59 | convert_method: Callable[[list[PIL.Image.Image]], list[PIL.Image.Image]] | None = None, |
| 60 | ) -> list[PIL.Image.Image]: |
| 61 | """ |
| 62 | Loads `video` to a list of PIL Image. |
| 63 | |
| 64 | Args: |
| 65 | video (`str`): |
| 66 | A URL or Path to a video to convert to a list of PIL Image format. |
| 67 | convert_method (Callable[[list[PIL.Image.Image]], list[PIL.Image.Image]], *optional*): |
| 68 | A conversion method to apply to the video after loading it. When set to `None` the images will be converted |
| 69 | to "RGB". |
| 70 | |
| 71 | Returns: |
| 72 | `list[PIL.Image.Image]`: |
| 73 | The video as a list of PIL images. |
| 74 | """ |
| 75 | is_url = video.startswith("http://") or video.startswith("https://") |
| 76 | is_file = os.path.isfile(video) |
| 77 | was_tempfile_created = False |
| 78 | |
| 79 | if not (is_url or is_file): |
| 80 | raise ValueError( |
| 81 | f"Incorrect path or URL. URLs must start with `http://` or `https://`, and {video} is not a valid path." |
| 82 | ) |
| 83 | |
| 84 | if is_url: |
| 85 | response = requests.get(video, stream=True) |
| 86 | if response.status_code != 200: |
| 87 | raise ValueError(f"Failed to download video. Status code: {response.status_code}") |
| 88 | |
| 89 | parsed_url = urlparse(video) |
| 90 | file_name = os.path.basename(unquote(parsed_url.path)) |
| 91 | |
| 92 | suffix = os.path.splitext(file_name)[1] or ".mp4" |
| 93 | video_path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False).name |
| 94 | |
| 95 | was_tempfile_created = True |
| 96 | |
| 97 | video_data = response.iter_content(chunk_size=8192) |
| 98 | with open(video_path, "wb") as f: |
| 99 | for chunk in video_data: |
| 100 | f.write(chunk) |
| 101 | |
| 102 | video = video_path |
| 103 | |
| 104 | pil_images = [] |
| 105 | if video.endswith(".gif"): |
| 106 | gif = PIL.Image.open(video) |
| 107 | try: |
| 108 | while True: |
| 109 | pil_images.append(gif.copy()) |
| 110 | gif.seek(gif.tell() + 1) |
| 111 | except EOFError: |
| 112 | pass |
| 113 | |
| 114 | else: |
nothing calls this directly
no test coverage detected
searching dependent graphs…