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.

Remove pyautogui in favor of pynput

Dillon DuPontfa2c40371b81
diff --git a/libs/python/computer-server/computer_server/diorama/diorama.py b/libs/python/computer-server/computer_server/diorama/diorama.py
index 3a63b0b6d8..e26f82959f 100644
--- a/libs/python/computer-server/computer_server/diorama/diorama.py
+++ b/libs/python/computer-server/computer_server/diorama/diorama.py
@@ -466,8 +466,8 @@ class Diorama:
return tx, ty
return x, y
-import pyautogui
import time
+from pynput.mouse import Controller as MouseController
async def main():
"""Main function demonstrating Diorama usage with multiple desktops and mouse tracking."""
@@ -502,8 +502,10 @@ async def main():
last_mouse_pos = None
print("Tracking mouse... Press Ctrl+C to stop.")
try:
+ mouse = MouseController()
while True:
- mouse_x, mouse_y = pyautogui.position()
+ mx, my = mouse.position
+ mouse_x, mouse_y = int(mx), int(my)
if last_mouse_pos != (mouse_x, mouse_y):
last_mouse_pos = (mouse_x, mouse_y)
# Map to screenshot coordinates
diff --git a/libs/python/computer-server/computer_server/handlers/linux.py b/libs/python/computer-server/computer_server/handlers/linux.py
index eb8ca7b8be..3304858752 100644
--- a/libs/python/computer-server/computer_server/handlers/linux.py
+++ b/libs/python/computer-server/computer_server/handlers/linux.py
@@ -1,8 +1,8 @@
"""
Linux implementation of automation and accessibility handlers.
-This implementation attempts to use pyautogui for GUI automation when available.
-If running in a headless environment without X11, it will fall back to simulated responses.
+This implementation uses pynput for GUI automation. For screenshots and screen size,
+it uses PIL's ImageGrab (works with X11/Xvfb) and provides simulated fallbacks where needed.
To use GUI automation in a headless environment:
1. Install Xvfb: sudo apt-get install xvfb
2. Run with virtual display: xvfb-run python -m computer_server
@@ -15,19 +15,12 @@ import base64
import os
import json
from io import BytesIO
+from PIL import ImageGrab, Image
# Configure logger
logger = logging.getLogger(__name__)
-# Try to import pyautogui, but don't fail if it's not available
-# This allows the server to run in headless environments
-try:
- import pyautogui
- pyautogui.FAILSAFE = False
-
- logger.info("pyautogui successfully imported, GUI automation available")
-except Exception as e:
- logger.warning(f"pyautogui import failed: {str(e)}. GUI operations will be simulated.")
+# pyautogui removed in favor of pynput
from pynput.mouse import Button, Controller as MouseController
from pynput.keyboard import Key, Controller as KeyboardController
@@ -85,13 +78,15 @@ class LinuxAccessibilityHandler(BaseAccessibilityHandler):
Returns (0, 0) if pyautogui is not available.
"""
try:
- pos = pyautogui.position()
- return pos.x, pos.y
+ # Use pynput mouse controller
+ from pynput.mouse import Controller as MouseController
+ m = MouseController()
+ x, y = m.position
+ return int(x), int(y)
except Exception as e:
- logger.warning(f"Failed to get cursor position with pyautogui: {e}")
-
- logger.info("Getting cursor position (simulated)")
- return 0, 0
+ logger.warning(f"Failed to get cursor position: {e}")
+ logger.info("Getting cursor position (simulated)")
+ return 0, 0
def get_screen_size(self) -> Tuple[int, int]:
"""Get the screen size.
@@ -101,16 +96,15 @@ class LinuxAccessibilityHandler(BaseAccessibilityHandler):
Returns (1920, 1080) if pyautogui is not available.
"""
try:
- size = pyautogui.size()
- return size.width, size.height
+ img = ImageGrab.grab()
+ return img.width, img.height
except Exception as e:
- logger.warning(f"Failed to get screen size with pyautogui: {e}")
-
- logger.info("Getting screen size (simulated)")
- return 1920, 1080
+ logger.warning(f"Failed to get screen size via ImageGrab: {e}")
+ logger.info("Getting screen size (simulated)")
+ return 1920, 1080
class LinuxAutomationHandler(BaseAutomationHandler):
- """Linux implementation of automation handler using pyautogui."""
+ """Linux implementation of automation handler using pynput."""
keyboard = KeyboardController()
mouse = MouseController()
@@ -128,8 +122,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):
"""
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.mouseDown(button=button)
+ self.mouse.position = (x, y)
+ from pynput.mouse import Button
+ btn = getattr(Button, button if button in ["left","right","middle"] else "left")
+ self.mouse.press(btn)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -147,8 +143,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):
"""
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.mouseUp(button=button)
+ self.mouse.position = (x, y)
+ from pynput.mouse import Button
+ btn = getattr(Button, button if button in ["left","right","middle"] else "left")
+ self.mouse.release(btn)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -164,7 +162,7 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.moveTo(x, y)
+ self.mouse.position = (x, y)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -180,9 +178,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
+ from pynput.mouse import Button
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.click()
+ self.mouse.position = (x, y)
+ self.mouse.click(Button.left, 1)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -198,9 +197,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
+ from pynput.mouse import Button
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.rightClick()
+ self.mouse.position = (x, y)
+ self.mouse.click(Button.right, 1)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -216,9 +216,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
+ from pynput.mouse import Button
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.doubleClick(interval=0.1)
+ self.mouse.position = (x, y)
+ self.mouse.click(Button.left, 2)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -235,9 +236,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
+ from pynput.mouse import Button
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.click(button=button)
+ self.mouse.position = (x, y)
+ btn = getattr(Button, button if button in ["left","right","middle"] else "left")
+ self.mouse.click(btn, 1)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -255,7 +258,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.dragTo(x, y, duration=duration, button=button)
+ from pynput.mouse import Button
+ btn = getattr(Button, button if button in ["left","right","middle"] else "left")
+ self.mouse.press(btn)
+ self.mouse.position = (x, y)
+ self.mouse.release(btn)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -274,8 +281,12 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.moveTo(start_x, start_y)
- pyautogui.dragTo(end_x, end_y, duration=0.5, button=button)
+ from pynput.mouse import Button
+ btn = getattr(Button, button if button in ["left","right","middle"] else "left")
+ self.mouse.position = (start_x, start_y)
+ self.mouse.press(btn)
+ self.mouse.position = (end_x, end_y)
+ self.mouse.release(btn)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -292,11 +303,15 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
+ from pynput.mouse import Button
if not path:
return {"success": False, "error": "Path is empty"}
- pyautogui.moveTo(*path[0])
+ btn = getattr(Button, button if button in ["left","right","middle"] else "left")
+ self.mouse.position = path[0]
for x, y in path[1:]:
- pyautogui.dragTo(x, y, duration=duration, button=button)
+ self.mouse.press(btn)
+ self.mouse.position = (x, y)
+ self.mouse.release(btn)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -312,7 +327,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.keyDown(key)
+ from pynput.keyboard import Key
+ k = getattr(Key, key) if hasattr(Key, key) else (key if len(key) == 1 else None)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.press(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -327,7 +346,11 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.keyUp(key)
+ from pynput.keyboard import Key
+ k = getattr(Key, key) if hasattr(Key, key) else (key if len(key) == 1 else None)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -358,7 +381,12 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.press(key)
+ from pynput.keyboard import Key
+ k = getattr(Key, key) if hasattr(Key, key) else (key if len(key) == 1 else None)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.press(k)
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -373,7 +401,20 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.hotkey(*keys)
+ from pynput.keyboard import Key
+ seq = []
+ for k in keys:
+ kk = getattr(Key, k) if hasattr(Key, k) else (k if len(k) == 1 else None)
+ if kk is None:
+ return {"success": False, "error": f"Unknown key in hotkey: {k}"}
+ seq.append(kk)
+ for k in seq[:-1]:
+ self.keyboard.press(k)
+ last = seq[-1]
+ self.keyboard.press(last)
+ self.keyboard.release(last)
+ for k in reversed(seq[:-1]):
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -405,7 +446,7 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.scroll(-clicks)
+ self.mouse.scroll(0, -abs(clicks))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -420,7 +461,7 @@ class LinuxAutomationHandler(BaseAutomationHandler):
Dict[str, Any]: A dictionary with success status and error message if failed.
"""
try:
- pyautogui.scroll(clicks)
+ self.mouse.scroll(0, abs(clicks))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -434,8 +475,7 @@ class LinuxAutomationHandler(BaseAutomationHandler):
or error message if failed.
"""
try:
- from PIL import Image
- screenshot = pyautogui.screenshot()
+ screenshot = ImageGrab.grab()
if not isinstance(screenshot, Image.Image):
return {"success": False, "error": "Failed to capture screenshot"}
buffered = BytesIO()
@@ -454,8 +494,8 @@ class LinuxAutomationHandler(BaseAutomationHandler):
or error message if failed.
"""
try:
- size = pyautogui.size()
- return {"success": True, "size": {"width": size.width, "height": size.height}}
+ img = ImageGrab.grab()
+ return {"success": True, "size": {"width": img.width, "height": img.height}}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -467,8 +507,10 @@ class LinuxAutomationHandler(BaseAutomationHandler):
or error message if failed.
"""
try:
- pos = pyautogui.position()
- return {"success": True, "position": {"x": pos.x, "y": pos.y}}
+ from pynput.mouse import Controller as MouseController
+ m = MouseController()
+ x, y = m.position
+ return {"success": True, "position": {"x": int(x), "y": int(y)}}
except Exception as e:
return {"success": False, "error": str(e)}
diff --git a/libs/python/computer-server/computer_server/handlers/macos.py b/libs/python/computer-server/computer_server/handlers/macos.py
index e23b8ea65a..8f4008cd88 100644
--- a/libs/python/computer-server/computer_server/handlers/macos.py
+++ b/libs/python/computer-server/computer_server/handlers/macos.py
@@ -1,7 +1,6 @@
-import pyautogui
-pyautogui.FAILSAFE = False
from pynput.mouse import Button, Controller as MouseController
from pynput.keyboard import Key, Controller as KeyboardController
+from PIL import ImageGrab, Image
import time
import base64
from io import BytesIO
@@ -664,8 +663,10 @@ def get_dock_items():
item_type = "document"
elif subrole == "AXSeparatorDockItem" or role == "AXSeparator":
item_type = "separator"
- elif "trash" in title.lower():
- item_type = "trash"
+ else:
+ title_str = title if isinstance(title, str) else str(title)
+ if "trash" in title_str.lower():
+ item_type = "trash"
dock_items.append({
"title": title,
"description": description,
@@ -1116,14 +1117,16 @@ class MacOSAutomationHandler(BaseAutomationHandler):
"""Press and hold a keyboard key.
Args:
- key: Key name to press (using pyautogui key names)
-
+ key: Key name to press
+
Returns:
Dictionary containing success status and error message if failed
"""
try:
- # use pyautogui for their key names
- pyautogui.keyDown(key)
+ k = getattr(Key, key) if hasattr(Key, key) else (key if len(key) == 1 else None)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.press(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -1132,14 +1135,16 @@ class MacOSAutomationHandler(BaseAutomationHandler):
"""Release a keyboard key.
Args:
- key: Key name to release (using pyautogui key names)
-
+ key: Key name to release
+
Returns:
Dictionary containing success status and error message if failed
"""
try:
- # use pyautogui for their key names
- pyautogui.keyUp(key)
+ k = getattr(Key, key) if hasattr(Key, key) else (key if len(key) == 1 else None)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -1149,12 +1154,11 @@ class MacOSAutomationHandler(BaseAutomationHandler):
Args:
text: Text string to type
-
+
Returns:
Dictionary containing success status and error message if failed
"""
try:
- # use pynput for Unicode support
self.keyboard.type(text)
return {"success": True}
except Exception as e:
@@ -1164,14 +1168,17 @@ class MacOSAutomationHandler(BaseAutomationHandler):
"""Press and release a keyboard key.
Args:
- key: Key name to press (using pyautogui key names)
-
+ key: Key name to press
+
Returns:
Dictionary containing success status and error message if failed
"""
try:
- # use pyautogui for their key names
- pyautogui.press(key)
+ k = getattr(Key, key) if hasattr(Key, key) else (key if len(key) == 1 else None)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.press(k)
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -1180,14 +1187,25 @@ class MacOSAutomationHandler(BaseAutomationHandler):
"""Press a combination of keys simultaneously.
Args:
- keys: List of key names to press together (using pyautogui key names)
-
+ keys: List of key names to press together
+
Returns:
Dictionary containing success status and error message if failed
"""
try:
- # use pyautogui for their key names
- pyautogui.hotkey(*keys)
+ seq = []
+ for k in keys:
+ kk = getattr(Key, k) if hasattr(Key, k) else (k if len(k) == 1 else None)
+ if kk is None:
+ return {"success": False, "error": f"Unknown key in hotkey: {k}"}
+ seq.append(kk)
+ for k in seq[:-1]:
+ self.keyboard.press(k)
+ last = seq[-1]
+ self.keyboard.press(last)
+ self.keyboard.release(last)
+ for k in reversed(seq[:-1]):
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -1199,7 +1217,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):
Args:
x: Horizontal scroll amount
y: Vertical scroll amount (positive for up, negative for down)
-
+
Returns:
Dictionary containing success status and error message if failed
"""
@@ -1214,7 +1232,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):
Args:
clicks: Number of scroll clicks to perform
-
+
Returns:
Dictionary containing success status and error message if failed
"""
@@ -1229,7 +1247,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):
Args:
clicks: Number of scroll clicks to perform
-
+
Returns:
Dictionary containing success status and error message if failed
"""
@@ -1247,9 +1265,7 @@ class MacOSAutomationHandler(BaseAutomationHandler):
Dictionary containing success status and base64-encoded image data or error message
"""
try:
- from PIL import Image
-
- screenshot = pyautogui.screenshot()
+ screenshot = ImageGrab.grab()
if not isinstance(screenshot, Image.Image):
return {"success": False, "error": "Failed to capture screenshot"}
@@ -1268,8 +1284,8 @@ class MacOSAutomationHandler(BaseAutomationHandler):
Dictionary containing success status and screen size or error message
"""
try:
- size = pyautogui.size()
- return {"success": True, "size": {"width": size.width, "height": size.height}}
+ img = ImageGrab.grab()
+ return {"success": True, "size": {"width": img.width, "height": img.height}}
except Exception as e:
return {"success": False, "error": str(e)}
diff --git a/libs/python/computer-server/computer_server/handlers/windows.py b/libs/python/computer-server/computer_server/handlers/windows.py
index 216a9f8b57..523e6398f4 100644
--- a/libs/python/computer-server/computer_server/handlers/windows.py
+++ b/libs/python/computer-server/computer_server/handlers/windows.py
@@ -1,7 +1,7 @@
"""
Windows implementation of automation and accessibility handlers.
-This implementation uses pyautogui for GUI automation and Windows-specific APIs
+This implementation uses pynput for GUI automation and Windows-specific APIs
for accessibility and system operations.
"""
from typing import Dict, Any, List, Tuple, Optional
@@ -11,20 +11,15 @@ import asyncio
import base64
import os
from io import BytesIO
-from pynput.mouse import Controller as MouseController
-from pynput.keyboard import Controller as KeyboardController
+from pynput.mouse import Controller as MouseController, Button as MouseButton
+from pynput.keyboard import Controller as KeyboardController, Key as KBKey
+from typing import Union, List as _List
+from PIL import ImageGrab, Image
# Configure logger
logger = logging.getLogger(__name__)
-# Try to import pyautogui
-try:
- import pyautogui
- pyautogui.FAILSAFE = False
- logger.info("pyautogui successfully imported, GUI automation available")
-except Exception as e:
- logger.error(f"pyautogui import failed: {str(e)}. GUI operations will not work.")
- pyautogui = None
+# pyautogui removed in favor of pynput
# Try to import Windows-specific modules
try:
@@ -166,9 +161,63 @@ class WindowsAccessibilityHandler(BaseAccessibilityHandler):
return {"success": False, "error": str(e)}
class WindowsAutomationHandler(BaseAutomationHandler):
- """Windows implementation of automation handler using pyautogui and Windows APIs."""
+ """Windows implementation of automation handler using pynput and Windows APIs."""
mouse = MouseController()
+ keyboard = KeyboardController()
+
+ def _map_button(self, button: str) -> MouseButton:
+ """Map a string button name to pynput MouseButton."""
+ b = (button or "left").lower()
+ if b == "left":
+ return MouseButton.left
+ if b == "right":
+ return MouseButton.right
+ if b == "middle":
+ return MouseButton.middle
+ # default to left
+ return MouseButton.left
+
+ def _key_from_string(self, key: str):
+ """Convert a key string (e.g., 'enter', 'ctrl', 'a') to pynput Key or char."""
+ if not key:
+ return None
+ lk = key.lower()
+ special = {
+ "enter": KBKey.enter,
+ "return": KBKey.enter,
+ "esc": KBKey.esc,
+ "escape": KBKey.esc,
+ "space": KBKey.space,
+ "tab": KBKey.tab,
+ "backspace": KBKey.backspace,
+ "delete": KBKey.delete,
+ "home": KBKey.home,
+ "end": KBKey.end,
+ "pageup": KBKey.page_up,
+ "pagedown": KBKey.page_down,
+ "up": KBKey.up,
+ "down": KBKey.down,
+ "left": KBKey.left,
+ "right": KBKey.right,
+ "shift": KBKey.shift,
+ "ctrl": KBKey.ctrl,
+ "control": KBKey.ctrl,
+ "alt": KBKey.alt,
+ "cmd": KBKey.cmd,
+ "win": KBKey.cmd,
+ "meta": KBKey.cmd,
+ "capslock": KBKey.caps_lock,
+ "f1": KBKey.f1, "f2": KBKey.f2, "f3": KBKey.f3, "f4": KBKey.f4,
+ "f5": KBKey.f5, "f6": KBKey.f6, "f7": KBKey.f7, "f8": KBKey.f8,
+ "f9": KBKey.f9, "f10": KBKey.f10, "f11": KBKey.f11, "f12": KBKey.f12,
+ }
+ if lk in special:
+ return special[lk]
+ # single character
+ if len(key) == 1:
+ return key
+ return None
# Mouse Actions
async def mouse_down(self, x: Optional[int] = None, y: Optional[int] = None, button: str = "left") -> Dict[str, Any]:
@@ -182,13 +231,10 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.mouseDown(button=button)
+ self.mouse.position = (x, y)
+ self.mouse.press(self._map_button(button))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -204,13 +250,10 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.mouseUp(button=button)
+ self.mouse.position = (x, y)
+ self.mouse.release(self._map_button(button))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -225,11 +268,8 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.moveTo(x, y)
+ self.mouse.position = (x, y)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -244,13 +284,10 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.click()
+ self.mouse.position = (x, y)
+ self.mouse.click(MouseButton.left, 1)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -265,13 +302,10 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.rightClick()
+ self.mouse.position = (x, y)
+ self.mouse.click(MouseButton.right, 1)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -286,13 +320,10 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
if x is not None and y is not None:
- pyautogui.moveTo(x, y)
- pyautogui.doubleClick(interval=0.1)
+ self.mouse.position = (x, y)
+ self.mouse.click(MouseButton.left, 2)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -309,11 +340,11 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.dragTo(x, y, duration=duration, button=button)
+ # simple drag implementation
+ self.mouse.press(self._map_button(button))
+ self.mouse.position = (x, y)
+ self.mouse.release(self._map_button(button))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -329,19 +360,18 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
if not path:
return {"success": False, "error": "Path is empty"}
# Move to first position
- pyautogui.moveTo(*path[0])
+ self.mouse.position = path[0]
# Drag through all positions
for x, y in path[1:]:
- pyautogui.dragTo(x, y, duration=duration/len(path), button=button)
+ self.mouse.press(self._map_button(button))
+ self.mouse.position = (x, y)
+ self.mouse.release(self._map_button(button))
return {"success": True}
except Exception as e:
@@ -357,11 +387,11 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.keyDown(key)
+ k = self._key_from_string(key)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.press(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -375,11 +405,11 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.keyUp(key)
+ k = self._key_from_string(key)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -393,11 +423,8 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.write(text)
+ self.keyboard.type(text)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -411,11 +438,12 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.press(key)
+ k = self._key_from_string(key)
+ if k is None:
+ return {"success": False, "error": f"Unknown key: {key}"}
+ self.keyboard.press(k)
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -429,11 +457,24 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.hotkey(*keys)
+ # press keys sequentially while holding modifiers
+ resolved = [self._key_from_string(k) for k in keys]
+ if any(k is None for k in resolved):
+ return {"success": False, "error": "Unknown key in hotkey sequence"}
+ seq: _List[Union[str, KBKey]] = [k for k in resolved if k is not None] # type: ignore[assignment]
+ if not seq:
+ return {"success": False, "error": "Empty hotkey sequence"}
+ # hold all except the last
+ for k in seq[:-1]:
+ self.keyboard.press(k)
+ # tap last
+ last = seq[-1]
+ self.keyboard.press(last)
+ self.keyboard.release(last)
+ # release modifiers
+ for k in reversed(seq[:-1]):
+ self.keyboard.release(k)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -449,9 +490,6 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
self.mouse.scroll(x, y)
return {"success": True}
@@ -467,11 +505,9 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.scroll(-clicks)
+ # negative y to scroll down
+ self.mouse.scroll(0, -abs(clicks))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -485,11 +521,8 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Returns:
Dict[str, Any]: A dictionary with success status and optional error message.
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- pyautogui.scroll(clicks)
+ self.mouse.scroll(0, abs(clicks))
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -504,15 +537,11 @@ class WindowsAutomationHandler(BaseAutomationHandler):
Structure: {"success": bool, "image_data": str} or
{"success": bool, "error": str}
"""
- if not pyautogui:
- return {"success": False, "error": "pyautogui not available"}
-
try:
- from PIL import Image
- screenshot = pyautogui.screenshot()
+ screenshot = ImageGrab.grab()
if not isinstance(screenshot, Image.Image):
return {"success": False, "error": "Failed to capture screenshot"}
-
+
buffered = BytesIO()
screenshot.save(buffered, format="PNG", optimize=True)
buffered.seek(0)
@@ -531,16 +560,14 @@ class WindowsAutomationHandler(BaseAutomationHandler):
{"success": bool, "error": str}
"""
try:
- if pyautogui:
- size = pyautogui.size()
- return {"success": True, "size": {"width": size.width, "height": size.height}}
- elif WINDOWS_API_AVAILABLE:
- # Fallback to Windows API
+ if WINDOWS_API_AVAILABLE:
width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
return {"success": True, "size": {"width": width, "height": height}}
else:
- return {"success": False, "error": "No screen size detection method available"}
+ # Fallback: use ImageGrab
+ img = ImageGrab.grab()
+ return {"success": True, "size": {"width": img.width, "height": img.height}}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -554,15 +581,13 @@ class WindowsAutomationHandler(BaseAutomationHandler):
{"success": bool, "error": str}
"""
try:
- if pyautogui:
- pos = pyautogui.position()
- return {"success": True, "position": {"x": pos.x, "y": pos.y}}
- elif WINDOWS_API_AVAILABLE:
- # Fallback to Windows API
+ if WINDOWS_API_AVAILABLE:
pos = win32gui.GetCursorPos()
return {"success": True, "position": {"x": pos[0], "y": pos[1]}}
else:
- return {"success": False, "error": "No cursor position detection method available"}
+ # Fallback: use pynput controller
+ x, y = self.mouse.position
+ return {"success": True, "position": {"x": int(x), "y": int(y)}}
except Exception as e:
return {"success": False, "error": str(e)}
diff --git a/libs/python/computer-server/pyproject.toml b/libs/python/computer-server/pyproject.toml
index 6468a48ddf..ad4d24185e 100644
--- a/libs/python/computer-server/pyproject.toml
+++ b/libs/python/computer-server/pyproject.toml
@@ -17,7 +17,6 @@ dependencies = [
"fastapi>=0.111.0",
"uvicorn[standard]>=0.27.0",
"pydantic>=2.0.0",
- "pyautogui>=0.9.54",
"pynput>=1.8.1",
"pillow>=10.2.0",
"aiohttp>=3.9.1",