""" 用户自定义节点(Python 拓展节点)。 用户在自己的 .py 文件里写这么两段: ToolName = { name: "转大写", icon: "text", input: [ {type: "str", name: "A1", value: ""}, {type: "bool", name: "B1", value: true}, {type: "list", name: "L1", value: []}, ], output: [ {type: "exec", name: "e1"}, {type: "exec", name: "e2"}, {type: "str", name: "xx"}, ], } def run(ctx, node): ctx.log("收到:", node["input"]["A1"]) node["output"]["xx"] = "666" node["output"]["e1"] = True # 多个 exec 只能一个为 True node["output"]["e2"] = False return node 内核把它变成一种可用的节点类型。 --------------------------------------------------------------------------- # 三条语义(**必须在文档和界面上都写清楚**,不然用户一定踩) --------------------------------------------------------------------------- # 【1】node["input"][名] 拿到的是**引擎填进去的实际值**,不是声明里的 value。 声明里的 value 只是"这根线没接的时候用什么"。一旦有线接进来, 引擎会在跑之前把它覆盖成上游传过来的值。 所以千万别把声明里的 value 当"运行时的值"读 —— 那是默认值。 【2】多个 exec 输出:**最多只能有一个为 True**。 这就是"多路分支"。规则和判断节点保持一致: · 恰好一个 True → 走那一条,其余不执行 · 一个都不 True → **停在原地**,并在节点上报一条警告 (不猜、不顺走第一条 —— 猜错了用户根本查不出来) · 超过一个 True → 报错(引擎没法替你选) 非 exec 的输出(str / num / bool / list)不受这条限制, 它们的值会照常沿数据线传给下游。 【3】return 什么无所谓。 引擎读的是 node["output"] 这个字典,不看 run() 的返回值。 `return node` 只是写着顺眼,留着也行。 --------------------------------------------------------------------------- # 为什么这样设计(而不是让用户写完整节点类) --------------------------------------------------------------------------- # 用户要的是"像写一个函数那样加一种节点"。声明 + run() 正好是两层: 上面那层(引脚、类型)让引擎和界面能自动处理连线和校验, 下面那层就是纯代码。用户不用知道什么 exec 传播、什么拓扑排序。 只用标准库。 """ import os import sys import threading import traceback # 单个自定义节点最多跑多久(和会议里的 Python 节点同一套兜底) RUN_TIMEOUT = 10 # 引脚类型:exec 是执行引脚,其余是数据引脚 PIN_KINDS = ('exec', 'str', 'bool', 'num', 'list') def nodes_dir() -> str: """自定义节点放在数据目录下的 nodes/(安卓上那里可写,源码目录只读)""" try: import paths base = paths.get().data_dir except Exception: # noqa: BLE001 base = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') return os.path.join(base, 'nodes') def _find_decl(ns: dict) -> tuple: """ 在模块命名空间里找那份声明。 约定是"**同时有 input 和 output 两个键的字典**",不要求变量名叫什么 —— 用户想叫 ToolName / MyNode / 转大写 都行。 """ for key, value in ns.items(): if key.startswith('__') or not isinstance(value, dict): continue if 'input' in value and 'output' in value: return key, value return '', None def _norm_pins(raw, kind: str) -> list: """把用户写的 input / output 规整成统一的引脚列表""" out = [] for i, item in enumerate(raw or []): if not isinstance(item, dict): continue ptype = str(item.get('type') or '').strip() name = str(item.get('name') or '').strip() if not ptype or not name: continue if ptype not in PIN_KINDS: # 类型写错了要说出来,静默忽略会让用户以为节点没加载 raise ValueError(f'{kind}[{i}] 的类型 "{ptype}" 不认识,只能是 {"/".join(PIN_KINDS)}') pin = {'type': ptype, 'name': name} if kind == 'input' and 'value' in item: pin['value'] = item['value'] if item.get('label'): pin['label'] = str(item['label']) out.append(pin) return out def _explain(exc: Exception, code: str) -> str: """ 把 Python 的报错翻译成"用户能照着改"的话。 ★ 最常见的一个:把 JS 的对象写法搬过来了 —— ToolName = { name:"转大写", input:[...] } 键没加引号,Python 会报 `NameError: name 'name' is not defined`。 这条报错本身完全看不出问题在哪,所以专门认出来并给出正确写法。 (这是真实踩过的:用户给的第一版就是这么写的。) """ msg = f'{type(exc).__name__}: {exc}' # 找代码里"像键但没加引号"的行:行首(可有缩进)一个标识符后面直接跟冒号 bare = [] for line in code.splitlines(): s = line.strip() if not s or s.startswith('#'): continue head = s.split(':', 1)[0].strip() if ':' in s else '' if ( head and head.isidentifier() and not s.startswith(('"', "'", '{', '[')) and 'lambda' not in s # 排除 Python 自己的语法:def / if / for / while / else / try ... and head not in ( 'def', 'if', 'elif', 'else', 'for', 'while', 'try', 'except', 'finally', 'with', 'class', 'return', 'lambda', 'case', ) ): bare.append(head) if bare: uniq = [] for b in bare: if b not in uniq: uniq.append(b) sample = '、'.join(f'"{b}":' for b in uniq[:3]) return ( f'{msg}\n' f'→ 看起来有键忘了加引号({"、".join(uniq[:3])})。' f'这是 Python,不是 JS:\n' f' 要写 {sample} …,不能写 {uniq[0]}: …\n' f' (两种写法看着差不多,Python 会把没引号的当成变量名)' ) if isinstance(exc, NameError): text = str(exc) bad = text.split("'")[1] if text.count("'") >= 2 else '' if bad: return ( f'{msg}\n' f'→ 检查一下是不是「{bad}:」这个键忘了加引号,' f'或者是 run() 里用了一个没定义的变量名。' ) return msg def load_file(path: str) -> dict: """ 加载一个自定义节点文件。返回节点定义;出错时返回 {'error': 说明}。 """ name = os.path.splitext(os.path.basename(path))[0] try: with open(path, 'r', encoding='utf-8') as fh: code = fh.read() except OSError as exc: return {'error': f'读不了这个文件:{exc}'} ns = {'__name__': f'custom_node_{name}'} try: exec(compile(code, path, 'exec'), ns) except Exception as exc: # noqa: BLE001 return {'error': _explain(exc, code)} var_name, decl = _find_decl(ns) if decl is None: return { 'error': '没找到节点声明 —— 需要一个同时有 input 和 output ' '两个键的字典,比如 ToolName = {"input": [...], "output": [...]}', } fn = ns.get('run') if not callable(fn): return {'error': '没找到 run 函数 —— 约定是 def run(ctx, node):'} try: ins = _norm_pins(decl.get('input'), 'input') outs = _norm_pins(decl.get('output'), 'output') except ValueError as exc: return {'error': str(exc)} if not any(p['type'] == 'exec' for p in outs): # 没有 exec 出口的话这个节点就没法接在执行链上了。 # 不拦(可以当纯数据节点用),但要提醒。 pass return { 'file': path, 'varName': var_name, 'key': f'custom_{name}', 'label': str(decl.get('name') or name), 'desc': str(decl.get('desc') or ''), 'icon': str(decl.get('icon') or ''), 'inputs': ins, 'outputs': outs, 'code': code, # 有 exec 入口就是执行节点,否则是被"拉取"的纯节点 'hasExecIn': any(p['type'] == 'exec' for p in ins), } def load_all() -> list: """加载 nodes/ 下的全部 .py,按文件名排序(顺序稳定,界面列表才不会跳)""" folder = nodes_dir() if not os.path.isdir(folder): return [] defs = [] for fname in sorted(os.listdir(folder)): if not fname.endswith('.py') or fname.startswith('_'): continue defs.append(load_file(os.path.join(folder, fname))) return defs def list_defs() -> list: """给界面用的:好的坏的都返回(坏的带 error,界面上要能看见)""" return load_all() def by_key(key: str) -> dict: for d in load_all(): if d.get('key') == key: return d return {} class CustomNodeError(Exception): pass def run_custom(defn: dict, inputs: dict, variables: dict, node: dict, log_sink: list) -> tuple: """ 跑一个自定义节点。返回 (outputs, error)。 outputs 是 {引脚名: 值};exec 引脚的值是 True/False。 """ class Ctx: def __init__(self): self.input = dict(inputs) self.vars = dict(variables or {}) self.nodeId = node.get('id') self.node = node def log(self, *parts): text = ' '.join(str(p) for p in parts) log_sink.append(text) def set_var(self, name, value): variables[str(name)] = str(value) def get_var(self, name, default=''): return self.vars.get(str(name), default) ctx = Ctx() result = {'outs': {}, 'err': ''} def work(): try: ns = {'__name__': 'custom_node_run'} exec(compile(defn.get('code') or '', defn.get('file') or '<节点>', 'exec'), ns) _, decl = _find_decl(ns) if decl is None: result['err'] = '运行时找不到节点声明' return fn = ns.get('run') if not callable(fn): result['err'] = '运行时找不到 run 函数' return # ★【1】把**引擎的实际值**填进去,并且把 input / output # **从声明的列表换成按名字取的字典**。 # # 为什么必须换:用户声明的时候写的是列表 # "input": [ {"type":"str","name":"A1"} ] # (列表才能表达顺序和类型),但 run() 里读的是名字 # node["input"]["A1"] # 这两个对不上,报的是 "list indices must be integers"。 # 声明用列表、运行时用字典,是两边都自然的形式 —— # 引擎负责在中间转一次,用户不用知道。 in_dict = {} for pin in defn.get('inputs') or []: if pin['type'] == 'exec': continue name = pin['name'] # 有线接进来就用线上的值,没接就用声明里的默认值 in_dict[name] = inputs.get(name, pin.get('value')) decl['input'] = in_dict # 出口同样换成字典:exec 默认 False,数据默认空;用户按名字赋值 out_dict = {} for pin in defn.get('outputs') or []: out_dict[pin['name']] = False if pin['type'] == 'exec' else '' decl['output'] = out_dict # 跑(第二个参数就是这份声明本身 —— 用户写 ToolName["output"]["xx"] 也是它) fn(ctx, decl) # 读回出口 outs = dict(out_dict) raw_out = decl.get('output') if isinstance(raw_out, dict): for k in outs: if k in raw_out: outs[k] = raw_out[k] elif isinstance(raw_out, list): for item in raw_out: if isinstance(item, dict) and item.get('name') in outs: outs[item['name']] = item.get('value', outs[item['name']]) result['outs'] = outs except Exception as exc: # noqa: BLE001 result['err'] = f'{type(exc).__name__}: {exc}' log_sink.append(traceback.format_exc().splitlines()[-1]) th = threading.Thread(target=work, daemon=True) th.start() th.join(RUN_TIMEOUT) if th.is_alive(): return {}, f'超过 {RUN_TIMEOUT} 秒还没跑完(可能有死循环)' return result['outs'], result['err'] def split_execs(defn: dict, outs: dict) -> tuple: """ ★【2】把 exec 出口按"最多一个 True"的规则理清楚。 返回 (走哪几个 exec 引脚的**名字**, 警告说明)。 """ names = [p['name'] for p in (defn.get('outputs') or []) if p['type'] == 'exec'] if not names: return [], '' on = [n for n in names if _truthy(outs.get(n))] if len(on) == 1: return on, '' if not on: return [], ('这个节点一个 exec 出口都没置 True —— 执行链在这里停了。' '要往下走就至少把一个 exec 出口设成 True。') return on[:1], (f'有 {len(on)} 个 exec 出口同时是 True({"、".join(on)})—— ' f'只能走一个,这次走了「{on[0]}」。') def _truthy(v) -> bool: if isinstance(v, bool): return v if v is None: return False return str(v).strip().lower() not in ('', '0', 'false', 'no', 'off', 'none')