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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
4
+ from qwen_vl_utils import process_vision_info
5
+ import re
6
+ from PIL import Image, ImageDraw
7
+ import numpy as np
8
+
9
+ # Initialize model
10
+ model_path = 'GD-ML/UniVG-R1'
11
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
12
+ model_path,
13
+ torch_dtype=torch.bfloat16,
14
+ attn_implementation="flash_attention_2",
15
+ device_map="cuda:0",
16
+ )
17
+ processor = AutoProcessor.from_pretrained(model_path, max_pixels=401408)
18
+
19
+ # Keep the original examples content unchanged
20
+ examples = {
21
+ "Reasoning 1": {
22
+ "images": ["./demo_img/case046_r.png", "./demo_img/case046_1.png"],
23
+ "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. ",
24
+ },
25
+ "Reasoning 2": {
26
+ "images": ["./demo_img/case044_r.png", "./demo_img/case044_2.png"],
27
+ "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. ",
28
+ },
29
+ "Reasoning 3": {
30
+ "images": ["./demo_img/case096_1.png", "./demo_img/case096_2.png"],
31
+ "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. ",
32
+ },
33
+ "Correspondence 1": {
34
+ "images": ["./demo_img/case039_1.jpg", "./demo_img/case039_2.jpg"],
35
+ "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. ",
36
+ },
37
+ "Correspondence 2": {
38
+ "images": ["./demo_img/case076_1.jpg", "./demo_img/case076_2.jpg"],
39
+ "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. ",
40
+ },
41
+ "Correspondence 3": {
42
+ "images": ["./demo_img/case050_r.jpg", "./demo_img/case050_1.jpg"],
43
+ "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. ",
44
+ },
45
+ "Difference": {
46
+ "images": ["./demo_img/DSC_2185.jpg", "./demo_img/DSC_2184.jpg"],
47
+ "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.",
48
+ },
49
+ "Refer Grounding": {
50
+ "images": ["./demo_img/case31_ref.jpg", "./demo_img/case31_raw.jpg"],
51
+ "instruction": "Find and locate where does the object in image-1 locate in the image-2.",
52
+ },
53
+ "Group Grounding": {
54
+ "images": [
55
+ "./demo_img/sa_6136360.jpg",
56
+ "./demo_img/sa_2260999.jpg",
57
+ "./demo_img/sa_6785496.jpg",
58
+ "./demo_img/sa_444372.jpg"
59
+ ],
60
+ "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|>.",
61
+ },
62
+ "Region Locating": {
63
+ "images": [
64
+ "./demo_img/objects365_v1_00085860.jpg",
65
+ "./demo_img/objects365_v1_00085860_1.jpg",
66
+ "./demo_img/objects365_v1_00085860_3.jpg",
67
+ "./demo_img/objects365_v1_00085860_2.jpg"
68
+ ],
69
+ "instruction": "You are given a source image followed by its several regions. Please locate the 1th region picture in the source image. ",
70
+ },
71
+ "Multi View": {
72
+ "images": [
73
+ "./demo_img/123648.jpg",
74
+ "./demo_img/123654.jpg",
75
+ "./demo_img/123701.jpg",
76
+ "./demo_img/123750.jpg"
77
+ ],
78
+ "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. ",
79
+ },
80
+ "Common Object": {
81
+ "images": [
82
+ "./demo_img/objects365_v1_00603066.jpg",
83
+ "./demo_img/images3.jpg",
84
+ "./demo_img/objects365_v1_00606066.jpg",
85
+ "./demo_img/images.jpg"
86
+ ],
87
+ "instruction": "These images share one object in common. Recognize and locate this object in the 2th image. ",
88
+ }
89
+ }
90
+
91
+ def normalize_and_scale_bbox(bbox, image_path):
92
+ """Convert coordinates from [0,1000] range to actual image coordinates"""
93
+ img = Image.open(image_path)
94
+ width, height = img.size
95
+
96
+ # Convert coordinates from [0,1000] range to actual image coordinates
97
+ x1 = int((bbox[0] / 1000.0) * width)
98
+ y1 = int((bbox[1] / 1000.0) * height)
99
+ x2 = int((bbox[2] / 1000.0) * width)
100
+ y2 = int((bbox[3] / 1000.0) * height)
101
+
102
+ return [x1, y1, x2, y2]
103
+
104
+ def draw_bbox(image_path, bbox):
105
+ """Draw bounding box on the image"""
106
+ img = Image.open(image_path)
107
+ draw = ImageDraw.Draw(img)
108
+
109
+ # Get scaled coordinates
110
+ scaled_bbox = normalize_and_scale_bbox(bbox, image_path)
111
+
112
+ # Draw red bounding box with width 8
113
+ draw.rectangle(scaled_bbox, outline='red', width=8)
114
+
115
+ return img
116
+
117
+ def extract_bbox(output_text):
118
+ """Extract bounding box coordinates from output text"""
119
+ pattern = r'<answer>\((\d+),(\d+)\),\((\d+),(\d+)\)</answer>'
120
+ match = re.search(pattern, output_text)
121
+ if match:
122
+ return [int(match.group(1)), int(match.group(2)),
123
+ int(match.group(3)), int(match.group(4))]
124
+ return None
125
+
126
+ def update_preview(example_name):
127
+ """Update preview images and instruction"""
128
+ if not example_name:
129
+ return None, "", gr.Gallery(value=None, visible=False)
130
+
131
+ selected_example = examples[example_name]
132
+ return (
133
+ gr.Gallery(value=selected_example["images"], visible=True),
134
+ selected_example["instruction"],
135
+ gr.Gallery(value=None, visible=False) # Clear result display
136
+ )
137
+
138
+ def clear_outputs():
139
+ """Clear all outputs"""
140
+ return (
141
+ None, # Clear dropdown selection
142
+ gr.Gallery(value=None, visible=False), # Clear preview images
143
+ "", # Clear instruction
144
+ gr.Gallery(value=None, visible=False), # Clear result images
145
+ "" # Clear output text
146
+ )
147
+
148
+ def process_example(example_name):
149
+ """Process selected example"""
150
+ if not example_name:
151
+ return (
152
+ gr.Gallery(value=None, visible=False),
153
+ "",
154
+ ""
155
+ )
156
+
157
+ selected_example = examples[example_name]
158
+ images = selected_example["images"]
159
+ instruction = selected_example["instruction"]
160
+
161
+ messages = [
162
+ {
163
+ "role": "user",
164
+ "content": [
165
+ *[{"type": "image", "image": img} for img in images],
166
+ {
167
+ "type": "text",
168
+ "text": instruction + " First output the thinking process in <think> </think> tags and then output the bounding box in <answer> </answer> tags."
169
+ }
170
+ ]
171
+ }
172
+ ]
173
+
174
+ # Process input
175
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
176
+ image_inputs, video_inputs = process_vision_info(messages)
177
+ inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
178
+ inputs = inputs.to("cuda:0")
179
+
180
+ # Generate output
181
+ generated_ids = model.generate(**inputs, max_new_tokens=256)
182
+ generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
183
+ output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
184
+
185
+ # Extract bounding box coordinates and draw
186
+ bbox = extract_bbox(output_text)
187
+ if bbox:
188
+ # Draw bounding box on all images
189
+ visualized_images = [draw_bbox(img_path, bbox) for img_path in images]
190
+ else:
191
+ # If no bounding box detected, use original images
192
+ visualized_images = [Image.open(img_path) for img_path in images]
193
+
194
+ return (
195
+ gr.Gallery(value=visualized_images, visible=True),
196
+ instruction,
197
+ output_text
198
+ )
199
+
200
+ def process_custom_input(images, instruction):
201
+ """Process custom user input"""
202
+ if not images or not instruction:
203
+ return (
204
+ gr.Gallery(value=None, visible=False),
205
+ instruction,
206
+ ""
207
+ )
208
+
209
+ # Save uploaded images to temporary files
210
+ image_paths = []
211
+ for i, img in enumerate(images):
212
+ if isinstance(img, str): # If already a path
213
+ image_paths.append(img)
214
+ else: # If uploaded image
215
+ temp_path = f"temp_image_{i}.png"
216
+ if isinstance(img, Image.Image):
217
+ img.save(temp_path)
218
+ else:
219
+ Image.fromarray(img).save(temp_path)
220
+ image_paths.append(temp_path)
221
+
222
+ messages = [
223
+ {
224
+ "role": "user",
225
+ "content": [
226
+ *[{"type": "image", "image": img} for img in image_paths],
227
+ {
228
+ "type": "text",
229
+ "text": instruction + " First output the thinking process in <think> </think> tags and then output the bounding box in <answer> </answer> tags."
230
+ }
231
+ ]
232
+ }
233
+ ]
234
+
235
+ # Process input
236
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
237
+ image_inputs, video_inputs = process_vision_info(messages)
238
+ inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
239
+ inputs = inputs.to("cuda:0")
240
+
241
+ # Generate output
242
+ generated_ids = model.generate(**inputs, max_new_tokens=256)
243
+ generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
244
+ output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
245
+
246
+ # Extract bounding box coordinates and draw
247
+ bbox = extract_bbox(output_text)
248
+ if bbox:
249
+ # Draw bounding box on all images
250
+ visualized_images = [draw_bbox(img_path, bbox) for img_path in image_paths]
251
+ else:
252
+ # If no bounding box detected, use original images
253
+ visualized_images = [Image.open(img_path) for img_path in image_paths]
254
+
255
+ return (
256
+ gr.Gallery(value=visualized_images, visible=True),
257
+ instruction,
258
+ output_text
259
+ )
260
+
261
+ css = """
262
+ .example-container {
263
+ border: 1px solid #ddd;
264
+ border-radius: 8px;
265
+ padding: 15px;
266
+ margin: 10px 0;
267
+ transition: all 0.3s ease;
268
+ }
269
+
270
+ .example-container:hover {
271
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1);
272
+ transform: translateY(-2px);
273
+ }
274
+
275
+ .button-row {
276
+ display: flex;
277
+ gap: 10px;
278
+ justify-content: center;
279
+ margin: 20px 0;
280
+ }
281
+
282
+ .examples-table {
283
+ border-collapse: collapse;
284
+ width: 100%;
285
+ }
286
+
287
+ .examples-table td {
288
+ padding: 10px;
289
+ border: 1px solid #ddd;
290
+ }
291
+
292
+ .example-title {
293
+ font-weight: bold;
294
+ margin-bottom: 10px;
295
+ }
296
+
297
+ .example-preview {
298
+ cursor: pointer;
299
+ padding: 10px;
300
+ border-radius: 8px;
301
+ transition: all 0.3s ease;
302
+ }
303
+
304
+ .example-preview:hover {
305
+ background-color: #f5f5f5;
306
+ }
307
+
308
+ /* Add custom button styles */
309
+ .custom-button {
310
+ background-color: #2196F3 !important;
311
+ color: white !important;
312
+ font-weight: bold !important;
313
+ border: none !important;
314
+ border-radius: 4px !important;
315
+ padding: 8px 16px !important;
316
+ margin: 8px 0 !important;
317
+ transition: all 0.3s ease !important;
318
+ }
319
+
320
+ .custom-button:hover {
321
+ background-color: #1976D2 !important;
322
+ box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important;
323
+ }
324
+ """
325
+
326
+ def create_example_preview(example_name):
327
+ """Create single example preview component"""
328
+ example_data = examples[example_name]
329
+ with gr.Column(elem_classes="example-preview"):
330
+ gr.Markdown(f"**{example_name}**")
331
+ gr.Gallery(value=example_data["images"], columns=2, rows=1, height=200, object_fit="contain")
332
+ gr.Markdown(example_data["instruction"])
333
+ return example_name
334
+
335
+ # Create Gradio interface
336
+ with gr.Blocks(theme=gr.themes.Default(), css=css) as demo:
337
+ gr.Markdown("# UniVG-R1 Demo")
338
+ gr.Markdown("Use our provided examples or upload your own local images for universal visual grounding.")
339
+ 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)")
340
+
341
+ with gr.Tabs():
342
+ with gr.Tab("Preset Examples"):
343
+ with gr.Row():
344
+ example_dropdown = gr.Dropdown(
345
+ choices=list(examples.keys()),
346
+ label="Select Example",
347
+ value=None
348
+ )
349
+
350
+ with gr.Row():
351
+ preview_gallery = gr.Gallery(
352
+ label="Preview Images",
353
+ show_label=True,
354
+ columns=2,
355
+ rows=1,
356
+ height=300,
357
+ object_fit="contain",
358
+ preview=True,
359
+ visible=False
360
+ )
361
+
362
+ with gr.Row():
363
+ instruction_text = gr.Textbox(label="Instruction", interactive=False)
364
+
365
+ with gr.Row(elem_classes="button-row"):
366
+ submit_btn = gr.Button("Submit", variant="primary")
367
+ clear_btn = gr.Button("Clear")
368
+
369
+ with gr.Row():
370
+ result_gallery = gr.Gallery(
371
+ label="Results with Bounding Box",
372
+ show_label=True,
373
+ columns=2,
374
+ rows=1,
375
+ height=400,
376
+ object_fit="contain",
377
+ preview=True,
378
+ visible=False,
379
+ allow_preview=True, # 添加这个参数
380
+ show_download_button=True, # 可选:添加下载按钮
381
+ elem_id="result_gallery" # 可选:添加唯一ID
382
+ )
383
+
384
+ with gr.Row():
385
+ output_box = gr.Textbox(label="Model Output", interactive=False, lines=5)
386
+
387
+ # Example preview area
388
+ gr.Markdown("## Examples")
389
+
390
+ # Use grid layout to display examples
391
+ with gr.Row():
392
+ with gr.Column():
393
+ for i, (example_name, example_data) in enumerate(examples.items()):
394
+ if i % 2 == 0: # Display two examples per row
395
+ row_examples = []
396
+ with gr.Group(elem_classes="example-preview"):
397
+ gr.Markdown(f"### {example_name}")
398
+ gallery = gr.Gallery(
399
+ value=example_data["images"],
400
+ columns=len(example_data["images"]),
401
+ rows=1,
402
+ height=300,
403
+ object_fit="scale-down",
404
+ preview=True,
405
+ show_label=False,
406
+ allow_preview=True
407
+ )
408
+ gr.Markdown(f"**Instruction**: {example_data['instruction']}")
409
+ # Add a select button, using custom styles
410
+ select_btn = gr.Button(
411
+ f"Select {example_name}",
412
+ size="sm",
413
+ elem_classes="custom-button"
414
+ )
415
+ select_btn.click(
416
+ lambda x: x,
417
+ inputs=[gr.State(example_name)],
418
+ outputs=[example_dropdown]
419
+ )
420
+
421
+ # Event handling
422
+ example_dropdown.change(
423
+ update_preview,
424
+ inputs=[example_dropdown],
425
+ outputs=[preview_gallery, instruction_text, result_gallery]
426
+ )
427
+
428
+ submit_btn.click(
429
+ process_example,
430
+ inputs=[example_dropdown],
431
+ outputs=[result_gallery, instruction_text, output_box]
432
+ )
433
+
434
+ clear_btn.click(
435
+ clear_outputs,
436
+ inputs=[],
437
+ outputs=[example_dropdown, preview_gallery, instruction_text, result_gallery, output_box]
438
+ )
439
+
440
+ with gr.Tab("Custom Input"):
441
+ with gr.Row():
442
+ custom_images = gr.File(
443
+ label="Upload Images (Multiple Supported)",
444
+ file_count="multiple",
445
+ file_types=["image"]
446
+ )
447
+
448
+ with gr.Row():
449
+ custom_instruction = gr.Textbox(
450
+ label="Enter Instruction",
451
+ placeholder="Please enter your instruction...",
452
+ lines=3
453
+ )
454
+
455
+ with gr.Row():
456
+ custom_submit_btn = gr.Button("Submit", variant="primary")
457
+ custom_clear_btn = gr.Button("Clear")
458
+
459
+ with gr.Row():
460
+ custom_result_gallery = gr.Gallery(
461
+ label="Results",
462
+ show_label=True,
463
+ columns=2,
464
+ rows=1,
465
+ height=400,
466
+ object_fit="contain",
467
+ preview=True,
468
+ visible=False
469
+ )
470
+
471
+ with gr.Row():
472
+ custom_output_box = gr.Textbox(label="Model Output", interactive=False, lines=5)
473
+
474
+ # Custom input event handling
475
+ custom_submit_btn.click(
476
+ process_custom_input,
477
+ inputs=[custom_images, custom_instruction],
478
+ outputs=[custom_result_gallery, custom_instruction, custom_output_box]
479
+ )
480
+
481
+ custom_clear_btn.click(
482
+ lambda: [None, "", None, ""], # Fix return value format
483
+ outputs=[custom_images, custom_instruction, custom_result_gallery, custom_output_box]
484
+ )
485
+
486
+ if __name__ == "__main__":
487
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.30.1
2
+ addict==2.4.0
3
+ # bitsandbytes==0.43.3
4
+ datasets==2.16.1
5
+ decord==0.6.0
6
+ deepspeed==0.12.3
7
+ editdistance==0.6.2
8
+ einops==0.7.0
9
+ fairscale==0.4.0
10
+
11
+ # gradio==4.41.0
12
+ # gradio_client==1.3.0
13
+ huggingface-hub==0.24.6
14
+ jsonlines==4.0.0
15
+ llava==0.0.1.dev0
16
+
17
+ # lmms_eval==0.2.4
18
+ Markdown==3.7
19
+ matplotlib==3.7.4
20
+ modelscope==1.20.1
21
+ multiprocess==0.70.15
22
+ ninja==1.11.1.1
23
+ nltk==3.8.1
24
+ numpy==1.24.4
25
+
26
+ omegaconf==2.3.0
27
+ open_clip_torch==2.26.1
28
+ openai==1.55.0
29
+ opencv-python==4.10.0.84
30
+ opendatasets==0.1.22
31
+
32
+ packaging==23.2
33
+ pandas==2.2.2
34
+ peft==0.12.0
35
+ Pillow==10.1.0
36
+ polars==1.8.2
37
+ protobuf==4.25.0
38
+ pyarrow==17.0.0
39
+ qwen-vl-utils==0.0.8
40
+ ray==2.39.0
41
+ referencing==0.35.1
42
+ regex==2024.7.24
43
+ safetensors==0.4.4
44
+ scipy==1.14.1
45
+ seaborn==0.13.0
46
+ sentencepiece==0.1.99
47
+ spacy==3.8.2
48
+ starlette==0.38.6
49
+ streamlit==1.39.0
50
+
51
+ timm==0.9.10
52
+ tokenizers==0.20.3
53
+ torch==2.1.2
54
+ torchaudio==2.1.2
55
+ torchvision==0.16.2
56
+ transformers==4.45.2
57
+ tqdm==4.66.1
58
+ transformers-stream-generator==0.0.5
59
+ trl==0.9.6
60
+ typing_extensions==4.11.0
61
+ wandb==0.17.8
62
+
63
+ xformers
64
+ uvicorn==0.24.0.post1
65
+ flash-attn==2.3.4