← All Engineering Blueprints
// blueprint #04 · complexity score: 91/100 · multimodal vision rpa

Driving legacy desktop GUIs without APIs via Set-of-Mark grounding and closed-loop dHash verification

Legacy ERP, accounting, and industrial desktop applications expose zero REST APIs and obfuscated accessibility trees. This 3,155-line Python engine captures high-DPI frames, grounds UI controls on a normalized 0–1000 coordinate grid via multimodal Vision LLMs, executes hardware-level OS input, and verifies state transitions before advancing.

0–1000 GridDPI-invariant bounding box math
Closed-LoopPre/post dHash frame verification
3,155 LOCPython · Vision Parser · OS Driver

The engineering problem

Traditional RPA tools rely on brittle Windows COM selectors or static pixel templates that break the moment an OS theme updates, a window resizes, or Windows display scaling shifts from 100% to 150% DPI.

To automate air-gapped or legacy desktop workflows reliably, the engine must perceive the screen visually like an operator, map semantic labels to DPI-normalized bounding boxes, and verify that every click or keystroke actually mutated the target UI region before executing the next step.

System architecture & interactive topology

A 3,155-line modular Python architecture across vision_parser.py, os_controller.py, task_runner.py, and engine.py:

  • Win32 Per-Monitor DPI Awareness (os_controller.py): Calls SetProcessDpiAwarenessContext to prevent Windows virtualization scaling drift on 4K/Retina displays.
  • Normalized 0–1000 Coordinate Grounding (vision_parser.py): Enforces Pydantic-validated NormalizedBoundingBox(ymin, xmin, ymax, xmax) schemas and projects centers onto physical monitor geometry.
  • Annotated Visual Audit Trail: Draws bounding-box overlays and target crosshairs onto every captured step frame for deterministic debugging.
  • Closed-Loop Perceptual Diffing: Computes post-action frame deltas to detect frozen dialogs or missed clicks, triggering automatic coordinate re-grounding.
SYSTEM TOPOLOGY & ARCHITECTURE BLUEPRINT
PRODUCTION ENGINE
Zero-API Desktop RPA & Vision Execution Engine architecture visualization
END-TO-END FLOW: DPI Screen Grab → Vision Grounder → Bounds Validator → OS Input Driver → Closed-Loop Diff → Audit Annotator ● DETERMINISTIC PIPELINE
NODE 01 DPI Screen Grab Win32 / Xvfb Capture NODE 02 Vision Grounder 0-1000 Box Parser NODE 03 Bounds Validator Pydantic + DPI Math NODE 04 OS Input Driver Smooth Bezier + Key NODE 05 Closed-Loop Diff Post-Action Verify NODE 06 Audit Annotator Crosshair + JSON Log

Click any node in the SVG diagram or list below to inspect its payload contract, latency SLA, and retry policy.

01 · INTERACTIVE NODE TOPOLOGY INSPECTOR
Inspect Stage-by-Stage Execution Contracts & Fault Boundaries

Select any node in the pipeline to examine its architectural responsibility, input/output schema types, p95 execution latency, and error recovery policy.

NODE 01 · DPI Screen Grab
LATENCY: 14 ms
Architectural Role
Locks process DPI awareness, captures raw RGB viewport buffer from the target monitor or virtual Xvfb display, and encodes lossless PNG bytes.
Input / Output Payload Contract
IN: MonitorConfig(monitor_idx=1, dpi_aware=True) -> OUT: ScreenFrame(image_bytes, width=2560, height=1440)
Error & Retry Policy
Automatic virtual display re-initialization if headless frame buffer returns all-black bytes.

Real code & schema inspector

Extracted directly from the production repository. Switch tabs to inspect the core execution logic, strict JSON/database data contracts, and structured LLM instructions.

// SOURCE: products/zero-api-desktop-automation-engine-python-vision-llm-20261005/package/vision_parser.py
    SCROLLBAR = "scrollbar"
    WINDOW_CONTROL = "window_control"
    DIALOG = "dialog"
    UNKNOWN = "unknown"


class NormalizedBoundingBox(BaseModel):
    """
    Coordinates normalized to a standard 0-1000 scale.
    ymin, xmin, ymax, xmax representing the perimeter box.
    """
    ymin: int = Field(..., ge=0, le=1000, description="Top bound in 0-1000 scale")
    xmin: int = Field(..., ge=0, le=1000, description="Left bound in 0-1000 scale")
    ymax: int = Field(..., ge=0, le=1000, description="Bottom bound in 0-1000 scale")
    xmax: int = Field(..., ge=0, le=1000, description="Right bound in 0-1000 scale")

    @field_validator("ymax")
    @classmethod
    def validate_vertical_bounds(cls, v: int, info) -> int:
        ymin = info.data.get("ymin", 0)
        if v < ymin:
            raise ValueError(f"ymax ({v}) cannot be less than ymin ({ymin})")
        return v

    @field_validator("xmax")
    @classmethod
    def validate_horizontal_bounds(cls, v: int, info) -> int:
        xmin = info.data.get("xmin", 0)
        if v < xmin:
            raise ValueError(f"xmax ({v}) cannot be less than xmin ({xmin})")
        return v

    def to_pixel_coords(self, screen_width: int, screen_height: int) -> Tuple[int, int, int, int]:
        """Convert normalized (0-1000) coordinates to actual pixel coordinates (left, top, right, bottom)."""
        left = int(round((self.xmin / 1000.0) * screen_width))
        top = int(round((self.ymin / 1000.0) * screen_height))
        right = int(round((self.xmax / 1000.0) * screen_width))
        bottom = int(round((self.ymax / 1000.0) * screen_height))
        return left, top, right, bottom

    def get_pixel_center(self, screen_width: int, screen_height: int) -> Tuple[int, int]:
        """Calculates the absolute pixel center point for direct mouse interactions."""
        left, top, right, bottom = self.to_pixel_coords(screen_width, screen_height)
        return (left + right) // 2, (top + bottom) // 2


class UIElement(BaseModel):
    """Represents a visually identified and grounded interface element."""
    id: str = Field(default_factory=lambda: f"elem_{int(time.time() * 1000)}")
    label: str = Field(..., description="Visible text or semantic label of the element")
    element_type: UIElementType = Field(default=UIElementType.UNKNOWN)
    bbox: NormalizedBoundingBox
    confidence: float = Field(default=1.0, ge=0.0, le=1.0)
    state: Optional[str] = Field(default=None, description="e.g., 'enabled', 'disabled', 'checked', 'active'")
    value: Optional[str] = Field(default=None, description="Current contained text or selected value")

    def get_click_target(self, screen_width: int, screen_height: int, offset_x: float = 0.5, offset_y: float = 0.5) -> Tuple[int, int]:
        """
        Calculate targeting coordinates within the element bounds.
        Default is the geometric center (0.5, 0.5).
        """
        left, top, right, bottom = self.bbox.to_pixel_coords(screen_width, screen_height)
        width = right - left
        height = bottom - top
        target_x = int(left + (width * offset_x))
        target_y = int(top + (height * offset_y))
        return target_x, target_y


class VisionParseResult(BaseModel):
    """Aggregate result from visual screen interpretation."""
    success: bool
    query: Optional[str] = None
    target_element: Optional[UIElement] = None
    elements: List[UIElement] = Field(default_factory=list)
    screen_width: int
    screen_height: int
    execution_time_ms: float
    raw_response: Optional[str] = None
    error_message: Optional[str] = None


class VisionParser:
    """
    Core visual interpreter for legacy UI elements without API access.
    Interfaces with Vision-Language Models (OpenAI, Anthropic, or local endpoints)
    to perform visual UI grounding and coordinate translation.
    """

    SYSTEM_PROMPT = """
You are a high-precision Computer Vision Agent specialized in Legacy Enterprise Desktop GUI Grounding (Win32, SAP GUI, Visual Basic, Java Swing, Mainframe Terminals, Access, legacy web).
Your role is to visually identify controls, buttons, grid cells, tabs, dialogs, and text boxes from the provided screenshot.

Output coordinate format:
- All bounding boxes MUST be normalized integers on a scale of [0 to 1000] for both X and Y.
- ymin: 0 (top of image) to 1000 (bottom of image)
- xmin: 0 (left of image) to 1000 (right of image)
- ymax: 0 to 1000
- xmax: 0 to 1000

Interactive dry-run simulator

Select a test scenario and trigger a deterministic dry-run execution across the node topology to inspect real-time logs, compute metrics, and final output payloads.

03 · LIVE DETERMINISTIC DRY-RUN SIMULATOR
Step Through Topology Nodes & Stream Execution Telemetry

Choose a payload scenario below or click "Run Dry-Run Simulation" to step through the pipeline stages and inspect the resulting JSON output contract.

SELECT TEST SCENARIO:
NODE 01 · DPI Screen GrabNODE 02 · Vision GrounderNODE 03 · Bounds ValidatorNODE 04 · OS Input DriverNODE 05 · Closed-Loop DiffNODE 06 · Audit Annotator
// TIMESTAMPED EXECUTION TRACE TASK COMPLETED (4/4 STEPS) ✓
[00:00.014] CAPTURE: Grabbed 2560x1440 frame (Win32 DPI scaling factor: 1.50x locked) [00:00.904] VISION: Grounded button 'Export Ledger CSV' at norm_box=[412, 780, 448, 890] (conf=0.96) [00:00.906] DENORM: Projected 0-1000 box center (835, 430) -> physical pixel (2138, 619) [00:01.086] OS_DRIVER: Dispatched left_click at (2138, 619) + hotkey('ctrl', 's') [00:01.121] VERIFY: Post-action frame delta=18.4% (Save dialog detected) -> Step verified! [00:01.133] AUDIT: Saved annotated crosshair artifact step_01_click.png

By locking Win32 per-monitor DPI awareness and projecting from a resolution-independent 0-1000 grid, clicks land dead-center on 4K 150%-scaled legacy controls.

FINAL OUTPUT PAYLOAD CONTRACT SCHEMA VALIDATED ✓
{
  "task": "Export monthly ledger CSV from legacy ERP client",
  "status": "COMPLETED",
  "dpi_scaling_factor": 1.5,
  "resolution": "2560x1440",
  "last_step": {
    "action_type": "click",
    "element_label": "Export Ledger CSV",
    "normalized_box": {"ymin": 412, "xmin": 780, "ymax": 448, "xmax": 890},
    "pixel_center": [2138, 619],
    "confidence": 0.96,
    "post_action_verified": true
  }
}
TOTAL LATENCY 1,133 ms per step
COMPUTE / TOKENS 2560x1440 frame + 420 tokens/step
ESTIMATED RUN COST $0.00068 USD total run
EXECUTION MODE Deterministic Self-Hosted

Production resilience & edge-case handling

Every production system is defined by how it behaves when upstream dependencies fail, rate-limits trigger, or malformed payloads arrive at the boundary.

01 · DPI-INVARIANT 0-1000 GRID

Zero Resolution or Scaling Drift

All Vision LLM bounding boxes use a strict 0..1000 scale and are projected onto physical monitor dimensions after locking Win32 Per-Monitor DPI awareness.

02 · CLOSED-LOOP FRAME VERIFICATION

Never Assumes a Click Succeeded

Compares pre-action and post-action screen buffers after every input. If the UI did not mutate, the runner triggers automatic re-grounding instead of cascading errors.

03 · HARDWARE FAIL-SAFE & BOUNDS

Confidence Thresholds & Kill-Switch

Enforces confidence ≥ 0.75, validates ymax ≥ ymin via Pydantic, and aborts within 10ms if the mouse enters the top-left (0,0) corner.

PRODUCTION PITFALL

Windows 150% DPI scaling silently shifts click coordinates by 33%

On modern 4K laptops, Windows defaults to 150% display scaling. Standard Python screenshot libraries return physical pixels (3840x2160) while mouse APIs operate in logical pixels (2560x1440)—causing every click to miss by hundreds of pixels.

I wired ctypes.windll.shcore.SetProcessDpiAwareness(2) at process boot and normalized all Vision LLM coordinates to a 0–1000 canvas before projecting to physical monitor bounds.

FIX 100% pixel-accurate targeting across 100%, 125%, 150%, and 200% DPI monitors.

ARCHITECTURAL DECISION

Visual crosshair artifacts for every single step

When an unattended desktop automation fails at 3 AM, text logs saying Clicked (840, 520) are useless without knowing what was actually on screen at that millisecond.

Every step renders the exact bounding box and red target crosshair onto a copy of the screenshot buffer, creating an instant visual black-box flight recorder.

TRADE-OFF 12ms of Pillow drawing overhead per step in exchange for instant visual root-cause debugging.

Stack & specifications

  • Python 3.11+ & Pydantic v2: Strict coordinate bounding-box validation and state machine
  • Multimodal Vision LLM (Gemini Vision): 0–1000 spatial grounding and semantic UI classification
  • Win32 API / PyAutoGUI / Xvfb: DPI-aware hardware input controller & headless virtual display
  • Pillow (PIL): Real-time bounding-box annotation and perceptual frame comparison

Architectural takeaway

UI automation breaks when you trust open-loop coordinates. Pairing resolution-independent 0–1000 visual grounding with closed-loop frame verification makes legacy GUIs as programmable as a REST API.