Download frozen/trace2task/visual_nanojev_agentnet.py from dongjintao/GUI-Swift-4B: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/dongjintao/GUI-Swift-4B/resolve/main/frozen/trace2task/visual_nanojev_agentnet.py
- Command line
-
hf download hf://dongjintao/GUI-Swift-4B/frozen/trace2task/visual_nanojev_agentnet.py
-
curl -L -o visual_nanojev_agentnet.py https://huggingface.co/dongjintao/GUI-Swift-4B/resolve/main/frozen/trace2task/visual_nanojev_agentnet.py
11.3 kB
| """Conservative AgentNet code-to-action adapter, without training admission. | |
| Source semantics inspected at OpenCUA dfc91ba89f700d10f26ec50362d308571482ab8b. | |
| Coordinates are already normalized by width/height and rounded to four decimals. | |
| The original code must be retained in audit evidence by the caller. This module | |
| never executes it, fabricates intermediate observations, or guesses drag duration. | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import json | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from .visual_nanojev_data import validate_action, validate_step | |
| class Adaptation: | |
| action: dict | None | |
| reason: str | |
| # Syntax/contract conversion is not screenshot or semantic admission. | |
| training_admitted: bool = False | |
| def _calls(code): | |
| if not isinstance(code, str) or not code or len(code) > 100000: | |
| raise ValueError("missing_or_oversize_code") | |
| try: | |
| tree = ast.parse(code) | |
| except (SyntaxError, RecursionError): | |
| raise ValueError("syntax_invalid") from None | |
| calls = [] | |
| for statement in tree.body: | |
| if not isinstance(statement, ast.Expr) or not isinstance(statement.value, ast.Call): | |
| raise ValueError("non_call_statement") # noqa: TRY004 - invalid source program value | |
| call = statement.value | |
| if ( | |
| not isinstance(call.func, ast.Attribute) | |
| or not isinstance(call.func.value, ast.Name) | |
| or call.func.value.id not in {"pyautogui", "computer"} | |
| ): | |
| raise ValueError("unsupported_callee") | |
| kwargs = {} | |
| try: | |
| args = [ast.literal_eval(arg) for arg in call.args] | |
| for kw in call.keywords: | |
| if kw.arg is None or kw.arg in kwargs: | |
| raise ValueError("expanded_or_duplicate_keyword") | |
| kwargs[kw.arg] = ast.literal_eval(kw.value) | |
| except (ValueError, TypeError, RecursionError): | |
| raise ValueError("nonliteral_or_ambiguous_arguments") from None | |
| calls.append((call.func.value.id + "." + call.func.attr, args, kwargs)) | |
| if not calls: | |
| raise ValueError("empty_code") | |
| return calls | |
| def adapt_code(code): | |
| """Return a validated candidate action or an explicit rejection reason.""" | |
| try: | |
| calls = _calls(code) | |
| except ValueError as error: | |
| return Adaptation(None, str(error)) | |
| action = None | |
| if len(calls) == 2 and calls[0][0] == "pyautogui.moveTo": | |
| _, start_args, position = calls[0] | |
| name, args, kwargs = calls[1] | |
| if name == "pyautogui.dragTo": | |
| return Adaptation(None, "drag_duration_not_in_source") | |
| if name == "pyautogui.scroll" and not start_args and set(position) == {"x", "y"}: | |
| if len(args) != 1 or kwargs: | |
| return Adaptation(None, "unsupported_scroll_signature") | |
| action = {"skill": "scroll", "args": {**position, "wheel_units": args[0]}} | |
| if action is None and len(calls) != 1: | |
| return Adaptation(None, "unsupported_macro_without_intermediate_observations") | |
| if action is None: | |
| name, args, kwargs = calls[0] | |
| click_types = { | |
| "pyautogui.click": ("click", "left"), | |
| "pyautogui.doubleClick": ("double_click", "left"), | |
| "pyautogui.rightClick": ("click", "right"), | |
| "pyautogui.middleClick": ("click", "middle"), | |
| } | |
| if name in click_types: | |
| if args or set(kwargs) != {"x", "y"}: | |
| return Adaptation(None, "unsupported_click_signature") | |
| skill, button = click_types[name] | |
| action = {"skill": skill, "args": {**kwargs, "button": button}} | |
| elif name == "pyautogui.write": | |
| if args or set(kwargs) != {"message"}: | |
| return Adaptation(None, "unsupported_write_signature") | |
| action = {"skill": "type_text", "args": {"text": kwargs["message"]}} | |
| elif name == "pyautogui.press": | |
| if len(args) == 1 and set(kwargs) <= {"presses"}: | |
| if "presses" in kwargs and ( | |
| type(kwargs["presses"]) is not int or kwargs["presses"] != 1 | |
| ): | |
| return Adaptation(None, "repeated_press_not_single_action") | |
| key = args[0] | |
| elif not args and set(kwargs) == {"keys"}: | |
| key = kwargs["keys"] | |
| else: | |
| return Adaptation(None, "unsupported_press_signature") | |
| if isinstance(key, list): | |
| if len(key) != 1: | |
| return Adaptation(None, "key_sequence_not_single_action") | |
| key = key[0] | |
| action = {"skill": "press_key", "args": {"key": key}} | |
| elif name == "pyautogui.hotkey": | |
| if len(args) != 1 or kwargs or not isinstance(args[0], list): | |
| return Adaptation(None, "unsupported_hotkey_signature") | |
| action = {"skill": "hotkey", "args": {"keys": args[0]}} | |
| elif name == "computer.terminate": | |
| return Adaptation(None, "terminal_status_and_screenshot_require_review") | |
| elif name == "pyautogui.scroll": | |
| return Adaptation(None, "scroll_location_missing") | |
| elif name == "pyautogui.dragTo": | |
| return Adaptation(None, "drag_start_and_duration_missing") | |
| else: | |
| return Adaptation(None, "unsupported_action_type") | |
| try: | |
| return Adaptation(validate_action(action), "converted_contract_only") | |
| except (ValueError, TypeError): | |
| return Adaptation(None, "outside_action_contract") | |
| def audit_conversion(annotation): | |
| """Retain the all-step denominator; never export raw text or training rows.""" | |
| reasons, types = Counter(), Counter() | |
| rows = full = steps = 0 | |
| with Path(annotation).open() as stream: | |
| for line in stream: | |
| row = json.loads(line) | |
| rows += 1 | |
| accepted = 0 | |
| for step in row["traj"]: | |
| result = adapt_code(step.get("value", {}).get("code")) | |
| reasons[result.reason] += 1 | |
| steps += 1 | |
| if result.action is not None: | |
| accepted += 1 | |
| types[result.action.get("skill", "done")] += 1 | |
| full += bool(row["traj"]) and accepted == len(row["traj"]) | |
| return { | |
| "rows": rows, | |
| "steps": steps, | |
| "reasons": dict(reasons), | |
| "candidate_action_types": dict(types), | |
| "all_steps_convertible_rows": full, | |
| "training_admitted": False, | |
| "images_opened": 0, | |
| "source_code_executed": False, | |
| } | |
| def adapt_sequence(code): | |
| """Preserve an official source step as ordered primitives, without execution. | |
| Unlike the historical single-action adapter, movement and scrolling remain | |
| separate actions. Missing drag duration retains the source API default; | |
| termination teaches demonstration stopping, never independently verified success. | |
| """ | |
| try: | |
| actions = [] | |
| for name, args, kwargs in _calls(code): | |
| skill, values = None, None | |
| if name in {"pyautogui.moveTo", "pyautogui.dragTo"}: | |
| expected = {"x", "y"} | ({"button"} if name.endswith("dragTo") else set()) | |
| if args or set(kwargs) != expected: | |
| raise ValueError("unsupported_pointer_signature") | |
| skill = "move_to" if name.endswith("moveTo") else "drag_to" | |
| values = kwargs | |
| elif name in {"pyautogui.scroll", "pyautogui.hscroll"}: | |
| if len(args) == 1 and not kwargs: | |
| units = args[0] | |
| elif not args and set(kwargs) == {"clicks"}: | |
| units = kwargs["clicks"] | |
| else: | |
| raise ValueError("unsupported_wheel_signature") | |
| skill = "wheel" if name.endswith(".scroll") else "horizontal_wheel" | |
| values = {"wheel_units": units} | |
| elif name in {"computer.tripleClick", "pyautogui.tripleClick"}: | |
| if args or set(kwargs) != {"x", "y"}: | |
| raise ValueError("unsupported_triple_click_signature") | |
| skill, values = "triple_click", {**kwargs, "button": "left"} | |
| elif name == "computer.terminate": | |
| if args or set(kwargs) != {"status"} or kwargs["status"] not in {"success", "fail"}: | |
| raise ValueError("unsupported_terminal_signature") | |
| actions.append({"done": True}) | |
| continue | |
| elif name == "pyautogui.press": | |
| if len(args) == 1 and set(kwargs) <= {"presses"}: | |
| keys, repeats = args[0], kwargs.get("presses", 1) | |
| elif not args and set(kwargs) == {"keys"}: | |
| keys, repeats = kwargs["keys"], 1 | |
| else: | |
| raise ValueError("unsupported_press_signature") | |
| if type(repeats) is not int or not 1 <= repeats <= 10000: | |
| raise ValueError("invalid_repeat_count") | |
| keys = keys if isinstance(keys, list) else [keys] | |
| if not keys: | |
| raise ValueError("empty_key_sequence") | |
| for _ in range(repeats): | |
| for key in keys: | |
| actions.append( | |
| validate_action({"skill": "press_key", "args": {"key": key}}) | |
| ) | |
| continue | |
| elif name == "pyautogui.hotkey": | |
| if len(args) != 1 or kwargs or not isinstance(args[0], list) or not args[0]: | |
| raise ValueError("unsupported_hotkey_signature") | |
| keys = args[0] | |
| if len(keys) > 4 or len(set(keys)) != len(keys): | |
| # Preserve even repeated key events exactly as the official | |
| # hotkey API: down in order, up in reverse; never deduplicate. | |
| for event, event_keys in (("key_down", keys), ("key_up", keys[::-1])): | |
| for key in event_keys: | |
| actions.append(validate_action({"skill": event, "args": {"key": key}})) | |
| continue | |
| # PyAutoGUI presses hotkey keys down in order and releases them | |
| # in reverse. A one-key hotkey is therefore exactly a key press. | |
| skill = "press_key" if len(keys) == 1 else "hotkey" | |
| values = {"key": keys[0]} if len(keys) == 1 else {"keys": keys} | |
| else: | |
| # Serialize literal calls only; parsing this string never runs it. | |
| arguments = [repr(value) for value in args] | |
| arguments.extend(f"{key}={value!r}" for key, value in kwargs.items()) | |
| result = adapt_code(f"{name}({', '.join(arguments)})") | |
| if result.action is None: | |
| raise ValueError(result.reason) | |
| actions.append(result.action) | |
| continue | |
| actions.append(validate_action({"skill": skill, "args": values})) | |
| return Adaptation(validate_step({"actions": actions}), "converted_source_sequence") | |
| except (TypeError, ValueError) as error: | |
| return Adaptation(None, str(error)) | |