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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import re
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from datasets import load_dataset
|
| 9 |
+
from PIL.Image import Image
|
| 10 |
+
from PIL.Image import open as open_img
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 13 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 14 |
+
from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize
|
| 15 |
+
from transformers.processing_utils import ProcessorMixin
|
| 16 |
+
|
| 17 |
+
INSTRUCTION_LOCALIZATION: 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."
|
| 18 |
+
INSTRUCTION_LOCALIZATION_TOOLCALL: str = "Localize an element on the GUI image according to my instructions and output a click position. You must output a valid JSON format."
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_screenspot(dataset_id: str, subset: str = "test"):
|
| 22 |
+
dataset = load_dataset(dataset_id)
|
| 23 |
+
return dataset[subset]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def l1(dx: float, dy: float) -> float:
|
| 27 |
+
"""Return L1 length of a vector"""
|
| 28 |
+
return abs(dx) + abs(dy)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def l2(dx: float, dy: float) -> float:
|
| 32 |
+
"""Return L2 length of a vector"""
|
| 33 |
+
return (dx**2 + dy**2) ** 0.5
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def point_to_rectangle_dist(x: float, y: float, rectangle: tuple, distance_type="L2"):
|
| 37 |
+
"""Compute the distance of a predicted point to the closest edge of the bbox. If the point is in the bbox, then return 0."""
|
| 38 |
+
x1, y1, x2, y2 = rectangle # x1,y1 is top-left, x2,y2 is bottom-right
|
| 39 |
+
|
| 40 |
+
# Check if the point is inside the rectangle
|
| 41 |
+
if x1 <= x <= x2 and y1 <= y <= y2:
|
| 42 |
+
return 0
|
| 43 |
+
|
| 44 |
+
# Calculate the closest point on the rectangle
|
| 45 |
+
closest_x = max(x1, min(x, x2))
|
| 46 |
+
closest_y = max(y1, min(y, y2))
|
| 47 |
+
|
| 48 |
+
# Calculate the distance
|
| 49 |
+
dx = x - closest_x
|
| 50 |
+
dy = y - closest_y
|
| 51 |
+
if distance_type == "L1":
|
| 52 |
+
return l1(dx, dy)
|
| 53 |
+
elif distance_type == "L2":
|
| 54 |
+
return l2(dx, dy)
|
| 55 |
+
else:
|
| 56 |
+
raise ValueError("Invalid distance type. Use 'L1' or 'L2'.")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def is_in_bbox(bbox: tuple, x: float, y: float) -> bool:
|
| 60 |
+
"""Check if a point is inside a bounding box."""
|
| 61 |
+
x_top_left, y_top_left, x_bottom_right, y_bottom_right = bbox
|
| 62 |
+
return x_top_left <= x <= x_bottom_right and y_top_left <= y <= y_bottom_right
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def assemble_message(image, instruction, use_tool_call: bool = True):
|
| 66 |
+
system_message = {
|
| 67 |
+
"role": "system",
|
| 68 |
+
"content": '[{"name": "click_action", "description": "Click at specific coordinates on the screen.", "parameters": {"additionalProperties": false, "description": "Click at specific coordinates on the screen.", "properties": {"action": {"const": "click", "default": "click", "title": "Action", "type": "string"}, "x": {"description": "The x coordinate, number of pixels from the left edge.", "title": "X", "type": "integer"}, "y": {"description": "The y coordinate, number of pixels from the top edge.", "title": "Y", "type": "integer"}}, "required": ["action", "x", "y"], "title": "ClickAction", "type": "object"}, "strict": true}]',
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
user_message = {
|
| 72 |
+
"role": "user",
|
| 73 |
+
"content": [
|
| 74 |
+
{
|
| 75 |
+
"type": "image",
|
| 76 |
+
"image": image,
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"type": "text",
|
| 80 |
+
"text": f"{INSTRUCTION_LOCALIZATION_TOOLCALL if use_tool_call else INSTRUCTION_LOCALIZATION}\n{instruction}",
|
| 81 |
+
},
|
| 82 |
+
],
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
messages = [system_message, user_message] if use_tool_call else [user_message]
|
| 86 |
+
return messages
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def do_smart_resize(image: Image, image_processor: ProcessorMixin) -> tuple[Image, int, int]:
|
| 90 |
+
"""Do a QWEN2.5-VL smart resize using parameters of an image-processor"""
|
| 91 |
+
resized_height, resized_width = smart_resize(
|
| 92 |
+
image.height,
|
| 93 |
+
image.width,
|
| 94 |
+
factor=image_processor.patch_size * image_processor.merge_size,
|
| 95 |
+
min_pixels=image_processor.min_pixels,
|
| 96 |
+
max_pixels=image_processor.max_pixels,
|
| 97 |
+
)
|
| 98 |
+
return image.resize(size=(resized_width, resized_height), resample=None), resized_height, resized_width
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def inference(
|
| 102 |
+
model: PreTrainedModel, processor: ProcessorMixin, dataset, smart_resize: bool = True, use_toolcall: bool = True
|
| 103 |
+
):
|
| 104 |
+
"""Gather raw inference results from the model"""
|
| 105 |
+
results = []
|
| 106 |
+
for i, sample in enumerate(tqdm(dataset, "running inference requests")):
|
| 107 |
+
bbox = sample["bbox"]
|
| 108 |
+
instruction = sample["instruction"]
|
| 109 |
+
image = sample["image"] # this seems to be a pnd , maybe jpg artifacts cause the difference?
|
| 110 |
+
image_shape_raw = (image.height, image.width)
|
| 111 |
+
message = assemble_message(image=image, instruction=instruction)
|
| 112 |
+
|
| 113 |
+
# Preparation for inference
|
| 114 |
+
if smart_resize:
|
| 115 |
+
image, resized_height, resized_width = do_smart_resize(
|
| 116 |
+
image=image, image_processor=processor.image_processor
|
| 117 |
+
)
|
| 118 |
+
else:
|
| 119 |
+
resized_height, resized_width = image_shape_raw
|
| 120 |
+
text = processor.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
|
| 121 |
+
|
| 122 |
+
# compress to JPEG, which is needed for highest possible performance
|
| 123 |
+
buffer = BytesIO()
|
| 124 |
+
image.convert("RGB").save(buffer, format="JPEG", quality=90)
|
| 125 |
+
image = open_img(buffer)
|
| 126 |
+
|
| 127 |
+
inputs = processor(
|
| 128 |
+
text=[text],
|
| 129 |
+
images=image,
|
| 130 |
+
padding=True,
|
| 131 |
+
return_tensors="pt",
|
| 132 |
+
)
|
| 133 |
+
inputs = inputs.to("cuda")
|
| 134 |
+
|
| 135 |
+
# Inference: Generation of the output
|
| 136 |
+
generated_ids = model.generate(**inputs, max_new_tokens=128, do_sample=False)
|
| 137 |
+
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 138 |
+
output_text = processor.batch_decode(
|
| 139 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 140 |
+
)
|
| 141 |
+
# print(output_text)
|
| 142 |
+
if use_toolcall:
|
| 143 |
+
try:
|
| 144 |
+
content = json.loads(output_text[0])
|
| 145 |
+
prediction_raw = f"Click({content['arguments']['x']}, {content['arguments']['y']})"
|
| 146 |
+
except Exception as e:
|
| 147 |
+
print(f"Error parsing tool call, using message content instead if available: {repr(e)}")
|
| 148 |
+
prediction_raw = output_text[0]
|
| 149 |
+
else:
|
| 150 |
+
prediction_raw = output_text[0]
|
| 151 |
+
|
| 152 |
+
results.append(
|
| 153 |
+
{
|
| 154 |
+
"sample_id": i,
|
| 155 |
+
"ground_truth": tuple(bbox),
|
| 156 |
+
"prediction_raw": prediction_raw,
|
| 157 |
+
"image_shape_raw": image_shape_raw,
|
| 158 |
+
"img_shape_processed": (resized_height, resized_width),
|
| 159 |
+
}
|
| 160 |
+
)
|
| 161 |
+
return results
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def get_sample_result(result: dict):
|
| 165 |
+
"""Postprocess a inference result and compute metrics for this sample."""
|
| 166 |
+
raw_height, raw_width = result["image_shape_raw"]
|
| 167 |
+
height, width = result["img_shape_processed"]
|
| 168 |
+
has_resized_image = height != raw_height or width != raw_width
|
| 169 |
+
try:
|
| 170 |
+
bbox = result["ground_truth"]
|
| 171 |
+
prediction_raw = result["prediction_raw"]
|
| 172 |
+
match = re.match(r"Click\((\d+),\s*(\d+)\)", prediction_raw)
|
| 173 |
+
assert match is not None
|
| 174 |
+
predicted_x = float(match.group(1)) / width
|
| 175 |
+
predicted_y = float(match.group(2)) / height
|
| 176 |
+
|
| 177 |
+
except Exception as e:
|
| 178 |
+
sample_metric = {
|
| 179 |
+
"sample_id": result["sample_id"],
|
| 180 |
+
"has_correct_format": False,
|
| 181 |
+
"has_resized_image": has_resized_image,
|
| 182 |
+
"click_in_box": False,
|
| 183 |
+
"click_l1_dist_to_bbox": 2, # Longest possible L1 distance in the unit square
|
| 184 |
+
"click_l2_dist_to_bbox": math.sqrt(2), # Longest possible L2 distance in the unit square
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
sample_metric = {
|
| 188 |
+
"sample_id": result["sample_id"],
|
| 189 |
+
"has_correct_format": True,
|
| 190 |
+
"has_resized_image": has_resized_image,
|
| 191 |
+
"click_in_box": True if is_in_bbox(bbox, x=predicted_x, y=predicted_y) else False,
|
| 192 |
+
"click_l1_dist_to_bbox": point_to_rectangle_dist(
|
| 193 |
+
predicted_x, predicted_y, bbox, "L1"
|
| 194 |
+
), # Longest possible L1 distance in the unit square
|
| 195 |
+
"click_l2_dist_to_bbox": point_to_rectangle_dist(
|
| 196 |
+
predicted_x, predicted_y, bbox, "L2"
|
| 197 |
+
), # Longest possible L2 distance in the unit square
|
| 198 |
+
}
|
| 199 |
+
return sample_metric
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def aggregate_metrics(sample_metrics):
|
| 203 |
+
"""Aggregate per-sample metrics into metrics for the entire dataset."""
|
| 204 |
+
aggregated_metrics = {}
|
| 205 |
+
aggregated_metrics["click_accuracy"] = np.mean([r["click_in_box"] for r in sample_metrics])
|
| 206 |
+
|
| 207 |
+
for threshold in [0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5]:
|
| 208 |
+
aggregated_metrics[f"click_accuracy_p{threshold}"] = np.mean(
|
| 209 |
+
[r["click_l2_dist_to_bbox"] < threshold for r in sample_metrics]
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
aggregated_metrics["avg_click_l1_dist_to_bbox"] = np.mean([r["click_l1_dist_to_bbox"] for r in sample_metrics])
|
| 213 |
+
aggregated_metrics["avg_click_l2_dist_to_bbox"] = np.mean([r["click_l2_dist_to_bbox"] for r in sample_metrics])
|
| 214 |
+
aggregated_metrics["format_accuracy"] = np.mean([r["has_correct_format"] for r in sample_metrics])
|
| 215 |
+
aggregated_metrics["has_resized_image"] = np.mean([r["has_resized_image"] for r in sample_metrics])
|
| 216 |
+
return aggregated_metrics
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def evaluate_results(results: list[dict]):
|
| 220 |
+
"""Do evaluate based on the raw model outputs."""
|
| 221 |
+
per_sample_metrics = []
|
| 222 |
+
for result in results:
|
| 223 |
+
metric_dict = get_sample_result(result)
|
| 224 |
+
per_sample_metrics.append(metric_dict)
|
| 225 |
+
aggregated = aggregate_metrics(per_sample_metrics)
|
| 226 |
+
return aggregated
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def main(
|
| 230 |
+
model_id: str = "Hcompany/Holo1-3B",
|
| 231 |
+
dataset_id: str = "rootsautomation/ScreenSpot",
|
| 232 |
+
outfile: str = "results.json",
|
| 233 |
+
use_toolcall: bool = True,
|
| 234 |
+
):
|
| 235 |
+
model = AutoModelForImageTextToText.from_pretrained(model_id)
|
| 236 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 237 |
+
dataset = load_screenspot(dataset_id)
|
| 238 |
+
results = inference(model.cuda(), processor, dataset, use_toolcall=use_toolcall)
|
| 239 |
+
metrics = evaluate_results(results)
|
| 240 |
+
with open(outfile, "w") as fp:
|
| 241 |
+
json.dump(metrics, fp)
|
| 242 |
+
for metric, value in metrics.items():
|
| 243 |
+
print(f"{metric}:\t{value}")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
parser = argparse.ArgumentParser(description="Run the main function with model and dataset IDs.")
|
| 248 |
+
|
| 249 |
+
parser.add_argument(
|
| 250 |
+
"--model_id",
|
| 251 |
+
type=str,
|
| 252 |
+
default="Hcompany/Holo1-3B",
|
| 253 |
+
help="The identifier for the model to use (default: Hcompany/Holo1-3B)",
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
"--dataset_id",
|
| 258 |
+
type=str,
|
| 259 |
+
default="rootsautomation/ScreenSpot",
|
| 260 |
+
help="The identifier for the dataset to use (default: rootsautomation/ScreenSpot)",
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
parser.add_argument(
|
| 264 |
+
"--outfile",
|
| 265 |
+
type=str,
|
| 266 |
+
default="result.json",
|
| 267 |
+
help="Output json-file containing the aggregated metrics.",
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
"--use_toolcall",
|
| 272 |
+
type=bool,
|
| 273 |
+
default=True,
|
| 274 |
+
help="Enable or disable tool call prompting",
|
| 275 |
+
)
|
| 276 |
+
args = parser.parse_args()
|
| 277 |
+
main(model_id=args.model_id, dataset_id=args.dataset_id, outfile=args.outfile, use_toolcall=args.use_toolcall)
|