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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from typing import Any, List
|
| 8 |
+
import spaces
|
| 9 |
+
|
| 10 |
+
from PIL import Image, ImageDraw
|
| 11 |
+
import requests
|
| 12 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 13 |
+
from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize
|
| 14 |
+
import torch
|
| 15 |
+
import re
|
| 16 |
+
|
| 17 |
+
# --- Configuration ---
|
| 18 |
+
MODEL_ID = "Hcompany/Holo1-7B"
|
| 19 |
+
|
| 20 |
+
# --- Model and Processor Loading (Load once) ---
|
| 21 |
+
print(f"Loading model and processor for {MODEL_ID}...")
|
| 22 |
+
model = None
|
| 23 |
+
processor = None
|
| 24 |
+
model_loaded = False
|
| 25 |
+
load_error_message = ""
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 29 |
+
MODEL_ID,
|
| 30 |
+
torch_dtype=torch.bfloat16,
|
| 31 |
+
attn_implementation="flash_attention_2",
|
| 32 |
+
trust_remote_code=True
|
| 33 |
+
).to("cuda")
|
| 34 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
| 35 |
+
model_loaded = True
|
| 36 |
+
print("Model and processor loaded successfully.")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
load_error_message = f"Error loading model/processor: {e}\n" \
|
| 39 |
+
"This might be due to network issues, an incorrect model ID, or missing dependencies (like flash_attention_2 if enabled by default in some config).\n" \
|
| 40 |
+
"Ensure you have a stable internet connection and the necessary libraries installed."
|
| 41 |
+
print(load_error_message)
|
| 42 |
+
|
| 43 |
+
# --- Helper functions from the model card (or adapted) ---
|
| 44 |
+
|
| 45 |
+
def get_localization_prompt(pil_image: Image.Image, instruction: str) -> List[dict[str, Any]]:
|
| 46 |
+
"""
|
| 47 |
+
Prepares the prompt structure for the Holo1 model for localization tasks.
|
| 48 |
+
The `pil_image` argument here is primarily for semantic completeness in the prompt structure,
|
| 49 |
+
as the actual image tensor is handled by the processor later.
|
| 50 |
+
"""
|
| 51 |
+
guidelines: str = "Localize an element on the GUI image according to my instructions and output a click position as Click(x, y) with x num pixels from the left edge and y num pixels from the top edge."
|
| 52 |
+
|
| 53 |
+
return [
|
| 54 |
+
{
|
| 55 |
+
"role": "user",
|
| 56 |
+
"content": [
|
| 57 |
+
{
|
| 58 |
+
"type": "image",
|
| 59 |
+
"image": pil_image,
|
| 60 |
+
},
|
| 61 |
+
{"type": "text", "text": f"{guidelines}\n{instruction}"},
|
| 62 |
+
],
|
| 63 |
+
}
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
@spaces.GPU(duration=20)
|
| 67 |
+
def run_inference_localization(
|
| 68 |
+
messages_for_template: List[dict[str, Any]],
|
| 69 |
+
pil_image_for_processing: Image.Image
|
| 70 |
+
) -> str:
|
| 71 |
+
model.to("cuda")
|
| 72 |
+
torch.cuda.set_device(0)
|
| 73 |
+
"""
|
| 74 |
+
Runs inference using the Holo1 model.
|
| 75 |
+
- messages_for_template: The prompt structure, potentially including the PIL image object
|
| 76 |
+
(which apply_chat_template converts to an image tag).
|
| 77 |
+
- pil_image_for_processing: The actual PIL image to be processed into tensors.
|
| 78 |
+
"""
|
| 79 |
+
# 1. Apply chat template to messages. This will create the text part of the prompt,
|
| 80 |
+
# including image tags if the image was part of `messages_for_template`.
|
| 81 |
+
text_prompt = processor.apply_chat_template(
|
| 82 |
+
messages_for_template,
|
| 83 |
+
tokenize=False,
|
| 84 |
+
add_generation_prompt=True
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# 2. Process text and image together to get model inputs
|
| 88 |
+
inputs = processor(
|
| 89 |
+
text=[text_prompt],
|
| 90 |
+
images=[pil_image_for_processing], # Provide the actual image data here
|
| 91 |
+
padding=True,
|
| 92 |
+
return_tensors="pt",
|
| 93 |
+
)
|
| 94 |
+
inputs = inputs.to(model.device)
|
| 95 |
+
|
| 96 |
+
# 3. Generate response
|
| 97 |
+
# Using do_sample=False for more deterministic output, as in the model card's structured output example
|
| 98 |
+
generated_ids = model.generate(**inputs, max_new_tokens=128, do_sample=False)
|
| 99 |
+
|
| 100 |
+
# 4. Trim input_ids from generated_ids to get only the generated part
|
| 101 |
+
generated_ids_trimmed = [
|
| 102 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
# 5. Decode the generated tokens
|
| 106 |
+
decoded_output = processor.batch_decode(
|
| 107 |
+
generated_ids_trimmed,
|
| 108 |
+
skip_special_tokens=True,
|
| 109 |
+
clean_up_tokenization_spaces=False
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
return decoded_output[0] if decoded_output else ""
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# --- Gradio processing function ---
|
| 116 |
+
def predict_click_location(input_pil_image: Image.Image, instruction: str):
|
| 117 |
+
if not model_loaded or not processor or not model:
|
| 118 |
+
return f"Model not loaded. Error: {load_error_message}", None
|
| 119 |
+
if not input_pil_image:
|
| 120 |
+
return "No image provided. Please upload an image.", None
|
| 121 |
+
if not instruction or instruction.strip() == "":
|
| 122 |
+
return "No instruction provided. Please type an instruction.", input_pil_image.copy().convert("RGB")
|
| 123 |
+
|
| 124 |
+
# 1. Prepare image: Resize according to model's image processor's expected properties
|
| 125 |
+
# This ensures predicted coordinates match the (resized) image dimensions.
|
| 126 |
+
image_proc_config = processor.image_processor
|
| 127 |
+
try:
|
| 128 |
+
resized_height, resized_width = smart_resize(
|
| 129 |
+
input_pil_image.height,
|
| 130 |
+
input_pil_image.width,
|
| 131 |
+
factor=image_proc_config.patch_size * image_proc_config.merge_size,
|
| 132 |
+
min_pixels=image_proc_config.min_pixels,
|
| 133 |
+
max_pixels=image_proc_config.max_pixels,
|
| 134 |
+
)
|
| 135 |
+
# Using LANCZOS for resampling as it's generally good for downscaling.
|
| 136 |
+
# The model card used `resample=None`, which might imply nearest or default.
|
| 137 |
+
# For visual quality in the demo, LANCZOS is reasonable.
|
| 138 |
+
resized_image = input_pil_image.resize(
|
| 139 |
+
size=(resized_width, resized_height),
|
| 140 |
+
resample=Image.Resampling.LANCZOS # type: ignore
|
| 141 |
+
)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
print(f"Error resizing image: {e}")
|
| 144 |
+
return f"Error resizing image: {e}", input_pil_image.copy().convert("RGB")
|
| 145 |
+
|
| 146 |
+
# 2. Create the prompt using the resized image (for correct image tagging context) and instruction
|
| 147 |
+
messages = get_localization_prompt(resized_image, instruction)
|
| 148 |
+
|
| 149 |
+
# 3. Run inference
|
| 150 |
+
# Pass `messages` (which includes the image object for template processing)
|
| 151 |
+
# and `resized_image` (for actual tensor conversion).
|
| 152 |
+
try:
|
| 153 |
+
coordinates_str = run_inference_localization(messages, resized_image)
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print(f"Error during model inference: {e}")
|
| 156 |
+
return f"Error during model inference: {e}", resized_image.copy().convert("RGB")
|
| 157 |
+
|
| 158 |
+
# 4. Parse coordinates and draw on the image
|
| 159 |
+
output_image_with_click = resized_image.copy().convert("RGB") # Ensure it's RGB for drawing
|
| 160 |
+
parsed_coords = None
|
| 161 |
+
|
| 162 |
+
# Expected format from the model: "Click(x, y)"
|
| 163 |
+
match = re.search(r"Click\((\d+),\s*(\d+)\)", coordinates_str)
|
| 164 |
+
if match:
|
| 165 |
+
try:
|
| 166 |
+
x = int(match.group(1))
|
| 167 |
+
y = int(match.group(2))
|
| 168 |
+
parsed_coords = (x, y)
|
| 169 |
+
|
| 170 |
+
draw = ImageDraw.Draw(output_image_with_click)
|
| 171 |
+
# Make the marker somewhat responsive to image size, but not too small/large
|
| 172 |
+
radius = max(5, min(resized_width // 100, resized_height // 100, 15))
|
| 173 |
+
|
| 174 |
+
# Define the bounding box for the ellipse (circle)
|
| 175 |
+
bbox = (x - radius, y - radius, x + radius, y + radius)
|
| 176 |
+
draw.ellipse(bbox, outline="red", width=max(2, radius // 4)) # Draw a red circle
|
| 177 |
+
print(f"Predicted and drawn click at: ({x}, {y}) on resized image ({resized_width}x{resized_height})")
|
| 178 |
+
except ValueError:
|
| 179 |
+
print(f"Could not parse integers from coordinates: {coordinates_str}")
|
| 180 |
+
# Keep original coordinates_str, output_image_with_click will be the resized image without a mark
|
| 181 |
+
except Exception as e:
|
| 182 |
+
print(f"Error drawing on image: {e}")
|
| 183 |
+
else:
|
| 184 |
+
print(f"Could not parse 'Click(x, y)' from model output: {coordinates_str}")
|
| 185 |
+
|
| 186 |
+
return coordinates_str, output_image_with_click
|
| 187 |
+
|
| 188 |
+
# --- Load Example Data ---
|
| 189 |
+
example_image = None
|
| 190 |
+
example_instruction = "Select July 14th as the check-out date"
|
| 191 |
+
try:
|
| 192 |
+
example_image_url = "https://huggingface.co/Hcompany/Holo1-7B/resolve/main/calendar_example.jpg"
|
| 193 |
+
example_image = Image.open(requests.get(example_image_url, stream=True).raw)
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"Could not load example image from URL: {e}")
|
| 196 |
+
# Create a placeholder image if loading fails, so Gradio example still works
|
| 197 |
+
try:
|
| 198 |
+
example_image = Image.new("RGB", (200, 150), color="lightgray")
|
| 199 |
+
draw = ImageDraw.Draw(example_image)
|
| 200 |
+
draw.text((10, 10), "Example image\nfailed to load", fill="black")
|
| 201 |
+
except: # If PIL itself is an issue (unlikely here but good for robustness)
|
| 202 |
+
pass
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# --- Gradio Interface Definition ---
|
| 206 |
+
title = "Holo1-7B: Action VLM Localization Demo"
|
| 207 |
+
description = """
|
| 208 |
+
This demo showcases **Holo1-7B**, an Action Vision-Language Model developed by HCompany, fine-tuned from Qwen/Qwen2.5-VL-7B-Instruct.
|
| 209 |
+
It's designed to interact with web interfaces like a human user. Here, we demonstrate its UI localization capability.
|
| 210 |
+
|
| 211 |
+
**How to use:**
|
| 212 |
+
1. Upload an image (e.g., a screenshot of a UI, like the calendar example).
|
| 213 |
+
2. Provide a textual instruction (e.g., "Select July 14th as the check-out date").
|
| 214 |
+
3. The model will predict the click coordinates in the format `Click(x, y)`.
|
| 215 |
+
4. The predicted click point will be marked with a red circle on the (resized) image.
|
| 216 |
+
|
| 217 |
+
The model processes a resized version of your input image. Coordinates are relative to this resized image.
|
| 218 |
+
"""
|
| 219 |
+
article = f"""
|
| 220 |
+
<p style='text-align: center'>
|
| 221 |
+
Model: <a href='https://huggingface.co/{MODEL_ID}' target='_blank'>{MODEL_ID}</a> by HCompany |
|
| 222 |
+
Paper: <a href='https://cdn.prod.website-files.com/67e2dbd9acff0c50d4c8a80c/683ec8095b353e8b38317f80_h_tech_report_v1.pdf' target='_blank'>HCompany Tech Report</a> |
|
| 223 |
+
Blog: <a href='https://www.hcompany.ai/surfer-h' target='_blank'>Surfer-H Blog Post</a>
|
| 224 |
+
</p>
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
if not model_loaded:
|
| 228 |
+
with gr.Blocks() as demo:
|
| 229 |
+
gr.Markdown(f"# <center>⚠️ Error: Model Failed to Load ⚠️</center>")
|
| 230 |
+
gr.Markdown(f"<center>{load_error_message}</center>")
|
| 231 |
+
gr.Markdown("<center>Please check the console output for more details. Reloading the space might help if it's a temporary issue.</center>")
|
| 232 |
+
else:
|
| 233 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 234 |
+
gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
|
| 235 |
+
# gr.Markdown(description)
|
| 236 |
+
|
| 237 |
+
with gr.Row():
|
| 238 |
+
with gr.Column(scale=1):
|
| 239 |
+
input_image_component = gr.Image(type="pil", label="Input UI Image", height=400)
|
| 240 |
+
instruction_component = gr.Textbox(
|
| 241 |
+
label="Instruction",
|
| 242 |
+
placeholder="e.g., Click the 'Login' button",
|
| 243 |
+
info="Type the action you want the model to localize on the image."
|
| 244 |
+
)
|
| 245 |
+
submit_button = gr.Button("Localize Click", variant="primary")
|
| 246 |
+
|
| 247 |
+
with gr.Column(scale=1):
|
| 248 |
+
output_coords_component = gr.Textbox(label="Predicted Coordinates (Format: Click(x,y))", interactive=False)
|
| 249 |
+
output_image_component = gr.Image(type="pil", label="Image with Predicted Click Point", height=400, interactive=False)
|
| 250 |
+
|
| 251 |
+
if example_image:
|
| 252 |
+
gr.Examples(
|
| 253 |
+
examples=[[example_image, example_instruction]],
|
| 254 |
+
inputs=[input_image_component, instruction_component],
|
| 255 |
+
outputs=[output_coords_component, output_image_component],
|
| 256 |
+
fn=predict_click_location,
|
| 257 |
+
cache_examples="lazy",
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
gr.Markdown(article)
|
| 261 |
+
|
| 262 |
+
submit_button.click(
|
| 263 |
+
fn=predict_click_location,
|
| 264 |
+
inputs=[input_image_component, instruction_component],
|
| 265 |
+
outputs=[output_coords_component, output_image_component]
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
demo.launch(debug=True)
|
commit
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git add .
|
| 2 |
+
git commit -m "$*"
|
| 3 |
+
git push
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+
accelerate
|
test
ADDED
|
File without changes
|