Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,395 +1,369 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import time
|
| 4 |
-
from typing import Tuple, Optional, List, Dict
|
| 5 |
-
|
| 6 |
import gradio as gr
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
import spaces
|
| 10 |
-
from PIL import Image, ImageDraw, ImageFont
|
| 11 |
-
|
| 12 |
-
# Transformers & Qwen Utils
|
| 13 |
-
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 14 |
-
from qwen_vl_utils import process_vision_info
|
| 15 |
-
|
| 16 |
-
# -----------------------------------------------------------------------------
|
| 17 |
-
# 1. PROMPT DEFINITIONS (from prompt.py)
|
| 18 |
-
# -----------------------------------------------------------------------------
|
| 19 |
-
|
| 20 |
-
OS_ACTIONS = """
|
| 21 |
-
def final_answer(answer: any) -> any:
|
| 22 |
-
\"\"\"
|
| 23 |
-
Provides a final answer to the given problem.
|
| 24 |
-
Args:
|
| 25 |
-
answer: The final answer to the problem
|
| 26 |
-
\"\"\"
|
| 27 |
-
|
| 28 |
-
def move_mouse(self, x: float, y: float) -> str:
|
| 29 |
-
\"\"\"
|
| 30 |
-
Moves the mouse cursor to the specified coordinates
|
| 31 |
-
Args:
|
| 32 |
-
x: The x coordinate (horizontal position)
|
| 33 |
-
y: The y coordinate (vertical position)
|
| 34 |
-
\"\"\"
|
| 35 |
-
|
| 36 |
-
def click(x: Optional[float] = None, y: Optional[float] = None) -> str:
|
| 37 |
-
\"\"\"
|
| 38 |
-
Performs a left-click at the specified normalized coordinates
|
| 39 |
-
Args:
|
| 40 |
-
x: The x coordinate (horizontal position)
|
| 41 |
-
y: The y coordinate (vertical position)
|
| 42 |
-
\"\"\"
|
| 43 |
-
|
| 44 |
-
def double_click(x: Optional[float] = None, y: Optional[float] = None) -> str:
|
| 45 |
-
\"\"\"
|
| 46 |
-
Performs a double-click at the specified normalized coordinates
|
| 47 |
-
Args:
|
| 48 |
-
x: The x coordinate (horizontal position)
|
| 49 |
-
y: The y coordinate (vertical position)
|
| 50 |
-
\"\"\"
|
| 51 |
-
|
| 52 |
-
def type(text: str) -> str:
|
| 53 |
-
\"\"\"
|
| 54 |
-
Types the specified text at the current cursor position.
|
| 55 |
-
Args:
|
| 56 |
-
text: The text to type
|
| 57 |
-
\"\"\"
|
| 58 |
-
|
| 59 |
-
def press(keys: str | list[str]) -> str:
|
| 60 |
-
\"\"\"
|
| 61 |
-
Presses a keyboard key
|
| 62 |
-
Args:
|
| 63 |
-
keys: The key or list of keys to press (e.g. "enter", "space", "backspace", "ctrl", etc.).
|
| 64 |
-
\"\"\"
|
| 65 |
-
|
| 66 |
-
def navigate_back() -> str:
|
| 67 |
-
\"\"\"
|
| 68 |
-
Goes back to the previous page in the browser. If using this tool doesn't work, just click the button directly.
|
| 69 |
-
\"\"\"
|
| 70 |
-
|
| 71 |
-
def drag(from_coord: list[float], to_coord: list[float]) -> str:
|
| 72 |
-
\"\"\"
|
| 73 |
-
Clicks [x1, y1], drags mouse to [x2, y2], then release click.
|
| 74 |
-
Args:
|
| 75 |
-
x1: origin x coordinate
|
| 76 |
-
y1: origin y coordinate
|
| 77 |
-
x2: end x coordinate
|
| 78 |
-
y2: end y coordinate
|
| 79 |
-
\"\"\"
|
| 80 |
-
|
| 81 |
-
def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) -> str:
|
| 82 |
-
\"\"\"
|
| 83 |
-
Moves the mouse to selected coordinates, then uses the scroll button: this could scroll the page or zoom, depending on the app. DO NOT use scroll to move through linux desktop menus.
|
| 84 |
-
Args:
|
| 85 |
-
x: The x coordinate (horizontal position) of the element to scroll/zoom, defaults to None to not focus on specific coordinates
|
| 86 |
-
y: The y coordinate (vertical position) of the element to scroll/zoom, defaults to None to not focus on specific coordinates
|
| 87 |
-
direction: The direction to scroll ("up" or "down"), defaults to "down". For zoom, "up" zooms in, "down" zooms out.
|
| 88 |
-
amount: The amount to scroll. A good amount is 1 or 2.
|
| 89 |
-
\"\"\"
|
| 90 |
-
|
| 91 |
-
def wait(seconds: float) -> str:
|
| 92 |
-
\"\"\"
|
| 93 |
-
Waits for the specified number of seconds. Very useful in case the prior order is still executing (for example starting very heavy applications like browsers or office apps)
|
| 94 |
-
Args:
|
| 95 |
-
seconds: Number of seconds to wait, generally 2 is enough.
|
| 96 |
-
\"\"\"
|
| 97 |
-
"""
|
| 98 |
-
|
| 99 |
-
OS_SYSTEM_PROMPT = f"""You are a helpful GUI agent. You’ll be given a task and a screenshot of the screen. Complete the task using Python function calls.
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
{OS_ACTIONS}
|
| 108 |
-
</code>
|
| 109 |
-
|
| 110 |
-
The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
| 111 |
-
"""
|
| 112 |
-
|
| 113 |
-
# -----------------------------------------------------------------------------
|
| 114 |
-
# 2. MODEL DEFINITION (Adapted for Fara-7B / Qwen2.5-VL)
|
| 115 |
-
# -----------------------------------------------------------------------------
|
| 116 |
|
|
|
|
| 117 |
MODEL_ID = "microsoft/Fara-7B"
|
| 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 |
-
def
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
return [
|
| 198 |
-
{
|
| 199 |
-
"role": "system",
|
| 200 |
-
"content": [{"type": "text", "text": OS_SYSTEM_PROMPT}],
|
| 201 |
-
},
|
| 202 |
{
|
| 203 |
"role": "user",
|
| 204 |
"content": [
|
| 205 |
-
{"type": "image", "image":
|
| 206 |
-
{"type": "text", "text": f"
|
| 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 |
-
def
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
try:
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
for i, coord in enumerate(coordinates):
|
| 272 |
-
# Normalize if model outputs 0-1 range (Fara usually does)
|
| 273 |
-
# If model outputs pixels, we need to handle that.
|
| 274 |
-
# Fara/SmolVLM usually output normalized coordinates 0-1000 or 0-1.
|
| 275 |
-
# Assuming Fara outputs 0-1 floats based on the System Prompt definition.
|
| 276 |
-
|
| 277 |
-
pixel_x = int(coord['x'] * width) if coord['x'] <= 1.0 else int(coord['x'])
|
| 278 |
-
pixel_y = int(coord['y'] * height) if coord['y'] <= 1.0 else int(coord['y'])
|
| 279 |
-
|
| 280 |
-
color = colors.get(coord['type'], 'red')
|
| 281 |
-
|
| 282 |
-
r = 10
|
| 283 |
-
draw.ellipse([pixel_x - r, pixel_y - r, pixel_x + r, pixel_y + r], outline=color, width=3)
|
| 284 |
-
|
| 285 |
-
label = f"{coord['type']}"
|
| 286 |
-
draw.text((pixel_x + 12, pixel_y - 10), label, fill=color, font=font)
|
| 287 |
-
|
| 288 |
-
# Draw drag arrows
|
| 289 |
-
if coord['type'] == 'drag_from' and i + 1 < len(coordinates) and coordinates[i + 1]['type'] == 'drag_to':
|
| 290 |
-
next_coord = coordinates[i + 1]
|
| 291 |
-
end_x = int(next_coord['x'] * width) if next_coord['x'] <= 1.0 else int(next_coord['x'])
|
| 292 |
-
end_y = int(next_coord['y'] * height) if next_coord['y'] <= 1.0 else int(next_coord['y'])
|
| 293 |
-
draw.line([pixel_x, pixel_y, end_x, end_y], fill='orange', width=3)
|
| 294 |
-
|
| 295 |
-
return img_copy
|
| 296 |
-
|
| 297 |
-
# -----------------------------------------------------------------------------
|
| 298 |
-
# 4. APP LOGIC (ZeroGPU)
|
| 299 |
-
# -----------------------------------------------------------------------------
|
| 300 |
-
|
| 301 |
-
@spaces.GPU(duration=60)
|
| 302 |
-
def navigate(input_numpy_image: np.ndarray, task: str) -> Tuple[str, Optional[Image.Image]]:
|
| 303 |
-
if input_numpy_image is None:
|
| 304 |
-
return "Please upload an image.", None
|
| 305 |
-
|
| 306 |
-
input_pil_image = array_to_image(input_numpy_image)
|
| 307 |
-
|
| 308 |
-
# 1. Build Prompt
|
| 309 |
-
prompt = get_navigation_prompt(task, input_pil_image)
|
| 310 |
-
|
| 311 |
-
# 2. Generate
|
| 312 |
-
if fara_model is None:
|
| 313 |
-
raise ValueError("Model not loaded")
|
| 314 |
-
|
| 315 |
-
navigation_str = fara_model.generate(prompt, max_new_tokens=500)
|
| 316 |
-
print(f"Raw Output: {navigation_str}")
|
| 317 |
-
|
| 318 |
-
# 3. Parse
|
| 319 |
-
navigation_str = navigation_str.strip()
|
| 320 |
-
actions = parse_actions_from_response(navigation_str)
|
| 321 |
-
|
| 322 |
-
all_coordinates = []
|
| 323 |
-
for action_code in actions:
|
| 324 |
-
coordinates = extract_coordinates_from_action(action_code)
|
| 325 |
-
all_coordinates.extend(coordinates)
|
| 326 |
-
|
| 327 |
-
# 4. Visualize
|
| 328 |
-
localized_image = input_pil_image
|
| 329 |
-
if all_coordinates:
|
| 330 |
-
visualized = create_localized_image(input_pil_image, all_coordinates)
|
| 331 |
-
if visualized:
|
| 332 |
-
localized_image = visualized
|
| 333 |
-
|
| 334 |
-
return navigation_str, localized_image
|
| 335 |
-
|
| 336 |
-
# -----------------------------------------------------------------------------
|
| 337 |
-
# 5. GRADIO UI
|
| 338 |
-
# -----------------------------------------------------------------------------
|
| 339 |
-
|
| 340 |
-
title = "Fara-7B GUI Operator 🖥️"
|
| 341 |
-
description = """
|
| 342 |
-
This demo uses **microsoft/Fara-7B** to understand GUI screenshots and generate navigation actions.
|
| 343 |
-
Upload a screenshot, define a task, and see the model's planned actions.
|
| 344 |
-
"""
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
(
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
input_image_component = gr.Image(label="Upload Interface Screenshot", height=500)
|
| 368 |
-
task_component = gr.Textbox(
|
| 369 |
-
label="Task Instruction",
|
| 370 |
-
placeholder="e.g., Click the Search bar and type 'Hello World'",
|
| 371 |
-
lines=2
|
| 372 |
-
)
|
| 373 |
-
submit_button = gr.Button("Generate Action", variant="primary")
|
| 374 |
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
output_code_component = gr.Textbox(label="Model Output (Code)", lines=10, show_copy_button=True)
|
| 378 |
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
outputs=[output_code_component, output_image_component],
|
| 390 |
-
fn=navigate,
|
| 391 |
-
cache_examples=True,
|
| 392 |
)
|
| 393 |
|
| 394 |
if __name__ == "__main__":
|
| 395 |
-
demo.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import json, os, re, traceback, contextlib
|
| 3 |
+
from typing import Any, List, Dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
import spaces
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image, ImageDraw
|
| 8 |
+
import requests
|
| 9 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 10 |
+
from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
# --- Configuration ---
|
| 13 |
MODEL_ID = "microsoft/Fara-7B"
|
| 14 |
|
| 15 |
+
# ---------------- Device / DType helpers ----------------
|
| 16 |
+
|
| 17 |
+
def pick_device() -> str:
|
| 18 |
+
"""
|
| 19 |
+
On HF Spaces (ZeroGPU), CUDA is only available inside @spaces.GPU calls.
|
| 20 |
+
We still honor FORCE_DEVICE for local testing.
|
| 21 |
+
"""
|
| 22 |
+
forced = os.getenv("FORCE_DEVICE", "").lower().strip()
|
| 23 |
+
if forced in {"cpu", "cuda", "mps"}:
|
| 24 |
+
return forced
|
| 25 |
+
if torch.cuda.is_available():
|
| 26 |
+
return "cuda"
|
| 27 |
+
if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
|
| 28 |
+
return "mps"
|
| 29 |
+
return "cpu"
|
| 30 |
+
|
| 31 |
+
def pick_dtype(device: str) -> torch.dtype:
|
| 32 |
+
if device == "cuda":
|
| 33 |
+
major, _ = torch.cuda.get_device_capability()
|
| 34 |
+
return torch.bfloat16 if major >= 8 else torch.float16 # Ampere+ -> bf16
|
| 35 |
+
if device == "mps":
|
| 36 |
+
return torch.float16
|
| 37 |
+
return torch.float32 # CPU: FP32 is usually fastest & most stable
|
| 38 |
+
|
| 39 |
+
def move_to_device(batch, device: str):
|
| 40 |
+
if isinstance(batch, dict):
|
| 41 |
+
return {k: (v.to(device, non_blocking=True) if hasattr(v, "to") else v) for k, v in batch.items()}
|
| 42 |
+
if hasattr(batch, "to"):
|
| 43 |
+
return batch.to(device, non_blocking=True)
|
| 44 |
+
return batch
|
| 45 |
+
|
| 46 |
+
# --- Chat/template helpers ---
|
| 47 |
+
def apply_chat_template_compat(processor, messages: List[Dict[str, Any]]) -> str:
|
| 48 |
+
tok = getattr(processor, "tokenizer", None)
|
| 49 |
+
if hasattr(processor, "apply_chat_template"):
|
| 50 |
+
return processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 51 |
+
if tok is not None and hasattr(tok, "apply_chat_template"):
|
| 52 |
+
return tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 53 |
+
texts = []
|
| 54 |
+
for m in messages:
|
| 55 |
+
for c in m.get("content", []):
|
| 56 |
+
if isinstance(c, dict) and c.get("type") == "text":
|
| 57 |
+
texts.append(c.get("text", ""))
|
| 58 |
+
return "\n".join(texts)
|
| 59 |
+
|
| 60 |
+
def batch_decode_compat(processor, token_id_batches, **kw):
|
| 61 |
+
tok = getattr(processor, "tokenizer", None)
|
| 62 |
+
if tok is not None and hasattr(tok, "batch_decode"):
|
| 63 |
+
return tok.batch_decode(token_id_batches, **kw)
|
| 64 |
+
if hasattr(processor, "batch_decode"):
|
| 65 |
+
return processor.batch_decode(token_id_batches, **kw)
|
| 66 |
+
raise AttributeError("No batch_decode available on processor or tokenizer.")
|
| 67 |
+
|
| 68 |
+
def get_image_proc_params(processor) -> Dict[str, int]:
|
| 69 |
+
ip = getattr(processor, "image_processor", None)
|
| 70 |
+
return {
|
| 71 |
+
"patch_size": getattr(ip, "patch_size", 14),
|
| 72 |
+
"merge_size": getattr(ip, "merge_size", 1),
|
| 73 |
+
"min_pixels": getattr(ip, "min_pixels", 256 * 256),
|
| 74 |
+
"max_pixels": getattr(ip, "max_pixels", 1280 * 1280),
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
def trim_generated(generated_ids, inputs):
|
| 78 |
+
in_ids = getattr(inputs, "input_ids", None)
|
| 79 |
+
if in_ids is None and isinstance(inputs, dict):
|
| 80 |
+
in_ids = inputs.get("input_ids", None)
|
| 81 |
+
if in_ids is None:
|
| 82 |
+
return [out_ids for out_ids in generated_ids]
|
| 83 |
+
return [out_ids[len(in_seq):] for in_seq, out_ids in zip(in_ids, generated_ids)]
|
| 84 |
+
|
| 85 |
+
# --- Parsing helper: normalize various UI-TARS click formats to (x, y) ---
|
| 86 |
+
def parse_click_coordinates(text: str, img_w: int, img_h: int):
|
| 87 |
+
"""
|
| 88 |
+
Returns (x, y) in image coordinates, clamped to bounds, or None.
|
| 89 |
+
Handles:
|
| 90 |
+
- Click(start_box='(x,y)') / Click(end_box='(x,y)')
|
| 91 |
+
- Click(box='(x1,y1,x2,y2)') -> center
|
| 92 |
+
- Click(x, y)
|
| 93 |
+
- Click({'x':..., 'y':...}) / Click({"x":...,"y":...})
|
| 94 |
+
Preference: start_box > end_box when both exist.
|
| 95 |
+
"""
|
| 96 |
+
s = str(text)
|
| 97 |
+
|
| 98 |
+
# 1) start_box / end_box
|
| 99 |
+
pairs = re.findall(r"(start_box|end_box)\s*=\s*['\"]\(\s*(\d+)\s*,\s*(\d+)\s*\)['\"]", s)
|
| 100 |
+
if pairs:
|
| 101 |
+
start = next(((int(x), int(y)) for k, x, y in pairs if k == "start_box"), None)
|
| 102 |
+
if start:
|
| 103 |
+
x, y = start
|
| 104 |
+
return max(0, min(x, img_w - 1)), max(0, min(y, img_h - 1))
|
| 105 |
+
end = next(((int(x), int(y)) for k, x, y in pairs if k == "end_box"), None)
|
| 106 |
+
if end:
|
| 107 |
+
x, y = end
|
| 108 |
+
return max(0, min(x, img_w - 1)), max(0, min(y, img_h - 1))
|
| 109 |
+
|
| 110 |
+
# 2) box='(x1,y1,x2,y2)' -> center
|
| 111 |
+
m = re.search(r"box\s*=\s*['\"]\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)['\"]", s)
|
| 112 |
+
if m:
|
| 113 |
+
x1, y1, x2, y2 = map(int, m.groups())
|
| 114 |
+
cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
|
| 115 |
+
return max(0, min(cx, img_w - 1)), max(0, min(cy, img_h - 1))
|
| 116 |
+
|
| 117 |
+
# 3) Direct Click(x, y)
|
| 118 |
+
m = re.search(r"Click\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)", s)
|
| 119 |
+
if m:
|
| 120 |
+
x, y = int(m.group(1)), int(m.group(2))
|
| 121 |
+
return max(0, min(x, img_w - 1)), max(0, min(y, img_h - 1))
|
| 122 |
+
|
| 123 |
+
# 4) JSON-ish dicts
|
| 124 |
+
m = re.search(r"Click\s*\(\s*[{[][^)}]*['\"]?x['\"]?\s*:\s*(\d+)\s*,\s*['\"]?y['\"]?\s*:\s*(\d+)[^)}]*\)\s*", s)
|
| 125 |
+
if m:
|
| 126 |
+
x, y = int(m.group(1)), int(m.group(2))
|
| 127 |
+
return max(0, min(x, img_w - 1)), max(0, min(y, img_h - 1))
|
| 128 |
+
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
# --- Load model/processor ON CPU at import time (ZeroGPU safe) ---
|
| 132 |
+
print(f"Loading model and processor for {MODEL_ID} on CPU startup (ZeroGPU safe)...")
|
| 133 |
+
model = None
|
| 134 |
+
processor = None
|
| 135 |
+
model_loaded = False
|
| 136 |
+
load_error_message = ""
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 140 |
+
MODEL_ID,
|
| 141 |
+
torch_dtype=torch.float32, # CPU-safe dtype at import
|
| 142 |
+
trust_remote_code=True,
|
| 143 |
+
)
|
| 144 |
+
# IMPORTANT: use_fast=False to avoid the breaking change error you hit
|
| 145 |
+
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True, use_fast=False)
|
| 146 |
+
model.eval()
|
| 147 |
+
model_loaded = True
|
| 148 |
+
print("Model and processor loaded on CPU.")
|
| 149 |
+
except Exception as e:
|
| 150 |
+
load_error_message = (
|
| 151 |
+
f"Error loading model/processor: {e}\n"
|
| 152 |
+
"This might be due to network/model ID/library versions.\n"
|
| 153 |
+
"Check the full traceback in the logs."
|
| 154 |
+
)
|
| 155 |
+
print(load_error_message)
|
| 156 |
+
traceback.print_exc()
|
| 157 |
+
|
| 158 |
+
# --- Prompt builder ---
|
| 159 |
+
def get_localization_prompt(pil_image: Image.Image, instruction: str) -> List[dict]:
|
| 160 |
+
guidelines: str = (
|
| 161 |
+
"Localize an element on the GUI image according to my instructions and "
|
| 162 |
+
"output a click position as Click(x, y) with x num pixels from the left edge "
|
| 163 |
+
"and y num pixels from the top edge."
|
| 164 |
+
)
|
| 165 |
return [
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
{
|
| 167 |
"role": "user",
|
| 168 |
"content": [
|
| 169 |
+
{"type": "image", "image": pil_image},
|
| 170 |
+
{"type": "text", "text": f"{guidelines}\n{instruction}"}
|
| 171 |
],
|
| 172 |
+
}
|
| 173 |
]
|
| 174 |
|
| 175 |
+
# --- Inference core (device passed in; AMP used when suitable) ---
|
| 176 |
+
@torch.inference_mode()
|
| 177 |
+
def run_inference_localization(
|
| 178 |
+
messages_for_template: List[dict[str, Any]],
|
| 179 |
+
pil_image_for_processing: Image.Image,
|
| 180 |
+
device: str,
|
| 181 |
+
dtype: torch.dtype,
|
| 182 |
+
) -> str:
|
| 183 |
+
text_prompt = apply_chat_template_compat(processor, messages, ) if False else apply_chat_template_compat(processor, messages_for_template)
|
| 184 |
+
|
| 185 |
+
inputs = processor(
|
| 186 |
+
text=[text_prompt],
|
| 187 |
+
images=[pil_image_for_processing],
|
| 188 |
+
padding=True,
|
| 189 |
+
return_tensors="pt",
|
| 190 |
+
)
|
| 191 |
+
inputs = move_to_device(inputs, device)
|
| 192 |
+
|
| 193 |
+
# AMP contexts
|
| 194 |
+
if device == "cuda":
|
| 195 |
+
amp_ctx = torch.autocast(device_type="cuda", dtype=dtype)
|
| 196 |
+
elif device == "mps":
|
| 197 |
+
amp_ctx = torch.autocast(device_type="mps", dtype=torch.float16)
|
| 198 |
+
else:
|
| 199 |
+
amp_ctx = contextlib.nullcontext()
|
| 200 |
+
|
| 201 |
+
with amp_ctx:
|
| 202 |
+
generated_ids = model.generate(
|
| 203 |
+
**inputs,
|
| 204 |
+
max_new_tokens=128,
|
| 205 |
+
do_sample=False,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
generated_ids_trimmed = trim_generated(generated_ids, inputs)
|
| 209 |
+
decoded_output = batch_decode_compat(
|
| 210 |
+
processor,
|
| 211 |
+
generated_ids_trimmed,
|
| 212 |
+
skip_special_tokens=True,
|
| 213 |
+
clean_up_tokenization_spaces=False
|
| 214 |
+
)
|
| 215 |
+
return decoded_output[0] if decoded_output else ""
|
| 216 |
+
|
| 217 |
+
# --- Gradio processing function (ZeroGPU-visible) ---
|
| 218 |
+
@spaces.GPU(duration=120) # keep GPU attached briefly between calls (seconds)
|
| 219 |
+
def predict_click_location(input_pil_image: Image.Image, instruction: str):
|
| 220 |
+
if not model_loaded or not processor or not model:
|
| 221 |
+
return f"Model not loaded. Error: {load_error_message}", None, "device: n/a | dtype: n/a"
|
| 222 |
+
if not input_pil_image:
|
| 223 |
+
return "No image provided. Please upload an image.", None, "device: n/a | dtype: n/a"
|
| 224 |
+
if not instruction or instruction.strip() == "":
|
| 225 |
+
return "No instruction provided. Please type an instruction.", input_pil_image.copy().convert("RGB"), "device: n/a | dtype: n/a"
|
| 226 |
+
|
| 227 |
+
# Decide device/dtype *inside* the GPU-decorated call
|
| 228 |
+
device = pick_device()
|
| 229 |
+
dtype = pick_dtype(device)
|
| 230 |
+
|
| 231 |
+
# Optional perf knobs for CUDA
|
| 232 |
+
if device == "cuda":
|
| 233 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 234 |
+
torch.set_float32_matmul_precision("high")
|
| 235 |
+
|
| 236 |
+
# If needed, move model now that GPU is available
|
| 237 |
try:
|
| 238 |
+
p = next(model.parameters())
|
| 239 |
+
cur_dev = p.device.type
|
| 240 |
+
cur_dtype = p.dtype
|
| 241 |
+
except StopIteration:
|
| 242 |
+
cur_dev, cur_dtype = "cpu", torch.float32
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
+
if cur_dev != device or cur_dtype != dtype:
|
| 245 |
+
model.to(device=device, dtype=dtype)
|
| 246 |
+
model.eval()
|
| 247 |
+
|
| 248 |
+
# 1) Resize according to image processor params (safe defaults if missing)
|
| 249 |
+
try:
|
| 250 |
+
ip = get_image_proc_params(processor)
|
| 251 |
+
resized_height, resized_width = smart_resize(
|
| 252 |
+
input_pil_image.height,
|
| 253 |
+
input_pil_image.width,
|
| 254 |
+
factor=ip["patch_size"] * ip["merge_size"],
|
| 255 |
+
min_pixels=ip["min_pixels"],
|
| 256 |
+
max_pixels=ip["max_pixels"],
|
| 257 |
+
)
|
| 258 |
+
resized_image = input_pil_image.resize(
|
| 259 |
+
size=(resized_width, resized_height),
|
| 260 |
+
resample=Image.Resampling.LANCZOS
|
| 261 |
+
)
|
| 262 |
+
except Exception as e:
|
| 263 |
+
traceback.print_exc()
|
| 264 |
+
return f"Error resizing image: {e}", input_pil_image.copy().convert("RGB"), f"device: {device} | dtype: {dtype}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
+
# 2) Build messages with image + instruction
|
| 267 |
+
messages = get_localization_prompt(resized_image, instruction)
|
|
|
|
| 268 |
|
| 269 |
+
# 3) Run inference
|
| 270 |
+
try:
|
| 271 |
+
coordinates_str = run_inference_localization(messages, resized_image, device, dtype)
|
| 272 |
+
except Exception as e:
|
| 273 |
+
traceback.print_exc()
|
| 274 |
+
return f"Error during model inference: {e}", resized_image.copy().convert("RGB"), f"device: {device} | dtype: {dtype}"
|
| 275 |
+
|
| 276 |
+
# 4) Parse coordinates and draw marker
|
| 277 |
+
output_image_with_click = resized_image.copy().convert("RGB")
|
| 278 |
+
coords = parse_click_coordinates(coordinates_str, resized_width, resized_height)
|
| 279 |
+
|
| 280 |
+
if coords is not None:
|
| 281 |
+
x, y = coords
|
| 282 |
+
draw = ImageDraw.Draw(output_image_with_click)
|
| 283 |
+
radius = max(5, min(resized_width // 100, resized_height // 100, 15))
|
| 284 |
+
bbox = (x - radius, y - radius, x + radius, y + radius)
|
| 285 |
+
draw.ellipse(bbox, outline="red", width=max(2, radius // 4))
|
| 286 |
+
print(f"Predicted and drawn click at: ({x}, {y}) on resized image ({resized_width}x{resized_height})")
|
| 287 |
+
else:
|
| 288 |
+
print(f"Could not parse a click from model output: {coordinates_str}")
|
| 289 |
+
|
| 290 |
+
return coordinates_str, output_image_with_click, f"device: {device} | dtype: {str(dtype).replace('torch.', '')}"
|
| 291 |
+
|
| 292 |
+
# --- Load Example Data ---
|
| 293 |
+
example_image = None
|
| 294 |
+
example_instruction = "Enter the server address readyforquantum.com to check its security"
|
| 295 |
+
try:
|
| 296 |
+
example_image_url = "https://readyforquantum.com/img/screentest.jpg"
|
| 297 |
+
example_image = Image.open(requests.get(example_image_url, stream=True).raw)
|
| 298 |
+
except Exception as e:
|
| 299 |
+
print(f"Could not load example image from URL: {e}")
|
| 300 |
+
traceback.print_exc()
|
| 301 |
+
try:
|
| 302 |
+
example_image = Image.new("RGB", (200, 150), color="lightgray")
|
| 303 |
+
draw = ImageDraw.Draw(example_image)
|
| 304 |
+
draw.text((10, 10), "Example image\nfailed to load", fill="black")
|
| 305 |
+
except Exception:
|
| 306 |
+
pass
|
| 307 |
+
|
| 308 |
+
# --- Gradio UI ---
|
| 309 |
+
title = "GUI Nav Demo"
|
| 310 |
+
article = f"""
|
| 311 |
+
<p style='text-align: center'>
|
| 312 |
+
Model: <a href='https://huggingface.co/{MODEL_ID}' target='_blank'>{MODEL_ID}</a>
|
| 313 |
+
</p>
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
if not model_loaded:
|
| 317 |
+
with gr.Blocks() as demo:
|
| 318 |
+
gr.Markdown(f"# <center>⚠️ Error: Model Failed to Load ⚠️</center>")
|
| 319 |
+
gr.Markdown(f"<center>{load_error_message}</center>")
|
| 320 |
+
gr.Markdown("<center>See logs for the full traceback.</center>")
|
| 321 |
+
else:
|
| 322 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 323 |
+
gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
|
| 324 |
+
gr.Markdown(article)
|
| 325 |
+
|
| 326 |
+
with gr.Row():
|
| 327 |
+
with gr.Column(scale=1):
|
| 328 |
+
input_image_component = gr.Image(type="pil", label="Input UI Image", height=400)
|
| 329 |
+
instruction_component = gr.Textbox(
|
| 330 |
+
label="Instruction",
|
| 331 |
+
placeholder="e.g., Click the 'Login' button",
|
| 332 |
+
info="Type the action you want the model to localize on the image."
|
| 333 |
+
)
|
| 334 |
+
submit_button = gr.Button("Localize Click", variant="primary")
|
| 335 |
+
|
| 336 |
+
with gr.Column(scale=1):
|
| 337 |
+
output_coords_component = gr.Textbox(
|
| 338 |
+
label="Predicted Coordinates / Action",
|
| 339 |
+
interactive=False
|
| 340 |
+
)
|
| 341 |
+
output_image_component = gr.Image(
|
| 342 |
+
type="pil",
|
| 343 |
+
label="Image with Predicted Click Point",
|
| 344 |
+
height=400,
|
| 345 |
+
interactive=False
|
| 346 |
+
)
|
| 347 |
+
runtime_info = gr.Textbox(
|
| 348 |
+
label="Runtime Info",
|
| 349 |
+
value="device: n/a | dtype: n/a",
|
| 350 |
+
interactive=False
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
if example_image:
|
| 354 |
+
gr.Examples(
|
| 355 |
+
examples=[[example_image, example_instruction]],
|
| 356 |
+
inputs=[input_image_component, instruction_component],
|
| 357 |
+
outputs=[output_coords_component, output_image_component, runtime_info],
|
| 358 |
+
fn=predict_click_location,
|
| 359 |
+
cache_examples="lazy",
|
| 360 |
+
)
|
| 361 |
|
| 362 |
+
submit_button.click(
|
| 363 |
+
fn=predict_click_location,
|
| 364 |
+
inputs=[input_image_component, instruction_component],
|
| 365 |
+
outputs=[output_coords_component, output_image_component, runtime_info]
|
|
|
|
|
|
|
|
|
|
| 366 |
)
|
| 367 |
|
| 368 |
if __name__ == "__main__":
|
| 369 |
+
demo.launch(debug=True)
|