File size: 11,186 Bytes
7d0d550
 
 
 
 
 
fcb0f85
7d0d550
 
 
 
c875d85
7d0d550
 
1c19f0a
7d0d550
 
1c19f0a
7d0d550
 
 
1c19f0a
7d0d550
fcb0f85
7d0d550
1c19f0a
fcb0f85
 
5c21f23
 
 
 
7d0d550
1c19f0a
fcb0f85
7d0d550
 
1c19f0a
7d0d550
 
1c19f0a
7d0d550
 
 
 
1c19f0a
7d0d550
 
 
 
1c19f0a
7d0d550
fcb0f85
7d0d550
 
fcb0f85
 
 
 
5c21f23
fcb0f85
 
 
 
 
 
 
 
 
 
 
 
 
7d0d550
fcb0f85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c21f23
fcb0f85
 
 
 
 
 
7d0d550
 
fcb0f85
 
 
 
7d0d550
fcb0f85
 
 
 
 
7d0d550
fcb0f85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d0d550
fcb0f85
 
 
 
 
 
 
 
 
 
7d0d550
 
5c21f23
7d0d550
 
 
 
 
 
 
 
c875d85
7d0d550
 
 
 
 
c875d85
 
7d0d550
 
fcb0f85
7d0d550
fcb0f85
7d0d550
fcb0f85
 
7d0d550
 
 
 
 
 
 
 
 
 
 
fcb0f85
7d0d550
fcb0f85
 
7d0d550
 
 
 
 
 
 
 
 
 
 
1c19f0a
7d0d550
 
 
 
 
 
 
 
 
 
 
 
 
5c21f23
7d0d550
 
 
fcb0f85
7d0d550
 
 
 
 
 
 
 
 
 
5c21f23
fcb0f85
 
 
7d0d550
5c21f23
7d0d550
 
 
 
 
fcb0f85
 
 
7d0d550
 
 
 
fcb0f85
7d0d550
 
5c21f23
fcb0f85
7d0d550
 
 
fcb0f85
 
 
 
7d0d550
 
 
fcb0f85
 
 
7d0d550
 
fcb0f85
7d0d550
 
 
 
 
 
 
 
 
 
 
fcb0f85
7d0d550
 
fcb0f85
7d0d550
fcb0f85
 
1c19f0a
 
7d0d550
 
 
1c19f0a
7d0d550
 
 
 
 
 
fcb0f85
 
5c21f23
 
 
 
 
 
 
 
7d0d550
 
 
 
1c19f0a
7d0d550
9e4971c
7d0d550
 
 
 
 
 
 
fcb0f85
7d0d550
 
 
 
 
fcb0f85
 
7d0d550
fcb0f85
7d0d550
 
c875d85
9e4971c
fcb0f85
 
7d0d550
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
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
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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import os
import re
import json
import time
import shutil
import uuid
import gc
import tempfile
import unicodedata
from io import BytesIO
from typing import Tuple, Optional, List, Dict, Any

import gradio as gr
import numpy as np
import torch
import spaces
from PIL import Image, ImageDraw, ImageFont

# Transformers & Qwen Utils
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info

# -----------------------------------------------------------------------------
# 1. CONSTANTS & CONFIGURATION
# -----------------------------------------------------------------------------

# Map display names to Hugging Face Repo IDs
MODEL_MAP = {
    "Fara-7B": "microsoft/Fara-7B",
    "UI-TARS-1.5-7B": "ByteDance-Seed/UI-TARS-1.5-7B"
}

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# System Prompt
OS_SYSTEM_PROMPT = """You are a GUI agent. You are given a task and a screenshot of the current status. 
You need to generate the next action to complete the task.

Output your action inside a <tool_call> block using JSON format.
Include "coordinate": [x, y] in pixels for interactions.

Examples:
<tool_call>
{"name": "User", "arguments": {"action": "click", "coordinate": [400, 300]}}
</tool_call>

<tool_call>
{"name": "User", "arguments": {"action": "type", "coordinate": [100, 200], "text": "hello"}}
</tool_call>
"""

# -----------------------------------------------------------------------------
# 2. GLOBAL MODEL STATE MANAGEMENT
# -----------------------------------------------------------------------------

# Global variables to track the currently loaded model
CURRENT_MODEL = None
CURRENT_PROCESSOR = None
CURRENT_MODEL_ID = None

def load_model(model_key: str):
    """
    Dynamically loads the requested model. 
    Unloads the previous model to free up GPU memory if a switch occurs.
    """
    global CURRENT_MODEL, CURRENT_PROCESSOR, CURRENT_MODEL_ID
    
    target_repo_id = MODEL_MAP[model_key]
    
    # If the requested model is already loaded, do nothing
    if CURRENT_MODEL is not None and CURRENT_MODEL_ID == target_repo_id:
        print(f"Model {model_key} is already loaded.")
        return

    print(f"--- Switching Model to {model_key} ({target_repo_id}) ---")
    
    # 1. Unload existing model to free GPU memory
    if CURRENT_MODEL is not None:
        print("Unloading current model...")
        del CURRENT_MODEL
        del CURRENT_PROCESSOR
        CURRENT_MODEL = None
        CURRENT_PROCESSOR = None
        gc.collect()
        torch.cuda.empty_cache()
        print("Memory cleared.")

    # 2. Load new model
    try:
        print(f"Loading processor for {target_repo_id}...")
        processor = AutoProcessor.from_pretrained(target_repo_id, trust_remote_code=True)
        
        print(f"Loading model weights for {target_repo_id}...")
        model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
            target_repo_id,
            trust_remote_code=True,
            torch_dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32,
            device_map="auto" if DEVICE == "cuda" else None,
        )
        
        if DEVICE == "cpu":
            model.to("cpu")
            
        model.eval()
        
        # Update global state
        CURRENT_MODEL = model
        CURRENT_PROCESSOR = processor
        CURRENT_MODEL_ID = target_repo_id
        print(f"Successfully loaded {model_key}.")
        
    except Exception as e:
        print(f"Error loading model {target_repo_id}: {e}")
        raise e

def generate_response(messages: list[dict], max_new_tokens=512):
    """
    Runs generation using the currently loaded global model.
    """
    if CURRENT_MODEL is None or CURRENT_PROCESSOR is None:
        raise ValueError("No model loaded.")

    text = CURRENT_PROCESSOR.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    image_inputs, video_inputs = process_vision_info(messages)
    
    inputs = CURRENT_PROCESSOR(
        text=[text],
        images=image_inputs,
        videos=video_inputs,
        padding=True,
        return_tensors="pt",
    )
    inputs = inputs.to(CURRENT_MODEL.device)

    with torch.no_grad():
        generated_ids = CURRENT_MODEL.generate(**inputs, max_new_tokens=max_new_tokens)
    
    generated_ids_trimmed = [
        out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
    ]
    
    return CURRENT_PROCESSOR.batch_decode(
        generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
    )[0]

# -----------------------------------------------------------------------------
# 3. PARSING & VISUALIZATION LOGIC
# -----------------------------------------------------------------------------

def array_to_image(image_array: np.ndarray) -> Image.Image:
    if image_array is None:
        raise ValueError("No image provided. Please upload an image.")
    return Image.fromarray(np.uint8(image_array))

def get_navigation_prompt(task, image):
    return [
        {"role": "system", "content": [{"type": "text", "text": OS_SYSTEM_PROMPT}]},
        {"role": "user", "content": [
            {"type": "image", "image": image},
            {"type": "text", "text": f"Instruction: {task}"},
        ]},
    ]

def parse_tool_calls(response: str) -> list[dict]:
    actions = []
    matches = re.findall(r"<tool_call>(.*?)</tool_call>", response, re.DOTALL)
    
    for match in matches:
        try:
            json_str = match.strip()
            data = json.loads(json_str)
            args = data.get("arguments", {})
            coords = args.get("coordinate", [])
            action_type = args.get("action", "unknown")
            text_content = args.get("text", "")
            
            if coords and isinstance(coords, list) and len(coords) == 2:
                actions.append({
                    "type": action_type,
                    "x": float(coords[0]),
                    "y": float(coords[1]),
                    "text": text_content,
                    "raw_json": data
                })
        except Exception as e:
            print(f"Error parsing tool call: {e}")
            
    return actions

def create_localized_image(original_image: Image.Image, actions: list[dict]) -> Optional[Image.Image]:
    if not actions:
        return None
    
    img_copy = original_image.copy()
    draw = ImageDraw.Draw(img_copy)
    width, height = img_copy.size
    
    try:
        font = ImageFont.load_default()
    except:
        font = None
    
    colors = {
        'type': 'blue', 
        'click': 'red', 
        'left_click': 'red',
        'right_click': 'purple',
        'double_click': 'orange',
        'unknown': 'green'
    }
    
    for act in actions:
        x = act['x']
        y = act['y']
        
        # Determine if coords are normalized or absolute
        if x <= 1.0 and y <= 1.0 and x > 0:
            pixel_x = int(x * width)
            pixel_y = int(y * height)
        else:
            pixel_x = int(x)
            pixel_y = int(y)
            
        action_type = act['type']
        color = colors.get(action_type, 'green')
        
        # Draw Target
        r = 12 
        draw.ellipse([pixel_x - r, pixel_y - r, pixel_x + r, pixel_y + r], outline=color, width=4)
        draw.ellipse([pixel_x - 3, pixel_y - 3, pixel_x + 3, pixel_y + 3], fill=color)
        
        # Label
        label_text = f"{action_type}"
        if act['text']:
            label_text += f": '{act['text']}'"
            
        text_pos = (pixel_x + 15, pixel_y - 10)
        bbox = draw.textbbox(text_pos, label_text, font=font)
        draw.rectangle(bbox, fill="black")
        draw.text(text_pos, label_text, fill="white", font=font)

    return img_copy

# -----------------------------------------------------------------------------
# 4. GRADIO PROCESSING LOGIC
# -----------------------------------------------------------------------------

@spaces.GPU(duration=120)
def process_screenshot(input_numpy_image: np.ndarray, task: str, selected_model_key: str) -> Tuple[str, Optional[Image.Image]]:
    if input_numpy_image is None:
        return "⚠️ Please upload an image first.", None

    # 1. Ensure correct model is loaded
    load_model(selected_model_key)

    # 2. Prepare Data
    input_pil_image = array_to_image(input_numpy_image)
    prompt = get_navigation_prompt(task, input_pil_image)

    # 3. Generate
    print(f"Generating with {selected_model_key}...")
    raw_response = generate_response(prompt, max_new_tokens=500)
    print(f"Raw Output:\n{raw_response}")
    
    # 4. Parse & Visualize
    actions = parse_tool_calls(raw_response)
    
    output_image = input_pil_image
    if actions:
        visualized = create_localized_image(input_pil_image, actions)
        if visualized:
            output_image = visualized
            
    return raw_response, output_image

# -----------------------------------------------------------------------------
# 5. UI SETUP
# -----------------------------------------------------------------------------

title = "Computer Use Agent (CUA) Playground 🖥️"
description = """
Analyze GUI screenshots and generate action coordinates using State-of-the-Art Vision Language Models.
Supported Models: **Microsoft Fara-7B** and **ByteDance UI-TARS-1.5-7B**.
"""

custom_css = """
#out_img { height: 600px; object-fit: contain; }
"""

with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
    gr.Markdown(description)

    with gr.Row():
        with gr.Column():
            input_image = gr.Image(label="Upload Screenshot", height=500)
            
            # Model Selector
            model_selector = gr.Dropdown(
                label="Choose CUA Model",
                choices=["Fara-7B", "UI-TARS-1.5-7B"],
                value="Fara-7B",
                interactive=True
            )
            
            task_input = gr.Textbox(
                label="Task Instruction",
                placeholder="e.g. Input the server address readyforquantum.com...",
                lines=2
            )
            submit_btn = gr.Button("Analyze UI & Generate Action", variant="primary")

        with gr.Column():
            output_image = gr.Image(label="Visualized Action Points", elem_id="out_img", height=500)
            output_text = gr.Textbox(label="Raw Model Output", lines=8, show_copy_button=True)

    # Wire up the button
    submit_btn.click(
        fn=process_screenshot,
        inputs=[input_image, task_input, model_selector],
        outputs=[output_text, output_image]
    )
    
    gr.Examples(
        examples=[
            ["./assets/google.png", "Search for 'Hugging Face'", "Fara-7B"],
            ["./assets/google.png", "Click the Sign In button", "UI-TARS-1.5-7B"],
        ],
        inputs=[input_image, task_input, model_selector],
        label="Quick Examples"
    )

if __name__ == "__main__":
    # Pre-load the default model on startup to speed up first inference (optional)
    # load_model("Fara-7B") 
    demo.queue().launch()