2026-10-17 10:46:29 +08:00

181 lines
6.8 KiB
Python

from __future__ import annotations
import json
import threading
from pathlib import Path
from typing import TYPE_CHECKING
from .base import BrowserScript, ScriptStep
if TYPE_CHECKING:
from logging import LoggerAdapter
from desktop_app import BrowserInstance
from ocr_task import OCRService
# Script definitions live here as JSON files; editing or adding one takes effect
# on the next script start (or dropdown refresh) without restarting the client.
SCRIPT_DIR = Path(__file__).resolve().parent.parent / "data" / "scripts"
STEP_KINDS = {
"home",
"ocr_click",
"scroll_ocr_click",
"await_click",
"delay_click",
"cond_ratio_click",
"cond_ocr_click",
"gray_end",
"delay_home",
"loop",
}
_lock = threading.Lock()
# path -> (mtime, class) cache; refreshed whenever the file changes on disk.
_cache: dict[Path, tuple[float, type[BrowserScript]]] = {}
# path -> last error message; kept so broken files are reported once per change.
_errors: dict[Path, str] = {}
def _normalize_absent(raw: dict) -> None:
"""Let "absent" be a single text or a list of texts (any one blocks).
Splits an array form into absent (first text) + alt_absents (the rest) so
ScriptStep stays a flat str/tuple pair.
"""
absent = raw.get("absent")
if isinstance(absent, list):
texts = [text for text in absent if text]
extras = [text for text in (raw.get("alt_absents") or []) if text]
raw["absent"] = texts[0] if texts else ""
raw["alt_absents"] = texts[1:] + extras
def _validate(spec: dict, path: Path) -> list[ScriptStep]:
"""Check one script spec and turn its steps into ScriptStep objects."""
for key in ("script_id", "label", "steps"):
if not spec.get(key):
raise ValueError(f"missing required field {key!r}")
raw_steps = spec["steps"]
if not isinstance(raw_steps, list) or not raw_steps:
raise ValueError("'steps' must be a non-empty list")
steps: list[ScriptStep] = []
for index, raw in enumerate(raw_steps):
if not isinstance(raw, dict):
raise ValueError(f"step {index} must be an object")
kind = raw.get("kind")
if kind not in STEP_KINDS:
raise ValueError(f"step {index}: unknown kind {kind!r}")
if not raw.get("label"):
raise ValueError(f"step {index}: missing label")
_normalize_absent(raw)
for field in ("alt_texts", "alt_confirms", "alt_absents"):
if field in raw and isinstance(raw[field], list):
raw[field] = tuple(raw[field])
steps.append(ScriptStep(**raw))
total = len(steps)
for index, step in enumerate(steps):
for field, minimum in (("loop_to", 0), ("skip_to", 0)):
value = getattr(step, field)
if value >= minimum and value >= total:
raise ValueError(
f"step {index}: {field}={value} out of range (script has {total} steps)"
)
return steps
def _build_class(spec: dict, steps: list[ScriptStep], path: Path) -> type[BrowserScript]:
def name(self: BrowserScript) -> str:
return self.label
return type(
f"JsonScript_{spec['script_id']}",
(BrowserScript,),
{
"script_id": str(spec["script_id"]),
"label": str(spec["label"]),
"target_text": str(spec.get("target_text", "")),
"click_offset_y_ratio": float(spec.get("click_offset_y_ratio", 0.0)),
"steps": steps,
"name": name,
"__module__": f"data.scripts.{path.stem}",
},
)
def build_debug_script_class(raw_steps: list) -> type[BrowserScript]:
"""Build an ad-hoc script class from raw step dicts (the live debug panel).
Accepts the same step objects as the JSON files; missing labels are filled
in so a pasted single step runs as-is.
"""
if not isinstance(raw_steps, list) or not raw_steps:
raise ValueError("需要至少一个步骤对象")
steps: list[ScriptStep] = []
for index, raw in enumerate(raw_steps):
if not isinstance(raw, dict):
raise ValueError(f"step {index} 必须是 JSON 对象")
raw = dict(raw)
raw.setdefault("label", f"调试步骤 {index + 1}")
kind = raw.get("kind")
if kind not in STEP_KINDS:
raise ValueError(f"step {index}: unknown kind {kind!r}")
_normalize_absent(raw)
for field in ("alt_texts", "alt_confirms", "alt_absents"):
if field in raw and isinstance(raw[field], list):
raw[field] = tuple(raw[field])
try:
steps.append(ScriptStep(**raw))
except TypeError as exc:
raise ValueError(f"step {index}: {exc}") from exc
total = len(steps)
for index, step in enumerate(steps):
for field in ("loop_to", "skip_to"):
value = getattr(step, field)
if value >= total:
raise ValueError(
f"step {index}: {field}={value} 超出范围(共 {total} 步)"
)
return _build_class({"script_id": "_debug", "label": "实时调试步骤"}, steps, Path("debug"))
def load_script_classes(logger: "LoggerAdapter | None" = None) -> list[type[BrowserScript]]:
"""Return every valid script class from data/scripts/*.json.
Files are re-read whenever their mtime changes, so editing a script takes
effect immediately; broken files are skipped with one error logged per change.
"""
with _lock:
SCRIPT_DIR.mkdir(parents=True, exist_ok=True)
classes: list[type[BrowserScript]] = []
for path in sorted(SCRIPT_DIR.glob("*.json")):
try:
mtime = path.stat().st_mtime
except OSError:
continue
cached = _cache.get(path)
if cached is not None and cached[0] == mtime:
classes.append(cached[1])
continue
try:
spec = json.loads(path.read_text(encoding="utf-8"))
steps = _validate(spec, path)
script_class = _build_class(spec, steps, path)
except (json.JSONDecodeError, ValueError, TypeError) as exc:
message = f"invalid script file {path.name}: {exc}"
if _errors.get(path) != message:
_errors[path] = message
(logger or __import__("logging").getLogger(__name__)).error(message)
_cache.pop(path, None)
continue
_errors.pop(path, None)
_cache[path] = (mtime, script_class)
classes.append(script_class)
# Drop cache entries for files deleted from disk.
for path in list(_cache):
if not path.exists():
del _cache[path]
_errors.pop(path, None)
return classes