Safetensors
English
llava
video-retrieval
text-to-video-search
multimodal-embedding
File size: 11,285 Bytes
7daf628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""Cuts multiple clips from a single video using ffmpeg."""
import os
from os.path import join, exists
import numpy as np
import pandas as pd
from subprocess import call
from tqdm import tqdm


def cut_multiple_clips_video_only(
        video_path: str,
        start_times: list,
        end_times: list,
        save_dir: str,
        video_id=None,
        ext=None,
        verbose=False,
    ):
    """Cuts multiple clips from a single video using ffmpeg.

    Args:
        video_path: Path to the video file.
        start_times: List of start times for each clip.
        end_times: List of end times for each clip.
    """
    os.makedirs(save_dir, exist_ok=True)
    assert len(start_times) == len(end_times), \
        'start_times and end_times must have the same length.'

    if video_id is None:
        video_id = os.path.basename(video_path).split(".")[0]
    if ext is None:
        ext = os.path.basename(video_path).split(".")[1]

    item_ids = [
        f"{video_id}_{np.round(s, 1)}_{np.round(e, 1)}" \
            for (s, e) in zip(start_times, end_times)
    ]

    ins = [
        f"[0:v]trim=start={s}:end={e},setpts=PTS-STARTPTS,scale=480:-1[v{i}]" \
        for i, (s, e) in enumerate(zip(start_times, end_times))
    ]
    ins = ";".join(ins)
    outs = [
        f"-map [v{i}] {save_dir}/{item_ids[i]}.{ext}" \
        for i in range(len(start_times))
    ]
    outs = " ".join(outs)
    if not verbose:
        suffix = "-loglevel panic"
    else:
        suffix = ""
    command = f"""
        ffmpeg -i {video_path} -filter_complex "{ins}" {outs} -y {suffix}
    """
    call(command, shell=True)


def cut_multiple_clips_audio_and_video(
        video_path: str,
        start_times: list,
        end_times: list,
        save_dir: str,
        video_id=None,
        ext=None,
        verbose=False,
    ):
    """Cuts multiple clips from a single video using ffmpeg.

    Args:
        video_path: Path to the video file.
        start_times: List of start times for each clip.
        end_times: List of end times for each clip.
    """

    if args.verbose:
        print("[:::] Cutting clips from video: ", video_path)
        print("[:::] Number of clips to cut: ", len(start_times))

    os.makedirs(save_dir, exist_ok=True)
    assert len(start_times) == len(end_times), \
        'start_times and end_times must have the same length.'

    if video_id is None:
        video_id = os.path.basename(video_path).split(".")[0]
    if ext is None:
        ext = os.path.basename(video_path).split(".")[1]

    item_ids = [
        f"{video_id}_{np.round(s, 1)}_{np.round(e, 1)}" \
            for (s, e) in zip(start_times, end_times)
    ]

    ins = [
        f"[0:v]trim=start={s}:end={e},setpts=PTS-STARTPTS,scale=480:-1[v{i}];"\
        f"[0:a:0]atrim=start={s}:end={e},asetpts=PTS-STARTPTS[a{i}]" \
        for i, (s, e) in enumerate(zip(start_times, end_times))
    ]
    ins = ";".join(ins)
    outs = [
        f"-map [v{i}] -map [a{i}] {save_dir}/{item_ids[i]}.{ext}" \
        for i in range(len(start_times))
    ]
    outs = " ".join(outs)
    if not verbose:
        suffix = "-loglevel panic"
    else:
        suffix = ""
    command = f"""
        ffmpeg -i {video_path} -filter_complex "{ins}" {outs} -y {suffix}
    """
    call(command, shell=True)




def cut_multiple_clips_audio_and_video_v2(
        video_path: str,
        start_times: list,
        end_times: list,
        save_dir: str,
        video_id=None,
        ext=None,
        verbose=False,
    ):
    """Cuts multiple clips from a single video using ffmpeg.

    Args:
        video_path: Path to the video file.
        start_times: List of start times for each clip.
        end_times: List of end times for each clip.
    """

    if args.verbose:
        print("[:::] Cutting clips from video: ", video_path)
        print("[:::] Number of clips to cut: ", len(start_times))

    os.makedirs(save_dir, exist_ok=True)
    assert len(start_times) == len(end_times), \
        'start_times and end_times must have the same length.'

    if video_id is None:
        video_id = os.path.basename(video_path).split(".")[0]
    if ext is None:
        ext = os.path.basename(video_path).split(".")[1]

    item_ids = [
        f"{video_id}_{np.round(s, 1)}_{np.round(e, 1)}" \
            for (s, e) in zip(start_times, end_times)
    ]

    ins = [
        f"[0:v]trim=start={s}:end={e},setpts=PTS-STARTPTS,scale=480:-1[v{i}];"\
        f"[0:a:0]atrim=start={s}:end={e},asetpts=PTS-STARTPTS[a{i}]" \
        for i, (s, e) in enumerate(zip(start_times, end_times))
    ]
    # ins = ";".join(ins)
    outs = [
        f"-map [v{i}] -map [a{i}] {save_dir}/{item_ids[i]}.{ext}" \
        for i in range(len(start_times))
    ]
    # outs = " ".join(outs)
    if not verbose:
        suffix = "-loglevel panic"
    else:
        suffix = ""

    iterator = tqdm(range(len(start_times)), desc="Cutting clips for {}".format(video_id))
    for i in iterator:
        ins_ = ins[i]
        outs_ = outs[i]
        save_path = f"{save_dir}/{item_ids[i]}.{ext}"
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        if os.path.exists(save_path):
            continue
        command = f"""
            ffmpeg -i {video_path} -filter_complex "{ins_}" {outs_} -y {suffix}
        """
        call(command, shell=True)


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    # General arguments
    parser.add_argument("--sanity", action="store_true")
    parser.add_argument("--debug", action="store_true")
    parser.add_argument("--verbose", action="store_true")
    parser.add_argument(
        "--ext", type=str, default="mp4",
    )
    # Arguments for input CSV
    parser.add_argument(
        "--csv", type=str, required=True,
        help="Path to CSV file containing video IDs and timestamps",
    )
    parser.add_argument(
        "--video_id_key", type=str, default="video_id",
    )
    parser.add_argument(
        "--start_time_key", type=str, default="start_time",
    )
    parser.add_argument(
        "--end_time_key", type=str, default="end_time",
    )
    parser.add_argument(
        "--video_dir", type=str, required=True,
        help="Path to directory containing downloaded videos",
    )
    parser.add_argument(
        "--cut_dir", type=str, required=True,
        help="Path to directory where cut videos will be saved",
    )
    parser.add_argument(
        "--overwrite", action="store_true",
        help="Whether to overwrite existing cut videos",
    )
    parser.add_argument(
        "--video_only", action="store_true",
    )
    parser.add_argument(
        "--si", type=int, default=0,
    )
    parser.add_argument(
        "--ei", type=int, default=None,
    )
    args = parser.parse_args()

    if args.sanity:

        # Test without audio
        video_path = "sample_data/folding_paper.mp4"
        start_times = [0, 5, 10]
        end_times = [5, 10, 15]
        cut_multiple_clips_video_only(
            video_path,
            start_times,
            end_times,
            "./sample_data/clips",
            verbose=args.verbose,
            ext=args.ext,
        )

        # Test with audio
        video_path = "sample_data/pouring_water_youtube.mp4"
        start_times = [0, 5, 10]
        end_times = [5, 10, 15]
        cut_multiple_clips_audio_and_video(
            video_path,
            start_times,
            end_times,
            "./sample_data/clips",
            verbose=args.verbose,
            ext=args.ext,
        )

    else:

        # Make cut_dir
        os.makedirs(args.cut_dir, exist_ok=True)
        
        # Load csv
        assert os.path.exists(args.csv), f"CSV file {args.csv} does not exist."
        df = pd.read_csv(args.csv)
        print(">>> Loaded CSV file with shape", df.shape)
        keys = [args.video_id_key, args.start_time_key, args.end_time_key]
        assert set(keys).issubset(df.columns), \
            f"CSV file must contain columns {keys}."
        
        # Filter out videos that don't exist
        df["video_path"] = df[args.video_id_key].apply(
            lambda video_id: join(args.video_dir, f"{video_id}.{args.ext}"),
        )
        df["check_video"] = df["video_path"].apply(exists)
        df = df[df["check_video"]]
        del df["check_video"]
        print(">>> Found videos for", df.shape[0], "rows.")

        si = args.si
        ei = args.ei if args.ei is not None else df.shape[0]
        print("Running from indices", si, "to", ei)
        df = df.iloc[si:ei]

        if args.debug:
            args.verbose = True
        ext = args.ext

        # Iterate over each video
        video_paths = df["video_path"].unique()
        # iterator = tqdm(range(len(video_paths)), desc="Cutting clips")
        print("Number of unique videos:", len(video_paths))
        for i in range(len(video_paths)):
            video_path = video_paths[i]

            # Find rows corresponding to this video
            df_video = df[df["video_path"] == video_path]
            print("Number of clips to cut from video", video_path, ":", df_video.shape[0])
            start_times = df_video[args.start_time_key].values
            end_times = df_video[args.end_time_key].values
            video_id = df_video[args.video_id_key].values[0]

            """
            # Cut to MAXLEN clips per video
            MAX_LEN = 10
            start_times_batches = np.array_split(start_times, MAX_LEN)
            end_times_batches = np.array_split(end_times, MAX_LEN)
            for start_times_, end_times_ in zip(start_times_batches, end_times_batches):
                if args.video_only:
                    cut_multiple_clips_video_only(
                        video_path,
                        start_times_,
                        end_times_,
                        args.cut_dir,
                        video_id=video_id,
                        ext=ext,
                        verbose=args.verbose,
                        # verbose=True,
                    )
                else:
                    cut_multiple_clips_audio_and_video_v2(
                        video_path,
                        start_times_,
                        end_times_,
                        args.cut_dir,
                        video_id=video_id,
                        ext=ext,
                        verbose=args.verbose,
                        # verbose=True,
                    )
            """
            # """
            # Cut videos
            if args.video_only:
                cut_multiple_clips_video_only(
                    video_path,
                    start_times,
                    end_times,
                    args.cut_dir,
                    video_id=video_id,
                    ext=ext,
                    verbose=args.verbose,
                )
            else:
                cut_multiple_clips_audio_and_video_v2(
                    video_path,
                    start_times,
                    end_times,
                    args.cut_dir,
                    video_id=video_id,
                    ext=ext,
                    verbose=args.verbose,
                )
            # """
            
            if args.debug:
                break