Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,369 +1,317 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
import
|
|
|
|
| 6 |
import torch
|
| 7 |
-
|
| 8 |
-
import
|
| 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 |
-
|
| 99 |
-
|
| 100 |
-
|
| 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 |
-
|
| 111 |
-
|
| 112 |
-
|
| 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 |
-
|
| 118 |
-
|
| 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 |
-
|
| 124 |
-
|
| 125 |
-
|
| 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 |
-
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
model_loaded = False
|
| 136 |
-
load_error_message = ""
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 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 |
-
#
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
return [
|
| 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 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
def
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 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 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
)
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
| 261 |
)
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
"""
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 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 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
)
|
|
|
|
| 361 |
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
|
| 368 |
if __name__ == "__main__":
|
| 369 |
-
demo.launch(
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import shutil
|
| 6 |
+
import uuid
|
| 7 |
+
import tempfile
|
| 8 |
+
import unicodedata
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
from typing import Tuple, Optional, List, Dict, Any
|
| 11 |
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import numpy as np
|
| 14 |
import torch
|
| 15 |
+
import spaces
|
| 16 |
+
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
# Transformers & Qwen Utils
|
| 19 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 20 |
+
from qwen_vl_utils import process_vision_info
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# -----------------------------------------------------------------------------
|
| 23 |
+
# 1. CONSTANTS & SYSTEM PROMPT
|
| 24 |
+
# -----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
MODEL_ID = "microsoft/Fara-7B"
|
| 27 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# Updated System Prompt to encourage the JSON format the model prefers
|
| 30 |
+
OS_SYSTEM_PROMPT = """You are a GUI agent. You are given a task and a screenshot of the current status.
|
| 31 |
+
You need to generate the next action to complete the task.
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
Output your action inside a <tool_call> block using JSON format.
|
| 34 |
+
Include "coordinate": [x, y] in pixels for interactions.
|
| 35 |
|
| 36 |
+
Examples:
|
| 37 |
+
<tool_call>
|
| 38 |
+
{"name": "User", "arguments": {"action": "click", "coordinate": [400, 300]}}
|
| 39 |
+
</tool_call>
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
<tool_call>
|
| 42 |
+
{"name": "User", "arguments": {"action": "type", "coordinate": [100, 200], "text": "hello"}}
|
| 43 |
+
</tool_call>
|
| 44 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
# -----------------------------------------------------------------------------
|
| 47 |
+
# 2. MODEL DEFINITION
|
| 48 |
+
# -----------------------------------------------------------------------------
|
| 49 |
+
|
| 50 |
+
class FaraTransformersModel:
|
| 51 |
+
def __init__(self, model_id: str, to_device: str = "cuda"):
|
| 52 |
+
print(f"Loading {model_id} on {to_device}...")
|
| 53 |
+
self.model_id = model_id
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
self.processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
| 57 |
+
self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 58 |
+
model_id,
|
| 59 |
+
trust_remote_code=True,
|
| 60 |
+
torch_dtype=torch.bfloat16 if to_device == "cuda" else torch.float32,
|
| 61 |
+
device_map="auto" if to_device == "cuda" else None,
|
| 62 |
+
)
|
| 63 |
+
if to_device == "cpu":
|
| 64 |
+
self.model.to("cpu")
|
| 65 |
+
self.model.eval()
|
| 66 |
+
print("Model loaded successfully.")
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"Error loading Fara: {e}")
|
| 69 |
+
raise e
|
| 70 |
+
|
| 71 |
+
def generate(self, messages: list[dict], max_new_tokens=512):
|
| 72 |
+
text = self.processor.apply_chat_template(
|
| 73 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 74 |
+
)
|
| 75 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 76 |
+
|
| 77 |
+
inputs = self.processor(
|
| 78 |
+
text=[text],
|
| 79 |
+
images=image_inputs,
|
| 80 |
+
videos=video_inputs,
|
| 81 |
+
padding=True,
|
| 82 |
+
return_tensors="pt",
|
| 83 |
+
)
|
| 84 |
+
inputs = inputs.to(self.model.device)
|
| 85 |
+
|
| 86 |
+
with torch.no_grad():
|
| 87 |
+
generated_ids = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
|
| 88 |
+
|
| 89 |
+
generated_ids_trimmed = [
|
| 90 |
+
out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
return self.processor.batch_decode(
|
| 94 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 95 |
+
)[0]
|
| 96 |
+
|
| 97 |
+
# Initialize Model
|
| 98 |
+
print(f"Initializing model class for {MODEL_ID}...")
|
| 99 |
+
fara_model = FaraTransformersModel(MODEL_ID, to_device=DEVICE)
|
| 100 |
+
|
| 101 |
+
# -----------------------------------------------------------------------------
|
| 102 |
+
# 3. PARSING & VISUALIZATION LOGIC (UPDATED)
|
| 103 |
+
# -----------------------------------------------------------------------------
|
| 104 |
+
|
| 105 |
+
def array_to_image(image_array: np.ndarray) -> Image.Image:
|
| 106 |
+
if image_array is None:
|
| 107 |
+
raise ValueError("No image provided. Please upload an image.")
|
| 108 |
+
return Image.fromarray(np.uint8(image_array))
|
| 109 |
+
|
| 110 |
+
def get_navigation_prompt(task, image):
|
| 111 |
return [
|
| 112 |
+
{"role": "system", "content": [{"type": "text", "text": OS_SYSTEM_PROMPT}]},
|
| 113 |
+
{"role": "user", "content": [
|
| 114 |
+
{"type": "image", "image": image},
|
| 115 |
+
{"type": "text", "text": f"Instruction: {task}"},
|
| 116 |
+
]},
|
|
|
|
|
|
|
| 117 |
]
|
| 118 |
|
| 119 |
+
def parse_tool_calls(response: str) -> list[dict]:
|
| 120 |
+
"""
|
| 121 |
+
Parses the <tool_call>{JSON}</tool_call> format specifically.
|
| 122 |
+
Extracts coordinates and action types.
|
| 123 |
+
"""
|
| 124 |
+
actions = []
|
| 125 |
+
|
| 126 |
+
# Regex to find content between <tool_call> tags
|
| 127 |
+
# re.DOTALL allows matching across newlines
|
| 128 |
+
matches = re.findall(r"<tool_call>(.*?)</tool_call>", response, re.DOTALL)
|
| 129 |
+
|
| 130 |
+
for match in matches:
|
| 131 |
+
try:
|
| 132 |
+
# Clean up the string just in case
|
| 133 |
+
json_str = match.strip()
|
| 134 |
+
data = json.loads(json_str)
|
| 135 |
+
|
| 136 |
+
# Access the 'arguments' dictionary
|
| 137 |
+
args = data.get("arguments", {})
|
| 138 |
+
|
| 139 |
+
# Extract coordinates: Expecting list like [399, 496]
|
| 140 |
+
coords = args.get("coordinate", [])
|
| 141 |
+
action_type = args.get("action", "unknown")
|
| 142 |
+
text_content = args.get("text", "")
|
| 143 |
+
|
| 144 |
+
if coords and isinstance(coords, list) and len(coords) == 2:
|
| 145 |
+
actions.append({
|
| 146 |
+
"type": action_type,
|
| 147 |
+
"x": float(coords[0]),
|
| 148 |
+
"y": float(coords[1]),
|
| 149 |
+
"text": text_content,
|
| 150 |
+
"raw_json": data
|
| 151 |
+
})
|
| 152 |
+
print(f"Parsed Action: {action_type} at {coords}")
|
| 153 |
+
else:
|
| 154 |
+
print(f"No valid coordinates found in tool call: {json_str}")
|
| 155 |
+
|
| 156 |
+
except json.JSONDecodeError as e:
|
| 157 |
+
print(f"Failed to parse JSON in tool call: {e}\nString was: {match}")
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"Unexpected error parsing tool call: {e}")
|
| 160 |
+
|
| 161 |
+
return actions
|
| 162 |
+
|
| 163 |
+
def create_localized_image(original_image: Image.Image, actions: list[dict]) -> Optional[Image.Image]:
|
| 164 |
+
"""Draws markers on the image based on parsed pixel coordinates."""
|
| 165 |
+
if not actions:
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
img_copy = original_image.copy()
|
| 169 |
+
draw = ImageDraw.Draw(img_copy)
|
| 170 |
+
width, height = img_copy.size
|
| 171 |
+
|
| 172 |
+
# Try loading font
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
try:
|
| 174 |
+
font = ImageFont.load_default()
|
| 175 |
+
except:
|
| 176 |
+
font = None
|
| 177 |
+
|
| 178 |
+
colors = {
|
| 179 |
+
'type': 'blue',
|
| 180 |
+
'click': 'red',
|
| 181 |
+
'left_click': 'red',
|
| 182 |
+
'right_click': 'purple',
|
| 183 |
+
'double_click': 'orange',
|
| 184 |
+
'unknown': 'green'
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
for i, act in enumerate(actions):
|
| 188 |
+
x = act['x']
|
| 189 |
+
y = act['y']
|
| 190 |
+
|
| 191 |
+
# Check if Normalized (0.0 - 1.0) or Absolute (Pixels > 1.0)
|
| 192 |
+
# The logs showed [399, 496], so these are pixels.
|
| 193 |
+
# However, to be safe, we check.
|
| 194 |
+
if x <= 1.0 and y <= 1.0 and x > 0:
|
| 195 |
+
# It's normalized, convert to pixels
|
| 196 |
+
pixel_x = int(x * width)
|
| 197 |
+
pixel_y = int(y * height)
|
| 198 |
+
else:
|
| 199 |
+
# It's absolute pixels
|
| 200 |
+
pixel_x = int(x)
|
| 201 |
+
pixel_y = int(y)
|
| 202 |
+
|
| 203 |
+
action_type = act['type']
|
| 204 |
+
color = colors.get(action_type, 'green')
|
| 205 |
+
|
| 206 |
+
# Draw Circle Target
|
| 207 |
+
r = 12 # Radius
|
| 208 |
+
draw.ellipse(
|
| 209 |
+
[pixel_x - r, pixel_y - r, pixel_x + r, pixel_y + r],
|
| 210 |
+
outline=color,
|
| 211 |
+
width=4
|
| 212 |
)
|
| 213 |
+
|
| 214 |
+
# Draw Center Dot
|
| 215 |
+
draw.ellipse(
|
| 216 |
+
[pixel_x - 3, pixel_y - 3, pixel_x + 3, pixel_y + 3],
|
| 217 |
+
fill=color
|
| 218 |
)
|
| 219 |
+
|
| 220 |
+
# Draw Label text
|
| 221 |
+
label_text = f"{action_type}"
|
| 222 |
+
if act['text']:
|
| 223 |
+
label_text += f": '{act['text']}'"
|
| 224 |
+
|
| 225 |
+
# Draw text background for readability
|
| 226 |
+
text_pos = (pixel_x + 15, pixel_y - 10)
|
| 227 |
+
bbox = draw.textbbox(text_pos, label_text, font=font)
|
| 228 |
+
draw.rectangle(bbox, fill="black")
|
| 229 |
+
draw.text(text_pos, label_text, fill="white", font=font)
|
| 230 |
+
|
| 231 |
+
return img_copy
|
| 232 |
+
|
| 233 |
+
# -----------------------------------------------------------------------------
|
| 234 |
+
# 4. GRADIO LOGIC
|
| 235 |
+
# -----------------------------------------------------------------------------
|
| 236 |
+
|
| 237 |
+
@spaces.GPU(duration=60)
|
| 238 |
+
def process_screenshot(input_numpy_image: np.ndarray, task: str) -> Tuple[str, Optional[Image.Image]]:
|
| 239 |
+
if input_numpy_image is None:
|
| 240 |
+
return "⚠️ Please upload an image first.", None
|
| 241 |
+
|
| 242 |
+
# Convert to PIL
|
| 243 |
+
input_pil_image = array_to_image(input_numpy_image)
|
| 244 |
+
|
| 245 |
+
# 1. Build Prompt
|
| 246 |
+
prompt = get_navigation_prompt(task, input_pil_image)
|
| 247 |
+
|
| 248 |
+
# 2. Generate Response
|
| 249 |
+
if fara_model is None:
|
| 250 |
+
raise ValueError("Model not loaded")
|
| 251 |
+
|
| 252 |
+
print("Generating response...")
|
| 253 |
+
raw_response = fara_model.generate(prompt, max_new_tokens=500)
|
| 254 |
+
print(f"Raw Output:\n{raw_response}")
|
| 255 |
+
|
| 256 |
+
# 3. Parse Actions
|
| 257 |
+
actions = parse_tool_calls(raw_response)
|
| 258 |
+
|
| 259 |
+
# 4. Visualize
|
| 260 |
+
output_image = input_pil_image
|
| 261 |
+
if actions:
|
| 262 |
+
visualized = create_localized_image(input_pil_image, actions)
|
| 263 |
+
if visualized:
|
| 264 |
+
output_image = visualized
|
| 265 |
+
|
| 266 |
+
return raw_response, output_image
|
| 267 |
+
|
| 268 |
+
# -----------------------------------------------------------------------------
|
| 269 |
+
# 5. GRADIO UI SETUP
|
| 270 |
+
# -----------------------------------------------------------------------------
|
| 271 |
+
|
| 272 |
+
title = "Fara-7B GUI Operator 🖥️"
|
| 273 |
+
description = """
|
| 274 |
+
This demo uses **microsoft/Fara-7B** to understand GUI screenshots.
|
| 275 |
+
It generates action coordinates which are then parsed and plotted on the image.
|
| 276 |
"""
|
| 277 |
|
| 278 |
+
custom_css = """
|
| 279 |
+
#out_img { height: 600px; object-fit: contain; }
|
| 280 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
|
| 283 |
+
gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
|
| 284 |
+
gr.Markdown(description)
|
| 285 |
+
|
| 286 |
+
with gr.Row():
|
| 287 |
+
with gr.Column():
|
| 288 |
+
input_image = gr.Image(label="Upload Screenshot", height=500)
|
| 289 |
+
task_input = gr.Textbox(
|
| 290 |
+
label="Task Instruction",
|
| 291 |
+
placeholder="e.g. Input the server address readyforquantum.com...",
|
| 292 |
+
lines=2
|
| 293 |
)
|
| 294 |
+
submit_btn = gr.Button("Analyze UI & Generate Action", variant="primary")
|
| 295 |
|
| 296 |
+
with gr.Column():
|
| 297 |
+
output_image = gr.Image(label="Visualized Action Points", elem_id="out_img", height=500)
|
| 298 |
+
output_text = gr.Textbox(label="Raw Model Output", lines=8, show_copy_button=True)
|
| 299 |
+
|
| 300 |
+
# Wire up the button
|
| 301 |
+
submit_btn.click(
|
| 302 |
+
fn=process_screenshot,
|
| 303 |
+
inputs=[input_image, task_input],
|
| 304 |
+
outputs=[output_text, output_image]
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# Example for quick testing
|
| 308 |
+
gr.Examples(
|
| 309 |
+
examples=[
|
| 310 |
+
["./assets/google.png", "Search for 'Hugging Face'"],
|
| 311 |
+
],
|
| 312 |
+
inputs=[input_image, task_input],
|
| 313 |
+
label="Quick Examples"
|
| 314 |
+
)
|
| 315 |
|
| 316 |
if __name__ == "__main__":
|
| 317 |
+
demo.queue().launch()
|