File size: 12,279 Bytes
d686824
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import asyncio
import numpy as np
import gradio as gr
from PIL import Image
from io import BytesIO
from moviepy import VideoFileClip
import matplotlib.pyplot as plt
import base64
from TStar.TStarFramework import run_tstar


def img2base64(image_path):
        return base64.b64encode(open(image_path, "rb").read()).decode("utf-8")

def create_timeline(frame_times, duration):
    """
    Creates a timeline visualization for the sampled frames.
    """
    fig, ax = plt.subplots(figsize=(10, 2))
    ax.set_xlim(0, duration)
    ax.hlines(0.5, 0, duration, colors="gray", linestyles="dotted")
    ax.plot(frame_times, [0.5] * len(frame_times), 'ro')
    ax.set_xlabel("Time (s)")

    buf = BytesIO()
    fig.savefig(buf, format='png')
    buf.seek(0)
    plt.close(fig)

    return Image.open(buf)

def analyze_and_sample_frames(
    video_file,
    question,
    openai_api_key,
    num_frames=8,
    batch=1,
    total_batches=3
):
    """
    结合后端 run_tstar 函数,对视频进行关键帧搜索,并在前端生成可视化所需的结果:
    - metadata: 记录后端结果与问题、答案等信息
    - frames: PIL 图像列表,用于在 Gradio Gallery 显示
    - frame_times: 关键帧时间戳列表(秒)
    - timeline_image: 带有关键帧标注的时间线图像
    """

    if not os.path.exists(video_file):
        print("video_file does not exist:", video_file)
        return None, None, None, None

    if not question:
        question = "No question provided"
    
    options = "Freeform Question"
     
    # 你也可以根据 batch / total_batches 动态改变 search 的参数
    # 例如 batch 越大,search_budget 越大;或者直接固定即可
    # 这里只做演示,不做复杂逻辑
    results = run_tstar(
        video_path=video_file,
        question=question,
        options=options,
        grounder="gpt-4o",
        heuristic="owl-vit",
        device="cuda:0",
        search_nframes=num_frames,
        grid_rows=4,
        grid_cols=4,
        confidence_threshold=0.6,
        search_budget=0.5,
        output_dir='./output',
        openai_api_key=openai_api_key
    )
    # 从后端结果解析关键信息
    frame_times = results.get("Frame Timestamps", [])
    answer = results.get("Answer", "No answer")
    grounding_objects = results.get("Grounding Objects", [])

    # 截取关键帧图像
    frames = []
    clip = VideoFileClip(video_file)
    video_duration = clip.duration

    for t in frame_times:
        # 确保时间戳不超过视频长度
        if t > video_duration:
            t = video_duration
        frame_img = clip.get_frame(t)  # 取对应秒的帧,返回 (H,W,3) numpy
        frame_pil = Image.fromarray(frame_img.astype(np.uint8))
        frames.append(frame_pil)

    clip.close()

    # 生成时间线图像
    timeline_image = create_timeline(frame_times, duration=video_duration)

    # 生成元数据(可根据需要增减字段)
    metadata = {
        "batch": batch,
        "total_batches": total_batches,
        "question": question,
        "answer": answer,
        "grounding_objects": grounding_objects,
        "frame_times": frame_times
    }

    return metadata, frames, frame_times, timeline_image


def switch_batch(state_batches, selected_batch):
    """
    Switches the display to the selected batch.
    """
    if not selected_batch or selected_batch == "":
        return None, None, None, None

    batch_index = int(selected_batch.split()[-1]) - 1
    timeline_image, frames, metadata = state_batches[batch_index]

    return (
        gr.update(value=timeline_image, visible=True),
        gr.update(value=frames, visible=True),
        gr.update(value=metadata, visible=True),
        selected_batch,
    )


async def process_video_iteratively_with_state(video_file, question_input, openai_api_key_input, state_batches, current_display_batch, total_batches=1, num_frames=8):
    """
    Processes the video and samples frames iteratively.
    """
    if not video_file:
        yield None, None, None, "No video uploaded!", None, state_batches, current_display_batch
        return

    metadata = None
    for batch in range(1, total_batches + 1):
        metadata, frames, frame_times, timeline_image = analyze_and_sample_frames(
            video_file, question=question_input, openai_api_key=openai_api_key_input, num_frames=num_frames, batch=batch, total_batches=total_batches
        )

        if metadata is None:
            continue

        state_batches.append((timeline_image, frames, metadata))
        batch_choices = [f"Batch {i + 1}" for i in range(len(state_batches))]

        if current_display_batch is None or current_display_batch == f"Batch {batch - 1}":
            current_display_batch = f"Batch {batch}"

        yield (
            gr.update(value=timeline_image, visible=True),
            gr.update(value=frames, visible=True),
            gr.update(value=metadata, visible=True),
            f"Processing Batch: {batch} / Total Batches: {total_batches}",
            gr.update(choices=batch_choices, value=f"Batch {batch}", visible=True),
            state_batches,
            current_display_batch,
        )

        await asyncio.sleep(0.5)


def generate_header(base64_logo, title="⭐ T - Efficient Long Video QA Tool"):
    """
    Generates the header section for the app.
    """
    return f"""
        <h1 style="text-align: center; font-size: 3em; color: #4CAF50; font-family: 'Open Sans', sans-serif; margin-bottom: 20px;">{title}</h1>
        <div style="display: flex; justify-content: center; align-items: center; height: 333px;">
            <img src="data:image/png;base64,{base64_logo}" alt="Logo" style="width: auto; height: 300px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
        </div>
        <div style="display: flex; justify-content: center; align-items: center; margin-top: 20px;">
            <h2 style="text-align: center; font-size: 2em; color: #333; margin-bottom: 30px;">📖 How to Use?</h2>
        </div>
    """

def generate_instruction(step, title, description):
    """
    Generates a single instruction card.
    """
    return f"""
        <div style="background-color: #F9F9F9; padding: 20px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); height: 150px; display: flex; flex-direction: column; justify-content: flex-start;">
            <h3 style="font-size: 1.5em; color: #4CAF50; font-family: 'Open Sans', sans-serif; margin-bottom: 10px;">Step {step}: {title}</h3>
            <p style="font-size: 1em; color: #666; line-height: 1.5; margin: 0;">
                {description}
            </p>
        </div>
    """

def create_ui_components(default_video_path):
    """
    Creates the UI components for the Gradio application.
    """
    # Layout in two columns
    with gr.Row(equal_height=True, elem_id="video-container"):
        with gr.Column(scale=1, min_width=300):
            # Left Column: Video Upload
            gr.Markdown("""
                <br>
                <h2 style="color: #333;">Upload Your Video</h3>
                <p style="color: #666; font-size: 0.9em;">You can upload a sample video or provide your own video for analysis.</p>
            """)
            video_input = gr.File(
                label="Select Video", 
                type="filepath",
                value=default_video_path,
                interactive=True
            )
            
        with gr.Column(scale=1.5, min_width=400):
            # Right Column: Video Preview
            gr.Markdown("""
                <br>
                <h2 style="color: #333;">Video Preview</h3>
                <p style="color: #666; font-size: 0.9em;">View your video here before starting the analysis.</p>
            """)
            video_preview = gr.Video(
                label="Preview",
                value=default_video_path,
                visible=True,
                autoplay=True,
                loop=True,
            )

    # add a textbox to input question

    openai_api_key_input = gr.Textbox(
        label="Provide your OpenAI API Key",
        placeholder="sk-...",
        value="sk-...",
        type="text",
        elem_id="openai-api-key-input",
    )
    
    question_input = gr.Textbox(
        label="Ask a Question",
        placeholder="",
        value="Where's the microwave? A. Under the cabinet B. On top of the refrigerator C. Next to the stove D. Beside the sink E. In the pantry",
        type="text",
        elem_id="question-input",
    )
    
    submit_button = gr.Button(
        "Analyze!", 
        elem_id="analyze-button", 
    )
    
    # Add a new component for displaying the video preview

    state_batches = gr.State([])  # Stores all generated batch data
    current_display_batch = gr.State(None)  # Tracks the currently displayed batch

    output_timeline = gr.Image(label="Video Timeline", type="pil", visible=False)
    output_frames = gr.Gallery(label="Sampled Frames", columns=8, visible=False, height=200)
    batch_status = gr.Text(label="Batch Status", value="No Batch Processed Yet", visible=True)
    batch_selector = gr.Dropdown(choices=[], label="Select Batch", visible=False)
    output_metadata = gr.JSON(label="Video Metadata", visible=False)

    return (
        openai_api_key_input,
        video_input,
        question_input,
        submit_button,
        video_preview,  # Add the video preview component
        state_batches,
        current_display_batch,
        output_timeline,
        output_frames,
        batch_status,
        batch_selector,
        output_metadata,
    )


def update_video_preview(video_file, default_video_path):
    return gr.update(value=(video_file.name if video_file else default_video_path), visible=True, autoplay=True, loop=True)

if __name__ == "__main__":
    # Default sample video path
    sample_video_path = "data/sample.mp4"
    logo_path = "data/logo.png"
    base64_logo = img2base64(logo_path)
    
    with gr.Blocks() as demo:
        # Add header
        gr.Markdown(generate_header(base64_logo))

        # Add instructions
        steps = [
            ("Upload", "Sample video is provided. You can also upload your own!<br>Click <strong>Video Preview</strong> to preview it."),
            ("Analyze", "Ask a question and click <strong>'Analyze'</strong>.<br>The system will track keyframes to answer your question."),
            ("Visualize", "View keyframes with their sample distribution.<br>Explore keyframe tracking dynamics visually!"),
        ]
        
        with gr.Row(equal_height=True, elem_id="instructions-container"):
            for i, (title, description) in enumerate(steps, start=1):
                with gr.Column(scale=1, min_width=100):
                    gr.Markdown(generate_instruction(i, title, description))

        (
            openai_api_key_input,
            video_input,
            question_input,
            submit_button,
            video_preview,  # Video preview component
            state_batches,
            current_display_batch,
            output_timeline,
            output_frames,
            batch_status,
            batch_selector,
            output_metadata,
        ) = create_ui_components(sample_video_path)

        video_input.change(
            fn=update_video_preview,
            inputs=[video_input, gr.State(sample_video_path)],
            outputs=video_preview,
        )
                
        submit_button.click(
            fn=process_video_iteratively_with_state,
            inputs=[video_input, question_input, openai_api_key_input, state_batches, current_display_batch],
            outputs=[
                output_timeline,
                output_frames,
                output_metadata,
                batch_status,
                batch_selector,
                state_batches,
                current_display_batch,
            ],
        )

        batch_selector.change(
            fn=switch_batch,
            inputs=[state_batches, batch_selector],
            outputs=[output_timeline, output_frames, output_metadata, current_display_batch],
        )

    # Launch Gradio application
    demo.launch(share=True, server_name="0.0.0.0", server_port=8088)