Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
"""
|
| 2 |
-
THE Z AI โ Computer Mode Server
|
| 3 |
-
====================================================
|
| 4 |
-
ู
|
| 5 |
-
|
| 6 |
-
- ุง
|
| 7 |
-
- ุง
|
| 8 |
-
-
|
| 9 |
-
- ุฏุนู
|
| 10 |
"""
|
| 11 |
|
| 12 |
import asyncio
|
|
@@ -17,24 +17,19 @@ import os
|
|
| 17 |
import re
|
| 18 |
import subprocess
|
| 19 |
import time
|
|
|
|
| 20 |
|
| 21 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 22 |
from fastapi.middleware.cors import CORSMiddleware
|
| 23 |
from fastapi.responses import JSONResponse
|
| 24 |
import uvicorn
|
| 25 |
|
| 26 |
-
# โโโ ENV โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 27 |
DISPLAY = os.environ.get("DISPLAY", ":1")
|
| 28 |
os.environ["DISPLAY"] = DISPLAY
|
| 29 |
|
| 30 |
-
app = FastAPI(title="Z-Computer-Mode API
|
| 31 |
-
app.add_middleware(
|
| 32 |
-
|
| 33 |
-
allow_origins=["*"],
|
| 34 |
-
allow_credentials=True,
|
| 35 |
-
allow_methods=["*"],
|
| 36 |
-
allow_headers=["*"],
|
| 37 |
-
)
|
| 38 |
|
| 39 |
active_connections: list[WebSocket] = []
|
| 40 |
stream_active = False
|
|
@@ -42,17 +37,107 @@ stream_fps = 3
|
|
| 42 |
stream_quality = 60
|
| 43 |
stream_scale = 0.5
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# โโโ Screen Capture โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 47 |
|
| 48 |
def capture_screen(scale=0.6, quality=65) -> str:
|
| 49 |
try:
|
| 50 |
tmp = f"/tmp/zs_{int(time.time()*1000)}.png"
|
| 51 |
-
r = subprocess.run(
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
timeout=8, capture_output=True
|
| 55 |
-
)
|
| 56 |
if r.returncode != 0 or not os.path.exists(tmp):
|
| 57 |
return _capture_xwd(scale, quality)
|
| 58 |
from PIL import Image
|
|
@@ -87,67 +172,123 @@ def _capture_xwd(scale=0.6, quality=65) -> str:
|
|
| 87 |
buf = io.BytesIO()
|
| 88 |
img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=True)
|
| 89 |
return base64.b64encode(buf.getvalue()).decode()
|
| 90 |
-
except
|
| 91 |
-
print(f"[capture_xwd] {e}")
|
| 92 |
return ""
|
| 93 |
|
| 94 |
|
| 95 |
-
# โโโ Command Runner
|
| 96 |
-
|
| 97 |
-
def run_command(cmd: str, timeout: int = 45) -> dict:
|
| 98 |
-
"""
|
| 99 |
-
ูููุฐ ุฃู
ุฑ bash ูููุชุธุฑ ุญุชู ููุชูู.
|
| 100 |
-
ูุฏุนู
:
|
| 101 |
-
- curl ู
ุน user-agent ุตุญูุญ
|
| 102 |
-
- python3 ู
ุน ุงูู
ูุชุจุงุช ุงูู
ุซุจุชุฉ
|
| 103 |
-
- ุฃูุงู
ุฑ ุทูููุฉ ุญุชู 45 ุซุงููุฉ
|
| 104 |
-
"""
|
| 105 |
-
# ุญูู user-agent ุชููุงุฆูุงู ูุฃูุงู
ุฑ curl ุจุฏููู
|
| 106 |
-
if "curl" in cmd and "user-agent" not in cmd.lower() and "-A" not in cmd:
|
| 107 |
-
cmd = cmd.replace(
|
| 108 |
-
"curl ",
|
| 109 |
-
'curl -A "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36" ',
|
| 110 |
-
1
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
env = {
|
| 114 |
-
**os.environ,
|
| 115 |
-
"DISPLAY": DISPLAY,
|
| 116 |
-
"PYTHONIOENCODING": "utf-8",
|
| 117 |
-
"LANG": "en_US.UTF-8",
|
| 118 |
-
}
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
try:
|
| 121 |
-
result = subprocess.run(
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
capture_output=True,
|
| 125 |
-
text=True,
|
| 126 |
-
timeout=timeout,
|
| 127 |
-
env=env,
|
| 128 |
-
executable="/bin/bash"
|
| 129 |
-
)
|
| 130 |
-
stdout = result.stdout
|
| 131 |
-
stderr = result.stderr
|
| 132 |
-
|
| 133 |
-
# ูุง ููุทุน ุงููุชุงุฆุฌ โ ูุงู
ูุฉ ุฏุงุฆู
ุงู (ุญุชู 15000 ุญุฑู)
|
| 134 |
return {
|
| 135 |
-
"stdout": stdout[-15000:]
|
| 136 |
-
"stderr": stderr[-
|
| 137 |
"returncode": result.returncode,
|
| 138 |
}
|
| 139 |
except subprocess.TimeoutExpired:
|
| 140 |
-
return {"stdout": "", "stderr": f"โฑ๏ธ Timeout
|
| 141 |
except Exception as e:
|
| 142 |
return {"stdout": "", "stderr": str(e), "returncode": -1}
|
| 143 |
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
def xdo(args: list, timeout=10) -> dict:
|
| 146 |
-
r = subprocess.run(
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
timeout=timeout, capture_output=True, text=True
|
| 150 |
-
)
|
| 151 |
return {"rc": r.returncode, "out": r.stdout, "err": r.stderr}
|
| 152 |
|
| 153 |
|
|
@@ -155,17 +296,13 @@ async def broadcast(msg: dict):
|
|
| 155 |
txt = json.dumps(msg, ensure_ascii=False)
|
| 156 |
dead = []
|
| 157 |
for ws in active_connections:
|
| 158 |
-
try:
|
| 159 |
-
|
| 160 |
-
except:
|
| 161 |
-
dead.append(ws)
|
| 162 |
for ws in dead:
|
| 163 |
if ws in active_connections:
|
| 164 |
active_connections.remove(ws)
|
| 165 |
|
| 166 |
|
| 167 |
-
# โโโ Stream Loop โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 168 |
-
|
| 169 |
async def screen_stream_loop():
|
| 170 |
global stream_active
|
| 171 |
interval = 1.0 / max(1, stream_fps)
|
|
@@ -174,8 +311,7 @@ async def screen_stream_loop():
|
|
| 174 |
frame = capture_screen(scale=stream_scale, quality=stream_quality)
|
| 175 |
if frame:
|
| 176 |
await broadcast({"type": "frame", "data": frame})
|
| 177 |
-
except:
|
| 178 |
-
pass
|
| 179 |
await asyncio.sleep(interval)
|
| 180 |
stream_active = False
|
| 181 |
|
|
@@ -189,46 +325,43 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 189 |
async def send(obj):
|
| 190 |
await ws.send_text(json.dumps(obj, ensure_ascii=False))
|
| 191 |
|
| 192 |
-
async def auto_shot(label="", delay=0.
|
| 193 |
await asyncio.sleep(delay)
|
| 194 |
-
frame = capture_screen(scale=0.7, quality=
|
| 195 |
if frame:
|
| 196 |
-
await send({
|
| 197 |
-
|
| 198 |
-
"data": frame,
|
| 199 |
-
"ts": int(time.time() * 1000),
|
| 200 |
-
"auto": True,
|
| 201 |
-
"label": label
|
| 202 |
-
})
|
| 203 |
return frame
|
| 204 |
|
| 205 |
# โโ SCREENSHOT โโ
|
| 206 |
if action == "screenshot":
|
| 207 |
frame = capture_screen(scale=0.8, quality=75)
|
| 208 |
-
await send({"type": "screenshot", "data": frame, "ts": int(time.time()
|
| 209 |
|
| 210 |
-
# โโ TERMINAL โ ุงูุฃูู
|
| 211 |
elif action == "terminal":
|
| 212 |
cmd = data.get("cmd", "")
|
| 213 |
timeout = int(data.get("timeout", 45))
|
| 214 |
if not cmd:
|
| 215 |
-
await send({"type": "terminal_result", "cmd": "", "stdout": "",
|
|
|
|
| 216 |
return
|
| 217 |
|
| 218 |
-
#
|
| 219 |
-
res =
|
| 220 |
|
| 221 |
-
# ุฃุฑุณู ุงููุชูุฌุฉ ููุฑุงู
|
| 222 |
await send({
|
| 223 |
"type": "terminal_result",
|
| 224 |
"cmd": cmd,
|
| 225 |
"stdout": res["stdout"],
|
| 226 |
-
"stderr": res
|
| 227 |
"returncode": res["returncode"],
|
|
|
|
|
|
|
| 228 |
})
|
| 229 |
|
| 230 |
-
# screenshot ุชููุงุฆู
|
| 231 |
-
await auto_shot(f"ุจุนุฏ: {cmd[:
|
| 232 |
|
| 233 |
# โโ MOUSE MOVE โโ
|
| 234 |
elif action == "mouse_move":
|
|
@@ -239,29 +372,15 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 239 |
# โโ MOUSE CLICK โโ
|
| 240 |
elif action == "mouse_click":
|
| 241 |
x, y = int(data.get("x", 0)), int(data.get("y", 0))
|
| 242 |
-
|
| 243 |
-
btn_num = {"left": "1", "middle": "2", "right": "3"}.get(button, "1")
|
| 244 |
-
double = data.get("double", False)
|
| 245 |
xdo(["mousemove", str(x), str(y)])
|
| 246 |
await asyncio.sleep(0.05)
|
| 247 |
-
if double:
|
| 248 |
xdo(["click", "--repeat", "2", "--delay", "100", btn_num])
|
| 249 |
else:
|
| 250 |
xdo(["click", btn_num])
|
| 251 |
await send({"type": "ack", "action": "mouse_click"})
|
| 252 |
-
await auto_shot("ุจุนุฏ ุงูููุฑ",
|
| 253 |
-
|
| 254 |
-
# โโ MOUSE DRAG โโ
|
| 255 |
-
elif action == "mouse_drag":
|
| 256 |
-
x1, y1 = int(data.get("x1", 0)), int(data.get("y1", 0))
|
| 257 |
-
x2, y2 = int(data.get("x2", 0)), int(data.get("y2", 0))
|
| 258 |
-
xdo(["mousemove", str(x1), str(y1)])
|
| 259 |
-
xdo(["mousedown", "1"])
|
| 260 |
-
await asyncio.sleep(0.1)
|
| 261 |
-
xdo(["mousemove", str(x2), str(y2)])
|
| 262 |
-
await asyncio.sleep(0.1)
|
| 263 |
-
xdo(["mouseup", "1"])
|
| 264 |
-
await send({"type": "ack", "action": "mouse_drag"})
|
| 265 |
|
| 266 |
# โโ KEYBOARD TYPE โโ
|
| 267 |
elif action == "keyboard_type":
|
|
@@ -269,7 +388,7 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 269 |
if text:
|
| 270 |
xdo(["type", "--clearmodifiers", "--delay", "30", text])
|
| 271 |
await send({"type": "ack", "action": "keyboard_type"})
|
| 272 |
-
await auto_shot("ุจุนุฏ ุงููุชุงุจุฉ",
|
| 273 |
|
| 274 |
# โโ KEYBOARD HOTKEY โโ
|
| 275 |
elif action == "keyboard_hotkey":
|
|
@@ -277,7 +396,7 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 277 |
if keys:
|
| 278 |
xdo(["key", "--clearmodifiers", "+".join(keys)])
|
| 279 |
await send({"type": "ack", "action": "keyboard_hotkey"})
|
| 280 |
-
await auto_shot("ุจุนุฏ ุงูุงุฎุชุตุงุฑ",
|
| 281 |
|
| 282 |
# โโ KEYBOARD PRESS โโ
|
| 283 |
elif action == "keyboard_press":
|
|
@@ -288,23 +407,19 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 288 |
|
| 289 |
# โโ CLIPBOARD โโ
|
| 290 |
elif action == "clipboard_write":
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
env={**os.environ, "DISPLAY": DISPLAY}
|
| 296 |
-
)
|
| 297 |
-
proc.communicate(text.encode())
|
| 298 |
await send({"type": "ack", "action": "clipboard_write"})
|
| 299 |
|
| 300 |
elif action == "clipboard_read":
|
| 301 |
-
res =
|
| 302 |
await send({"type": "clipboard_content", "text": res["stdout"]})
|
| 303 |
|
| 304 |
# โโ SCROLL โโ
|
| 305 |
elif action == "scroll":
|
| 306 |
-
x = int(data.get("x", 0))
|
| 307 |
-
y = int(data.get("y", 0))
|
| 308 |
clicks = int(data.get("clicks", 3))
|
| 309 |
btn = "4" if clicks > 0 else "5"
|
| 310 |
xdo(["mousemove", str(x), str(y)])
|
|
@@ -312,20 +427,30 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 312 |
xdo(["click", btn])
|
| 313 |
await send({"type": "ack", "action": "scroll"})
|
| 314 |
|
| 315 |
-
# โโ OPEN APP
|
| 316 |
elif action == "open_app":
|
| 317 |
app_cmd = data.get("cmd", "")
|
| 318 |
if app_cmd:
|
| 319 |
-
subprocess.Popen(
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
| 323 |
-
)
|
| 324 |
await send({"type": "ack", "action": "open_app", "cmd": app_cmd})
|
| 325 |
-
await auto_shot(f"ุจุนุฏ ูุชุญ: {app_cmd}",
|
| 326 |
else:
|
| 327 |
await send({"type": "ack", "action": "open_app"})
|
| 328 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
# โโ STREAM โโ
|
| 330 |
elif action == "start_stream":
|
| 331 |
global stream_active, stream_fps, stream_quality, stream_scale
|
|
@@ -343,64 +468,43 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 343 |
|
| 344 |
# โโ SCREEN INFO โโ
|
| 345 |
elif action == "screen_info":
|
| 346 |
-
res =
|
| 347 |
-
try:
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
except:
|
| 351 |
-
w, h = 1920, 1080
|
| 352 |
-
res2 = run_command("xdotool getmouselocation", timeout=5)
|
| 353 |
try:
|
| 354 |
mx = int(re.search(r"x:(\d+)", res2["stdout"]).group(1))
|
| 355 |
my = int(re.search(r"y:(\d+)", res2["stdout"]).group(1))
|
| 356 |
-
except:
|
| 357 |
-
|
| 358 |
-
await send({"type": "screen_info", "width": w, "height": h,
|
| 359 |
-
"mouse_x": mx, "mouse_y": my})
|
| 360 |
|
| 361 |
else:
|
| 362 |
await send({"type": "error", "msg": f"Unknown action: {action}"})
|
| 363 |
|
| 364 |
|
| 365 |
-
# โโโ WebSocket
|
| 366 |
|
| 367 |
@app.websocket("/ws")
|
| 368 |
async def websocket_endpoint(ws: WebSocket):
|
| 369 |
await ws.accept()
|
| 370 |
active_connections.append(ws)
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
try:
|
| 375 |
-
parts = res["stdout"].strip().split()
|
| 376 |
-
w, h = int(parts[0]), int(parts[1])
|
| 377 |
-
except:
|
| 378 |
-
w, h = 1920, 1080
|
| 379 |
-
|
| 380 |
await ws.send_text(json.dumps({
|
| 381 |
-
"type": "connected",
|
| 382 |
-
"
|
| 383 |
-
"screen_height": h,
|
| 384 |
-
"msg": "Z Computer Mode v4 โ Terminal Optimized"
|
| 385 |
}, ensure_ascii=False))
|
| 386 |
-
|
| 387 |
-
# Initial screenshot
|
| 388 |
frame = capture_screen(scale=0.75, quality=72)
|
| 389 |
if frame:
|
| 390 |
-
await ws.send_text(json.dumps({
|
| 391 |
-
|
| 392 |
-
"ts": int(time.time() * 1000), "label": "ุงูุดุงุดุฉ ุงูุฃูููุฉ"
|
| 393 |
-
}))
|
| 394 |
-
|
| 395 |
try:
|
| 396 |
while True:
|
| 397 |
raw = await ws.receive_text()
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
except
|
| 401 |
-
pass
|
| 402 |
-
except Exception as e:
|
| 403 |
-
print(f"[ws] error: {e}")
|
| 404 |
finally:
|
| 405 |
if ws in active_connections:
|
| 406 |
active_connections.remove(ws)
|
|
@@ -410,37 +514,34 @@ async def websocket_endpoint(ws: WebSocket):
|
|
| 410 |
|
| 411 |
@app.get("/screenshot")
|
| 412 |
async def rest_screenshot():
|
| 413 |
-
|
| 414 |
-
return JSONResponse({"image": frame, "ts": int(time.time() * 1000)})
|
| 415 |
-
|
| 416 |
|
| 417 |
@app.post("/terminal")
|
| 418 |
async def rest_terminal(body: dict):
|
| 419 |
-
|
| 420 |
-
res = run_command(cmd, timeout=body.get("timeout", 45))
|
| 421 |
-
return JSONResponse(res)
|
| 422 |
-
|
| 423 |
|
| 424 |
@app.get("/health")
|
| 425 |
async def health():
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
# Check curl works
|
| 430 |
-
curl_test = run_command(
|
| 431 |
-
"curl -s --max-time 5 'https://api.duckduckgo.com/?q=test&format=json&no_html=1' | python3 -c \"import sys,json;d=json.load(sys.stdin);print('OK',d.get('Type','?'))\"",
|
| 432 |
-
timeout=10
|
| 433 |
-
)
|
| 434 |
-
curl_ok = curl_test["returncode"] == 0
|
| 435 |
-
|
| 436 |
return {
|
| 437 |
"status": "ok",
|
| 438 |
-
"
|
| 439 |
-
"display_working":
|
| 440 |
-
"
|
| 441 |
-
"
|
| 442 |
}
|
| 443 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
if __name__ == "__main__":
|
| 446 |
port = int(os.environ.get("PORT", 7860))
|
|
|
|
| 1 |
"""
|
| 2 |
+
THE Z AI โ Computer Mode Server v5 โ Smart Terminal
|
| 3 |
+
====================================================
|
| 4 |
+
ุงูู
ุดููุฉ: curl ููุดู ุฃุญูุงูุงูุ ุงูุฐูุงุก ูุณุชุณูู
|
| 5 |
+
ุงูุญู ูู ุงูุณูุฑูุฑ:
|
| 6 |
+
- ุนูุฏู
ุง ูุฃุชู ุฃู
ุฑ terminal โ ูููุฐู
|
| 7 |
+
- ุฅุฐุง ูุดู ุฃู ุฌุงุก ูุงุฑุบ โ ูุฌุฑุจ ุจุฏุงุฆู ุชููุงุฆูุงู
|
| 8 |
+
- ูุฑุฌุน ุงููุชุงุฆุฌ ุงูุญููููุฉ ุฏุงุฆู
ุงู
|
| 9 |
+
- ุฏุนู
8+ ู
ุตุงุฏุฑ ุจุญุซ ุชููุงุฆูุฉ
|
| 10 |
"""
|
| 11 |
|
| 12 |
import asyncio
|
|
|
|
| 17 |
import re
|
| 18 |
import subprocess
|
| 19 |
import time
|
| 20 |
+
import urllib.parse
|
| 21 |
|
| 22 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 23 |
from fastapi.middleware.cors import CORSMiddleware
|
| 24 |
from fastapi.responses import JSONResponse
|
| 25 |
import uvicorn
|
| 26 |
|
|
|
|
| 27 |
DISPLAY = os.environ.get("DISPLAY", ":1")
|
| 28 |
os.environ["DISPLAY"] = DISPLAY
|
| 29 |
|
| 30 |
+
app = FastAPI(title="Z-Computer-Mode API v5")
|
| 31 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True,
|
| 32 |
+
allow_methods=["*"], allow_headers=["*"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
active_connections: list[WebSocket] = []
|
| 35 |
stream_active = False
|
|
|
|
| 37 |
stream_quality = 60
|
| 38 |
stream_scale = 0.5
|
| 39 |
|
| 40 |
+
# โโโ CURL HEADERS โ ูุนู
ู ู
ุน ุฌู
ูุน ุงูู
ูุงูุน โโโโโโโโโโโ
|
| 41 |
+
CURL_HEADERS = (
|
| 42 |
+
'-H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
|
| 43 |
+
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" '
|
| 44 |
+
'-H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" '
|
| 45 |
+
'-H "Accept-Language: en-US,en;q=0.9,ar;q=0.8" '
|
| 46 |
+
'-H "Accept-Encoding: gzip, deflate" '
|
| 47 |
+
'--compressed '
|
| 48 |
+
'--max-time 15 '
|
| 49 |
+
'-L ' # follow redirects
|
| 50 |
+
'-s '
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# โโโ ู
ุตุงุฏุฑ ุงูุจุญุซ โ 8 ู
ุตุงุฏุฑ โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 54 |
+
def _build_search_sources(query: str) -> list[dict]:
|
| 55 |
+
"""ูุจูู ูุงุฆู
ุฉ ู
ุตุงุฏุฑ ุจุญุซ ุจุฏููุฉ ูููููุฑู"""
|
| 56 |
+
q = urllib.parse.quote_plus(query)
|
| 57 |
+
q_raw = query.replace(' ', '+')
|
| 58 |
+
return [
|
| 59 |
+
{
|
| 60 |
+
"name": "DuckDuckGo Instant",
|
| 61 |
+
"cmd": f"curl -s 'https://api.duckduckgo.com/?q={q}&format=json&no_html=1&skip_disambig=1' | python3 -c \"import sys,json; d=json.load(sys.stdin); ans=d.get('AbstractText',''); rels=d.get('RelatedTopics',[]); print('ANSWER:',ans if ans else 'no direct answer'); [print('-',r.get('Text','')[:250]) for r in rels[:8] if isinstance(r,dict) and r.get('Text')]\""
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"name": "Google News RSS",
|
| 65 |
+
"cmd": f"curl -sL {CURL_HEADERS} 'https://news.google.com/rss/search?q={q_raw}&hl=en&gl=US&ceid=US:en' | python3 -c \"import sys,re; xml=sys.stdin.read(); titles=re.findall(r'<title><![CDATA[(.*?)]]></title>|<title>(.*?)</title>',xml); descs=re.findall(r'<description>(.*?)</description>',xml); clean=lambda s:re.sub('<[^>]+>','',s); results=[(a or b).strip() for a,b in titles if (a or b).strip()][1:9]; [print(str(i+1)+'. '+t[:180]) for i,t in enumerate(results)]\""
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"name": "Wikipedia English",
|
| 69 |
+
"cmd": f"curl -s 'https://en.wikipedia.org/api/rest_v1/page/summary/{q}' | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('title','')+'\\n'+d.get('extract','')[:1500])\" 2>/dev/null || curl -s 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={q}&format=json&srlimit=5' | python3 -c \"import sys,json; d=json.load(sys.stdin); [print(str(i+1)+'. '+r['title']+': '+re.sub('<[^>]+>','',r.get('snippet',''))[:200]) for i,r in enumerate(d.get('query',{}).get('search',[]))]\" 2>/dev/null"
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"name": "DuckDuckGo HTML",
|
| 73 |
+
"cmd": f"curl -sL {CURL_HEADERS} 'https://html.duckduckgo.com/html/?q={q}' | python3 -c \"import sys,re; h=sys.stdin.read(); snippets=re.findall(r'class=.result__snippet[^>]*>(.*?)</a>',h,re.DOTALL); titles=re.findall(r'class=.result__title[^>]*>.*?<a[^>]*>(.*?)</a>',h,re.DOTALL); clean=lambda s:re.sub('<[^>]+>','',s).strip(); [print(str(i+1)+'. '+clean(titles[i] if i<len(titles) else '')+'\\n '+clean(s)[:200]) for i,s in enumerate(snippets[:7])]\""
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"name": "Bing News RSS",
|
| 77 |
+
"cmd": f"curl -sL {CURL_HEADERS} 'https://www.bing.com/news/search?q={q}&format=RSS' | python3 -c \"import sys,re; xml=sys.stdin.read(); items=re.findall(r'<item>(.*?)</item>',xml,re.DOTALL); [print(str(i+1)+'. '+re.sub('<[^>]+>','',re.search(r'<title>(.*?)</title>',it).group(1) if re.search(r'<title>',it) else '')+'\\n '+re.sub('<[^>]+>','',re.search(r'<description>(.*?)</description>',it).group(1) if re.search(r'<description>',it) else '')[:150]) for i,it in enumerate(items[:6])]\""
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"name": "Reddit Search",
|
| 81 |
+
"cmd": f"curl -sL {CURL_HEADERS} -H 'Accept: application/json' 'https://www.reddit.com/search.json?q={q}&sort=new&limit=8&type=link' | python3 -c \"import sys,json; d=json.load(sys.stdin); posts=d.get('data',{}).get('children',[]); [print(str(i+1)+'. '+p['data'].get('title','')+'\\n r/'+p['data'].get('subreddit','')+' Score:'+str(p['data'].get('score',''))+'\\n '+p['data'].get('selftext','')[:200]) for i,p in enumerate(posts[:6])]\""
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"name": "HackerNews",
|
| 85 |
+
"cmd": f"curl -s 'https://hn.algolia.com/api/v1/search?query={q}&hitsPerPage=8&tags=story' | python3 -c \"import sys,json; d=json.load(sys.stdin); hits=d.get('hits',[]); [print(str(i+1)+'. '+h.get('title','')+'\\n Points:'+str(h.get('points','0'))+' | '+h.get('url','')[:80]) for i,h in enumerate(hits[:6])]\""
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"name": "ArXiv (academic)",
|
| 89 |
+
"cmd": f"curl -s 'https://export.arxiv.org/api/query?search_query=all:{q}&start=0&max_results=5' | python3 -c \"import sys,re; xml=sys.stdin.read(); titles=re.findall(r'<title>(.*?)</title>',xml)[1:]; summaries=re.findall(r'<summary>(.*?)</summary>',xml,re.DOTALL); [print(str(i+1)+'. '+t.strip()+'\\n '+summaries[i].strip()[:200] if i<len(summaries) else '') for i,t in enumerate(titles[:5])]\""
|
| 90 |
+
},
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _extract_query_from_cmd(cmd: str) -> str:
|
| 95 |
+
"""ูุณุชุฎุฑุฌ ููู
ุงุช ุงูุจุญุซ ู
ู ุฃู
ุฑ curl"""
|
| 96 |
+
patterns = [
|
| 97 |
+
r'[?&]q=([^&\'"]+)',
|
| 98 |
+
r'[?&]query=([^&\'"]+)',
|
| 99 |
+
r'[?&]search_query=all:([^&\'"]+)',
|
| 100 |
+
r"search\?q=([^&'\"\s]+)",
|
| 101 |
+
]
|
| 102 |
+
for p in patterns:
|
| 103 |
+
m = re.search(p, cmd)
|
| 104 |
+
if m:
|
| 105 |
+
q = m.group(1).replace('+', ' ').replace('%20', ' ')
|
| 106 |
+
return urllib.parse.unquote(q)
|
| 107 |
+
return ""
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _is_empty_result(stdout: str) -> bool:
|
| 111 |
+
"""ูุชุญูู ุฅุฐุง ูุงูุช ุงููุชูุฌุฉ ูุงุฑุบุฉ ุฃู ุจูุง ู
ุนููู
ุงุช"""
|
| 112 |
+
if not stdout or len(stdout.strip()) < 10:
|
| 113 |
+
return True
|
| 114 |
+
empty_signals = [
|
| 115 |
+
"no direct answer",
|
| 116 |
+
"no results",
|
| 117 |
+
"0 results",
|
| 118 |
+
"no items",
|
| 119 |
+
"[]",
|
| 120 |
+
"{}",
|
| 121 |
+
"error",
|
| 122 |
+
"not found",
|
| 123 |
+
"ANSWER: no",
|
| 124 |
+
]
|
| 125 |
+
s = stdout.strip().lower()
|
| 126 |
+
# ุฅุฐุง ุงููุชูุฌุฉ ูููุง ุนูุงู
ุงุช "ูุง ููุฌุฏ"
|
| 127 |
+
meaningful_lines = [l for l in s.split('\n') if l.strip() and not any(sig in l for sig in empty_signals)]
|
| 128 |
+
if len(meaningful_lines) < 1:
|
| 129 |
+
return True
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
|
| 133 |
# โโโ Screen Capture โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 134 |
|
| 135 |
def capture_screen(scale=0.6, quality=65) -> str:
|
| 136 |
try:
|
| 137 |
tmp = f"/tmp/zs_{int(time.time()*1000)}.png"
|
| 138 |
+
r = subprocess.run(["scrot", "-q", "90", tmp],
|
| 139 |
+
env={**os.environ, "DISPLAY": DISPLAY},
|
| 140 |
+
timeout=8, capture_output=True)
|
|
|
|
|
|
|
| 141 |
if r.returncode != 0 or not os.path.exists(tmp):
|
| 142 |
return _capture_xwd(scale, quality)
|
| 143 |
from PIL import Image
|
|
|
|
| 172 |
buf = io.BytesIO()
|
| 173 |
img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=True)
|
| 174 |
return base64.b64encode(buf.getvalue()).decode()
|
| 175 |
+
except:
|
|
|
|
| 176 |
return ""
|
| 177 |
|
| 178 |
|
| 179 |
+
# โโโ Command Runner โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
def run_raw_command(cmd: str, timeout: int = 45) -> dict:
|
| 182 |
+
"""ูููุฐ ุฃู
ุฑ bash ุฎุงู
"""
|
| 183 |
+
env = {**os.environ, "DISPLAY": DISPLAY,
|
| 184 |
+
"PYTHONIOENCODING": "utf-8", "LANG": "en_US.UTF-8"}
|
| 185 |
try:
|
| 186 |
+
result = subprocess.run(cmd, shell=True, capture_output=True,
|
| 187 |
+
text=True, timeout=timeout, env=env,
|
| 188 |
+
executable="/bin/bash")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
return {
|
| 190 |
+
"stdout": result.stdout[-15000:],
|
| 191 |
+
"stderr": result.stderr[-3000:],
|
| 192 |
"returncode": result.returncode,
|
| 193 |
}
|
| 194 |
except subprocess.TimeoutExpired:
|
| 195 |
+
return {"stdout": "", "stderr": f"โฑ๏ธ Timeout {timeout}s", "returncode": -1}
|
| 196 |
except Exception as e:
|
| 197 |
return {"stdout": "", "stderr": str(e), "returncode": -1}
|
| 198 |
|
| 199 |
|
| 200 |
+
def run_command_smart(cmd: str, timeout: int = 45) -> dict:
|
| 201 |
+
"""
|
| 202 |
+
ูููุฐ ุงูุฃู
ุฑ โ ุฅุฐุง ูุงู curl ุจุญุซ ููุดู/ูุฑุบ โ ูุฌุฑุจ ู
ุตุงุฏุฑ ุจุฏููุฉ ุชููุงุฆูุงู
|
| 203 |
+
ูุฑุฌุน ุงููุชูุฌุฉ ุงูุฃููู ุงูุชู ุชุญุชูู ู
ุนููู
ุงุช ุญููููุฉ
|
| 204 |
+
"""
|
| 205 |
+
# ููุฐ ุงูุฃู
ุฑ ุงูุฃุตูู ุฃููุงู
|
| 206 |
+
res = run_raw_command(cmd, timeout=timeout)
|
| 207 |
+
stdout = res["stdout"].strip()
|
| 208 |
+
|
| 209 |
+
# ุฅุฐุง ูุฌุญ ูููู ูุชุงุฆุฌ โ ุงุฑุฌุน ู
ุจุงุดุฑุฉ
|
| 210 |
+
if res["returncode"] == 0 and not _is_empty_result(stdout):
|
| 211 |
+
return res
|
| 212 |
+
|
| 213 |
+
# ูู ูู ุฃู
ุฑ curl ุจุญุซุ
|
| 214 |
+
is_curl_search = "curl" in cmd and any(x in cmd for x in [
|
| 215 |
+
"duckduckgo", "google", "bing", "wikipedia", "reddit",
|
| 216 |
+
"hackernews", "hn.algolia", "arxiv", "news", "search"
|
| 217 |
+
])
|
| 218 |
+
|
| 219 |
+
if not is_curl_search:
|
| 220 |
+
# ููุณ ุจุญุซุงู โ ุงุฑุฌุน ุงููุชูุฌุฉ ูู
ุง ูู
|
| 221 |
+
return res
|
| 222 |
+
|
| 223 |
+
# ุงุณุชุฎุฑุฌ ููู
ุงุช ุงูุจุญุซ
|
| 224 |
+
query = _extract_query_from_cmd(cmd)
|
| 225 |
+
if not query or len(query) < 3:
|
| 226 |
+
# ุญุงูู ุชุณุชุฎุฑุฌ ู
ู ุงููุต ุงูุนุงู
|
| 227 |
+
words = [w for w in cmd.split() if len(w) > 3 and not w.startswith('-')
|
| 228 |
+
and 'http' not in w and 'python3' not in w and 'curl' not in w]
|
| 229 |
+
query = ' '.join(words[:5]) if words else ""
|
| 230 |
+
|
| 231 |
+
if not query:
|
| 232 |
+
return res # ูุง ูุนุฑู ูุจุญุซ ุนู ุฅูุด
|
| 233 |
+
|
| 234 |
+
# ุฌุฑุจ ุงูู
ุตุงุฏุฑ ุงูุจุฏููุฉ ูุงุญุฏุฉ ูุงุญุฏุฉ
|
| 235 |
+
sources = _build_search_sources(query)
|
| 236 |
+
tried_names = []
|
| 237 |
+
all_results = []
|
| 238 |
+
|
| 239 |
+
# ุงูุฃู
ุฑ ุงูุฃุตูู ูุดู โ ูุจุฏุฃ ู
ู ุงูุจุฏุงุฆู
|
| 240 |
+
original_failed_msg = f"[ุงูู
ุตุฏุฑ ุงูุฃุตูู: ุฎุทุฃ/ูุงุฑุบ] "
|
| 241 |
+
|
| 242 |
+
for source in sources:
|
| 243 |
+
# ุชุฌูุจ ุชูุฑุงุฑ ููุณ ุงูููุน ุฅุฐุง ูุงู ูู ุงูุฃู
ุฑ ุงูุฃุตูู
|
| 244 |
+
src_name = source["name"]
|
| 245 |
+
if any(x in cmd.lower() for x in [src_name.lower().split()[0]]):
|
| 246 |
+
tried_names.append(f"โญ๏ธ {src_name} (ู
ุฌุฑุจ)")
|
| 247 |
+
continue
|
| 248 |
+
|
| 249 |
+
tried_names.append(f"๐ {src_name}")
|
| 250 |
+
src_res = run_raw_command(source["cmd"], timeout=20)
|
| 251 |
+
src_out = src_res["stdout"].strip()
|
| 252 |
+
|
| 253 |
+
if not _is_empty_result(src_out):
|
| 254 |
+
# ูุฌุฏูุง ูุชุงุฆุฌ!
|
| 255 |
+
combined_header = (
|
| 256 |
+
f"[ุชุนุฐุฑ ุงูุญุตูู ุนูู ูุชุงุฆุฌ ู
ู ุงูู
ุตุฏุฑ ุงูุฃุตูู]\n"
|
| 257 |
+
f"[ุงูุจุฏูู ุงูู
ุณุชุฎุฏู
: {src_name}]\n"
|
| 258 |
+
f"{'='*50}\n"
|
| 259 |
+
)
|
| 260 |
+
all_results.append(src_out)
|
| 261 |
+
# ุฌุฑุจ ู
ุตุฏุฑ ุซุงูู ูููุงุฑู
|
| 262 |
+
for source2 in sources:
|
| 263 |
+
if source2["name"] != src_name:
|
| 264 |
+
s2 = run_raw_command(source2["cmd"], timeout=15)
|
| 265 |
+
s2_out = s2["stdout"].strip()
|
| 266 |
+
if not _is_empty_result(s2_out):
|
| 267 |
+
all_results.append(f"\n[ู
ุตุฏุฑ ุฅุถุงูู: {source2['name']}]\n{s2_out}")
|
| 268 |
+
break
|
| 269 |
+
|
| 270 |
+
final_out = combined_header + "\n\n".join(all_results)
|
| 271 |
+
return {
|
| 272 |
+
"stdout": final_out[:15000],
|
| 273 |
+
"stderr": "",
|
| 274 |
+
"returncode": 0,
|
| 275 |
+
"_sources_tried": tried_names,
|
| 276 |
+
"_fallback_used": src_name,
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
# ูู ุงูู
ุตุงุฏุฑ ูุดูุช โ ุงุฑุฌุน ู
ุง ุนูุฏูุง ู
ุน ุฑุณุงูุฉ ูุงุถุญุฉ
|
| 280 |
+
return {
|
| 281 |
+
"stdout": f"[ูู
ุชูุฑุฌุน ุฃู ู
ุตุงุฏุฑ ูุชุงุฆุฌ ูู: {query}]\nุงูู
ุตุงุฏุฑ ุงูุชู ุฌุฑุจุชูุง: {', '.join(tried_names[:5])}",
|
| 282 |
+
"stderr": res["stderr"],
|
| 283 |
+
"returncode": -1,
|
| 284 |
+
"_sources_tried": tried_names,
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
def xdo(args: list, timeout=10) -> dict:
|
| 289 |
+
r = subprocess.run(["xdotool"] + args,
|
| 290 |
+
env={**os.environ, "DISPLAY": DISPLAY},
|
| 291 |
+
timeout=timeout, capture_output=True, text=True)
|
|
|
|
|
|
|
| 292 |
return {"rc": r.returncode, "out": r.stdout, "err": r.stderr}
|
| 293 |
|
| 294 |
|
|
|
|
| 296 |
txt = json.dumps(msg, ensure_ascii=False)
|
| 297 |
dead = []
|
| 298 |
for ws in active_connections:
|
| 299 |
+
try: await ws.send_text(txt)
|
| 300 |
+
except: dead.append(ws)
|
|
|
|
|
|
|
| 301 |
for ws in dead:
|
| 302 |
if ws in active_connections:
|
| 303 |
active_connections.remove(ws)
|
| 304 |
|
| 305 |
|
|
|
|
|
|
|
| 306 |
async def screen_stream_loop():
|
| 307 |
global stream_active
|
| 308 |
interval = 1.0 / max(1, stream_fps)
|
|
|
|
| 311 |
frame = capture_screen(scale=stream_scale, quality=stream_quality)
|
| 312 |
if frame:
|
| 313 |
await broadcast({"type": "frame", "data": frame})
|
| 314 |
+
except: pass
|
|
|
|
| 315 |
await asyncio.sleep(interval)
|
| 316 |
stream_active = False
|
| 317 |
|
|
|
|
| 325 |
async def send(obj):
|
| 326 |
await ws.send_text(json.dumps(obj, ensure_ascii=False))
|
| 327 |
|
| 328 |
+
async def auto_shot(label="", delay=0.4):
|
| 329 |
await asyncio.sleep(delay)
|
| 330 |
+
frame = capture_screen(scale=0.7, quality=68)
|
| 331 |
if frame:
|
| 332 |
+
await send({"type": "screenshot", "data": frame,
|
| 333 |
+
"ts": int(time.time()*1000), "auto": True, "label": label})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
return frame
|
| 335 |
|
| 336 |
# โโ SCREENSHOT โโ
|
| 337 |
if action == "screenshot":
|
| 338 |
frame = capture_screen(scale=0.8, quality=75)
|
| 339 |
+
await send({"type": "screenshot", "data": frame, "ts": int(time.time()*1000)})
|
| 340 |
|
| 341 |
+
# โโ TERMINAL โ ุงูุฃูู
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 342 |
elif action == "terminal":
|
| 343 |
cmd = data.get("cmd", "")
|
| 344 |
timeout = int(data.get("timeout", 45))
|
| 345 |
if not cmd:
|
| 346 |
+
await send({"type": "terminal_result", "cmd": "", "stdout": "",
|
| 347 |
+
"stderr": "no command", "returncode": -1})
|
| 348 |
return
|
| 349 |
|
| 350 |
+
# ุงุณุชุฎุฏู
run_command_smart โ ูุฌุฑุจ ุจุฏุงุฆู ุชููุงุฆูุงู
|
| 351 |
+
res = run_command_smart(cmd, timeout=timeout)
|
| 352 |
|
|
|
|
| 353 |
await send({
|
| 354 |
"type": "terminal_result",
|
| 355 |
"cmd": cmd,
|
| 356 |
"stdout": res["stdout"],
|
| 357 |
+
"stderr": res.get("stderr", ""),
|
| 358 |
"returncode": res["returncode"],
|
| 359 |
+
"fallback_used": res.get("_fallback_used", None),
|
| 360 |
+
"sources_tried": res.get("_sources_tried", []),
|
| 361 |
})
|
| 362 |
|
| 363 |
+
# screenshot ุชููุงุฆู
|
| 364 |
+
await auto_shot(f"ุจุนุฏ: {cmd[:45]}", delay=0.3)
|
| 365 |
|
| 366 |
# โโ MOUSE MOVE โโ
|
| 367 |
elif action == "mouse_move":
|
|
|
|
| 372 |
# โโ MOUSE CLICK โโ
|
| 373 |
elif action == "mouse_click":
|
| 374 |
x, y = int(data.get("x", 0)), int(data.get("y", 0))
|
| 375 |
+
btn_num = {"left": "1", "middle": "2", "right": "3"}.get(data.get("button","left"), "1")
|
|
|
|
|
|
|
| 376 |
xdo(["mousemove", str(x), str(y)])
|
| 377 |
await asyncio.sleep(0.05)
|
| 378 |
+
if data.get("double"):
|
| 379 |
xdo(["click", "--repeat", "2", "--delay", "100", btn_num])
|
| 380 |
else:
|
| 381 |
xdo(["click", btn_num])
|
| 382 |
await send({"type": "ack", "action": "mouse_click"})
|
| 383 |
+
await auto_shot("ุจุนุฏ ุงูููุฑ", 0.4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
# โโ KEYBOARD TYPE โโ
|
| 386 |
elif action == "keyboard_type":
|
|
|
|
| 388 |
if text:
|
| 389 |
xdo(["type", "--clearmodifiers", "--delay", "30", text])
|
| 390 |
await send({"type": "ack", "action": "keyboard_type"})
|
| 391 |
+
await auto_shot("ุจุนุฏ ุงููุชุงุจุฉ", 0.3)
|
| 392 |
|
| 393 |
# โโ KEYBOARD HOTKEY โโ
|
| 394 |
elif action == "keyboard_hotkey":
|
|
|
|
| 396 |
if keys:
|
| 397 |
xdo(["key", "--clearmodifiers", "+".join(keys)])
|
| 398 |
await send({"type": "ack", "action": "keyboard_hotkey"})
|
| 399 |
+
await auto_shot("ุจุนุฏ ุงูุงุฎุชุตุงุฑ", 0.4)
|
| 400 |
|
| 401 |
# โโ KEYBOARD PRESS โโ
|
| 402 |
elif action == "keyboard_press":
|
|
|
|
| 407 |
|
| 408 |
# โโ CLIPBOARD โโ
|
| 409 |
elif action == "clipboard_write":
|
| 410 |
+
proc = subprocess.Popen(["xclip", "-selection", "clipboard"],
|
| 411 |
+
stdin=subprocess.PIPE,
|
| 412 |
+
env={**os.environ, "DISPLAY": DISPLAY})
|
| 413 |
+
proc.communicate(data.get("text","").encode())
|
|
|
|
|
|
|
|
|
|
| 414 |
await send({"type": "ack", "action": "clipboard_write"})
|
| 415 |
|
| 416 |
elif action == "clipboard_read":
|
| 417 |
+
res = run_raw_command("xclip -selection clipboard -o", timeout=5)
|
| 418 |
await send({"type": "clipboard_content", "text": res["stdout"]})
|
| 419 |
|
| 420 |
# โโ SCROLL โโ
|
| 421 |
elif action == "scroll":
|
| 422 |
+
x, y = int(data.get("x", 0)), int(data.get("y", 0))
|
|
|
|
| 423 |
clicks = int(data.get("clicks", 3))
|
| 424 |
btn = "4" if clicks > 0 else "5"
|
| 425 |
xdo(["mousemove", str(x), str(y)])
|
|
|
|
| 427 |
xdo(["click", btn])
|
| 428 |
await send({"type": "ack", "action": "scroll"})
|
| 429 |
|
| 430 |
+
# โโ OPEN APP โโ
|
| 431 |
elif action == "open_app":
|
| 432 |
app_cmd = data.get("cmd", "")
|
| 433 |
if app_cmd:
|
| 434 |
+
subprocess.Popen(app_cmd, shell=True,
|
| 435 |
+
env={**os.environ, "DISPLAY": DISPLAY},
|
| 436 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
|
|
|
| 437 |
await send({"type": "ack", "action": "open_app", "cmd": app_cmd})
|
| 438 |
+
await auto_shot(f"ุจุนุฏ ูุชุญ: {app_cmd}", 3.0)
|
| 439 |
else:
|
| 440 |
await send({"type": "ack", "action": "open_app"})
|
| 441 |
|
| 442 |
+
# โโ DRAG โโ
|
| 443 |
+
elif action == "mouse_drag":
|
| 444 |
+
x1,y1 = int(data.get("x1",0)), int(data.get("y1",0))
|
| 445 |
+
x2,y2 = int(data.get("x2",0)), int(data.get("y2",0))
|
| 446 |
+
xdo(["mousemove", str(x1), str(y1)])
|
| 447 |
+
xdo(["mousedown", "1"])
|
| 448 |
+
await asyncio.sleep(0.1)
|
| 449 |
+
xdo(["mousemove", str(x2), str(y2)])
|
| 450 |
+
await asyncio.sleep(0.1)
|
| 451 |
+
xdo(["mouseup", "1"])
|
| 452 |
+
await send({"type": "ack", "action": "mouse_drag"})
|
| 453 |
+
|
| 454 |
# โโ STREAM โโ
|
| 455 |
elif action == "start_stream":
|
| 456 |
global stream_active, stream_fps, stream_quality, stream_scale
|
|
|
|
| 468 |
|
| 469 |
# โโ SCREEN INFO โโ
|
| 470 |
elif action == "screen_info":
|
| 471 |
+
res = run_raw_command("xdotool getdisplaygeometry", timeout=5)
|
| 472 |
+
try: parts = res["stdout"].strip().split(); w,h = int(parts[0]),int(parts[1])
|
| 473 |
+
except: w,h = 1920,1080
|
| 474 |
+
res2 = run_raw_command("xdotool getmouselocation", timeout=5)
|
|
|
|
|
|
|
|
|
|
| 475 |
try:
|
| 476 |
mx = int(re.search(r"x:(\d+)", res2["stdout"]).group(1))
|
| 477 |
my = int(re.search(r"y:(\d+)", res2["stdout"]).group(1))
|
| 478 |
+
except: mx,my = 0,0
|
| 479 |
+
await send({"type":"screen_info","width":w,"height":h,"mouse_x":mx,"mouse_y":my})
|
|
|
|
|
|
|
| 480 |
|
| 481 |
else:
|
| 482 |
await send({"type": "error", "msg": f"Unknown action: {action}"})
|
| 483 |
|
| 484 |
|
| 485 |
+
# โโโ WebSocket โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 486 |
|
| 487 |
@app.websocket("/ws")
|
| 488 |
async def websocket_endpoint(ws: WebSocket):
|
| 489 |
await ws.accept()
|
| 490 |
active_connections.append(ws)
|
| 491 |
+
res = run_raw_command("xdotool getdisplaygeometry", timeout=5)
|
| 492 |
+
try: parts = res["stdout"].strip().split(); w,h = int(parts[0]),int(parts[1])
|
| 493 |
+
except: w,h = 1920,1080
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
await ws.send_text(json.dumps({
|
| 495 |
+
"type": "connected", "screen_width": w, "screen_height": h,
|
| 496 |
+
"msg": "Z Computer Mode v5 โ Smart Terminal + Multi-Source Search"
|
|
|
|
|
|
|
| 497 |
}, ensure_ascii=False))
|
|
|
|
|
|
|
| 498 |
frame = capture_screen(scale=0.75, quality=72)
|
| 499 |
if frame:
|
| 500 |
+
await ws.send_text(json.dumps({"type":"screenshot","data":frame,
|
| 501 |
+
"ts":int(time.time()*1000),"label":"ุงูุดุงุดุฉ ุงูุฃูููุฉ"}))
|
|
|
|
|
|
|
|
|
|
| 502 |
try:
|
| 503 |
while True:
|
| 504 |
raw = await ws.receive_text()
|
| 505 |
+
await handle_action(ws, json.loads(raw))
|
| 506 |
+
except WebSocketDisconnect: pass
|
| 507 |
+
except Exception as e: print(f"[ws] {e}")
|
|
|
|
|
|
|
|
|
|
| 508 |
finally:
|
| 509 |
if ws in active_connections:
|
| 510 |
active_connections.remove(ws)
|
|
|
|
| 514 |
|
| 515 |
@app.get("/screenshot")
|
| 516 |
async def rest_screenshot():
|
| 517 |
+
return JSONResponse({"image": capture_screen(0.75,70), "ts": int(time.time()*1000)})
|
|
|
|
|
|
|
| 518 |
|
| 519 |
@app.post("/terminal")
|
| 520 |
async def rest_terminal(body: dict):
|
| 521 |
+
return JSONResponse(run_command_smart(body.get("cmd",""), body.get("timeout",45)))
|
|
|
|
|
|
|
|
|
|
| 522 |
|
| 523 |
@app.get("/health")
|
| 524 |
async def health():
|
| 525 |
+
display = run_raw_command("xdotool getdisplaygeometry", 4)
|
| 526 |
+
# Test multi-source search
|
| 527 |
+
test = run_command_smart("curl -s 'https://api.duckduckgo.com/?q=test&format=json&no_html=1'", 15)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
return {
|
| 529 |
"status": "ok",
|
| 530 |
+
"version": "v5-smart-terminal",
|
| 531 |
+
"display_working": display["returncode"] == 0,
|
| 532 |
+
"search_working": test["returncode"] == 0,
|
| 533 |
+
"fallback_used": test.get("_fallback_used"),
|
| 534 |
}
|
| 535 |
|
| 536 |
+
@app.get("/search/{query}")
|
| 537 |
+
async def quick_search(query: str):
|
| 538 |
+
"""ุงุฎุชุจุงุฑ ุณุฑูุน ููุจุญุซ"""
|
| 539 |
+
res = run_command_smart(
|
| 540 |
+
f"curl -s 'https://api.duckduckgo.com/?q={urllib.parse.quote_plus(query)}&format=json&no_html=1'",
|
| 541 |
+
timeout=30
|
| 542 |
+
)
|
| 543 |
+
return JSONResponse(res)
|
| 544 |
+
|
| 545 |
|
| 546 |
if __name__ == "__main__":
|
| 547 |
port = int(os.environ.get("PORT", 7860))
|