Spaces:
Running
on
Zero
Running
on
Zero
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 | |
) | |
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 | |
) | |
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 | |
) | |
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/) [GitHub](https://github.com/AMAP-ML/UniVG-R1) [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() |