prithivMLmods commited on
Commit
7d0d550
·
verified ·
1 Parent(s): 1c19f0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +294 -346
app.py CHANGED
@@ -1,369 +1,317 @@
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)
 
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()