File size: 12,857 Bytes
880de81
 
 
4c7362f
1167d4f
e05c441
141829b
 
 
a8bd881
 
e05c441
 
880de81
141829b
 
880de81
 
 
 
 
a8bd881
 
 
 
 
880de81
141829b
 
 
 
 
 
 
 
 
 
 
880de81
141829b
 
 
 
 
 
 
 
 
 
 
 
 
 
a8bd881
141829b
 
 
b7a96e8
141829b
b7a96e8
 
 
22498e9
141829b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ecd2e5
141829b
a8bd881
 
141829b
 
 
a8bd881
141829b
 
 
a8bd881
 
 
 
141829b
 
a8bd881
 
 
 
 
 
 
 
 
 
 
0836d7b
a8bd881
 
 
 
 
 
 
 
 
 
 
141829b
 
 
 
 
 
 
 
 
 
1ecd2e5
141829b
 
 
 
 
 
 
a8bd881
141829b
 
 
 
 
 
 
 
 
 
 
 
 
1ecd2e5
141829b
e05c441
a8bd881
 
e05c441
a8bd881
 
 
e05c441
a8bd881
 
e05c441
a8bd881
 
e05c441
a8bd881
e05c441
a8bd881
 
e05c441
a8bd881
 
e05c441
a8bd881
 
e05c441
a8bd881
 
e05c441
a8bd881
 
 
e05c441
a8bd881
e05c441
a8bd881
 
e05c441
a8bd881
141829b
 
880de81
 
 
a8bd881
 
880de81
 
c43a83e
 
c7fdc4d
946878e
c43a83e
 
 
 
a8bd881
 
c43a83e
 
 
946878e
a8bd881
0cb8d8c
a8bd881
0cb8d8c
 
 
 
 
a8bd881
 
880de81
946878e
0cb8d8c
880de81
a8bd881
 
be5d51f
 
 
 
8323202
880de81
946878e
 
e05c441
a8bd881
 
c7fdc4d
8323202
 
 
 
0cb8d8c
a8bd881
0cb8d8c
a8bd881
946878e
a8bd881
0cb8d8c
a8bd881
946878e
a8bd881
0cb8d8c
a8bd881
141829b
fc0912b
a8bd881
 
141829b
 
fc0912b
a8bd881
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141829b
a8bd881
 
 
 
 
 
 
141829b
a8bd881
 
 
141829b
 
 
 
 
a8bd881
 
141829b
 
 
 
 
946878e
 
141829b
a8bd881
 
8323202
 
 
 
 
f652e04
141829b
880de81
167ab4b
0cb8d8c
880de81
f38285f
a8bd881
f38285f
 
 
0cb8d8c
 
8323202
880de81
 
 
 
 
6a9b659
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
import os
import json
import gradio as gr
import torch
import spaces
import tempfile
from pathlib import Path
import subprocess
import logging
import xml.etree.ElementTree as ET
from xml.dom import minidom
from transformers import AutoProcessor, AutoModelForVision2Seq


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

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

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

def get_video_duration_seconds(video_path: str) -> float:
    cmd = [
        "ffprobe",
        "-v", "quiet",
        "-print_format", "json",
        "-show_format",
        video_path
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    info = json.loads(result.stdout)
    return float(info["format"]["duration"])

class VideoHighlightDetector:
    def __init__(
        self,
        model_path: str,
        device: str = "cuda",
        batch_size: int = 8
    ):
        self.device = device
        self.batch_size = batch_size
        
        # Initialize model and processor
        self.processor = AutoProcessor.from_pretrained(model_path)
        self.model = AutoModelForVision2Seq.from_pretrained(
            model_path,
            torch_dtype=torch.bfloat16
        ).to(device)
        
    def analyze_video_content(self, video_path: str) -> str:
        system_message = "You are a helpful assistant that can understand videos. Describe what type of video this is and what's happening in it."
        messages = [
            {
                "role": "system",
                "content": [{"type": "text", "text": system_message}]
            },
            {
                "role": "user",
                "content": [
                    {"type": "video", "path": video_path},
                    {"type": "text", "text": "What type of video is this and what's happening in it? Be specific about the content type and general activities you observe."}
                ]
            }
        ]
        
        inputs = self.processor.apply_chat_template(
            messages,
            add_generation_prompt=True,
            tokenize=True,
            return_dict=True,
            return_tensors="pt"
        ).to(self.device)
        
        outputs = self.model.generate(**inputs, max_new_tokens=512, do_sample=True, temperature=0.7)
        return self.processor.decode(outputs[0], skip_special_tokens=True).lower().split("assistant: ")[1]

    def analyze_segment(self, video_path: str) -> str:
        """Analyze a specific video segment and provide a brief description."""
        messages = [
            {
                "role": "system",
                "content": [{"type": "text", "text": "Describe what is happening in this specific video segment in a brief, concise way."}]
            },
            {
                "role": "user",
                "content": [
                    {"type": "video", "path": video_path},
                    {"type": "text", "text": "What is happening in this segment? Provide a brief description."}
                ]
            }
        ]
        
        inputs = self.processor.apply_chat_template(
            messages,
            add_generation_prompt=True,
            tokenize=True,
            return_dict=True,
            return_tensors="pt"
        ).to(self.device)
        
        outputs = self.model.generate(**inputs, max_new_tokens=128, do_sample=True, temperature=0.7)
        return self.processor.decode(outputs[0], skip_special_tokens=True).split("Assistant: ")[1]

    def determine_highlights(self, video_description: str) -> str:
        messages = [
            {
                "role": "system",
                "content": [{"type": "text", "text": "You are a professional video editor specializing in creating viral highlight reels."}]
            },
            {
                "role": "user",
                "content": [{"type": "text", "text": f"Based on this description, list which segments should be included in highlights: {video_description}"}]
            }
        ]
        
        inputs = self.processor.apply_chat_template(
            messages,
            add_generation_prompt=True,
            tokenize=True,
            return_dict=True,
            return_tensors="pt"
        ).to(self.device)
        
        outputs = self.model.generate(**inputs, max_new_tokens=256, do_sample=True, temperature=0.7)
        return self.processor.decode(outputs[0], skip_special_tokens=True).split("Assistant: ")[1]

    def process_segment(self, video_path: str, highlight_types: str) -> bool:
        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "video", "path": video_path},
                    {"type": "text", "text": f"Do you see any of these elements in the video: {highlight_types}? Answer yes or no."}
                ]
            }
        ]
        
        inputs = self.processor.apply_chat_template(
            messages,
            add_generation_prompt=True,
            tokenize=True,
            return_dict=True,
            return_tensors="pt"
        ).to(self.device)
        
        outputs = self.model.generate(**inputs, max_new_tokens=64, do_sample=False)
        response = self.processor.decode(outputs[0], skip_special_tokens=True).lower().split("assistant: ")[1]
        return "yes" in response

def create_xspf_playlist(video_path: str, segments: list, descriptions: list) -> str:
    """Create XSPF playlist from segments with descriptions."""
    root = ET.Element("playlist", version="1", xmlns="http://xspf.org/ns/0/")
    
    # Get video filename for the title
    video_filename = os.path.basename(video_path)
    title = ET.SubElement(root, "title")
    title.text = f"{video_filename} - Highlights"
    
    tracklist = ET.SubElement(root, "trackList")
    
    for idx, ((start_time, end_time), description) in enumerate(zip(segments, descriptions)):
        track = ET.SubElement(tracklist, "track")
        
        location = ET.SubElement(track, "location")
        location.text = f"file:///{video_filename}"
        
        title = ET.SubElement(track, "title")
        title.text = f"Highlight {idx + 1}"
        
        annotation = ET.SubElement(track, "annotation")
        annotation.text = description
        
        start_meta = ET.SubElement(track, "meta", rel="start")
        start_meta.text = format_duration(start_time)
        
        end_meta = ET.SubElement(track, "meta", rel="end")
        end_meta.text = format_duration(end_time)
    
    # Add VLC extension
    extension = ET.SubElement(root, "extension", application="http://www.videolan.org/vlc/playlist/0")
    for i in range(len(segments)):
        item = ET.SubElement(extension, "vlc:item", tid=str(i))
    
    # Convert to string with pretty printing
    xml_str = minidom.parseString(ET.tostring(root)).toprettyxml(indent="    ")
    return xml_str

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

    with gr.Blocks() as app:
        gr.Markdown("# Video Highlight Playlist Generator")
        gr.Markdown("Upload a video and get an XSPF playlist of highlights!")
        
        with gr.Row():
            with gr.Column(scale=1):
                input_video = gr.Video(
                    label="Upload your video (max 30 minutes)",
                    interactive=True
                )
                process_btn = gr.Button("Process Video", variant="primary")
            
            with gr.Column(scale=1):
                output_playlist = gr.File(
                    label="Highlight Playlist (XSPF)",
                    visible=False,
                    interactive=False,
                )
                status = gr.Markdown()
                
                analysis_accordion = gr.Accordion(
                    "Analysis Details", 
                    open=True, 
                    visible=False
                )
                
                with analysis_accordion:
                    video_description = gr.Markdown("")
                    highlight_types = gr.Markdown("")

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

                detector = VideoHighlightDetector(model_path=model_path)
                
                # Analyze video content
                video_desc = detector.analyze_video_content(video)
                formatted_desc = f"### Video Summary:\n{video_desc}"
                
                # Determine highlight types
                highlights = detector.determine_highlights(video_desc)
                formatted_highlights = f"### Highlight Criteria:\n{highlights}"
                
                # Process video in segments
                segment_length = 10.0
                kept_segments = []
                segment_descriptions = []
                
                for start_time in range(0, int(duration), int(segment_length)):
                    end_time = min(start_time + segment_length, duration)
                    
                    # Create temporary segment
                    with tempfile.NamedTemporaryFile(suffix='.mp4') as temp_segment:
                        cmd = [
                            "ffmpeg",
                            "-y",
                            "-i", video,
                            "-ss", str(start_time),
                            "-t", str(segment_length),
                            "-c:v", "libx264",
                            "-preset", "ultrafast",
                            temp_segment.name
                        ]
                        subprocess.run(cmd, check=True)
                        
                        if detector.process_segment(temp_segment.name, highlights):
                            # Get segment description
                            description = detector.analyze_segment(temp_segment.name)
                            kept_segments.append((start_time, end_time))
                            segment_descriptions.append(description)
                
                if kept_segments:
                    # Create XSPF playlist
                    playlist_content = create_xspf_playlist(video, kept_segments, segment_descriptions)
                    
                    # Save playlist to temporary file
                    with tempfile.NamedTemporaryFile(mode='w', suffix='.xspf', delete=False) as f:
                        f.write(playlist_content)
                        playlist_path = f.name
                    
                    return [
                        gr.update(value=playlist_path, visible=True),
                        "Processing complete! Download the XSPF playlist.",
                        formatted_desc,
                        formatted_highlights,
                        gr.update(visible=True)
                    ]
                else:
                    return [
                        None,
                        "No highlights detected in the video.",
                        formatted_desc,
                        formatted_highlights,
                        gr.update(visible=True)
                    ]

            except Exception as e:
                logger.exception("Error processing video")
                return [
                    None,
                    f"Error processing video: {str(e)}",
                    "",
                    "",
                    gr.update(visible=False)
                ]
            finally:
                torch.cuda.empty_cache()

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

    return app

if __name__ == "__main__":
    app = create_ui("video_spec.json", "HuggingFaceTB/SmolVLM2-2.2B-Instruct")
    app.launch()