|
| 1 | +import json |
| 2 | +import os |
| 3 | +import os.path as osp |
| 4 | + |
| 5 | +from pydantic import PositiveInt |
| 6 | + |
| 7 | +from data_juicer.utils.constant import Fields |
| 8 | +from data_juicer.utils.file_utils import create_directory_if_not_exists |
| 9 | +from data_juicer.utils.mm_utils import (SpecialTokens, close_video, |
| 10 | + extract_key_frames, |
| 11 | + extract_video_frames_uniformly, |
| 12 | + load_data_with_context, load_video) |
| 13 | + |
| 14 | +from ..base_op import OPERATORS, Mapper |
| 15 | +from ..op_fusion import LOADED_VIDEOS |
| 16 | + |
| 17 | +OP_NAME = 'video_extract_frames_mapper' |
| 18 | + |
| 19 | + |
| 20 | +@OPERATORS.register_module(OP_NAME) |
| 21 | +@LOADED_VIDEOS.register_module(OP_NAME) |
| 22 | +class VideoExtractFramesMapper(Mapper): |
| 23 | + """Mapper to extract frames from video files according to specified methods. |
| 24 | + Extracted Frames Data Format: |
| 25 | + The data format for the extracted frames is a dictionary mapping |
| 26 | + video keys to lists of file paths where the extracted frames are saved. |
| 27 | + The dictionary follows the structure: |
| 28 | + { |
| 29 | + "video_key_1": [ |
| 30 | + "/${frame_dir}/video_key_1_filename/frame_1.jpg", |
| 31 | + "/${frame_dir}/video_key_1_filename/frame_2.jpg", |
| 32 | + ...], |
| 33 | + "video_key_2": [ |
| 34 | + "/${frame_dir}/video_key_2_filename/frame_1.jpg", |
| 35 | + "/${frame_dir}/video_key_2_filename/frame_2.jpg", |
| 36 | + ...], |
| 37 | + ... |
| 38 | + } |
| 39 | + """ |
| 40 | + |
| 41 | + _batched_op = True |
| 42 | + |
| 43 | + def __init__( |
| 44 | + self, |
| 45 | + frame_sampling_method: str = 'all_keyframes', |
| 46 | + frame_num: PositiveInt = 3, |
| 47 | + frame_dir: str = None, |
| 48 | + frame_key=Fields.video_frames, |
| 49 | + *args, |
| 50 | + **kwargs, |
| 51 | + ): |
| 52 | + """ |
| 53 | + Initialization method. |
| 54 | + :param frame_sampling_method: sampling method of extracting frame |
| 55 | + videos from the videos. Should be one of |
| 56 | + ["all_keyframes", "uniform"]. |
| 57 | + The former one extracts all key frames (the number |
| 58 | + of which depends on the duration of the video) and the latter |
| 59 | + one extract specified number of frames uniformly from the video. |
| 60 | + Default: "all_keyframes". |
| 61 | + :param frame_num: the number of frames to be extracted uniformly from |
| 62 | + the video. Only works when frame_sampling_method is "uniform". If |
| 63 | + it's 1, only the middle frame will be extracted. If it's 2, only |
| 64 | + the first and the last frames will be extracted. If it's larger |
| 65 | + than 2, in addition to the first and the last frames, other frames |
| 66 | + will be extracted uniformly within the video duration. |
| 67 | + :param frame_dir: Output directory to save extracted frames. |
| 68 | + If None, a default directory based on the video file path is used. |
| 69 | + :param frame_key: The name of field to save generated frames info. |
| 70 | + :param args: extra args |
| 71 | + :param kwargs: extra args |
| 72 | + """ |
| 73 | + super().__init__(*args, **kwargs) |
| 74 | + self._init_parameters = self.remove_extra_parameters(locals()) |
| 75 | + |
| 76 | + if frame_sampling_method not in ['all_keyframes', 'uniform']: |
| 77 | + raise ValueError( |
| 78 | + f'Frame sampling method ' |
| 79 | + f'[{frame_sampling_method}] is not supported. ' |
| 80 | + f'Can only be one of ["all_keyframes", "uniform"].') |
| 81 | + |
| 82 | + self.frame_dir = frame_dir |
| 83 | + self.frame_sampling_method = frame_sampling_method |
| 84 | + self.frame_num = frame_num |
| 85 | + self.frame_key = frame_key |
| 86 | + self.frame_fname_template = 'frame_{}.jpg' |
| 87 | + |
| 88 | + def _get_default_frame_dir(self, original_filepath): |
| 89 | + original_dir = os.path.dirname(original_filepath) |
| 90 | + dir_token = f'/{Fields.multimodal_data_output_dir}/' |
| 91 | + if dir_token in original_dir: |
| 92 | + original_dir = original_dir.split(dir_token)[0] |
| 93 | + new_dir = os.path.join( |
| 94 | + original_dir, f'{Fields.multimodal_data_output_dir}/{OP_NAME}') |
| 95 | + create_directory_if_not_exists(new_dir) |
| 96 | + return osp.join(new_dir, |
| 97 | + osp.splitext(osp.basename(original_filepath))[0]) |
| 98 | + |
| 99 | + def process_single(self, sample, context=False): |
| 100 | + # check if it's generated already |
| 101 | + if self.frame_key in sample: |
| 102 | + return sample |
| 103 | + |
| 104 | + # there is no videos in this sample |
| 105 | + if self.video_key not in sample or not sample[self.video_key]: |
| 106 | + return [] |
| 107 | + |
| 108 | + # load videos |
| 109 | + loaded_video_keys = sample[self.video_key] |
| 110 | + sample, videos = load_data_with_context(sample, context, |
| 111 | + loaded_video_keys, load_video) |
| 112 | + video_to_frames = {} |
| 113 | + text = sample[self.text_key] |
| 114 | + offset = 0 |
| 115 | + |
| 116 | + for chunk in text.split(SpecialTokens.eoc): |
| 117 | + video_count = chunk.count(SpecialTokens.video) |
| 118 | + # no video or no text |
| 119 | + if video_count == 0 or len(chunk) == 0: |
| 120 | + continue |
| 121 | + else: |
| 122 | + for video_key in loaded_video_keys[offset:offset + |
| 123 | + video_count]: |
| 124 | + video = videos[video_key] |
| 125 | + # extract frame videos |
| 126 | + if self.frame_sampling_method == 'all_keyframes': |
| 127 | + frames = extract_key_frames(video) |
| 128 | + elif self.frame_sampling_method == 'uniform': |
| 129 | + frames = extract_video_frames_uniformly( |
| 130 | + video, self.frame_num) |
| 131 | + else: |
| 132 | + raise ValueError(f'Not support sampling method \ |
| 133 | + `{self.frame_sampling_method}`.') |
| 134 | + frames = [frame.to_image() for frame in frames] |
| 135 | + |
| 136 | + if self.frame_dir: |
| 137 | + frame_dir = osp.join( |
| 138 | + self.frame_dir, |
| 139 | + osp.splitext(osp.basename(video_key))[0]) |
| 140 | + else: |
| 141 | + # video path as frames directory |
| 142 | + frame_dir = self._get_default_frame_dir(video_key) |
| 143 | + os.makedirs(frame_dir, exist_ok=True) |
| 144 | + |
| 145 | + video_to_frames[video_key] = [] |
| 146 | + for i, frame in enumerate(frames): |
| 147 | + frame_path = osp.join( |
| 148 | + frame_dir, self.frame_fname_template.format(i)) |
| 149 | + if not os.path.exists(frame_path): |
| 150 | + frame.save(frame_path) |
| 151 | + |
| 152 | + video_to_frames[video_key].append(frame_path) |
| 153 | + |
| 154 | + offset += video_count |
| 155 | + |
| 156 | + if not context: |
| 157 | + for vid_key in videos: |
| 158 | + close_video(videos[vid_key]) |
| 159 | + |
| 160 | + sample[self.frame_key] = json.dumps(video_to_frames) |
| 161 | + # sample[self.frame_key] = video_to_frames |
| 162 | + |
| 163 | + return sample |
0 commit comments