Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

virtual desktop abstraction

Dillon DuPontb5a87f830cf1
diff --git a/notebooks/diorama/diorama.py b/notebooks/diorama/diorama.py
new file mode 100644
index 0000000000..5b0a41b373
--- /dev/null
+++ b/notebooks/diorama/diorama.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python3
+"""Diorama: A virtual desktop manager for macOS"""
+
+import asyncio
+import logging
+import sys
+
+from draw import capture_all_apps
+
+# simple, nicely formatted logging
+logging.basicConfig(
+ level=logging.INFO,
+ format='[%(asctime)s] [%(levelname)s] %(message)s',
+ datefmt='%H:%M:%S',
+ stream=sys.stdout
+)
+logger = logging.getLogger("diorama.virtual_desktop")
+
+class Diorama:
+ _scheduler_queue = None
+ _scheduler_task = None
+ _loop = None
+ _scheduler_started = False
+
+ def __init__(self, app_list):
+ self.app_list = app_list
+ self.interface = self.Interface(self)
+
+ @classmethod
+ def _ensure_scheduler(cls):
+ if not cls._scheduler_started:
+ logger.info("Starting Diorama scheduler loop…")
+ cls._scheduler_queue = asyncio.Queue()
+ cls._loop = asyncio.get_event_loop()
+ cls._scheduler_task = cls._loop.create_task(cls._scheduler_loop())
+ cls._scheduler_started = True
+
+ @classmethod
+ async def _scheduler_loop(cls):
+ while True:
+ cmd = await cls._scheduler_queue.get()
+ action = cmd.get("action")
+ args = cmd.get("arguments", {})
+ future = cmd.get("future")
+ logger.info(f"Processing command: {action} | args={args}")
+ if action == "screenshot":
+ try:
+ app_whitelist = list(args["app_list"]) + ["Window Server", "Dock"]
+ logger.info(f"Taking screenshot for apps: {app_whitelist}")
+ result, img = capture_all_apps(
+ save_to_disk=args.get("save_to_disk", False),
+ app_whitelist=app_whitelist,
+ output_dir=args.get("output_dir"),
+ take_focus=args.get("take_focus", True)
+ )
+ logger.info("Screenshot complete.")
+ if future:
+ future.set_result((result, img))
+ except Exception as e:
+ logger.error(f"Exception during screenshot: {e}", exc_info=True)
+ if future:
+ future.set_exception(e)
+ else:
+ logger.warning(f"Unknown action: {action}")
+ if future:
+ future.set_exception(ValueError(f"Unknown action: {action}"))
+
+ @classmethod
+ def create_from_apps(cls, app_list):
+ cls._ensure_scheduler()
+ return cls(app_list)
+
+ class Interface:
+ def __init__(self, diorama):
+ self._diorama = diorama
+
+ async def screenshot(self, save_to_disk=False, output_dir=None, take_focus=True):
+ Diorama._ensure_scheduler()
+ loop = asyncio.get_event_loop()
+ future = loop.create_future()
+ logger.info(f"Enqueuing screenshot command for apps: {self._diorama.app_list}")
+ await Diorama._scheduler_queue.put({
+ "action": "screenshot",
+ "arguments": {
+ "app_list": self._diorama.app_list,
+ "save_to_disk": save_to_disk,
+ "output_dir": output_dir,
+ "take_focus": take_focus
+ },
+ "future": future
+ })
+ return await future
+
+async def main():
+ desktop1 = Diorama.create_from_apps(["Discord", "Notes"])
+ desktop2 = Diorama.create_from_apps(["Google Chrome"])
+ await desktop1.interface.screenshot()
+ await desktop2.interface.screenshot()
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/notebooks/diorama/draw.py b/notebooks/diorama/draw.py
index fe7207f67c..4592b7b0cb 100644
--- a/notebooks/diorama/draw.py
+++ b/notebooks/diorama/draw.py
@@ -25,6 +25,17 @@ from PIL import Image, ImageDraw
import io
import asyncio
import functools
+import logging
+
+# simple, nicely formatted logging
+logging.basicConfig(
+ level=logging.INFO,
+ format='[%(asctime)s] [%(levelname)s] %(message)s',
+ datefmt='%H:%M:%S',
+ stream=sys.stdout
+)
+logger = logging.getLogger("diorama.draw")
+
from safezone import (
get_menubar_bounds,
@@ -39,7 +50,7 @@ def timing_decorator(func):
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
- print(f"Function {func.__name__} took {elapsed_time:.4f} seconds to run")
+ logger.debug(f"Function {func.__name__} took {elapsed_time:.4f} seconds to run")
return result
return wrapper
@@ -82,8 +93,8 @@ try:
from Foundation import NSObject, NSMakeRect
import objc
except ImportError:
- print("Error: This script requires PyObjC to be installed.")
- print("Please install it with: pip install pyobjc")
+ logger.error("Error: This script requires PyObjC to be installed.")
+ logger.error("Please install it with: pip install pyobjc")
sys.exit(1)
# Constants for accessibility API
@@ -586,25 +597,25 @@ def get_menubar_items(active_app_pid: int = None) -> List[Dict[str, Any]]:
if frontmost_app:
active_app_pid = frontmost_app.processIdentifier()
else:
- print("Error: Could not determine frontmost application")
+ logger.error("Error: Could not determine frontmost application")
return menubar_items
# Create an accessibility element for the application
app_element = AXUIElementCreateApplication(active_app_pid)
if app_element is None:
- print(f"Error: Could not create accessibility element for PID {active_app_pid}")
+ logger.error(f"Error: Could not create accessibility element for PID {active_app_pid}")
return menubar_items
# Get the menubar
menubar = element_attribute(app_element, kAXMenuBarAttribute)
if menubar is None:
- print(f"Error: Could not get menubar for application with PID {active_app_pid}")
+ logger.error(f"Error: Could not get menubar for application with PID {active_app_pid}")
return menubar_items
# Get the menubar items
children = element_attribute(menubar, kAXChildrenAttribute)
if children is None:
- print("Error: Could not get menubar items")
+ logger.error("Error: Could not get menubar items")
return menubar_items
# Process each menubar item
@@ -665,19 +676,19 @@ def get_dock_items() -> List[Dict[str, Any]]:
break
if dock_pid is None:
- print("Error: Could not find Dock process")
+ logger.error("Error: Could not find Dock process")
return dock_items
# Create an accessibility element for the Dock
dock_element = AXUIElementCreateApplication(dock_pid)
if dock_element is None:
- print(f"Error: Could not create accessibility element for Dock (PID {dock_pid})")
+ logger.error(f"Error: Could not create accessibility element for Dock (PID {dock_pid})")
return dock_items
# Get the Dock's main element
dock_list = element_attribute(dock_element, kAXChildrenAttribute)
if dock_list is None or len(dock_list) == 0:
- print("Error: Could not get Dock children")
+ logger.error("Error: Could not get Dock children")
return dock_items
# Find the Dock's application list (usually the first child)
@@ -689,13 +700,13 @@ def get_dock_items() -> List[Dict[str, Any]]:
break
if dock_app_list is None:
- print("Error: Could not find Dock application list")
+ logger.error("Error: Could not find Dock application list")
return dock_items
# Get all items in the Dock
items = element_attribute(dock_app_list, kAXChildrenAttribute)
if items is None:
- print("Error: Could not get Dock items")
+ logger.error("Error: Could not get Dock items")
return dock_items
# Process each Dock item
@@ -822,7 +833,7 @@ def capture_all_apps(save_to_disk: bool = False, app_whitelist: List[str] = None
# Activate the selected application
if active_app_pid:
- print(f"Automatically activating app '{active_app_to_use}' for screenshot composition")
+ logger.debug(f"Automatically activating app '{active_app_to_use}' for screenshot composition")
# Get all running applications
running_apps_list = NSWorkspace.sharedWorkspace().runningApplications()