File size: 13,111 Bytes
880de81
 
 
 
 
02abdab
880de81
02abdab
880de81
02abdab
4c7362f
1167d4f
0be0bad
4a445e6
880de81
 
 
 
fc0912b
 
880de81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946878e
880de81
 
 
36e4433
 
 
880de81
02abdab
6c8ddcc
880de81
6c8ddcc
880de81
84d7c6f
880de81
 
36e4433
880de81
6c8ddcc
880de81
6c8ddcc
880de81
84d7c6f
 
 
75813eb
880de81
 
c43a83e
 
 
946878e
c43a83e
 
 
 
 
 
 
 
 
946878e
 
 
0cb8d8c
 
 
 
 
 
 
946878e
 
880de81
946878e
0cb8d8c
880de81
8323202
be5d51f
 
 
 
 
8323202
0cb8d8c
880de81
946878e
 
 
8323202
 
 
 
 
 
 
0cb8d8c
 
 
8323202
 
 
 
 
 
 
0cb8d8c
946878e
277bb56
 
 
fc0912b
277bb56
946878e
8323202
 
 
 
 
 
 
0cb8d8c
946878e
4bc123c
 
8323202
 
 
 
 
 
 
0cb8d8c
946878e
4bc123c
0cb8d8c
fc0912b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946878e
fc0912b
946878e
 
fc0912b
946878e
8323202
 
 
 
 
 
 
946878e
 
8323202
 
 
 
 
 
 
880de81
167ab4b
0cb8d8c
880de81
f38285f
 
 
 
 
0cb8d8c
 
8323202
880de81
 
 
f38285f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bc123c
f38285f
c43a83e
be5d51f
 
 
 
 
 
 
 
c43a83e
4bc123c
 
 
be5d51f
 
 
 
 
 
 
 
4bc123c
f38285f
be5d51f
 
 
 
 
 
 
f38285f
4bc123c
 
 
be5d51f
 
 
 
 
 
 
f38285f
4bc123c
f38285f
 
 
be5d51f
 
 
 
 
 
 
4bc123c
 
f38285f
 
 
be5d51f
 
 
 
 
 
 
4bc123c
 
 
 
 
be5d51f
 
 
 
 
 
 
4bc123c
 
be5d51f
 
 
 
 
 
 
c43a83e
 
 
 
be5d51f
 
 
 
 
 
 
 
c43a83e
 
 
880de81
 
4c7362f
1167d4f
 
 
880de81
4c7362f
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
359
360
361
362
363
364
import os
import json
import gradio as gr
import tempfile
from PIL import Image, ImageDraw, ImageFont
import cv2
from typing import Tuple, Optional
import torch
from pathlib import Path
import time
import torch
import spaces
import os


from video_highlight_detector import (
    load_model,
    BatchedVideoHighlightDetector,
    get_video_duration_seconds,
    get_fixed_30s_segments
)

def load_examples(json_path: str) -> dict:
    with open(json_path, 'r') as f:
        return json.load(f)

def format_duration(seconds: int) -> str:
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    secs = seconds % 60
    if hours > 0:
        return f"{hours}:{minutes:02d}:{secs:02d}"
    return f"{minutes}:{secs:02d}"


def create_ui(examples_path: str):
    examples_data = load_examples(examples_path)

    with gr.Blocks() as app:
        gr.Markdown("# Video Highlight Generator")
        gr.Markdown("Upload a video and get an automated highlight reel!")
        
        with gr.Row():
            gr.Markdown("## Example Results")

        with gr.Row():
            for example in examples_data["examples"]:
                with gr.Column():
                    gr.Video(
                        value=example["original"]["url"],
                        label=f"Original ({format_duration(example['original']['duration_seconds'])})",
                        interactive=False
                    )
                    gr.Markdown(f"### {example['title']}")
                
                with gr.Column():

                    gr.Video(
                        value=example["highlights"]["url"],
                        label=f"Highlights ({format_duration(example['highlights']['duration_seconds'])})",
                        interactive=False
                    )
                    with gr.Accordion("Model chain of thought details", open=False):
                        gr.Markdown(f"#Summary: {example['analysis']['video_description']}")
                        gr.Markdown(f"#Highlights to search for: {example['analysis']['highlight_types']}")

        gr.Markdown("## Try It Yourself!")
        with gr.Row():
            with gr.Column(scale=1):
                input_video = gr.Video(
                    label="Upload your video (max 20 minutes)",
                    interactive=True
                )
                process_btn = gr.Button("Process Video", variant="primary")
            
            with gr.Column(scale=1):
                output_video = gr.Video(
                    label="Highlight Video",
                    visible=False,
                    interactive=False,
                )

                status = gr.Markdown()
        
                analysis_accordion = gr.Accordion(
                    "Model chain of thought details", 
                    open=True, 
                    visible=False
                )
                
                with analysis_accordion:
                    video_description = gr.Markdown("", elem_id="video_desc")
                    highlight_types = gr.Markdown("", elem_id="highlight_types")

        @spaces.GPU
        def on_process(video):
            if not video:
                yield [
                    "Please upload a video",
                    "",
                    "",
                    gr.update(visible=False),
                    gr.update(visible=False)
                ]
                return
            
            try:
                duration = get_video_duration_seconds(video)
                if duration > 1200:  # 20 minutes
                    yield [
                        "Video must be shorter than 20 minutes",
                        "",
                        "",
                        gr.update(visible=False),
                        gr.update(visible=False)
                    ]
                    return

                # Make accordion visible as soon as processing starts
                yield [
                    "Loading model...",
                    "",
                    "",
                    gr.update(visible=False),
                    gr.update(visible=True)
                ]

                model, processor = load_model()
                detector = BatchedVideoHighlightDetector(
                    model, 
                    processor, 
                    batch_size=8
                )

                yield [
                    "Analyzing video content...",
                    "",
                    "",
                    gr.update(visible=False),
                    gr.update(visible=True)
                ]
                
                video_desc = detector.analyze_video_content(video)
                formatted_desc = f"#Summary: {video_desc[:500] + '...' if len(video_desc) > 500 else video_desc}"
                
                yield [
                    "Determining highlight types...",
                    formatted_desc,
                    "",
                    gr.update(visible=False),
                    gr.update(visible=True)
                ]
                
                highlights = detector.determine_highlights(video_desc)
                formatted_highlights = f"#Highlights to search for: {highlights[:500] + '...' if len(highlights) > 500 else highlights}"
                
                # Get all segments
                segments = get_fixed_30s_segments(video)
                total_segments = len(segments)
                kept_segments = []
                
                # Process segments in batches with direct UI updates
                for i in range(0, len(segments), detector.batch_size):
                    batch_segments = segments[i:i + detector.batch_size]
                    
                    # Update progress
                    progress = int((i / total_segments) * 100)
                    yield [
                        f"Processing segments... {progress}% complete",
                        formatted_desc,
                        formatted_highlights,
                        gr.update(visible=False),
                        gr.update(visible=True)
                    ]
                    
                    # Process batch
                    keep_flags = detector._process_segment_batch(
                        video_path=video,
                        segments=batch_segments,
                        highlight_types=highlights,
                        total_segments=total_segments,
                        segments_processed=i
                    )
                    
                    # Keep track of segments to include
                    for segment, keep in zip(batch_segments, keep_flags):
                        if keep:
                            kept_segments.append(segment)

                # Create final video
                with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp_file:
                    temp_output = tmp_file.name
                    detector._concatenate_scenes(video, kept_segments, temp_output)
                
                yield [
                    "Processing complete!",
                    formatted_desc,
                    formatted_highlights,
                    gr.update(value=temp_output, visible=True),
                    gr.update(visible=True)
                ]

            except Exception as e:
                yield [
                    f"Error processing video: {str(e)}",
                    "",
                    "",
                    gr.update(visible=False),
                    gr.update(visible=False)
                ]

        process_btn.click(
            on_process,
            inputs=[input_video],
            outputs=[
                status,
                video_description,
                highlight_types,
                output_video,
                analysis_accordion
            ],
            queue=True,
        )

    return app
    #     gr.Markdown("## Try It Yourself!")
    #     with gr.Row():
    #         with gr.Column(scale=1):
    #             input_video = gr.Video(
    #                 label="Upload your video (max 20 minutes)",
    #                 interactive=True
    #             )
    #             process_btn = gr.Button("Process Video", variant="primary")
            
    #         with gr.Column(scale=1):
    #             output_video = gr.Video(
    #                 label="Highlight Video",
    #                 visible=False,
    #                 interactive=False,
    #             )

    #             status = gr.Markdown()
        
    #             analysis_accordion = gr.Accordion(
    #                 "Model chain of thought details", 
    #                 open=True, 
    #                 visible=False
    #             )
                
    #             with analysis_accordion:
    #                 video_description = gr.Markdown("", elem_id="video_desc")
    #                 highlight_types = gr.Markdown("", elem_id="highlight_types")

    #     @spaces.GPU
    #     def on_process(video):
    #         if not video:
    #             yield [
    #                 "Please upload a video",  # status
    #                 "",  # video_description
    #                 "",  # highlight_types
    #                 gr.update(visible=False),  # output_video
    #                 gr.update(visible=False)  # analysis_accordion
    #             ]
    #             return
            
    #         try:
    #             duration = get_video_duration_seconds(video)
    #             if duration > 1200:  # 20 minutes
    #                 yield [
    #                     "Video must be shorter than 20 minutes",
    #                     "",
    #                     "",
    #                     gr.update(visible=False),
    #                     gr.update(visible=False)
    #                 ]
    #                 return

    #             # Make accordion visible as soon as processing starts
    #             yield [
    #                 "Loading model...",
    #                 "",
    #                 "",
    #                 gr.update(visible=False),
    #                 gr.update(visible=True)
    #             ]

    #             model, processor = load_model()
    #             detector = BatchedVideoHighlightDetector(model, processor, batch_size=8)

    #             yield [
    #                 "Analyzing video content...",
    #                 "",
    #                 "",
    #                 gr.update(visible=False),
    #                 gr.update(visible=True)
    #             ]
                
    #             video_desc = detector.analyze_video_content(video)
    #             formatted_desc = f"#Summary: {video_desc[:500] + '...' if len(video_desc) > 500 else video_desc}"
                
    #             # Update description as soon as it's available
    #             yield [
    #                 "Determining highlight types...",
    #                 formatted_desc,
    #                 "",
    #                 gr.update(visible=False),
    #                 gr.update(visible=True)
    #             ]
                
    #             highlights = detector.determine_highlights(video_desc)
    #             formatted_highlights = f"#Highlights to search for: {highlights[:500] + '...' if len(highlights) > 500 else highlights}"
                
    #             # Update highlights as soon as they're available
    #             yield [
    #                 "Detecting and extracting highlights...",
    #                 formatted_desc,
    #                 formatted_highlights,
    #                 gr.update(visible=False),
    #                 gr.update(visible=True)
    #             ]

    #             with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp_file:
    #                 temp_output = tmp_file.name
    #             detector.create_highlight_video(video, temp_output)
                
    #             yield [
    #                 "Processing complete!",
    #                 formatted_desc,
    #                 formatted_highlights,
    #                 gr.update(value=temp_output, visible=True),
    #                 gr.update(visible=True)
    #             ]

    #         except Exception as e:
    #             yield [
    #                 f"Error processing video: {str(e)}",
    #                 "",
    #                 "",
    #                 gr.update(visible=False),
    #                 gr.update(visible=False)
    #             ]

    #     process_btn.click(
    #         on_process,
    #         inputs=[input_video],
    #         outputs=[
    #             status,
    #             video_description,
    #             highlight_types,
    #             output_video,
    #             analysis_accordion
    #         ],
    #         queue=True,
    #     )

    # return app

if __name__ == "__main__":
    # Initialize CUDA
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    zero = torch.Tensor([0]).to(device)

    app = create_ui("video_spec.json")
    app.launch()