"""Run a Sico-GUI model on an Android device over adb. Each step takes a screenshot, sends one request (system prompt, task, summaries of the previous steps and the screenshot) to an OpenAI-compatible endpoint, parses and , and executes the action with adb. Coordinates are normalized to [0, 1000]. """ from __future__ import annotations import argparse import base64 import io import json import re import shlex import subprocess import time from pathlib import Path from jinja2 import Environment, FileSystemLoader from openai import OpenAI from PIL import Image PROMPTS = Environment( loader=FileSystemLoader(Path(__file__).parent / "prompts"), trim_blocks=True, lstrip_blocks=True, ) SYSTEM_TEMPLATE = PROMPTS.get_template("system.j2").module SYSTEM_PROMPT = SYSTEM_TEMPLATE.system_prompt(scale_factor=1000).strip() USER_PROMPT = PROMPTS.get_template("user.j2").module.user_prompt KEYS = { "navigate_home": "KEYCODE_HOME", "navigate_back": "KEYCODE_BACK", "keyboard_enter": "KEYCODE_ENTER", } def adb(device: str | None, *args: str) -> bytes: """Run one adb command against ``device`` and return its stdout.""" serial = ["-s", device] if device else [] result = subprocess.run(["adb", *serial, *args], capture_output=True, check=True) return result.stdout def screenshot(device: str | None) -> tuple[bytes, tuple[int, int]]: """Return the screen as RGB JPEG (quality 85, original size) and its size.""" png = adb(device, "exec-out", "screencap", "-p") image = Image.open(io.BytesIO(png)).convert("RGB") buffer = io.BytesIO() image.save(buffer, format="JPEG", quality=85) return buffer.getvalue(), image.size def predict( client: OpenAI, model: str, task: str, history: list[str], jpeg: bytes ) -> tuple[str, dict]: """Ask the model for the next step; return its summary and action.""" image_url = "data:image/jpeg;base64," + base64.b64encode(jpeg).decode() user_content = [ {"type": "text", "text": USER_PROMPT(task, history).strip()}, {"type": "image_url", "image_url": {"url": image_url}}, ] response = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_content}, ], temperature=0, max_tokens=16384, extra_body={"chat_template_kwargs": {"enable_thinking": True}}, ) # Without a vLLM reasoning parser the reasoning precedes in the same field. text = (response.choices[0].message.content or "").split("")[-1] summary = re.search(r"(.*?)", text, re.S) action = re.search(r"(.*?)", text, re.S) if not action: raise ValueError(f"no in model output:\n{text}") return (summary.group(1).strip() if summary else ""), json.loads(action.group(1)) def execute(device: str | None, action: dict, width: int, height: int) -> None: """Perform one non-terminal action on the device.""" def pixel(point: list[float]) -> tuple[str, str]: return str(int(point[0] * width / 1000)), str(int(point[1] * height / 1000)) kind = action["action_type"] if kind == "click": adb(device, "shell", "input", "tap", *pixel(action["coordinate"])) elif kind == "double_tap": adb(device, "shell", "input", "tap", *pixel(action["coordinate"])) adb(device, "shell", "input", "tap", *pixel(action["coordinate"])) elif kind == "long_press": x, y = pixel(action["coordinate"]) adb(device, "shell", "input", "swipe", x, y, x, y, "1000") elif kind == "drag": start, end = pixel(action["start_coordinate"]), pixel(action["end_coordinate"]) adb(device, "shell", "input", "swipe", *start, *end, "400") elif kind == "scroll": # Same mapping as the evaluation harness (MobileWorld general_e2e): up/down # swipe opposite to the scroll, left/right move the finger in that direction. cx, cy, unit = width // 2, height // 2, width // 10 directions = {"down": (0, -4), "up": (0, 4), "left": (-2, 0), "right": (2, 0)} dx, dy = directions[action.get("direction", "down")] swipe = (cx, cy, cx + dx * unit, cy + dy * unit, 400) adb(device, "shell", "input", "swipe", *map(str, swipe)) elif kind == "input_text": # `input text` types ASCII only and reads %s as a space; quote for the shell. text = shlex.quote(action["text"].replace(" ", "%s")) adb(device, "shell", "input", "text", text) elif kind in KEYS: adb(device, "shell", "input", "keyevent", KEYS[kind]) elif kind == "wait": time.sleep(1) else: raise ValueError(f"unsupported action: {action}") def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--task", required=True, help="natural-language instruction") parser.add_argument("--base-url", default="http://localhost:8000/v1") parser.add_argument("--model", default="microsoft/Sico-GUI-2B") parser.add_argument("--device", help="adb serial, needed with several devices") parser.add_argument("--max-steps", type=int, default=50) args = parser.parse_args() client = OpenAI(base_url=args.base_url, api_key="EMPTY") history: list[str] = [] for step in range(1, args.max_steps + 1): jpeg, (width, height) = screenshot(args.device) summary, action = predict(client, args.model, args.task, history, jpeg) print(f"[{step}] {summary} -> {json.dumps(action, ensure_ascii=False)}") if action["action_type"] == "answer": print("answer:", action.get("text")) return if action["action_type"] == "status": print("status:", action.get("goal_status")) return execute(args.device, action, width, height) history.append(summary) time.sleep(5) # let the screen settle before the next screenshot print("stopped: step limit reached") if __name__ == "__main__": main()