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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import gradio as gr
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import re
from PIL import Image, ImageDraw
import numpy as np
import spaces

# Initialize model
model_path = 'GD-ML/UniVG-R1'
model = Qwen2VLForConditionalGeneration.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16,
    device_map="cuda:0",
)
processor = AutoProcessor.from_pretrained(model_path, max_pixels=401408)

# Keep the original examples content unchanged
examples = {
    "Reasoning": {
        "images": ["./demo_img/case046_r.png", "./demo_img/case046_1.png"],
        "instruction": "Locate the one appropriate object in Image-2 that can rotate the object of Image-1. Find it and locate it in the second image. ",
    },
    # "Reasoning 2": {
    #     "images": ["./demo_img/case044_r.png", "./demo_img/case044_2.png"],
    #     "instruction": "Considering the feature presented in Image-1, which object on the table of Image-2 may the child mostly skilled at? Find it and locate it in the second image. ",
    # },
    # "Reasoning 3": {
    #     "images": ["./demo_img/case096_1.png", "./demo_img/case096_2.png"],
    #     "instruction": "Which item in Image-2 can be worn on Image-1? Please find this object in Image-2. Find it and locate it in the second image. ",
    # },
    "Correspondence": {
        "images": ["./demo_img/case039_1.jpg", "./demo_img/case039_2.jpg"],
        "instruction": "You are now presented with two objects. For the area marked by the red bounding box in the first image, identify and locate the corresponding area in the second image that serves a similar function or shares a similar meaning. ",
    },
    # "Correspondence 2": {
    #     "images": ["./demo_img/case076_1.jpg", "./demo_img/case076_2.jpg"],
    #     "instruction": "You are now presented with two objects. For the area marked by the red bounding box in the first image, identify and locate the corresponding area in the second image that serves a similar function or shares a similar meaning. ",
    # },
    # "Correspondence 3": {
    #     "images": ["./demo_img/case050_r.jpg", "./demo_img/case050_1.jpg"],
    #     "instruction": "You are now presented with two objects. For the area marked by the red bounding box in the first image, identify and locate the corresponding area in the second image that serves a similar function or shares a similar meaning. ",
    # },
    "Difference": {
        "images": ["./demo_img/DSC_2185.jpg", "./demo_img/DSC_2184.jpg"],
        "instruction": "Compare these two images carefully and give me the coordinates of their real difference in the second image. Find it and locate it in the second image.",
    },
    "Refer Grounding": {
        "images": ["./demo_img/case31_ref.jpg", "./demo_img/case31_raw.jpg"],
        "instruction": "Find and locate where does the object in image-1 locate in the image-2.",
    },
    "Group Grounding": {
        "images": [
            "./demo_img/sa_6136360.jpg",
            "./demo_img/sa_2260999.jpg",
            "./demo_img/sa_6785496.jpg",
            "./demo_img/sa_444372.jpg"
        ],
        "instruction": "Please find the bounding box coordinates for the area described by: <|object_ref_start|>a white truck with a crane on top<|object_ref_end|>.",
    },
    "Region Locating": {
        "images": [
            "./demo_img/objects365_v1_00085860.jpg",
            "./demo_img/objects365_v1_00085860_1.jpg",
            "./demo_img/objects365_v1_00085860_3.jpg",
            "./demo_img/objects365_v1_00085860_2.jpg"
        ],
        "instruction": "You are given a source image followed by its several regions. Please locate the 1th region picture in the source image. ",
    },
    "Multi View": {
        "images": [
            "./demo_img/123648.jpg",
            "./demo_img/123654.jpg",
            "./demo_img/123701.jpg",
            "./demo_img/123750.jpg"
        ],
        "instruction": "These images share one object in common(the object marked with red bounding box in the first image(<|box_start|>(439,57),(689,999)<|box_end|>). Recognize and locate this object in the 2th image. ",
    },
    "Common Object": {
        "images": [
            "./demo_img/objects365_v1_00603066.jpg",
            "./demo_img/images3.jpg",
            "./demo_img/objects365_v1_00606066.jpg",
            "./demo_img/images.jpg"
        ],
        "instruction": "These images share one object in common. Recognize and locate this object in the 2th image. ",
    }
}

def normalize_and_scale_bbox(bbox, image_path):
    """Convert coordinates from [0,1000] range to actual image coordinates"""
    img = Image.open(image_path)
    width, height = img.size
    
    # Convert coordinates from [0,1000] range to actual image coordinates
    x1 = int((bbox[0] / 1000.0) * width)
    y1 = int((bbox[1] / 1000.0) * height)
    x2 = int((bbox[2] / 1000.0) * width)
    y2 = int((bbox[3] / 1000.0) * height)
    
    return [x1, y1, x2, y2]

def draw_bbox(image_path, bbox):
    """Draw bounding box on the image"""
    img = Image.open(image_path)
    draw = ImageDraw.Draw(img)
    
    # Get scaled coordinates
    scaled_bbox = normalize_and_scale_bbox(bbox, image_path)
    
    # Draw red bounding box with width 8
    draw.rectangle(scaled_bbox, outline='red', width=8)
    
    return img

def extract_bbox(output_text):
    """Extract bounding box coordinates from output text"""
    pattern = r'<answer>\((\d+),(\d+)\),\((\d+),(\d+)\)</answer>'
    match = re.search(pattern, output_text)
    if match:
        return [int(match.group(1)), int(match.group(2)), 
                int(match.group(3)), int(match.group(4))]
    return None

def update_preview(example_name):
    """Update preview images and instruction"""
    if not example_name:
        return None, "", gr.Gallery(value=None, visible=False)
    
    selected_example = examples[example_name]
    return (
        gr.Gallery(value=selected_example["images"], visible=True),
        selected_example["instruction"],
        gr.Gallery(value=None, visible=False)  # Clear result display
    )

@spaces.GPU
def clear_outputs():
    """Clear all outputs"""
    return (
        None,  # Clear dropdown selection
        gr.Gallery(value=None, visible=False),  # Clear preview images
        "",  # Clear instruction
        gr.Gallery(value=None, visible=False),  # Clear result images
        ""  # Clear output text
    )

@spaces.GPU
def process_example(example_name):
    """Process selected example"""
    if not example_name:
        return (
            gr.Gallery(value=None, visible=False),
            "",
            ""
        )
    
    selected_example = examples[example_name]
    images = selected_example["images"]
    instruction = selected_example["instruction"]
    
    messages = [
        {
            "role": "user",
            "content": [
                *[{"type": "image", "image": img} for img in images],
                {
                    "type": "text",
                    "text": instruction + " First output the thinking process in <think> </think> tags and then output the bounding box in <answer> </answer> tags."
                }
            ]
        }
    ]
    
    # Process input
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, video_inputs = process_vision_info(messages)
    inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
    inputs = inputs.to("cuda:0")
    
    # Generate output
    generated_ids = model.generate(**inputs, max_new_tokens=256)
    generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
    output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
    
    # Extract bounding box coordinates and draw
    bbox = extract_bbox(output_text)
    if bbox:
        # Draw bounding box on all images
        visualized_images = [draw_bbox(img_path, bbox) for img_path in images]
    else:
        # If no bounding box detected, use original images
        visualized_images = [Image.open(img_path) for img_path in images]
    
    return (
        gr.Gallery(value=visualized_images, visible=True),
        instruction,
        output_text
    )

@spaces.GPU
def process_custom_input(images, instruction):
    """Process custom user input"""
    if not images or not instruction:
        return (
            gr.Gallery(value=None, visible=False),
            instruction,
            ""
        )
    
    # Save uploaded images to temporary files
    image_paths = []
    for i, img in enumerate(images):
        if isinstance(img, str):  # If already a path
            image_paths.append(img)
        else:  # If uploaded image
            temp_path = f"temp_image_{i}.png"
            if isinstance(img, Image.Image):
                img.save(temp_path)
            else:
                Image.fromarray(img).save(temp_path)
            image_paths.append(temp_path)
    
    messages = [
        {
            "role": "user",
            "content": [
                *[{"type": "image", "image": img} for img in image_paths],
                {
                    "type": "text",
                    "text": instruction + " First output the thinking process in <think> </think> tags and then output the bounding box in <answer> </answer> tags."
                }
            ]
        }
    ]
    
    # Process input
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, video_inputs = process_vision_info(messages)
    inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
    inputs = inputs.to("cuda:0")
    
    # Generate output
    generated_ids = model.generate(**inputs, max_new_tokens=256)
    generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
    output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
    
    # Extract bounding box coordinates and draw
    bbox = extract_bbox(output_text)
    if bbox:
        # Draw bounding box on all images
        visualized_images = [draw_bbox(img_path, bbox) for img_path in image_paths]
    else:
        # If no bounding box detected, use original images
        visualized_images = [Image.open(img_path) for img_path in image_paths]
    
    return (
        gr.Gallery(value=visualized_images, visible=True),
        instruction,
        output_text
    )

css = """
.example-container {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    margin: 10px 0;
    transition: all 0.3s ease;
}

.example-container:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}

.button-row {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin: 20px 0;
}

.examples-table {
    border-collapse: collapse;
    width: 100%;
}

.examples-table td {
    padding: 10px;
    border: 1px solid #ddd;
}

.example-title {
    font-weight: bold;
    margin-bottom: 10px;
}

.example-preview {
    cursor: pointer;
    padding: 10px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.example-preview:hover {
    background-color: #f5f5f5;
}

/* Add custom button styles */
.custom-button {
    background-color: #2196F3 !important;
    color: white !important;
    font-weight: bold !important;
    border: none !important;
    border-radius: 4px !important;
    padding: 8px 16px !important;
    margin: 8px 0 !important;
    transition: all 0.3s ease !important;
}

.custom-button:hover {
    background-color: #1976D2 !important;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important;
}
"""

def create_example_preview(example_name):
    """Create single example preview component"""
    example_data = examples[example_name]
    with gr.Column(elem_classes="example-preview"):
        gr.Markdown(f"**{example_name}**")
        gr.Gallery(value=example_data["images"], columns=2, rows=1, height=200, object_fit="contain")
        gr.Markdown(example_data["instruction"])
    return example_name

# Create Gradio interface
with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
    gr.Markdown("# UniVG-R1 Demo")
    gr.Markdown("Use our provided examples or upload your own local images for universal visual grounding.")
    gr.Markdown("[Project Page](https://amap-ml.github.io/UniVG-R1-page/) &nbsp;&nbsp;&nbsp;&nbsp; [GitHub](https://github.com/AMAP-ML/UniVG-R1) &nbsp;&nbsp;&nbsp;&nbsp; [arXiv](https://arxiv.org/abs/2505.14231)")
    
    with gr.Tabs():
        with gr.Tab("Preset Examples"):
            with gr.Row():
                example_dropdown = gr.Dropdown(
                    choices=list(examples.keys()),
                    label="Select Example",
                    value=None
                )
            
            with gr.Row():
                preview_gallery = gr.Gallery(
                    label="Preview Images",
                    show_label=True,
                    columns=2,
                    rows=1,
                    height=300,
                    object_fit="contain",
                    preview=True,
                    visible=False
                )
            
            with gr.Row():
                instruction_text = gr.Textbox(label="Instruction", interactive=False)
            
            with gr.Row(elem_classes="button-row"):
                submit_btn = gr.Button("Submit", variant="primary")
                clear_btn = gr.Button("Clear")
            
            with gr.Row():
                result_gallery = gr.Gallery(
                    label="Results with Bounding Box",
                    show_label=True,
                    columns=2,
                    rows=1,
                    height=400,
                    object_fit="contain",
                    preview=True,
                    visible=False,
                    allow_preview=True,  # 添加这个参数
        show_download_button=True,  # 可选:添加下载按钮
        elem_id="result_gallery"  # 可选:添加唯一ID
                )
            
            with gr.Row():
                output_box = gr.Textbox(label="Model Output", interactive=False, lines=5)
            
            # Example preview area
            gr.Markdown("## Examples")
            
            # Use grid layout to display examples
            with gr.Row():
                with gr.Column():
                    for i, (example_name, example_data) in enumerate(examples.items()):
                        if i % 2 == 0:  # Display two examples per row
                            row_examples = []
                        with gr.Group(elem_classes="example-preview"):
                            gr.Markdown(f"### {example_name}")
                            gallery = gr.Gallery(
                                value=example_data["images"],
                                columns=len(example_data["images"]),
                                rows=1,
                                height=300,
                                object_fit="scale-down",
                                preview=True,
                                show_label=False,
                                allow_preview=True
                            )
                            gr.Markdown(f"**Instruction**: {example_data['instruction']}")
                            # Add a select button, using custom styles
                            select_btn = gr.Button(
                                f"Select {example_name}",
                                size="sm",
                                elem_classes="custom-button"
                            )
                            select_btn.click(
                                lambda x: x,
                                inputs=[gr.State(example_name)],
                                outputs=[example_dropdown]
                            )
        
            # Event handling
            example_dropdown.change(
                update_preview,
                inputs=[example_dropdown],
                outputs=[preview_gallery, instruction_text, result_gallery]
            )
            
            submit_btn.click(
                process_example,
                inputs=[example_dropdown],
                outputs=[result_gallery, instruction_text, output_box]
            )
            
            clear_btn.click(
                clear_outputs,
                inputs=[],
                outputs=[example_dropdown, preview_gallery, instruction_text, result_gallery, output_box]
            )
        
        with gr.Tab("Custom Input"):
            with gr.Row():
                custom_images = gr.File(
                    label="Upload Images (Multiple Supported)",
                    file_count="multiple",
                    file_types=["image"]
                )
            
            with gr.Row():
                custom_instruction = gr.Textbox(
                    label="Enter Instruction",
                    placeholder="Please enter your instruction...",
                    lines=3
                )
            
            with gr.Row():
                custom_submit_btn = gr.Button("Submit", variant="primary")
                custom_clear_btn = gr.Button("Clear")
            
            with gr.Row():
                custom_result_gallery = gr.Gallery(
                    label="Results",
                    show_label=True,
                    columns=2,
                    rows=1,
                    height=400,
                    object_fit="contain",
                    preview=True,
                    visible=False
                )
            
            with gr.Row():
                custom_output_box = gr.Textbox(label="Model Output", interactive=False, lines=5)
            
            # Custom input event handling
            custom_submit_btn.click(
                process_custom_input,
                inputs=[custom_images, custom_instruction],
                outputs=[custom_result_gallery, custom_instruction, custom_output_box]
            )
            
            custom_clear_btn.click(
                lambda: [None, "", None, ""],  # Fix return value format
                outputs=[custom_images, custom_instruction, custom_result_gallery, custom_output_box]
            )

if __name__ == "__main__":
    demo.launch()