Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- osworld_plugin/README.md +105 -0
- osworld_plugin/__pycache__/main.cpython-312.pyc +3 -0
- osworld_plugin/main.py +1852 -0
- osworld_plugin/update_qcow2.sh +100 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 60 |
ubuntu.qcow2 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 60 |
ubuntu.qcow2 filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
osworld_plugin/__pycache__/main.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
osworld_plugin/README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OSWorld Plugin
|
| 2 |
+
|
| 3 |
+
This directory contains customized OSWorld server components and deployment scripts.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
|
| 7 |
+
- `main.py` - Modified OSWorld Flask server with performance optimizations
|
| 8 |
+
- `update_qcow2.sh` - Script to update main.py in the QCOW2 VM image
|
| 9 |
+
|
| 10 |
+
## Key Optimizations
|
| 11 |
+
|
| 12 |
+
### `/pyautogui` Endpoint (NEW)
|
| 13 |
+
|
| 14 |
+
A new endpoint that executes pyautogui code directly in the Flask process, avoiding the overhead of spawning a new Python process for each action.
|
| 15 |
+
|
| 16 |
+
**Before (slow):**
|
| 17 |
+
```
|
| 18 |
+
client β manager β OSWorld /execute β subprocess.run(["python", "-c", "import pyautogui; ..."])
|
| 19 |
+
β ~2-3 seconds per action (Python startup + pyautogui import)
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
**After (fast):**
|
| 23 |
+
```
|
| 24 |
+
client β manager β OSWorld /pyautogui β exec(code) in Flask process
|
| 25 |
+
β ~50ms per action
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
**Performance improvement:** `step_time` reduced from **8.8s to 0.9s** (89% faster)
|
| 29 |
+
|
| 30 |
+
## Usage
|
| 31 |
+
|
| 32 |
+
### Update QCOW2 Image
|
| 33 |
+
|
| 34 |
+
After modifying `main.py`, run the update script to deploy changes to the VM image:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
sudo ./update_qcow2.sh
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
**Note:** Existing running VMs will NOT be affected. You need to destroy and recreate runners to use the updated image.
|
| 41 |
+
|
| 42 |
+
### Manual Steps (if script fails)
|
| 43 |
+
|
| 44 |
+
1. Connect NBD device:
|
| 45 |
+
```bash
|
| 46 |
+
sudo modprobe nbd max_part=8
|
| 47 |
+
sudo qemu-nbd --connect=/dev/nbd0 /data/sandbox-platform/mnt/qemu-image/ubuntu.qcow2
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
2. Mount partition:
|
| 51 |
+
```bash
|
| 52 |
+
sudo mkdir -p /mnt/qcow2
|
| 53 |
+
sudo mount /dev/nbd0p3 /mnt/qcow2
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
3. Copy main.py:
|
| 57 |
+
```bash
|
| 58 |
+
sudo cp main.py /mnt/qcow2/home/user/server/main.py
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
4. Cleanup:
|
| 62 |
+
```bash
|
| 63 |
+
sudo umount /mnt/qcow2
|
| 64 |
+
sudo qemu-nbd --disconnect /dev/nbd0
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## API Reference
|
| 68 |
+
|
| 69 |
+
### POST /pyautogui
|
| 70 |
+
|
| 71 |
+
Execute pyautogui code directly in the Flask process.
|
| 72 |
+
|
| 73 |
+
**Request:**
|
| 74 |
+
```json
|
| 75 |
+
{
|
| 76 |
+
"code": "pyautogui.click(500, 300)"
|
| 77 |
+
}
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
**Response:**
|
| 81 |
+
```json
|
| 82 |
+
{
|
| 83 |
+
"status": "success",
|
| 84 |
+
"result": null
|
| 85 |
+
}
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
**Error Response:**
|
| 89 |
+
```json
|
| 90 |
+
{
|
| 91 |
+
"status": "error",
|
| 92 |
+
"message": "Error description"
|
| 93 |
+
}
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
## File Sync
|
| 97 |
+
|
| 98 |
+
The `main.py` in this directory should be kept in sync with:
|
| 99 |
+
- `third_party/OSWorld/desktop_env/server/main.py` (source of truth)
|
| 100 |
+
- QCOW2 image at `/home/user/server/main.py` (deployed version)
|
| 101 |
+
|
| 102 |
+
When making changes:
|
| 103 |
+
1. Edit `third_party/OSWorld/desktop_env/server/main.py`
|
| 104 |
+
2. Copy to this directory: `cp ../third_party/OSWorld/desktop_env/server/main.py .`
|
| 105 |
+
3. Run `sudo ./update_qcow2.sh` to deploy
|
osworld_plugin/__pycache__/main.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:73aa2e7bd91a4e77477bc27a11a5733dbcd93f5239295a315db2e601456ca747
|
| 3 |
+
size 102358
|
osworld_plugin/main.py
ADDED
|
@@ -0,0 +1,1852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ctypes
|
| 2 |
+
import os
|
| 3 |
+
import platform
|
| 4 |
+
import shlex
|
| 5 |
+
import shutil
|
| 6 |
+
import json
|
| 7 |
+
import subprocess, signal
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Optional, Sequence
|
| 11 |
+
from typing import List, Dict, Tuple, Literal
|
| 12 |
+
import concurrent.futures
|
| 13 |
+
|
| 14 |
+
import Xlib
|
| 15 |
+
import lxml.etree
|
| 16 |
+
import pyautogui
|
| 17 |
+
import requests
|
| 18 |
+
import re
|
| 19 |
+
from PIL import Image, ImageGrab
|
| 20 |
+
from Xlib import display, X
|
| 21 |
+
from flask import Flask, request, jsonify, send_file, abort # , send_from_directory
|
| 22 |
+
from lxml.etree import _Element
|
| 23 |
+
|
| 24 |
+
platform_name: str = platform.system()
|
| 25 |
+
|
| 26 |
+
if platform_name == "Linux":
|
| 27 |
+
import pyatspi
|
| 28 |
+
from pyatspi import Accessible, StateType, STATE_SHOWING
|
| 29 |
+
from pyatspi import Action as ATAction
|
| 30 |
+
from pyatspi import Component # , Document
|
| 31 |
+
from pyatspi import Text as ATText
|
| 32 |
+
from pyatspi import Value as ATValue
|
| 33 |
+
|
| 34 |
+
BaseWrapper = Any
|
| 35 |
+
|
| 36 |
+
elif platform_name == "Windows":
|
| 37 |
+
from pywinauto import Desktop
|
| 38 |
+
from pywinauto.base_wrapper import BaseWrapper
|
| 39 |
+
import pywinauto.application
|
| 40 |
+
import win32ui, win32gui
|
| 41 |
+
|
| 42 |
+
Accessible = Any
|
| 43 |
+
|
| 44 |
+
elif platform_name == "Darwin":
|
| 45 |
+
import plistlib
|
| 46 |
+
|
| 47 |
+
import AppKit
|
| 48 |
+
import ApplicationServices
|
| 49 |
+
import Foundation
|
| 50 |
+
import Quartz
|
| 51 |
+
import oa_atomacos
|
| 52 |
+
|
| 53 |
+
Accessible = Any
|
| 54 |
+
BaseWrapper = Any
|
| 55 |
+
|
| 56 |
+
else:
|
| 57 |
+
# Platform not supported
|
| 58 |
+
Accessible = None
|
| 59 |
+
BaseWrapper = Any
|
| 60 |
+
|
| 61 |
+
from pyxcursor import Xcursor
|
| 62 |
+
|
| 63 |
+
# todo: need to reformat and organize this whole file
|
| 64 |
+
|
| 65 |
+
app = Flask(__name__)
|
| 66 |
+
|
| 67 |
+
pyautogui.PAUSE = 0
|
| 68 |
+
pyautogui.DARWIN_CATCH_UP_TIME = 0
|
| 69 |
+
pyautogui.FAILSAFE = False # Disable failsafe to allow clicks at screen corners (0,0)
|
| 70 |
+
|
| 71 |
+
TIMEOUT = 1800 # seconds
|
| 72 |
+
|
| 73 |
+
logger = app.logger
|
| 74 |
+
recording_process = None # fixme: this is a temporary solution for recording, need to be changed to support multiple-process
|
| 75 |
+
recording_path = "/tmp/recording.mp4"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@app.route('/setup/execute', methods=['POST'])
|
| 79 |
+
@app.route('/execute', methods=['POST'])
|
| 80 |
+
def execute_command():
|
| 81 |
+
data = request.json
|
| 82 |
+
# The 'command' key in the JSON request should contain the command to be executed.
|
| 83 |
+
shell = data.get('shell', False)
|
| 84 |
+
command = data.get('command', "" if shell else [])
|
| 85 |
+
|
| 86 |
+
if isinstance(command, str) and not shell:
|
| 87 |
+
command = shlex.split(command)
|
| 88 |
+
|
| 89 |
+
# Expand user directory
|
| 90 |
+
for i, arg in enumerate(command):
|
| 91 |
+
if arg.startswith("~/"):
|
| 92 |
+
command[i] = os.path.expanduser(arg)
|
| 93 |
+
|
| 94 |
+
# Execute the command without any safety checks.
|
| 95 |
+
try:
|
| 96 |
+
if platform_name == "Windows":
|
| 97 |
+
flags = subprocess.CREATE_NO_WINDOW
|
| 98 |
+
else:
|
| 99 |
+
flags = 0
|
| 100 |
+
result = subprocess.run(
|
| 101 |
+
command,
|
| 102 |
+
stdout=subprocess.PIPE,
|
| 103 |
+
stderr=subprocess.PIPE,
|
| 104 |
+
shell=shell,
|
| 105 |
+
text=True,
|
| 106 |
+
timeout=120,
|
| 107 |
+
creationflags=flags,
|
| 108 |
+
)
|
| 109 |
+
return jsonify({
|
| 110 |
+
'status': 'success',
|
| 111 |
+
'output': result.stdout,
|
| 112 |
+
'error': result.stderr,
|
| 113 |
+
'returncode': result.returncode
|
| 114 |
+
})
|
| 115 |
+
except Exception as e:
|
| 116 |
+
return jsonify({
|
| 117 |
+
'status': 'error',
|
| 118 |
+
'message': str(e)
|
| 119 |
+
}), 500
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@app.route('/pyautogui', methods=['POST'])
|
| 123 |
+
def execute_pyautogui():
|
| 124 |
+
"""Execute pyautogui code directly in the Flask process.
|
| 125 |
+
|
| 126 |
+
This avoids the overhead of spawning a new Python process for each action,
|
| 127 |
+
which typically adds ~2-3 seconds per action due to:
|
| 128 |
+
- Python interpreter startup
|
| 129 |
+
- import pyautogui (X11 initialization)
|
| 130 |
+
|
| 131 |
+
Request JSON:
|
| 132 |
+
code: str - The pyautogui code to execute (e.g., "pyautogui.click(500, 300)")
|
| 133 |
+
|
| 134 |
+
Response JSON:
|
| 135 |
+
status: "success" | "error"
|
| 136 |
+
result: Any - The return value of the executed code (if any)
|
| 137 |
+
message: str - Error message (if status is "error")
|
| 138 |
+
"""
|
| 139 |
+
data = request.json
|
| 140 |
+
code = data.get('code', '')
|
| 141 |
+
|
| 142 |
+
if not code:
|
| 143 |
+
return jsonify({
|
| 144 |
+
'status': 'error',
|
| 145 |
+
'message': 'No code provided'
|
| 146 |
+
}), 400
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
# Create a restricted execution environment
|
| 150 |
+
# Only allow pyautogui and time modules for safety
|
| 151 |
+
exec_globals = {
|
| 152 |
+
'pyautogui': pyautogui,
|
| 153 |
+
'time': time,
|
| 154 |
+
}
|
| 155 |
+
exec_locals = {}
|
| 156 |
+
|
| 157 |
+
# Execute the pyautogui code
|
| 158 |
+
exec(code, exec_globals, exec_locals)
|
| 159 |
+
|
| 160 |
+
# Return the result if there's a 'result' variable
|
| 161 |
+
result = exec_locals.get('result', None)
|
| 162 |
+
|
| 163 |
+
return jsonify({
|
| 164 |
+
'status': 'success',
|
| 165 |
+
'result': result
|
| 166 |
+
})
|
| 167 |
+
except Exception as e:
|
| 168 |
+
logger.error(f"pyautogui execution error: {e}")
|
| 169 |
+
return jsonify({
|
| 170 |
+
'status': 'error',
|
| 171 |
+
'message': str(e)
|
| 172 |
+
}), 500
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@app.route('/setup/execute_with_verification', methods=['POST'])
|
| 176 |
+
@app.route('/execute_with_verification', methods=['POST'])
|
| 177 |
+
def execute_command_with_verification():
|
| 178 |
+
"""Execute command and verify the result based on provided verification criteria"""
|
| 179 |
+
data = request.json
|
| 180 |
+
shell = data.get('shell', False)
|
| 181 |
+
command = data.get('command', "" if shell else [])
|
| 182 |
+
verification = data.get('verification', {})
|
| 183 |
+
max_wait_time = data.get('max_wait_time', 10) # Maximum wait time in seconds
|
| 184 |
+
check_interval = data.get('check_interval', 1) # Check interval in seconds
|
| 185 |
+
|
| 186 |
+
if isinstance(command, str) and not shell:
|
| 187 |
+
command = shlex.split(command)
|
| 188 |
+
|
| 189 |
+
# Expand user directory
|
| 190 |
+
for i, arg in enumerate(command):
|
| 191 |
+
if arg.startswith("~/"):
|
| 192 |
+
command[i] = os.path.expanduser(arg)
|
| 193 |
+
|
| 194 |
+
# Execute the main command
|
| 195 |
+
try:
|
| 196 |
+
if platform_name == "Windows":
|
| 197 |
+
flags = subprocess.CREATE_NO_WINDOW
|
| 198 |
+
else:
|
| 199 |
+
flags = 0
|
| 200 |
+
result = subprocess.run(
|
| 201 |
+
command,
|
| 202 |
+
stdout=subprocess.PIPE,
|
| 203 |
+
stderr=subprocess.PIPE,
|
| 204 |
+
shell=shell,
|
| 205 |
+
text=True,
|
| 206 |
+
timeout=120,
|
| 207 |
+
creationflags=flags,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# If no verification is needed, return immediately
|
| 211 |
+
if not verification:
|
| 212 |
+
return jsonify({
|
| 213 |
+
'status': 'success',
|
| 214 |
+
'output': result.stdout,
|
| 215 |
+
'error': result.stderr,
|
| 216 |
+
'returncode': result.returncode
|
| 217 |
+
})
|
| 218 |
+
|
| 219 |
+
# Wait and verify the result
|
| 220 |
+
import time
|
| 221 |
+
start_time = time.time()
|
| 222 |
+
while time.time() - start_time < max_wait_time:
|
| 223 |
+
verification_passed = True
|
| 224 |
+
|
| 225 |
+
# Check window existence if specified
|
| 226 |
+
if 'window_exists' in verification:
|
| 227 |
+
window_name = verification['window_exists']
|
| 228 |
+
try:
|
| 229 |
+
if platform_name == 'Linux':
|
| 230 |
+
wmctrl_result = subprocess.run(['wmctrl', '-l'],
|
| 231 |
+
capture_output=True, text=True, check=True)
|
| 232 |
+
if window_name.lower() not in wmctrl_result.stdout.lower():
|
| 233 |
+
verification_passed = False
|
| 234 |
+
elif platform_name in ['Windows', 'Darwin']:
|
| 235 |
+
import pygetwindow as gw
|
| 236 |
+
windows = gw.getWindowsWithTitle(window_name)
|
| 237 |
+
if not windows:
|
| 238 |
+
verification_passed = False
|
| 239 |
+
except Exception:
|
| 240 |
+
verification_passed = False
|
| 241 |
+
|
| 242 |
+
# Check command execution if specified
|
| 243 |
+
if 'command_success' in verification:
|
| 244 |
+
verify_cmd = verification['command_success']
|
| 245 |
+
try:
|
| 246 |
+
verify_result = subprocess.run(verify_cmd, shell=True,
|
| 247 |
+
capture_output=True, text=True, timeout=5)
|
| 248 |
+
if verify_result.returncode != 0:
|
| 249 |
+
verification_passed = False
|
| 250 |
+
except Exception:
|
| 251 |
+
verification_passed = False
|
| 252 |
+
|
| 253 |
+
if verification_passed:
|
| 254 |
+
return jsonify({
|
| 255 |
+
'status': 'success',
|
| 256 |
+
'output': result.stdout,
|
| 257 |
+
'error': result.stderr,
|
| 258 |
+
'returncode': result.returncode,
|
| 259 |
+
'verification': 'passed',
|
| 260 |
+
'wait_time': time.time() - start_time
|
| 261 |
+
})
|
| 262 |
+
|
| 263 |
+
time.sleep(check_interval)
|
| 264 |
+
|
| 265 |
+
# Verification failed
|
| 266 |
+
return jsonify({
|
| 267 |
+
'status': 'verification_failed',
|
| 268 |
+
'output': result.stdout,
|
| 269 |
+
'error': result.stderr,
|
| 270 |
+
'returncode': result.returncode,
|
| 271 |
+
'verification': 'failed',
|
| 272 |
+
'wait_time': max_wait_time
|
| 273 |
+
}), 500
|
| 274 |
+
|
| 275 |
+
except Exception as e:
|
| 276 |
+
return jsonify({
|
| 277 |
+
'status': 'error',
|
| 278 |
+
'message': str(e)
|
| 279 |
+
}), 500
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _get_machine_architecture() -> str:
|
| 283 |
+
""" Get the machine architecture, e.g., x86_64, arm64, aarch64, i386, etc.
|
| 284 |
+
"""
|
| 285 |
+
architecture = platform.machine().lower()
|
| 286 |
+
if architecture in ['amd32', 'amd64', 'x86', 'x86_64', 'x86-64', 'x64', 'i386', 'i686']:
|
| 287 |
+
return 'amd'
|
| 288 |
+
elif architecture in ['arm64', 'aarch64', 'aarch32']:
|
| 289 |
+
return 'arm'
|
| 290 |
+
else:
|
| 291 |
+
return 'unknown'
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@app.route('/setup/launch', methods=["POST"])
|
| 295 |
+
def launch_app():
|
| 296 |
+
data = request.json
|
| 297 |
+
shell = data.get("shell", False)
|
| 298 |
+
command: List[str] = data.get("command", "" if shell else [])
|
| 299 |
+
|
| 300 |
+
if isinstance(command, str) and not shell:
|
| 301 |
+
command = shlex.split(command)
|
| 302 |
+
|
| 303 |
+
# Expand user directory
|
| 304 |
+
for i, arg in enumerate(command):
|
| 305 |
+
if arg.startswith("~/"):
|
| 306 |
+
command[i] = os.path.expanduser(arg)
|
| 307 |
+
|
| 308 |
+
try:
|
| 309 |
+
if 'google-chrome' in command and _get_machine_architecture() == 'arm':
|
| 310 |
+
index = command.index('google-chrome')
|
| 311 |
+
command[index] = 'chromium' # arm64 chrome is not available yet, can only use chromium
|
| 312 |
+
subprocess.Popen(command, shell=shell)
|
| 313 |
+
return "{:} launched successfully".format(command if shell else " ".join(command))
|
| 314 |
+
except Exception as e:
|
| 315 |
+
return jsonify({"status": "error", "message": str(e)}), 500
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@app.route('/screenshot', methods=['GET'])
|
| 319 |
+
def capture_screen_with_cursor():
|
| 320 |
+
# fixme: when running on virtual machines, the cursor is not captured, don't know why
|
| 321 |
+
|
| 322 |
+
file_path = os.path.join(os.path.dirname(__file__), "screenshots", "screenshot.jpg")
|
| 323 |
+
user_platform = platform.system()
|
| 324 |
+
|
| 325 |
+
# Ensure the screenshots directory exists
|
| 326 |
+
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
| 327 |
+
|
| 328 |
+
# fixme: This is a temporary fix for the cursor not being captured on Windows and Linux
|
| 329 |
+
if user_platform == "Windows":
|
| 330 |
+
def get_cursor():
|
| 331 |
+
hcursor = win32gui.GetCursorInfo()[1]
|
| 332 |
+
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
|
| 333 |
+
hbmp = win32ui.CreateBitmap()
|
| 334 |
+
hbmp.CreateCompatibleBitmap(hdc, 36, 36)
|
| 335 |
+
hdc = hdc.CreateCompatibleDC()
|
| 336 |
+
hdc.SelectObject(hbmp)
|
| 337 |
+
hdc.DrawIcon((0,0), hcursor)
|
| 338 |
+
|
| 339 |
+
bmpinfo = hbmp.GetInfo()
|
| 340 |
+
bmpstr = hbmp.GetBitmapBits(True)
|
| 341 |
+
cursor = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1).convert("RGBA")
|
| 342 |
+
|
| 343 |
+
win32gui.DestroyIcon(hcursor)
|
| 344 |
+
win32gui.DeleteObject(hbmp.GetHandle())
|
| 345 |
+
hdc.DeleteDC()
|
| 346 |
+
|
| 347 |
+
pixdata = cursor.load()
|
| 348 |
+
|
| 349 |
+
width, height = cursor.size
|
| 350 |
+
for y in range(height):
|
| 351 |
+
for x in range(width):
|
| 352 |
+
if pixdata[x, y] == (0, 0, 0, 255):
|
| 353 |
+
pixdata[x, y] = (0, 0, 0, 0)
|
| 354 |
+
|
| 355 |
+
hotspot = win32gui.GetIconInfo(hcursor)[1:3]
|
| 356 |
+
|
| 357 |
+
return (cursor, hotspot)
|
| 358 |
+
|
| 359 |
+
ratio = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100
|
| 360 |
+
|
| 361 |
+
img = ImageGrab.grab(bbox=None, include_layered_windows=True)
|
| 362 |
+
|
| 363 |
+
try:
|
| 364 |
+
cursor, (hotspotx, hotspoty) = get_cursor()
|
| 365 |
+
|
| 366 |
+
pos_win = win32gui.GetCursorPos()
|
| 367 |
+
pos = (round(pos_win[0]*ratio - hotspotx), round(pos_win[1]*ratio - hotspoty))
|
| 368 |
+
|
| 369 |
+
img.paste(cursor, pos, cursor)
|
| 370 |
+
except Exception as e:
|
| 371 |
+
logger.warning(f"Failed to capture cursor on Windows, screenshot will not have a cursor. Error: {e}")
|
| 372 |
+
|
| 373 |
+
img.save(file_path, "JPEG", quality=85)
|
| 374 |
+
elif user_platform == "Linux":
|
| 375 |
+
cursor_obj = Xcursor()
|
| 376 |
+
imgarray = cursor_obj.getCursorImageArrayFast()
|
| 377 |
+
cursor_img = Image.fromarray(imgarray)
|
| 378 |
+
screenshot = pyautogui.screenshot()
|
| 379 |
+
cursor_x, cursor_y = pyautogui.position()
|
| 380 |
+
screenshot.paste(cursor_img, (cursor_x, cursor_y), cursor_img)
|
| 381 |
+
screenshot.save(file_path, "JPEG", quality=85)
|
| 382 |
+
elif user_platform == "Darwin": # (Mac OS)
|
| 383 |
+
# Use the screencapture utility to capture the screen with the cursor
|
| 384 |
+
subprocess.run(["screencapture", "-C", file_path])
|
| 385 |
+
else:
|
| 386 |
+
logger.warning(f"The platform you're using ({user_platform}) is not currently supported")
|
| 387 |
+
|
| 388 |
+
return send_file(file_path, mimetype='image/jpeg')
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def _has_active_terminal(desktop: Accessible) -> bool:
|
| 392 |
+
""" A quick check whether the terminal window is open and active.
|
| 393 |
+
"""
|
| 394 |
+
for app in desktop:
|
| 395 |
+
if app.getRoleName() == "application" and app.name == "gnome-terminal-server":
|
| 396 |
+
for frame in app:
|
| 397 |
+
if frame.getRoleName() == "frame" and frame.getState().contains(pyatspi.STATE_ACTIVE):
|
| 398 |
+
return True
|
| 399 |
+
return False
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@app.route('/terminal', methods=['GET'])
|
| 403 |
+
def get_terminal_output():
|
| 404 |
+
user_platform = platform.system()
|
| 405 |
+
output: Optional[str] = None
|
| 406 |
+
try:
|
| 407 |
+
if user_platform == "Linux":
|
| 408 |
+
desktop: Accessible = pyatspi.Registry.getDesktop(0)
|
| 409 |
+
if _has_active_terminal(desktop):
|
| 410 |
+
desktop_xml: _Element = _create_atspi_node(desktop)
|
| 411 |
+
# 1. the terminal window (frame of application is st:active) is open and active
|
| 412 |
+
# 2. the terminal tab (terminal status is st:focused) is focused
|
| 413 |
+
xpath = '//application[@name="gnome-terminal-server"]/frame[@st:active="true"]//terminal[@st:focused="true"]'
|
| 414 |
+
terminals: List[_Element] = desktop_xml.xpath(xpath, namespaces=_accessibility_ns_map_ubuntu)
|
| 415 |
+
output = terminals[0].text.rstrip() if len(terminals) == 1 else None
|
| 416 |
+
else: # windows and macos platform is not implemented currently
|
| 417 |
+
# raise NotImplementedError
|
| 418 |
+
return "Currently not implemented for platform {:}.".format(platform.platform()), 500
|
| 419 |
+
return jsonify({"output": output, "status": "success"})
|
| 420 |
+
except Exception as e:
|
| 421 |
+
logger.error("Failed to get terminal output. Error: %s", e)
|
| 422 |
+
return jsonify({"status": "error", "message": str(e)}), 500
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
_accessibility_ns_map = {
|
| 426 |
+
"ubuntu": {
|
| 427 |
+
"st": "https://accessibility.ubuntu.example.org/ns/state",
|
| 428 |
+
"attr": "https://accessibility.ubuntu.example.org/ns/attributes",
|
| 429 |
+
"cp": "https://accessibility.ubuntu.example.org/ns/component",
|
| 430 |
+
"doc": "https://accessibility.ubuntu.example.org/ns/document",
|
| 431 |
+
"docattr": "https://accessibility.ubuntu.example.org/ns/document/attributes",
|
| 432 |
+
"txt": "https://accessibility.ubuntu.example.org/ns/text",
|
| 433 |
+
"val": "https://accessibility.ubuntu.example.org/ns/value",
|
| 434 |
+
"act": "https://accessibility.ubuntu.example.org/ns/action",
|
| 435 |
+
},
|
| 436 |
+
"windows": {
|
| 437 |
+
"st": "https://accessibility.windows.example.org/ns/state",
|
| 438 |
+
"attr": "https://accessibility.windows.example.org/ns/attributes",
|
| 439 |
+
"cp": "https://accessibility.windows.example.org/ns/component",
|
| 440 |
+
"doc": "https://accessibility.windows.example.org/ns/document",
|
| 441 |
+
"docattr": "https://accessibility.windows.example.org/ns/document/attributes",
|
| 442 |
+
"txt": "https://accessibility.windows.example.org/ns/text",
|
| 443 |
+
"val": "https://accessibility.windows.example.org/ns/value",
|
| 444 |
+
"act": "https://accessibility.windows.example.org/ns/action",
|
| 445 |
+
"class": "https://accessibility.windows.example.org/ns/class"
|
| 446 |
+
},
|
| 447 |
+
"macos": {
|
| 448 |
+
"st": "https://accessibility.macos.example.org/ns/state",
|
| 449 |
+
"attr": "https://accessibility.macos.example.org/ns/attributes",
|
| 450 |
+
"cp": "https://accessibility.macos.example.org/ns/component",
|
| 451 |
+
"doc": "https://accessibility.macos.example.org/ns/document",
|
| 452 |
+
"txt": "https://accessibility.macos.example.org/ns/text",
|
| 453 |
+
"val": "https://accessibility.macos.example.org/ns/value",
|
| 454 |
+
"act": "https://accessibility.macos.example.org/ns/action",
|
| 455 |
+
"role": "https://accessibility.macos.example.org/ns/role",
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
_accessibility_ns_map_ubuntu = _accessibility_ns_map['ubuntu']
|
| 461 |
+
_accessibility_ns_map_windows = _accessibility_ns_map['windows']
|
| 462 |
+
_accessibility_ns_map_macos = _accessibility_ns_map['macos']
|
| 463 |
+
|
| 464 |
+
# A11y tree getter for Ubuntu
|
| 465 |
+
libreoffice_version_tuple: Optional[Tuple[int, ...]] = None
|
| 466 |
+
MAX_DEPTH = 50
|
| 467 |
+
MAX_WIDTH = 1024
|
| 468 |
+
MAX_CALLS = 5000
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def _get_libreoffice_version() -> Tuple[int, ...]:
|
| 472 |
+
"""Function to get the LibreOffice version as a tuple of integers."""
|
| 473 |
+
result = subprocess.run("libreoffice --version", shell=True, text=True, stdout=subprocess.PIPE)
|
| 474 |
+
version_str = result.stdout.split()[1] # Assuming version is the second word in the command output
|
| 475 |
+
return tuple(map(int, version_str.split(".")))
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _create_atspi_node(node: Accessible, depth: int = 0, flag: Optional[str] = None) -> _Element:
|
| 479 |
+
node_name = node.name
|
| 480 |
+
attribute_dict: Dict[str, Any] = {"name": node_name}
|
| 481 |
+
|
| 482 |
+
# States
|
| 483 |
+
states: List[StateType] = node.getState().get_states()
|
| 484 |
+
for st in states:
|
| 485 |
+
state_name: str = StateType._enum_lookup[st]
|
| 486 |
+
state_name: str = state_name.split("_", maxsplit=1)[1].lower()
|
| 487 |
+
if len(state_name) == 0:
|
| 488 |
+
continue
|
| 489 |
+
attribute_dict["{{{:}}}{:}".format(_accessibility_ns_map_ubuntu["st"], state_name)] = "true"
|
| 490 |
+
|
| 491 |
+
# Attributes
|
| 492 |
+
attributes: Dict[str, str] = node.get_attributes()
|
| 493 |
+
for attribute_name, attribute_value in attributes.items():
|
| 494 |
+
if len(attribute_name) == 0:
|
| 495 |
+
continue
|
| 496 |
+
attribute_dict["{{{:}}}{:}".format(_accessibility_ns_map_ubuntu["attr"], attribute_name)] = attribute_value
|
| 497 |
+
|
| 498 |
+
# Component
|
| 499 |
+
if attribute_dict.get("{{{:}}}visible".format(_accessibility_ns_map_ubuntu["st"]), "false") == "true" \
|
| 500 |
+
and attribute_dict.get("{{{:}}}showing".format(_accessibility_ns_map_ubuntu["st"]), "false") == "true":
|
| 501 |
+
try:
|
| 502 |
+
component: Component = node.queryComponent()
|
| 503 |
+
except NotImplementedError:
|
| 504 |
+
pass
|
| 505 |
+
else:
|
| 506 |
+
bbox: Sequence[int] = component.getExtents(pyatspi.XY_SCREEN)
|
| 507 |
+
attribute_dict["{{{:}}}screencoord".format(_accessibility_ns_map_ubuntu["cp"])] = \
|
| 508 |
+
str(tuple(bbox[0:2]))
|
| 509 |
+
attribute_dict["{{{:}}}size".format(_accessibility_ns_map_ubuntu["cp"])] = str(tuple(bbox[2:]))
|
| 510 |
+
|
| 511 |
+
text = ""
|
| 512 |
+
# Text
|
| 513 |
+
try:
|
| 514 |
+
text_obj: ATText = node.queryText()
|
| 515 |
+
# only text shown on current screen is available
|
| 516 |
+
# attribute_dict["txt:text"] = text_obj.getText(0, text_obj.characterCount)
|
| 517 |
+
text: str = text_obj.getText(0, text_obj.characterCount)
|
| 518 |
+
# if flag=="thunderbird":
|
| 519 |
+
# appeared in thunderbird (uFFFC) (not only in thunderbird), "Object
|
| 520 |
+
# Replacement Character" in Unicode, "used as placeholder in text for
|
| 521 |
+
# an otherwise unspecified object; uFFFD is another "Replacement
|
| 522 |
+
# Character", just in case
|
| 523 |
+
text = text.replace("\ufffc", "").replace("\ufffd", "")
|
| 524 |
+
except NotImplementedError:
|
| 525 |
+
pass
|
| 526 |
+
|
| 527 |
+
# Image, Selection, Value, Action
|
| 528 |
+
try:
|
| 529 |
+
node.queryImage()
|
| 530 |
+
attribute_dict["image"] = "true"
|
| 531 |
+
except NotImplementedError:
|
| 532 |
+
pass
|
| 533 |
+
|
| 534 |
+
try:
|
| 535 |
+
node.querySelection()
|
| 536 |
+
attribute_dict["selection"] = "true"
|
| 537 |
+
except NotImplementedError:
|
| 538 |
+
pass
|
| 539 |
+
|
| 540 |
+
try:
|
| 541 |
+
value: ATValue = node.queryValue()
|
| 542 |
+
value_key = f"{{{_accessibility_ns_map_ubuntu['val']}}}"
|
| 543 |
+
|
| 544 |
+
for attr_name, attr_func in [
|
| 545 |
+
("value", lambda: value.currentValue),
|
| 546 |
+
("min", lambda: value.minimumValue),
|
| 547 |
+
("max", lambda: value.maximumValue),
|
| 548 |
+
("step", lambda: value.minimumIncrement)
|
| 549 |
+
]:
|
| 550 |
+
try:
|
| 551 |
+
attribute_dict[f"{value_key}{attr_name}"] = str(attr_func())
|
| 552 |
+
except:
|
| 553 |
+
pass
|
| 554 |
+
except NotImplementedError:
|
| 555 |
+
pass
|
| 556 |
+
|
| 557 |
+
try:
|
| 558 |
+
action: ATAction = node.queryAction()
|
| 559 |
+
for i in range(action.nActions):
|
| 560 |
+
action_name: str = action.getName(i).replace(" ", "-")
|
| 561 |
+
attribute_dict[
|
| 562 |
+
"{{{:}}}{:}_desc".format(_accessibility_ns_map_ubuntu["act"], action_name)] = action.getDescription(
|
| 563 |
+
i)
|
| 564 |
+
attribute_dict[
|
| 565 |
+
"{{{:}}}{:}_kb".format(_accessibility_ns_map_ubuntu["act"], action_name)] = action.getKeyBinding(i)
|
| 566 |
+
except NotImplementedError:
|
| 567 |
+
pass
|
| 568 |
+
|
| 569 |
+
# Add from here if we need more attributes in the future...
|
| 570 |
+
|
| 571 |
+
raw_role_name: str = node.getRoleName().strip()
|
| 572 |
+
node_role_name = (raw_role_name or "unknown").replace(" ", "-")
|
| 573 |
+
|
| 574 |
+
if not flag:
|
| 575 |
+
if raw_role_name == "document spreadsheet":
|
| 576 |
+
flag = "calc"
|
| 577 |
+
if raw_role_name == "application" and node.name == "Thunderbird":
|
| 578 |
+
flag = "thunderbird"
|
| 579 |
+
|
| 580 |
+
xml_node = lxml.etree.Element(
|
| 581 |
+
node_role_name,
|
| 582 |
+
attrib=attribute_dict,
|
| 583 |
+
nsmap=_accessibility_ns_map_ubuntu
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
if len(text) > 0:
|
| 587 |
+
xml_node.text = text
|
| 588 |
+
|
| 589 |
+
if depth == MAX_DEPTH:
|
| 590 |
+
logger.warning("Max depth reached")
|
| 591 |
+
return xml_node
|
| 592 |
+
|
| 593 |
+
if flag == "calc" and node_role_name == "table":
|
| 594 |
+
# Maximum column: 1024 if ver<=7.3 else 16384
|
| 595 |
+
# Maximum row: 104 8576
|
| 596 |
+
# Maximun sheet: 1 0000
|
| 597 |
+
|
| 598 |
+
global libreoffice_version_tuple
|
| 599 |
+
MAXIMUN_COLUMN = 1024 if libreoffice_version_tuple < (7, 4) else 16384
|
| 600 |
+
MAX_ROW = 104_8576
|
| 601 |
+
|
| 602 |
+
index_base = 0
|
| 603 |
+
first_showing = False
|
| 604 |
+
column_base = None
|
| 605 |
+
for r in range(MAX_ROW):
|
| 606 |
+
for clm in range(column_base or 0, MAXIMUN_COLUMN):
|
| 607 |
+
child_node: Accessible = node[index_base + clm]
|
| 608 |
+
showing: bool = child_node.getState().contains(STATE_SHOWING)
|
| 609 |
+
if showing:
|
| 610 |
+
child_node: _Element = _create_atspi_node(child_node, depth + 1, flag)
|
| 611 |
+
if not first_showing:
|
| 612 |
+
column_base = clm
|
| 613 |
+
first_showing = True
|
| 614 |
+
xml_node.append(child_node)
|
| 615 |
+
elif first_showing and column_base is not None or clm >= 500:
|
| 616 |
+
break
|
| 617 |
+
if first_showing and clm == column_base or not first_showing and r >= 500:
|
| 618 |
+
break
|
| 619 |
+
index_base += MAXIMUN_COLUMN
|
| 620 |
+
return xml_node
|
| 621 |
+
else:
|
| 622 |
+
try:
|
| 623 |
+
for i, ch in enumerate(node):
|
| 624 |
+
if i == MAX_WIDTH:
|
| 625 |
+
logger.warning("Max width reached")
|
| 626 |
+
break
|
| 627 |
+
xml_node.append(_create_atspi_node(ch, depth + 1, flag))
|
| 628 |
+
except:
|
| 629 |
+
logger.warning("Error occurred during children traversing. Has Ignored. Node: %s",
|
| 630 |
+
lxml.etree.tostring(xml_node, encoding="unicode"))
|
| 631 |
+
return xml_node
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
# A11y tree getter for Windows
|
| 635 |
+
def _create_pywinauto_node(node, nodes, depth: int = 0, flag: Optional[str] = None) -> _Element:
|
| 636 |
+
nodes = nodes or set()
|
| 637 |
+
if node in nodes:
|
| 638 |
+
return
|
| 639 |
+
nodes.add(node)
|
| 640 |
+
|
| 641 |
+
attribute_dict: Dict[str, Any] = {"name": node.element_info.name}
|
| 642 |
+
|
| 643 |
+
base_properties = {}
|
| 644 |
+
try:
|
| 645 |
+
base_properties.update(
|
| 646 |
+
node.get_properties()) # get all writable/not writable properties, but have bugs when landing on chrome and it's slower!
|
| 647 |
+
except:
|
| 648 |
+
logger.debug("Failed to call get_properties(), trying to get writable properites")
|
| 649 |
+
try:
|
| 650 |
+
_element_class = node.__class__
|
| 651 |
+
|
| 652 |
+
class TempElement(node.__class__):
|
| 653 |
+
writable_props = pywinauto.base_wrapper.BaseWrapper.writable_props
|
| 654 |
+
|
| 655 |
+
# Instantiate the subclass
|
| 656 |
+
node.__class__ = TempElement
|
| 657 |
+
# Retrieve properties using get_properties()
|
| 658 |
+
properties = node.get_properties()
|
| 659 |
+
node.__class__ = _element_class
|
| 660 |
+
|
| 661 |
+
base_properties.update(properties) # only get all writable properties
|
| 662 |
+
logger.debug("get writable properties")
|
| 663 |
+
except Exception as e:
|
| 664 |
+
logger.error(e)
|
| 665 |
+
pass
|
| 666 |
+
|
| 667 |
+
# Count-cnt
|
| 668 |
+
for attr_name in ["control_count", "button_count", "item_count", "column_count"]:
|
| 669 |
+
try:
|
| 670 |
+
attribute_dict[f"{{{_accessibility_ns_map_windows['cnt']}}}{attr_name}"] = base_properties[
|
| 671 |
+
attr_name].lower()
|
| 672 |
+
except:
|
| 673 |
+
pass
|
| 674 |
+
|
| 675 |
+
# Columns-cols
|
| 676 |
+
try:
|
| 677 |
+
attribute_dict[f"{{{_accessibility_ns_map_windows['cols']}}}columns"] = base_properties["columns"].lower()
|
| 678 |
+
except:
|
| 679 |
+
pass
|
| 680 |
+
|
| 681 |
+
# Id-id
|
| 682 |
+
for attr_name in ["control_id", "automation_id", "window_id"]:
|
| 683 |
+
try:
|
| 684 |
+
attribute_dict[f"{{{_accessibility_ns_map_windows['id']}}}{attr_name}"] = base_properties[attr_name].lower()
|
| 685 |
+
except:
|
| 686 |
+
pass
|
| 687 |
+
|
| 688 |
+
# States
|
| 689 |
+
# 19 sec out of 20
|
| 690 |
+
for attr_name, attr_func in [
|
| 691 |
+
("enabled", lambda: node.is_enabled()),
|
| 692 |
+
("visible", lambda: node.is_visible()),
|
| 693 |
+
# ("active", lambda: node.is_active()), # occupied most of the time: 20s out of 21s for slack, 51.5s out of 54s for WeChat # maybe use for cutting branches
|
| 694 |
+
("minimized", lambda: node.is_minimized()),
|
| 695 |
+
("maximized", lambda: node.is_maximized()),
|
| 696 |
+
("normal", lambda: node.is_normal()),
|
| 697 |
+
("unicode", lambda: node.is_unicode()),
|
| 698 |
+
("collapsed", lambda: node.is_collapsed()),
|
| 699 |
+
("checkable", lambda: node.is_checkable()),
|
| 700 |
+
("checked", lambda: node.is_checked()),
|
| 701 |
+
("focused", lambda: node.is_focused()),
|
| 702 |
+
("keyboard_focused", lambda: node.is_keyboard_focused()),
|
| 703 |
+
("selected", lambda: node.is_selected()),
|
| 704 |
+
("selection_required", lambda: node.is_selection_required()),
|
| 705 |
+
("pressable", lambda: node.is_pressable()),
|
| 706 |
+
("pressed", lambda: node.is_pressed()),
|
| 707 |
+
("expanded", lambda: node.is_expanded()),
|
| 708 |
+
("editable", lambda: node.is_editable()),
|
| 709 |
+
("has_keyboard_focus", lambda: node.has_keyboard_focus()),
|
| 710 |
+
("is_keyboard_focusable", lambda: node.is_keyboard_focusable()),
|
| 711 |
+
]:
|
| 712 |
+
try:
|
| 713 |
+
attribute_dict[f"{{{_accessibility_ns_map_windows['st']}}}{attr_name}"] = str(attr_func()).lower()
|
| 714 |
+
except:
|
| 715 |
+
pass
|
| 716 |
+
|
| 717 |
+
# Component
|
| 718 |
+
try:
|
| 719 |
+
rectangle = node.rectangle()
|
| 720 |
+
attribute_dict["{{{:}}}screencoord".format(_accessibility_ns_map_windows["cp"])] = \
|
| 721 |
+
"({:d}, {:d})".format(rectangle.left, rectangle.top)
|
| 722 |
+
attribute_dict["{{{:}}}size".format(_accessibility_ns_map_windows["cp"])] = \
|
| 723 |
+
"({:d}, {:d})".format(rectangle.width(), rectangle.height())
|
| 724 |
+
|
| 725 |
+
except Exception as e:
|
| 726 |
+
logger.error("Error accessing rectangle: ", e)
|
| 727 |
+
|
| 728 |
+
# Text
|
| 729 |
+
text: str = node.window_text()
|
| 730 |
+
if text == attribute_dict["name"]:
|
| 731 |
+
text = ""
|
| 732 |
+
|
| 733 |
+
# Selection
|
| 734 |
+
if hasattr(node, "select"):
|
| 735 |
+
attribute_dict["selection"] = "true"
|
| 736 |
+
|
| 737 |
+
# Value
|
| 738 |
+
for attr_name, attr_funcs in [
|
| 739 |
+
("step", [lambda: node.get_step()]),
|
| 740 |
+
("value", [lambda: node.value(), lambda: node.get_value(), lambda: node.get_position()]),
|
| 741 |
+
("min", [lambda: node.min_value(), lambda: node.get_range_min()]),
|
| 742 |
+
("max", [lambda: node.max_value(), lambda: node.get_range_max()])
|
| 743 |
+
]:
|
| 744 |
+
for attr_func in attr_funcs:
|
| 745 |
+
if hasattr(node, attr_func.__name__):
|
| 746 |
+
try:
|
| 747 |
+
attribute_dict[f"{{{_accessibility_ns_map_windows['val']}}}{attr_name}"] = str(attr_func())
|
| 748 |
+
break # exit once the attribute is set successfully
|
| 749 |
+
except:
|
| 750 |
+
pass
|
| 751 |
+
|
| 752 |
+
attribute_dict["{{{:}}}class".format(_accessibility_ns_map_windows["class"])] = str(type(node))
|
| 753 |
+
|
| 754 |
+
# class_name
|
| 755 |
+
for attr_name in ["class_name", "friendly_class_name"]:
|
| 756 |
+
try:
|
| 757 |
+
attribute_dict[f"{{{_accessibility_ns_map_windows['class']}}}{attr_name}"] = base_properties[
|
| 758 |
+
attr_name].lower()
|
| 759 |
+
except:
|
| 760 |
+
pass
|
| 761 |
+
|
| 762 |
+
node_role_name: str = node.class_name().lower().replace(" ", "-")
|
| 763 |
+
node_role_name = "".join(
|
| 764 |
+
map(lambda _ch: _ch if _ch.isidentifier() or _ch in {"-"} or _ch.isalnum() else "-", node_role_name))
|
| 765 |
+
|
| 766 |
+
if node_role_name.strip() == "":
|
| 767 |
+
node_role_name = "unknown"
|
| 768 |
+
if not node_role_name[0].isalpha():
|
| 769 |
+
node_role_name = "tag" + node_role_name
|
| 770 |
+
|
| 771 |
+
xml_node = lxml.etree.Element(
|
| 772 |
+
node_role_name,
|
| 773 |
+
attrib=attribute_dict,
|
| 774 |
+
nsmap=_accessibility_ns_map_windows
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
if text is not None and len(text) > 0 and text != attribute_dict["name"]:
|
| 778 |
+
xml_node.text = text
|
| 779 |
+
|
| 780 |
+
if depth == MAX_DEPTH:
|
| 781 |
+
logger.warning("Max depth reached")
|
| 782 |
+
return xml_node
|
| 783 |
+
|
| 784 |
+
# use multi thread to accelerate children fetching
|
| 785 |
+
children = node.children()
|
| 786 |
+
if children:
|
| 787 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 788 |
+
future_to_child = [executor.submit(_create_pywinauto_node, ch, nodes, depth + 1, flag) for ch in
|
| 789 |
+
children[:MAX_WIDTH]]
|
| 790 |
+
try:
|
| 791 |
+
xml_node.extend([future.result() for future in concurrent.futures.as_completed(future_to_child)])
|
| 792 |
+
except Exception as e:
|
| 793 |
+
logger.error(f"Exception occurred: {e}")
|
| 794 |
+
return xml_node
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
# A11y tree getter for macOS
|
| 798 |
+
|
| 799 |
+
def _create_axui_node(node, nodes: set = None, depth: int = 0, bbox: tuple = None):
|
| 800 |
+
nodes = nodes or set()
|
| 801 |
+
if node in nodes:
|
| 802 |
+
return
|
| 803 |
+
nodes.add(node)
|
| 804 |
+
|
| 805 |
+
reserved_keys = {
|
| 806 |
+
"AXEnabled": "st",
|
| 807 |
+
"AXFocused": "st",
|
| 808 |
+
"AXFullScreen": "st",
|
| 809 |
+
"AXTitle": "attr",
|
| 810 |
+
"AXChildrenInNavigationOrder": "attr",
|
| 811 |
+
"AXChildren": "attr",
|
| 812 |
+
"AXFrame": "attr",
|
| 813 |
+
"AXRole": "role",
|
| 814 |
+
"AXHelp": "attr",
|
| 815 |
+
"AXRoleDescription": "role",
|
| 816 |
+
"AXSubrole": "role",
|
| 817 |
+
"AXURL": "attr",
|
| 818 |
+
"AXValue": "val",
|
| 819 |
+
"AXDescription": "attr",
|
| 820 |
+
"AXDOMIdentifier": "attr",
|
| 821 |
+
"AXSelected": "st",
|
| 822 |
+
"AXInvalid": "st",
|
| 823 |
+
"AXRows": "attr",
|
| 824 |
+
"AXColumns": "attr",
|
| 825 |
+
}
|
| 826 |
+
attribute_dict = {}
|
| 827 |
+
|
| 828 |
+
if depth == 0:
|
| 829 |
+
bbox = (
|
| 830 |
+
node["kCGWindowBounds"]["X"],
|
| 831 |
+
node["kCGWindowBounds"]["Y"],
|
| 832 |
+
node["kCGWindowBounds"]["X"] + node["kCGWindowBounds"]["Width"],
|
| 833 |
+
node["kCGWindowBounds"]["Y"] + node["kCGWindowBounds"]["Height"]
|
| 834 |
+
)
|
| 835 |
+
app_ref = ApplicationServices.AXUIElementCreateApplication(node["kCGWindowOwnerPID"])
|
| 836 |
+
|
| 837 |
+
attribute_dict["name"] = node["kCGWindowOwnerName"]
|
| 838 |
+
if attribute_dict["name"] != "Dock":
|
| 839 |
+
error_code, app_wins_ref = ApplicationServices.AXUIElementCopyAttributeValue(
|
| 840 |
+
app_ref, "AXWindows", None)
|
| 841 |
+
if error_code:
|
| 842 |
+
logger.error("MacOS parsing %s encountered Error code: %d", app_ref, error_code)
|
| 843 |
+
else:
|
| 844 |
+
app_wins_ref = [app_ref]
|
| 845 |
+
node = app_wins_ref[0]
|
| 846 |
+
|
| 847 |
+
error_code, attr_names = ApplicationServices.AXUIElementCopyAttributeNames(node, None)
|
| 848 |
+
|
| 849 |
+
if error_code:
|
| 850 |
+
# -25202: AXError.invalidUIElement
|
| 851 |
+
# The accessibility object received in this event is invalid.
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
value = None
|
| 855 |
+
|
| 856 |
+
if "AXFrame" in attr_names:
|
| 857 |
+
error_code, attr_val = ApplicationServices.AXUIElementCopyAttributeValue(node, "AXFrame", None)
|
| 858 |
+
rep = repr(attr_val)
|
| 859 |
+
x_value = re.search(r"x:(-?[\d.]+)", rep)
|
| 860 |
+
y_value = re.search(r"y:(-?[\d.]+)", rep)
|
| 861 |
+
w_value = re.search(r"w:(-?[\d.]+)", rep)
|
| 862 |
+
h_value = re.search(r"h:(-?[\d.]+)", rep)
|
| 863 |
+
type_value = re.search(r"type\s?=\s?(\w+)", rep)
|
| 864 |
+
value = {
|
| 865 |
+
"x": float(x_value.group(1)) if x_value else None,
|
| 866 |
+
"y": float(y_value.group(1)) if y_value else None,
|
| 867 |
+
"w": float(w_value.group(1)) if w_value else None,
|
| 868 |
+
"h": float(h_value.group(1)) if h_value else None,
|
| 869 |
+
"type": type_value.group(1) if type_value else None,
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
if not any(v is None for v in value.values()):
|
| 873 |
+
x_min = max(bbox[0], value["x"])
|
| 874 |
+
x_max = min(bbox[2], value["x"] + value["w"])
|
| 875 |
+
y_min = max(bbox[1], value["y"])
|
| 876 |
+
y_max = min(bbox[3], value["y"] + value["h"])
|
| 877 |
+
|
| 878 |
+
if x_min > x_max or y_min > y_max:
|
| 879 |
+
# No intersection
|
| 880 |
+
return
|
| 881 |
+
|
| 882 |
+
role = None
|
| 883 |
+
text = None
|
| 884 |
+
|
| 885 |
+
for attr_name, ns_key in reserved_keys.items():
|
| 886 |
+
if attr_name not in attr_names:
|
| 887 |
+
continue
|
| 888 |
+
|
| 889 |
+
if value and attr_name == "AXFrame":
|
| 890 |
+
bb = value
|
| 891 |
+
if not any(v is None for v in bb.values()):
|
| 892 |
+
attribute_dict["{{{:}}}screencoord".format(_accessibility_ns_map_macos["cp"])] = \
|
| 893 |
+
"({:d}, {:d})".format(int(bb["x"]), int(bb["y"]))
|
| 894 |
+
attribute_dict["{{{:}}}size".format(_accessibility_ns_map_macos["cp"])] = \
|
| 895 |
+
"({:d}, {:d})".format(int(bb["w"]), int(bb["h"]))
|
| 896 |
+
continue
|
| 897 |
+
|
| 898 |
+
error_code, attr_val = ApplicationServices.AXUIElementCopyAttributeValue(node, attr_name, None)
|
| 899 |
+
|
| 900 |
+
full_attr_name = f"{{{_accessibility_ns_map_macos[ns_key]}}}{attr_name}"
|
| 901 |
+
|
| 902 |
+
if attr_name == "AXValue" and not text:
|
| 903 |
+
text = str(attr_val)
|
| 904 |
+
continue
|
| 905 |
+
|
| 906 |
+
if attr_name == "AXRoleDescription":
|
| 907 |
+
role = attr_val
|
| 908 |
+
continue
|
| 909 |
+
|
| 910 |
+
# Set the attribute_dict
|
| 911 |
+
if not (isinstance(attr_val, ApplicationServices.AXUIElementRef)
|
| 912 |
+
or isinstance(attr_val, (AppKit.NSArray, list))):
|
| 913 |
+
if attr_val is not None:
|
| 914 |
+
attribute_dict[full_attr_name] = str(attr_val)
|
| 915 |
+
|
| 916 |
+
node_role_name = role.lower().replace(" ", "_") if role else "unknown_role"
|
| 917 |
+
|
| 918 |
+
xml_node = lxml.etree.Element(
|
| 919 |
+
node_role_name,
|
| 920 |
+
attrib=attribute_dict,
|
| 921 |
+
nsmap=_accessibility_ns_map_macos
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
if text is not None and len(text) > 0:
|
| 925 |
+
xml_node.text = text
|
| 926 |
+
|
| 927 |
+
if depth == MAX_DEPTH:
|
| 928 |
+
logger.warning("Max depth reached")
|
| 929 |
+
return xml_node
|
| 930 |
+
|
| 931 |
+
future_to_child = []
|
| 932 |
+
|
| 933 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 934 |
+
for attr_name, ns_key in reserved_keys.items():
|
| 935 |
+
if attr_name not in attr_names:
|
| 936 |
+
continue
|
| 937 |
+
|
| 938 |
+
error_code, attr_val = ApplicationServices.AXUIElementCopyAttributeValue(node, attr_name, None)
|
| 939 |
+
if isinstance(attr_val, ApplicationServices.AXUIElementRef):
|
| 940 |
+
future_to_child.append(executor.submit(_create_axui_node, attr_val, nodes, depth + 1, bbox))
|
| 941 |
+
|
| 942 |
+
elif isinstance(attr_val, (AppKit.NSArray, list)):
|
| 943 |
+
for child in attr_val:
|
| 944 |
+
future_to_child.append(executor.submit(_create_axui_node, child, nodes, depth + 1, bbox))
|
| 945 |
+
|
| 946 |
+
try:
|
| 947 |
+
for future in concurrent.futures.as_completed(future_to_child):
|
| 948 |
+
result = future.result()
|
| 949 |
+
if result is not None:
|
| 950 |
+
xml_node.append(result)
|
| 951 |
+
except Exception as e:
|
| 952 |
+
logger.error(f"Exception occurred: {e}")
|
| 953 |
+
|
| 954 |
+
return xml_node
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
@app.route("/accessibility", methods=["GET"])
|
| 958 |
+
def get_accessibility_tree():
|
| 959 |
+
os_name: str = platform.system()
|
| 960 |
+
|
| 961 |
+
# AT-SPI works for KDE as well
|
| 962 |
+
if os_name == "Linux":
|
| 963 |
+
global libreoffice_version_tuple
|
| 964 |
+
libreoffice_version_tuple = _get_libreoffice_version()
|
| 965 |
+
|
| 966 |
+
desktop: Accessible = pyatspi.Registry.getDesktop(0)
|
| 967 |
+
xml_node = lxml.etree.Element("desktop-frame", nsmap=_accessibility_ns_map_ubuntu)
|
| 968 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 969 |
+
futures = [executor.submit(_create_atspi_node, app_node, 1) for app_node in desktop]
|
| 970 |
+
for future in concurrent.futures.as_completed(futures):
|
| 971 |
+
xml_tree = future.result()
|
| 972 |
+
xml_node.append(xml_tree)
|
| 973 |
+
return jsonify({"AT": lxml.etree.tostring(xml_node, encoding="unicode")})
|
| 974 |
+
|
| 975 |
+
elif os_name == "Windows":
|
| 976 |
+
# Attention: Windows a11y tree is implemented to be read through `pywinauto` module, however,
|
| 977 |
+
# two different backends `win32` and `uia` are supported and different results may be returned
|
| 978 |
+
desktop: Desktop = Desktop(backend="uia")
|
| 979 |
+
xml_node = lxml.etree.Element("desktop", nsmap=_accessibility_ns_map_windows)
|
| 980 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 981 |
+
futures = [executor.submit(_create_pywinauto_node, wnd, {}, 1) for wnd in desktop.windows()]
|
| 982 |
+
for future in concurrent.futures.as_completed(futures):
|
| 983 |
+
xml_tree = future.result()
|
| 984 |
+
xml_node.append(xml_tree)
|
| 985 |
+
return jsonify({"AT": lxml.etree.tostring(xml_node, encoding="unicode")})
|
| 986 |
+
|
| 987 |
+
elif os_name == "Darwin":
|
| 988 |
+
# TODO: Add Dock and MenuBar
|
| 989 |
+
xml_node = lxml.etree.Element("desktop", nsmap=_accessibility_ns_map_macos)
|
| 990 |
+
|
| 991 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 992 |
+
foreground_windows = [
|
| 993 |
+
win for win in Quartz.CGWindowListCopyWindowInfo(
|
| 994 |
+
(Quartz.kCGWindowListExcludeDesktopElements |
|
| 995 |
+
Quartz.kCGWindowListOptionOnScreenOnly),
|
| 996 |
+
Quartz.kCGNullWindowID
|
| 997 |
+
) if win["kCGWindowLayer"] == 0 and win["kCGWindowOwnerName"] != "Window Server"
|
| 998 |
+
]
|
| 999 |
+
dock_info = [
|
| 1000 |
+
win for win in Quartz.CGWindowListCopyWindowInfo(
|
| 1001 |
+
Quartz.kCGWindowListOptionAll,
|
| 1002 |
+
Quartz.kCGNullWindowID
|
| 1003 |
+
) if win.get("kCGWindowName", None) == "Dock"
|
| 1004 |
+
]
|
| 1005 |
+
|
| 1006 |
+
futures = [
|
| 1007 |
+
executor.submit(_create_axui_node, wnd, None, 0)
|
| 1008 |
+
for wnd in foreground_windows + dock_info
|
| 1009 |
+
]
|
| 1010 |
+
|
| 1011 |
+
for future in concurrent.futures.as_completed(futures):
|
| 1012 |
+
xml_tree = future.result()
|
| 1013 |
+
if xml_tree is not None:
|
| 1014 |
+
xml_node.append(xml_tree)
|
| 1015 |
+
|
| 1016 |
+
return jsonify({"AT": lxml.etree.tostring(xml_node, encoding="unicode")})
|
| 1017 |
+
|
| 1018 |
+
else:
|
| 1019 |
+
return "Currently not implemented for platform {:}.".format(platform.platform()), 500
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
@app.route('/screen_size', methods=['POST'])
|
| 1023 |
+
def get_screen_size():
|
| 1024 |
+
if platform_name == "Linux":
|
| 1025 |
+
d = display.Display()
|
| 1026 |
+
screen_width = d.screen().width_in_pixels
|
| 1027 |
+
screen_height = d.screen().height_in_pixels
|
| 1028 |
+
elif platform_name == "Windows":
|
| 1029 |
+
user32 = ctypes.windll.user32
|
| 1030 |
+
screen_width: int = user32.GetSystemMetrics(0)
|
| 1031 |
+
screen_height: int = user32.GetSystemMetrics(1)
|
| 1032 |
+
return jsonify(
|
| 1033 |
+
{
|
| 1034 |
+
"width": screen_width,
|
| 1035 |
+
"height": screen_height
|
| 1036 |
+
}
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
@app.route('/window_size', methods=['POST'])
|
| 1041 |
+
def get_window_size():
|
| 1042 |
+
if 'app_class_name' in request.form:
|
| 1043 |
+
app_class_name = request.form['app_class_name']
|
| 1044 |
+
else:
|
| 1045 |
+
return jsonify({"error": "app_class_name is required"}), 400
|
| 1046 |
+
|
| 1047 |
+
d = display.Display()
|
| 1048 |
+
root = d.screen().root
|
| 1049 |
+
window_ids = root.get_full_property(d.intern_atom('_NET_CLIENT_LIST'), X.AnyPropertyType).value
|
| 1050 |
+
|
| 1051 |
+
for window_id in window_ids:
|
| 1052 |
+
try:
|
| 1053 |
+
window = d.create_resource_object('window', window_id)
|
| 1054 |
+
wm_class = window.get_wm_class()
|
| 1055 |
+
|
| 1056 |
+
if wm_class is None:
|
| 1057 |
+
continue
|
| 1058 |
+
|
| 1059 |
+
if app_class_name.lower() in [name.lower() for name in wm_class]:
|
| 1060 |
+
geom = window.get_geometry()
|
| 1061 |
+
return jsonify(
|
| 1062 |
+
{
|
| 1063 |
+
"width": geom.width,
|
| 1064 |
+
"height": geom.height
|
| 1065 |
+
}
|
| 1066 |
+
)
|
| 1067 |
+
except Xlib.error.XError: # Ignore windows that give an error
|
| 1068 |
+
continue
|
| 1069 |
+
return None
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
@app.route('/desktop_path', methods=['POST'])
|
| 1073 |
+
def get_desktop_path():
|
| 1074 |
+
# Get the home directory in a platform-independent manner using pathlib
|
| 1075 |
+
home_directory = str(Path.home())
|
| 1076 |
+
|
| 1077 |
+
# Determine the desktop path based on the operating system
|
| 1078 |
+
desktop_path = {
|
| 1079 |
+
"Windows": os.path.join(home_directory, "Desktop"),
|
| 1080 |
+
"Darwin": os.path.join(home_directory, "Desktop"), # macOS
|
| 1081 |
+
"Linux": os.path.join(home_directory, "Desktop")
|
| 1082 |
+
}.get(platform.system(), None)
|
| 1083 |
+
|
| 1084 |
+
# Check if the operating system is supported and the desktop path exists
|
| 1085 |
+
if desktop_path and os.path.exists(desktop_path):
|
| 1086 |
+
return jsonify(desktop_path=desktop_path)
|
| 1087 |
+
else:
|
| 1088 |
+
return jsonify(error="Unsupported operating system or desktop path not found"), 404
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
@app.route('/wallpaper', methods=['POST'])
|
| 1092 |
+
def get_wallpaper():
|
| 1093 |
+
def get_wallpaper_windows():
|
| 1094 |
+
SPI_GETDESKWALLPAPER = 0x73
|
| 1095 |
+
MAX_PATH = 260
|
| 1096 |
+
buffer = ctypes.create_unicode_buffer(MAX_PATH)
|
| 1097 |
+
ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, MAX_PATH, buffer, 0)
|
| 1098 |
+
return buffer.value
|
| 1099 |
+
|
| 1100 |
+
def get_wallpaper_macos():
|
| 1101 |
+
script = """
|
| 1102 |
+
tell application "System Events" to tell every desktop to get picture
|
| 1103 |
+
"""
|
| 1104 |
+
process = subprocess.Popen(['osascript', '-e', script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 1105 |
+
output, error = process.communicate()
|
| 1106 |
+
if error:
|
| 1107 |
+
app.logger.error("Error: %s", error.decode('utf-8'))
|
| 1108 |
+
return None
|
| 1109 |
+
return output.strip().decode('utf-8')
|
| 1110 |
+
|
| 1111 |
+
def get_wallpaper_linux():
|
| 1112 |
+
try:
|
| 1113 |
+
output = subprocess.check_output(
|
| 1114 |
+
["gsettings", "get", "org.gnome.desktop.background", "picture-uri"],
|
| 1115 |
+
stderr=subprocess.PIPE
|
| 1116 |
+
)
|
| 1117 |
+
return output.decode('utf-8').strip().replace('file://', '').replace("'", "")
|
| 1118 |
+
except subprocess.CalledProcessError as e:
|
| 1119 |
+
app.logger.error("Error: %s", e)
|
| 1120 |
+
return None
|
| 1121 |
+
|
| 1122 |
+
os_name = platform.system()
|
| 1123 |
+
wallpaper_path = None
|
| 1124 |
+
if os_name == 'Windows':
|
| 1125 |
+
wallpaper_path = get_wallpaper_windows()
|
| 1126 |
+
elif os_name == 'Darwin':
|
| 1127 |
+
wallpaper_path = get_wallpaper_macos()
|
| 1128 |
+
elif os_name == 'Linux':
|
| 1129 |
+
wallpaper_path = get_wallpaper_linux()
|
| 1130 |
+
else:
|
| 1131 |
+
app.logger.error(f"Unsupported OS: {os_name}")
|
| 1132 |
+
abort(400, description="Unsupported OS")
|
| 1133 |
+
|
| 1134 |
+
if wallpaper_path:
|
| 1135 |
+
try:
|
| 1136 |
+
# Ensure the filename is secure
|
| 1137 |
+
return send_file(wallpaper_path, mimetype='image/png')
|
| 1138 |
+
except Exception as e:
|
| 1139 |
+
app.logger.error(f"An error occurred while serving the wallpaper file: {e}")
|
| 1140 |
+
abort(500, description="Unable to serve the wallpaper file")
|
| 1141 |
+
else:
|
| 1142 |
+
abort(404, description="Wallpaper file not found")
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
@app.route('/list_directory', methods=['POST'])
|
| 1146 |
+
def get_directory_tree():
|
| 1147 |
+
def _list_dir_contents(directory):
|
| 1148 |
+
"""
|
| 1149 |
+
List the contents of a directory recursively, building a tree structure.
|
| 1150 |
+
|
| 1151 |
+
:param directory: The path of the directory to inspect.
|
| 1152 |
+
:return: A nested dictionary with the contents of the directory.
|
| 1153 |
+
"""
|
| 1154 |
+
tree = {'type': 'directory', 'name': os.path.basename(directory), 'children': []}
|
| 1155 |
+
try:
|
| 1156 |
+
# List all files and directories in the current directory
|
| 1157 |
+
for entry in os.listdir(directory):
|
| 1158 |
+
full_path = os.path.join(directory, entry)
|
| 1159 |
+
# If entry is a directory, recurse into it
|
| 1160 |
+
if os.path.isdir(full_path):
|
| 1161 |
+
tree['children'].append(_list_dir_contents(full_path))
|
| 1162 |
+
else:
|
| 1163 |
+
tree['children'].append({'type': 'file', 'name': entry})
|
| 1164 |
+
except OSError as e:
|
| 1165 |
+
# If the directory cannot be accessed, return the exception message
|
| 1166 |
+
tree = {'error': str(e)}
|
| 1167 |
+
return tree
|
| 1168 |
+
|
| 1169 |
+
# Extract the 'path' parameter from the JSON request
|
| 1170 |
+
data = request.get_json()
|
| 1171 |
+
if 'path' not in data:
|
| 1172 |
+
return jsonify(error="Missing 'path' parameter"), 400
|
| 1173 |
+
|
| 1174 |
+
start_path = data['path']
|
| 1175 |
+
# Ensure the provided path is a directory
|
| 1176 |
+
if not os.path.isdir(start_path):
|
| 1177 |
+
return jsonify(error="The provided path is not a directory"), 400
|
| 1178 |
+
|
| 1179 |
+
# Generate the directory tree starting from the provided path
|
| 1180 |
+
directory_tree = _list_dir_contents(start_path)
|
| 1181 |
+
return jsonify(directory_tree=directory_tree)
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
@app.route('/file', methods=['POST'])
|
| 1185 |
+
def get_file():
|
| 1186 |
+
# Retrieve filename from the POST request
|
| 1187 |
+
if 'file_path' in request.form:
|
| 1188 |
+
file_path = os.path.expandvars(os.path.expanduser(request.form['file_path']))
|
| 1189 |
+
else:
|
| 1190 |
+
return jsonify({"error": "file_path is required"}), 400
|
| 1191 |
+
|
| 1192 |
+
try:
|
| 1193 |
+
# Check if the file exists and get its size
|
| 1194 |
+
if not os.path.exists(file_path):
|
| 1195 |
+
return jsonify({"error": "File not found"}), 404
|
| 1196 |
+
|
| 1197 |
+
file_size = os.path.getsize(file_path)
|
| 1198 |
+
logger.info(f"Serving file: {file_path} ({file_size} bytes)")
|
| 1199 |
+
|
| 1200 |
+
# Check if the file exists and send it to the user
|
| 1201 |
+
return send_file(file_path, as_attachment=True)
|
| 1202 |
+
except FileNotFoundError:
|
| 1203 |
+
# If the file is not found, return a 404 error
|
| 1204 |
+
return jsonify({"error": "File not found"}), 404
|
| 1205 |
+
except Exception as e:
|
| 1206 |
+
logger.error(f"Error serving file {file_path}: {e}")
|
| 1207 |
+
return jsonify({"error": f"Failed to serve file: {str(e)}"}), 500
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
@app.route("/setup/upload", methods=["POST"])
|
| 1211 |
+
def upload_file():
|
| 1212 |
+
# Retrieve filename from the POST request
|
| 1213 |
+
if 'file_path' in request.form and 'file_data' in request.files:
|
| 1214 |
+
file_path = os.path.expandvars(os.path.expanduser(request.form['file_path']))
|
| 1215 |
+
file = request.files["file_data"]
|
| 1216 |
+
|
| 1217 |
+
try:
|
| 1218 |
+
# Ensure target directory exists
|
| 1219 |
+
target_dir = os.path.dirname(file_path)
|
| 1220 |
+
if target_dir: # Only create directory if it's not empty
|
| 1221 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 1222 |
+
|
| 1223 |
+
# Save file and get size for verification
|
| 1224 |
+
file.save(file_path)
|
| 1225 |
+
uploaded_size = os.path.getsize(file_path)
|
| 1226 |
+
|
| 1227 |
+
logger.info(f"File uploaded successfully: {file_path} ({uploaded_size} bytes)")
|
| 1228 |
+
return f"File Uploaded: {uploaded_size} bytes"
|
| 1229 |
+
|
| 1230 |
+
except Exception as e:
|
| 1231 |
+
logger.error(f"Error uploading file to {file_path}: {e}")
|
| 1232 |
+
# Clean up partial file if it exists
|
| 1233 |
+
if os.path.exists(file_path):
|
| 1234 |
+
try:
|
| 1235 |
+
os.remove(file_path)
|
| 1236 |
+
except:
|
| 1237 |
+
pass
|
| 1238 |
+
return jsonify({"error": f"Failed to upload file: {str(e)}"}), 500
|
| 1239 |
+
else:
|
| 1240 |
+
return jsonify({"error": "file_path and file_data are required"}), 400
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
@app.route('/platform', methods=['GET'])
|
| 1244 |
+
def get_platform():
|
| 1245 |
+
return platform.system()
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
@app.route('/cursor_position', methods=['GET'])
|
| 1249 |
+
def get_cursor_position():
|
| 1250 |
+
pos = pyautogui.position()
|
| 1251 |
+
return jsonify(pos.x, pos.y)
|
| 1252 |
+
|
| 1253 |
+
@app.route("/setup/change_wallpaper", methods=['POST'])
|
| 1254 |
+
def change_wallpaper():
|
| 1255 |
+
data = request.json
|
| 1256 |
+
path = data.get('path', None)
|
| 1257 |
+
|
| 1258 |
+
if not path:
|
| 1259 |
+
return "Path not supplied!", 400
|
| 1260 |
+
|
| 1261 |
+
path = Path(os.path.expandvars(os.path.expanduser(path)))
|
| 1262 |
+
|
| 1263 |
+
if not path.exists():
|
| 1264 |
+
return f"File not found: {path}", 404
|
| 1265 |
+
|
| 1266 |
+
try:
|
| 1267 |
+
user_platform = platform.system()
|
| 1268 |
+
if user_platform == "Windows":
|
| 1269 |
+
import ctypes
|
| 1270 |
+
ctypes.windll.user32.SystemParametersInfoW(20, 0, str(path), 3)
|
| 1271 |
+
elif user_platform == "Linux":
|
| 1272 |
+
import subprocess
|
| 1273 |
+
subprocess.run(["gsettings", "set", "org.gnome.desktop.background", "picture-uri", f"file://{path}"])
|
| 1274 |
+
elif user_platform == "Darwin": # (Mac OS)
|
| 1275 |
+
import subprocess
|
| 1276 |
+
subprocess.run(
|
| 1277 |
+
["osascript", "-e", f'tell application "Finder" to set desktop picture to POSIX file "{path}"'])
|
| 1278 |
+
return "Wallpaper changed successfully"
|
| 1279 |
+
except Exception as e:
|
| 1280 |
+
return f"Failed to change wallpaper. Error: {e}", 500
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
@app.route("/setup/download_file", methods=['POST'])
|
| 1284 |
+
def download_file():
|
| 1285 |
+
data = request.json
|
| 1286 |
+
url = data.get('url', None)
|
| 1287 |
+
path = data.get('path', None)
|
| 1288 |
+
|
| 1289 |
+
if not url or not path:
|
| 1290 |
+
return "Path or URL not supplied!", 400
|
| 1291 |
+
|
| 1292 |
+
path = Path(os.path.expandvars(os.path.expanduser(path)))
|
| 1293 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 1294 |
+
|
| 1295 |
+
max_retries = 3
|
| 1296 |
+
error: Optional[Exception] = None
|
| 1297 |
+
|
| 1298 |
+
for i in range(max_retries):
|
| 1299 |
+
try:
|
| 1300 |
+
logger.info(f"Download attempt {i+1}/{max_retries} for {url}")
|
| 1301 |
+
response = requests.get(url, stream=True, timeout=300)
|
| 1302 |
+
response.raise_for_status()
|
| 1303 |
+
|
| 1304 |
+
# Get expected file size if available
|
| 1305 |
+
total_size = int(response.headers.get('content-length', 0))
|
| 1306 |
+
if total_size > 0:
|
| 1307 |
+
logger.info(f"Expected file size: {total_size / (1024*1024):.2f} MB")
|
| 1308 |
+
|
| 1309 |
+
downloaded_size = 0
|
| 1310 |
+
with open(path, 'wb') as f:
|
| 1311 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 1312 |
+
if chunk:
|
| 1313 |
+
f.write(chunk)
|
| 1314 |
+
downloaded_size += len(chunk)
|
| 1315 |
+
if total_size > 0 and downloaded_size % (1024*1024) == 0: # Log every MB
|
| 1316 |
+
progress = (downloaded_size / total_size) * 100
|
| 1317 |
+
logger.info(f"Download progress: {progress:.1f}%")
|
| 1318 |
+
|
| 1319 |
+
# Verify download completeness
|
| 1320 |
+
actual_size = os.path.getsize(path)
|
| 1321 |
+
if total_size > 0 and actual_size != total_size:
|
| 1322 |
+
raise Exception(f"Download incomplete. Expected {total_size} bytes, got {actual_size} bytes")
|
| 1323 |
+
|
| 1324 |
+
logger.info(f"File downloaded successfully: {path} ({actual_size} bytes)")
|
| 1325 |
+
return f"File downloaded successfully: {actual_size} bytes"
|
| 1326 |
+
|
| 1327 |
+
except (requests.RequestException, Exception) as e:
|
| 1328 |
+
error = e
|
| 1329 |
+
logger.error(f"Failed to download {url}: {e}. Retrying... ({max_retries - i - 1} attempts left)")
|
| 1330 |
+
# Clean up partial download
|
| 1331 |
+
if path.exists():
|
| 1332 |
+
try:
|
| 1333 |
+
path.unlink()
|
| 1334 |
+
except:
|
| 1335 |
+
pass
|
| 1336 |
+
|
| 1337 |
+
return f"Failed to download {url}. No retries left. Error: {error}", 500
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
@app.route("/setup/open_file", methods=['POST'])
|
| 1341 |
+
def open_file():
|
| 1342 |
+
data = request.json
|
| 1343 |
+
path = data.get('path', None)
|
| 1344 |
+
|
| 1345 |
+
if not path:
|
| 1346 |
+
return "Path not supplied!", 400
|
| 1347 |
+
|
| 1348 |
+
path_obj = Path(os.path.expandvars(os.path.expanduser(path)))
|
| 1349 |
+
|
| 1350 |
+
# Check if it's a file path that exists
|
| 1351 |
+
is_file_path = path_obj.exists()
|
| 1352 |
+
|
| 1353 |
+
# If it's not a file path, treat it as an application name/command
|
| 1354 |
+
if not is_file_path:
|
| 1355 |
+
# Check if it's a valid command by trying to find it in PATH
|
| 1356 |
+
import shutil
|
| 1357 |
+
if not shutil.which(path):
|
| 1358 |
+
return f"Application/file not found: {path}", 404
|
| 1359 |
+
|
| 1360 |
+
try:
|
| 1361 |
+
if is_file_path:
|
| 1362 |
+
# Handle file opening
|
| 1363 |
+
if platform.system() == "Windows":
|
| 1364 |
+
os.startfile(path_obj)
|
| 1365 |
+
else:
|
| 1366 |
+
open_cmd: str = "open" if platform.system() == "Darwin" else "xdg-open"
|
| 1367 |
+
subprocess.Popen([open_cmd, str(path_obj)])
|
| 1368 |
+
file_name = path_obj.name
|
| 1369 |
+
file_name_without_ext, _ = os.path.splitext(file_name)
|
| 1370 |
+
else:
|
| 1371 |
+
# Handle application launching
|
| 1372 |
+
if platform.system() == "Windows":
|
| 1373 |
+
subprocess.Popen([path])
|
| 1374 |
+
else:
|
| 1375 |
+
subprocess.Popen([path])
|
| 1376 |
+
file_name = path
|
| 1377 |
+
file_name_without_ext = path
|
| 1378 |
+
|
| 1379 |
+
# Wait for the file/application to open
|
| 1380 |
+
|
| 1381 |
+
start_time = time.time()
|
| 1382 |
+
window_found = False
|
| 1383 |
+
|
| 1384 |
+
while time.time() - start_time < TIMEOUT:
|
| 1385 |
+
os_name = platform.system()
|
| 1386 |
+
if os_name in ['Windows', 'Darwin']:
|
| 1387 |
+
import pygetwindow as gw
|
| 1388 |
+
# Check for window title containing file name or file name without extension
|
| 1389 |
+
windows = gw.getWindowsWithTitle(file_name)
|
| 1390 |
+
if not windows:
|
| 1391 |
+
windows = gw.getWindowsWithTitle(file_name_without_ext)
|
| 1392 |
+
|
| 1393 |
+
if windows:
|
| 1394 |
+
# To be more specific, we can try to activate it
|
| 1395 |
+
windows[0].activate()
|
| 1396 |
+
window_found = True
|
| 1397 |
+
break
|
| 1398 |
+
elif os_name == 'Linux':
|
| 1399 |
+
try:
|
| 1400 |
+
# Using wmctrl to list windows and check if any window title contains the filename
|
| 1401 |
+
result = subprocess.run(['wmctrl', '-l'], capture_output=True, text=True, check=True)
|
| 1402 |
+
window_list = result.stdout.strip().split('\n')
|
| 1403 |
+
if not result.stdout.strip():
|
| 1404 |
+
pass # No windows, just continue waiting
|
| 1405 |
+
else:
|
| 1406 |
+
for window in window_list:
|
| 1407 |
+
if file_name in window or file_name_without_ext in window:
|
| 1408 |
+
# a window is found, now activate it
|
| 1409 |
+
window_id = window.split()[0]
|
| 1410 |
+
subprocess.run(['wmctrl', '-i', '-a', window_id], check=True)
|
| 1411 |
+
window_found = True
|
| 1412 |
+
break
|
| 1413 |
+
if window_found:
|
| 1414 |
+
break
|
| 1415 |
+
except (subprocess.CalledProcessError, FileNotFoundError):
|
| 1416 |
+
# wmctrl might not be installed or the window manager isn't ready.
|
| 1417 |
+
# We just log it once and let the main loop retry.
|
| 1418 |
+
if 'wmctrl_failed_once' not in locals():
|
| 1419 |
+
logger.warning("wmctrl command is not ready, will keep retrying...")
|
| 1420 |
+
wmctrl_failed_once = True
|
| 1421 |
+
pass # Let the outer loop retry
|
| 1422 |
+
|
| 1423 |
+
time.sleep(1)
|
| 1424 |
+
|
| 1425 |
+
if window_found:
|
| 1426 |
+
return "File opened and window activated successfully"
|
| 1427 |
+
else:
|
| 1428 |
+
return f"Failed to find window for {file_name} within {TIMEOUT} seconds.", 500
|
| 1429 |
+
|
| 1430 |
+
except Exception as e:
|
| 1431 |
+
return f"Failed to open {path}. Error: {e}", 500
|
| 1432 |
+
|
| 1433 |
+
|
| 1434 |
+
@app.route("/setup/activate_window", methods=['POST'])
|
| 1435 |
+
def activate_window():
|
| 1436 |
+
data = request.json
|
| 1437 |
+
window_name = data.get('window_name', None)
|
| 1438 |
+
if not window_name:
|
| 1439 |
+
return "window_name required", 400
|
| 1440 |
+
strict: bool = data.get("strict", False) # compare case-sensitively and match the whole string
|
| 1441 |
+
by_class_name: bool = data.get("by_class", False)
|
| 1442 |
+
|
| 1443 |
+
os_name = platform.system()
|
| 1444 |
+
|
| 1445 |
+
if os_name == 'Windows':
|
| 1446 |
+
import pygetwindow as gw
|
| 1447 |
+
if by_class_name:
|
| 1448 |
+
return "Get window by class name is not supported on Windows currently.", 500
|
| 1449 |
+
windows: List[gw.Window] = gw.getWindowsWithTitle(window_name)
|
| 1450 |
+
|
| 1451 |
+
window: Optional[gw.Window] = None
|
| 1452 |
+
if len(windows) == 0:
|
| 1453 |
+
return "Window {:} not found (empty results)".format(window_name), 404
|
| 1454 |
+
elif strict:
|
| 1455 |
+
for wnd in windows:
|
| 1456 |
+
if wnd.title == wnd:
|
| 1457 |
+
window = wnd
|
| 1458 |
+
if window is None:
|
| 1459 |
+
return "Window {:} not found (strict mode).".format(window_name), 404
|
| 1460 |
+
else:
|
| 1461 |
+
window = windows[0]
|
| 1462 |
+
window.activate()
|
| 1463 |
+
|
| 1464 |
+
elif os_name == 'Darwin':
|
| 1465 |
+
import pygetwindow as gw
|
| 1466 |
+
if by_class_name:
|
| 1467 |
+
return "Get window by class name is not supported on macOS currently.", 500
|
| 1468 |
+
# Find the VS Code window
|
| 1469 |
+
windows = gw.getWindowsWithTitle(window_name)
|
| 1470 |
+
|
| 1471 |
+
window: Optional[gw.Window] = None
|
| 1472 |
+
if len(windows) == 0:
|
| 1473 |
+
return "Window {:} not found (empty results)".format(window_name), 404
|
| 1474 |
+
elif strict:
|
| 1475 |
+
for wnd in windows:
|
| 1476 |
+
if wnd.title == wnd:
|
| 1477 |
+
window = wnd
|
| 1478 |
+
if window is None:
|
| 1479 |
+
return "Window {:} not found (strict mode).".format(window_name), 404
|
| 1480 |
+
else:
|
| 1481 |
+
window = windows[0]
|
| 1482 |
+
|
| 1483 |
+
# Un-minimize the window and then bring it to the front
|
| 1484 |
+
window.unminimize()
|
| 1485 |
+
window.activate()
|
| 1486 |
+
|
| 1487 |
+
elif os_name == 'Linux':
|
| 1488 |
+
# Attempt to activate VS Code window using wmctrl
|
| 1489 |
+
subprocess.run(["wmctrl"
|
| 1490 |
+
, "-{:}{:}a".format("x" if by_class_name else ""
|
| 1491 |
+
, "F" if strict else ""
|
| 1492 |
+
)
|
| 1493 |
+
, window_name
|
| 1494 |
+
]
|
| 1495 |
+
)
|
| 1496 |
+
|
| 1497 |
+
else:
|
| 1498 |
+
return f"Operating system {os_name} not supported.", 400
|
| 1499 |
+
|
| 1500 |
+
return "Window activated successfully", 200
|
| 1501 |
+
|
| 1502 |
+
|
| 1503 |
+
@app.route("/setup/close_window", methods=["POST"])
|
| 1504 |
+
def close_window():
|
| 1505 |
+
data = request.json
|
| 1506 |
+
if "window_name" not in data:
|
| 1507 |
+
return "window_name required", 400
|
| 1508 |
+
window_name: str = data["window_name"]
|
| 1509 |
+
strict: bool = data.get("strict", False) # compare case-sensitively and match the whole string
|
| 1510 |
+
by_class_name: bool = data.get("by_class", False)
|
| 1511 |
+
|
| 1512 |
+
os_name: str = platform.system()
|
| 1513 |
+
if os_name == "Windows":
|
| 1514 |
+
import pygetwindow as gw
|
| 1515 |
+
|
| 1516 |
+
if by_class_name:
|
| 1517 |
+
return "Get window by class name is not supported on Windows currently.", 500
|
| 1518 |
+
windows: List[gw.Window] = gw.getWindowsWithTitle(window_name)
|
| 1519 |
+
|
| 1520 |
+
window: Optional[gw.Window] = None
|
| 1521 |
+
if len(windows) == 0:
|
| 1522 |
+
return "Window {:} not found (empty results)".format(window_name), 404
|
| 1523 |
+
elif strict:
|
| 1524 |
+
for wnd in windows:
|
| 1525 |
+
if wnd.title == wnd:
|
| 1526 |
+
window = wnd
|
| 1527 |
+
if window is None:
|
| 1528 |
+
return "Window {:} not found (strict mode).".format(window_name), 404
|
| 1529 |
+
else:
|
| 1530 |
+
window = windows[0]
|
| 1531 |
+
window.close()
|
| 1532 |
+
elif os_name == "Linux":
|
| 1533 |
+
subprocess.run(["wmctrl"
|
| 1534 |
+
, "-{:}{:}c".format("x" if by_class_name else ""
|
| 1535 |
+
, "F" if strict else ""
|
| 1536 |
+
)
|
| 1537 |
+
, window_name
|
| 1538 |
+
]
|
| 1539 |
+
)
|
| 1540 |
+
elif os_name == "Darwin":
|
| 1541 |
+
import pygetwindow as gw
|
| 1542 |
+
return "Currently not supported on macOS.", 500
|
| 1543 |
+
else:
|
| 1544 |
+
return "Not supported platform {:}".format(os_name), 500
|
| 1545 |
+
|
| 1546 |
+
return "Window closed successfully.", 200
|
| 1547 |
+
|
| 1548 |
+
|
| 1549 |
+
@app.route('/start_recording', methods=['POST'])
|
| 1550 |
+
def start_recording():
|
| 1551 |
+
global recording_process
|
| 1552 |
+
if recording_process and recording_process.poll() is None:
|
| 1553 |
+
return jsonify({'status': 'error', 'message': 'Recording is already in progress.'}), 400
|
| 1554 |
+
|
| 1555 |
+
# Clean up previous recording if it exists
|
| 1556 |
+
if os.path.exists(recording_path):
|
| 1557 |
+
try:
|
| 1558 |
+
os.remove(recording_path)
|
| 1559 |
+
except OSError as e:
|
| 1560 |
+
logger.error(f"Error removing old recording file: {e}")
|
| 1561 |
+
return jsonify({'status': 'error', 'message': f'Failed to remove old recording file: {e}'}), 500
|
| 1562 |
+
|
| 1563 |
+
d = display.Display()
|
| 1564 |
+
screen_width = d.screen().width_in_pixels
|
| 1565 |
+
screen_height = d.screen().height_in_pixels
|
| 1566 |
+
|
| 1567 |
+
start_command = f"ffmpeg -y -f x11grab -draw_mouse 1 -s {screen_width}x{screen_height} -i :0.0 -c:v libx264 -r 30 {recording_path}"
|
| 1568 |
+
|
| 1569 |
+
# Use stderr=PIPE to capture potential errors from ffmpeg
|
| 1570 |
+
recording_process = subprocess.Popen(shlex.split(start_command),
|
| 1571 |
+
stdout=subprocess.DEVNULL,
|
| 1572 |
+
stderr=subprocess.PIPE,
|
| 1573 |
+
text=True # To get stderr as string
|
| 1574 |
+
)
|
| 1575 |
+
|
| 1576 |
+
# Wait a couple of seconds to see if ffmpeg starts successfully
|
| 1577 |
+
try:
|
| 1578 |
+
# Wait for 2 seconds. If ffmpeg exits within this time, it's an error.
|
| 1579 |
+
recording_process.wait(timeout=2)
|
| 1580 |
+
# If wait() returns, it means the process has terminated.
|
| 1581 |
+
error_output = recording_process.stderr.read()
|
| 1582 |
+
return jsonify({
|
| 1583 |
+
'status': 'error',
|
| 1584 |
+
'message': f'Failed to start recording. ffmpeg terminated unexpectedly. Error: {error_output}'
|
| 1585 |
+
}), 500
|
| 1586 |
+
except subprocess.TimeoutExpired:
|
| 1587 |
+
# This is the expected outcome: the process is still running after 2 seconds.
|
| 1588 |
+
return jsonify({'status': 'success', 'message': 'Started recording successfully.'})
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
@app.route('/end_recording', methods=['POST'])
|
| 1592 |
+
def end_recording():
|
| 1593 |
+
global recording_process
|
| 1594 |
+
|
| 1595 |
+
if not recording_process or recording_process.poll() is not None:
|
| 1596 |
+
recording_process = None # Clean up stale process object
|
| 1597 |
+
return jsonify({'status': 'error', 'message': 'No recording in progress to stop.'}), 400
|
| 1598 |
+
|
| 1599 |
+
error_output = ""
|
| 1600 |
+
try:
|
| 1601 |
+
# Send SIGINT for a graceful shutdown, allowing ffmpeg to finalize the file.
|
| 1602 |
+
recording_process.send_signal(signal.SIGINT)
|
| 1603 |
+
# Wait for ffmpeg to terminate. communicate() gets output and waits.
|
| 1604 |
+
_, error_output = recording_process.communicate(timeout=15)
|
| 1605 |
+
except subprocess.TimeoutExpired:
|
| 1606 |
+
logger.error("ffmpeg did not respond to SIGINT, killing the process.")
|
| 1607 |
+
recording_process.kill()
|
| 1608 |
+
# After killing, communicate to get any remaining output.
|
| 1609 |
+
_, error_output = recording_process.communicate()
|
| 1610 |
+
recording_process = None
|
| 1611 |
+
return jsonify({
|
| 1612 |
+
'status': 'error',
|
| 1613 |
+
'message': f'Recording process was unresponsive and had to be killed. Stderr: {error_output}'
|
| 1614 |
+
}), 500
|
| 1615 |
+
|
| 1616 |
+
recording_process = None # Clear the process from global state
|
| 1617 |
+
|
| 1618 |
+
# Check if the recording file was created and is not empty.
|
| 1619 |
+
if os.path.exists(recording_path) and os.path.getsize(recording_path) > 0:
|
| 1620 |
+
return send_file(recording_path, as_attachment=True)
|
| 1621 |
+
else:
|
| 1622 |
+
logger.error(f"Recording failed. The output file is missing or empty. ffmpeg stderr: {error_output}")
|
| 1623 |
+
return abort(500, description=f"Recording failed. The output file is missing or empty. ffmpeg stderr: {error_output}")
|
| 1624 |
+
|
| 1625 |
+
|
| 1626 |
+
@app.route("/run_python", methods=['POST'])
|
| 1627 |
+
def run_python():
|
| 1628 |
+
data = request.json
|
| 1629 |
+
code = data.get('code', None)
|
| 1630 |
+
|
| 1631 |
+
if not code:
|
| 1632 |
+
return jsonify({'status': 'error', 'message': 'Code not supplied!'}), 400
|
| 1633 |
+
|
| 1634 |
+
# Create a temporary file to save the Python code
|
| 1635 |
+
import tempfile
|
| 1636 |
+
import uuid
|
| 1637 |
+
|
| 1638 |
+
# Generate unique filename
|
| 1639 |
+
temp_filename = f"/tmp/python_exec_{uuid.uuid4().hex}.py"
|
| 1640 |
+
|
| 1641 |
+
try:
|
| 1642 |
+
# Write code to temporary file
|
| 1643 |
+
with open(temp_filename, 'w') as f:
|
| 1644 |
+
f.write(code)
|
| 1645 |
+
|
| 1646 |
+
# Execute the file using subprocess to capture all output
|
| 1647 |
+
result = subprocess.run(
|
| 1648 |
+
['/usr/bin/python3', temp_filename],
|
| 1649 |
+
stdout=subprocess.PIPE,
|
| 1650 |
+
stderr=subprocess.PIPE,
|
| 1651 |
+
text=True,
|
| 1652 |
+
timeout=30 # 30 second timeout
|
| 1653 |
+
)
|
| 1654 |
+
|
| 1655 |
+
# Clean up the temporary file
|
| 1656 |
+
try:
|
| 1657 |
+
os.remove(temp_filename)
|
| 1658 |
+
except:
|
| 1659 |
+
pass # Ignore cleanup errors
|
| 1660 |
+
|
| 1661 |
+
# Prepare response
|
| 1662 |
+
output = result.stdout
|
| 1663 |
+
error_output = result.stderr
|
| 1664 |
+
|
| 1665 |
+
# Combine output and errors if both exist
|
| 1666 |
+
combined_message = output
|
| 1667 |
+
if error_output:
|
| 1668 |
+
combined_message += ('\n' + error_output) if output else error_output
|
| 1669 |
+
|
| 1670 |
+
# Determine status based on return code and errors
|
| 1671 |
+
if result.returncode != 0:
|
| 1672 |
+
status = 'error'
|
| 1673 |
+
if not error_output:
|
| 1674 |
+
# If no stderr but non-zero return code, add a generic error message
|
| 1675 |
+
error_output = f"Process exited with code {result.returncode}"
|
| 1676 |
+
combined_message = combined_message + '\n' + error_output if combined_message else error_output
|
| 1677 |
+
else:
|
| 1678 |
+
status = 'success'
|
| 1679 |
+
|
| 1680 |
+
return jsonify({
|
| 1681 |
+
'status': status,
|
| 1682 |
+
'message': combined_message,
|
| 1683 |
+
'need_more': False, # Not applicable for file execution
|
| 1684 |
+
'output': output, # stdout only
|
| 1685 |
+
'error': error_output, # stderr only
|
| 1686 |
+
'return_code': result.returncode
|
| 1687 |
+
})
|
| 1688 |
+
|
| 1689 |
+
except subprocess.TimeoutExpired:
|
| 1690 |
+
# Clean up the temporary file on timeout
|
| 1691 |
+
try:
|
| 1692 |
+
os.remove(temp_filename)
|
| 1693 |
+
except:
|
| 1694 |
+
pass
|
| 1695 |
+
|
| 1696 |
+
return jsonify({
|
| 1697 |
+
'status': 'error',
|
| 1698 |
+
'message': 'Execution timeout: Code took too long to execute',
|
| 1699 |
+
'error': 'TimeoutExpired',
|
| 1700 |
+
'need_more': False,
|
| 1701 |
+
'output': None,
|
| 1702 |
+
}), 500
|
| 1703 |
+
|
| 1704 |
+
except Exception as e:
|
| 1705 |
+
# Clean up the temporary file on error
|
| 1706 |
+
try:
|
| 1707 |
+
os.remove(temp_filename)
|
| 1708 |
+
except:
|
| 1709 |
+
pass
|
| 1710 |
+
|
| 1711 |
+
# Capture the exception details
|
| 1712 |
+
return jsonify({
|
| 1713 |
+
'status': 'error',
|
| 1714 |
+
'message': f'Execution error: {str(e)}',
|
| 1715 |
+
'error': traceback.format_exc(),
|
| 1716 |
+
'need_more': False,
|
| 1717 |
+
'output': None,
|
| 1718 |
+
}), 500
|
| 1719 |
+
|
| 1720 |
+
|
| 1721 |
+
@app.route("/run_bash_script", methods=['POST'])
|
| 1722 |
+
def run_bash_script():
|
| 1723 |
+
data = request.json
|
| 1724 |
+
script = data.get('script', None)
|
| 1725 |
+
timeout = data.get('timeout', 100) # Default timeout of 30 seconds
|
| 1726 |
+
working_dir = data.get('working_dir', None)
|
| 1727 |
+
|
| 1728 |
+
if not script:
|
| 1729 |
+
return jsonify({
|
| 1730 |
+
'status': 'error',
|
| 1731 |
+
'output': 'Script not supplied!',
|
| 1732 |
+
'error': "", # Always empty as requested
|
| 1733 |
+
'returncode': -1
|
| 1734 |
+
}), 400
|
| 1735 |
+
|
| 1736 |
+
# Expand user directory if provided
|
| 1737 |
+
if working_dir:
|
| 1738 |
+
working_dir = os.path.expanduser(working_dir)
|
| 1739 |
+
if not os.path.exists(working_dir):
|
| 1740 |
+
return jsonify({
|
| 1741 |
+
'status': 'error',
|
| 1742 |
+
'output': f'Working directory does not exist: {working_dir}',
|
| 1743 |
+
'error': "", # Always empty as requested
|
| 1744 |
+
'returncode': -1
|
| 1745 |
+
}), 400
|
| 1746 |
+
|
| 1747 |
+
# Create a temporary script file
|
| 1748 |
+
import tempfile
|
| 1749 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.sh', delete=False) as tmp_file:
|
| 1750 |
+
if "#!/bin/bash" not in script:
|
| 1751 |
+
script = "#!/bin/bash\n\n" + script
|
| 1752 |
+
tmp_file.write(script)
|
| 1753 |
+
tmp_file_path = tmp_file.name
|
| 1754 |
+
|
| 1755 |
+
try:
|
| 1756 |
+
# Make the script executable
|
| 1757 |
+
os.chmod(tmp_file_path, 0o755)
|
| 1758 |
+
|
| 1759 |
+
# Execute the script
|
| 1760 |
+
if platform_name == "Windows":
|
| 1761 |
+
# On Windows, use Git Bash or WSL if available, otherwise cmd
|
| 1762 |
+
flags = subprocess.CREATE_NO_WINDOW
|
| 1763 |
+
# Try to use bash if available (Git Bash, WSL, etc.)
|
| 1764 |
+
result = subprocess.run(
|
| 1765 |
+
['bash', tmp_file_path],
|
| 1766 |
+
stdout=subprocess.PIPE,
|
| 1767 |
+
stderr=subprocess.STDOUT, # Merge stderr into stdout
|
| 1768 |
+
text=True,
|
| 1769 |
+
timeout=timeout,
|
| 1770 |
+
cwd=working_dir,
|
| 1771 |
+
creationflags=flags,
|
| 1772 |
+
shell=False
|
| 1773 |
+
)
|
| 1774 |
+
else:
|
| 1775 |
+
# On Unix-like systems, use bash directly
|
| 1776 |
+
flags = 0
|
| 1777 |
+
result = subprocess.run(
|
| 1778 |
+
['/bin/bash', tmp_file_path],
|
| 1779 |
+
stdout=subprocess.PIPE,
|
| 1780 |
+
stderr=subprocess.STDOUT, # Merge stderr into stdout
|
| 1781 |
+
text=True,
|
| 1782 |
+
timeout=timeout,
|
| 1783 |
+
cwd=working_dir,
|
| 1784 |
+
creationflags=flags,
|
| 1785 |
+
shell=False
|
| 1786 |
+
)
|
| 1787 |
+
|
| 1788 |
+
# Log the command execution for trajectory recording
|
| 1789 |
+
_append_event("BashScript",
|
| 1790 |
+
{"script": script, "output": result.stdout, "error": "", "returncode": result.returncode},
|
| 1791 |
+
ts=time.time())
|
| 1792 |
+
|
| 1793 |
+
return jsonify({
|
| 1794 |
+
'status': 'success' if result.returncode == 0 else 'error',
|
| 1795 |
+
'output': result.stdout, # Contains both stdout and stderr merged
|
| 1796 |
+
'error': "", # Always empty as requested
|
| 1797 |
+
'returncode': result.returncode
|
| 1798 |
+
})
|
| 1799 |
+
|
| 1800 |
+
except subprocess.TimeoutExpired:
|
| 1801 |
+
return jsonify({
|
| 1802 |
+
'status': 'error',
|
| 1803 |
+
'output': f'Script execution timed out after {timeout} seconds',
|
| 1804 |
+
'error': "", # Always empty as requested
|
| 1805 |
+
'returncode': -1
|
| 1806 |
+
}), 500
|
| 1807 |
+
except FileNotFoundError:
|
| 1808 |
+
# Bash not found, try with sh
|
| 1809 |
+
try:
|
| 1810 |
+
result = subprocess.run(
|
| 1811 |
+
['sh', tmp_file_path],
|
| 1812 |
+
stdout=subprocess.PIPE,
|
| 1813 |
+
stderr=subprocess.STDOUT, # Merge stderr into stdout
|
| 1814 |
+
text=True,
|
| 1815 |
+
timeout=timeout,
|
| 1816 |
+
cwd=working_dir,
|
| 1817 |
+
shell=False
|
| 1818 |
+
)
|
| 1819 |
+
|
| 1820 |
+
_append_event("BashScript",
|
| 1821 |
+
{"script": script, "output": result.stdout, "error": "", "returncode": result.returncode},
|
| 1822 |
+
ts=time.time())
|
| 1823 |
+
|
| 1824 |
+
return jsonify({
|
| 1825 |
+
'status': 'success' if result.returncode == 0 else 'error',
|
| 1826 |
+
'output': result.stdout, # Contains both stdout and stderr merged
|
| 1827 |
+
'error': "", # Always empty as requested
|
| 1828 |
+
'returncode': result.returncode,
|
| 1829 |
+
})
|
| 1830 |
+
except Exception as e:
|
| 1831 |
+
return jsonify({
|
| 1832 |
+
'status': 'error',
|
| 1833 |
+
'output': f'Failed to execute script: {str(e)}',
|
| 1834 |
+
'error': "", # Always empty as requested
|
| 1835 |
+
'returncode': -1
|
| 1836 |
+
}), 500
|
| 1837 |
+
except Exception as e:
|
| 1838 |
+
return jsonify({
|
| 1839 |
+
'status': 'error',
|
| 1840 |
+
'output': f'Failed to execute script: {str(e)}',
|
| 1841 |
+
'error': "", # Always empty as requested
|
| 1842 |
+
'returncode': -1
|
| 1843 |
+
}), 500
|
| 1844 |
+
finally:
|
| 1845 |
+
# Clean up the temporary file
|
| 1846 |
+
try:
|
| 1847 |
+
os.unlink(tmp_file_path)
|
| 1848 |
+
except:
|
| 1849 |
+
pass
|
| 1850 |
+
|
| 1851 |
+
if __name__ == '__main__':
|
| 1852 |
+
app.run(debug=True, host="0.0.0.0")
|
osworld_plugin/update_qcow2.sh
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Script to update main.py in ubuntu.qcow2 image
|
| 3 |
+
# Usage: sudo ./update_qcow2.sh
|
| 4 |
+
#
|
| 5 |
+
# This script copies the customized main.py (with /pyautogui endpoint)
|
| 6 |
+
# into the QCOW2 VM image used by sandbox-platform.
|
| 7 |
+
#
|
| 8 |
+
# IMPORTANT: After running this script, you must destroy and recreate
|
| 9 |
+
# any running VMs to use the updated main.py.
|
| 10 |
+
|
| 11 |
+
set -e
|
| 12 |
+
|
| 13 |
+
# Check for root privileges
|
| 14 |
+
if [ "$EUID" -ne 0 ]; then
|
| 15 |
+
echo "β This script must be run as root (use sudo)"
|
| 16 |
+
exit 1
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
# Check for required tools
|
| 20 |
+
if ! command -v qemu-nbd &> /dev/null; then
|
| 21 |
+
echo "β qemu-nbd not found. Installing qemu-utils..."
|
| 22 |
+
apt-get update && apt-get install -y qemu-utils
|
| 23 |
+
fi
|
| 24 |
+
|
| 25 |
+
if ! command -v modprobe &> /dev/null; then
|
| 26 |
+
echo "β modprobe not found. Please install kmod package."
|
| 27 |
+
exit 1
|
| 28 |
+
fi
|
| 29 |
+
|
| 30 |
+
# Configuration
|
| 31 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 32 |
+
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
| 33 |
+
|
| 34 |
+
QCOW2_IMAGE="${REPO_ROOT}/mnt/qemu-image/ubuntu.qcow2"
|
| 35 |
+
SOURCE_FILE="${SCRIPT_DIR}/main.py"
|
| 36 |
+
MOUNT_POINT="/mnt/qcow2"
|
| 37 |
+
NBD_DEVICE="/dev/nbd0"
|
| 38 |
+
|
| 39 |
+
echo "π Updating main.py in qcow2 image..."
|
| 40 |
+
echo " Source: ${SOURCE_FILE}"
|
| 41 |
+
echo " Target: ${QCOW2_IMAGE}"
|
| 42 |
+
|
| 43 |
+
# Check if source file exists
|
| 44 |
+
if [ ! -f "$SOURCE_FILE" ]; then
|
| 45 |
+
echo "β Source file not found: $SOURCE_FILE"
|
| 46 |
+
exit 1
|
| 47 |
+
fi
|
| 48 |
+
|
| 49 |
+
# Check if qcow2 image exists
|
| 50 |
+
if [ ! -f "$QCOW2_IMAGE" ]; then
|
| 51 |
+
echo "β QCOW2 image not found: $QCOW2_IMAGE"
|
| 52 |
+
exit 1
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
# Load nbd module if not loaded
|
| 56 |
+
if ! lsmod | grep -q nbd; then
|
| 57 |
+
echo "π¦ Loading nbd module..."
|
| 58 |
+
modprobe nbd max_part=8
|
| 59 |
+
fi
|
| 60 |
+
|
| 61 |
+
# Disconnect if already connected
|
| 62 |
+
if [ -b "${NBD_DEVICE}p1" ]; then
|
| 63 |
+
echo "β οΈ NBD device already connected, disconnecting first..."
|
| 64 |
+
umount "$MOUNT_POINT" 2>/dev/null || true
|
| 65 |
+
qemu-nbd --disconnect "$NBD_DEVICE" 2>/dev/null || true
|
| 66 |
+
sleep 1
|
| 67 |
+
fi
|
| 68 |
+
|
| 69 |
+
# Create mount point if not exists
|
| 70 |
+
mkdir -p "$MOUNT_POINT"
|
| 71 |
+
|
| 72 |
+
# Connect qemu-nbd
|
| 73 |
+
echo "π Connecting qemu-nbd..."
|
| 74 |
+
qemu-nbd --connect="$NBD_DEVICE" "$QCOW2_IMAGE"
|
| 75 |
+
sleep 2
|
| 76 |
+
|
| 77 |
+
# Mount partition 3 (Linux filesystem)
|
| 78 |
+
echo "π Mounting partition..."
|
| 79 |
+
mount "${NBD_DEVICE}p3" "$MOUNT_POINT"
|
| 80 |
+
|
| 81 |
+
# Copy the file
|
| 82 |
+
echo "π Copying main.py..."
|
| 83 |
+
cp "$SOURCE_FILE" "$MOUNT_POINT/home/user/server/main.py"
|
| 84 |
+
echo "β
Copy successful"
|
| 85 |
+
|
| 86 |
+
# Unmount
|
| 87 |
+
echo "π€ Unmounting..."
|
| 88 |
+
umount "$MOUNT_POINT"
|
| 89 |
+
|
| 90 |
+
# Disconnect nbd
|
| 91 |
+
echo "π Disconnecting nbd..."
|
| 92 |
+
qemu-nbd --disconnect "$NBD_DEVICE"
|
| 93 |
+
|
| 94 |
+
echo ""
|
| 95 |
+
echo "β
Done! main.py has been updated in the qcow2 image."
|
| 96 |
+
echo ""
|
| 97 |
+
echo "β οΈ IMPORTANT: Existing running VMs still use the OLD main.py."
|
| 98 |
+
echo " To use the updated version, destroy and recreate your runners:"
|
| 99 |
+
echo " - Stop current task execution"
|
| 100 |
+
echo " - Runners will be recreated automatically on next task run"
|