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