146 lines
16 KiB
Plaintext
146 lines
16 KiB
Plaintext
from pathlib import Path
|
|
import json,ast
|
|
R=Path.cwd();D=R/'docs/hel-892/scail-document-evidence';F=R/'docs/hel-892/scail-reference';p=next((R/'example_ComfyUI_workflows/6-动作迁移').glob('*SCAIL2*FOR*'));g=json.loads(p.read_bytes());rows=json.loads((F/'sources.json').read_bytes())['sources'];hostids={n['type']:str(n['id'])for n in g['nodes']if n['type']in {s['id']for s in g['definitions']['subgraphs']}};scopes=[('','',g)]+[(hostids[s['id']]+':',f'/definitions/subgraphs/{i}',s)for i,s in enumerate(g['definitions']['subgraphs'])]
|
|
files={'ComfyMathExpression':'comfy_extras/nodes_math.py','CreateVideo':'comfy_extras/nodes_video.py','SaveVideo':'comfy_extras/nodes_video.py','LoadVideo':'comfy_extras/nodes_video.py','GetVideoComponents':'comfy_extras/nodes_video.py','Video Slice':'comfy_extras/nodes_video.py','GetImageSize':'comfy_extras/nodes_images.py','PrimitiveStringMultiline':'comfy_extras/nodes_primitive.py','PrimitiveBoolean':'comfy_extras/nodes_primitive.py','PrimitiveInt':'comfy_extras/nodes_primitive.py','PrimitiveFloat':'comfy_extras/nodes_primitive.py','SamplerCustom':'comfy_extras/nodes_custom_sampler.py','BasicScheduler':'comfy_extras/nodes_custom_sampler.py','KSamplerSelect':'comfy_extras/nodes_custom_sampler.py','ModelSamplingSD3':'comfy_extras/nodes_model_advanced.py','ComfySwitchNode':'comfy_extras/nodes_logic.py','PreviewAny':'comfy_extras/nodes_preview_any.py','ResizeImageMaskNode':'comfy_extras/nodes_post_processing.py','BatchImagesNode':'comfy_extras/nodes_post_processing.py','ColorTransfer':'comfy_extras/nodes_post_processing.py','SCAIL2ColoredMask':'comfy_extras/nodes_wan.py','WanSCAILToVideo':'comfy_extras/nodes_wan.py','SAM3_VideoTrack':'comfy_extras/nodes_sam3.py','ImageFromBatch':'comfy_extras/nodes_images.py'}
|
|
layouts={'SetNode':['position_0'],'GetNode':['position_0'],'ComfyMathExpression':['expression'],'CreateVideo':['fps','position_1'],'SaveVideo':['filename_prefix','format','codec'],'PrimitiveStringMultiline':['value'],'PrimitiveBoolean':['value'],'PrimitiveInt':['value','control_after_generate'],'PrimitiveFloat':['value'],'LoadVideo':['file','upload'],'LoadImage':['image','upload'],'Video Slice':['start_time','duration','strict_duration'],'PreviewAny':['position_0','position_1','position_2'],'Display Any (rgthree)':['position_0'],'INTConstant':['value'],'LoraLoaderModelOnly':['lora_name','strength_model'],'VAELoader':['vae_name'],'CLIPLoader':['clip_name','type','device'],'CLIPVisionLoader':['clip_name'],'UNETLoader':['unet_name','weight_dtype'],'ModelSamplingSD3':['shift'],'KSamplerSelect':['sampler_name'],'BasicScheduler':['scheduler','steps','denoise'],'SamplerCustom':['add_noise','noise_seed','control_after_generate','cfg'],'ComfySwitchNode':['switch'],'ImageFromBatch':['batch_index','length'],'CLIPTextEncode':['text'],'CheckpointLoaderSimple':['ckpt_name'],'SCAIL2ColoredMask':['object_indices','sort_by','replacement_mode'],'SAM3_VideoTrack':['detection_threshold','max_objects','detect_interval'],'WanSCAILToVideo':['width','height','length','batch_size','pose_strength','pose_start','pose_end','video_frame_offset','previous_frame_count','replacement_mode'],'ResizeImageMaskNode':['resize_type','resize_type.width','resize_type.height','resize_type.crop','scale_method'],'CLIPVisionEncode':['crop'],'ColorTransfer':['method','source_stats','strength'],'MathExpression|pysssss':['expression'],'easy forLoopStart':['total'],'easy showAnything':['position_0']}
|
|
bindings={};ls={}
|
|
for pre,ptr,s in scopes:
|
|
for n in s['nodes']:
|
|
typ=n['type'];nid=pre+str(n['id']);v=n.get('properties',{}).get('ver')
|
|
if typ in ['Note','MarkdownNote']:continue
|
|
if typ in hostids:bindings[nid]=('boundary','','');ls[nid]=[];continue
|
|
if not v:bindings[nid]=('unknown','',typ)
|
|
else:
|
|
if n['properties'].get('cnr_id')=='comfy-core':key={'0.19.3':'core0193','0.24.0':'core0240','0.25.0':'core0250','0.27.1':'core0271'}[v];file=files.get(typ,'nodes.py');symbol=typ
|
|
elif typ=='INTConstant':key,file,symbol='kjint','nodes/nodes.py','INTConstant'
|
|
elif typ=='Display Any (rgthree)':key,file,symbol='rgthree','py/display_any.py','RgthreeDisplayAny'
|
|
elif typ.startswith('easy '):key,file,symbol='easy','py/nodes/logic.py',typ[5:]
|
|
elif typ=='MathExpression|pysssss':key,file,symbol='mathpkg','py/math_expression.py','MathExpression'
|
|
else:raise ValueError((nid,typ,v))
|
|
e=next(x for x in rows if x['id']==key and x['file']==file);tree=ast.parse((F/e['local_file']).read_bytes())
|
|
for c in tree.body:
|
|
if not isinstance(c,ast.ClassDef):continue
|
|
if c.name==symbol or any(isinstance(x,ast.keyword)and x.arg=='node_id'and isinstance(x.value,ast.Constant)and x.value.value==typ for m in c.body if isinstance(m,ast.FunctionDef)and m.name=='define_schema'for x in ast.walk(m)):symbol=c.name;break
|
|
bindings[nid]=(key,file,symbol)
|
|
w=n.get('widgets_values')
|
|
if isinstance(w,list):ls[nid]=layouts.get(typ,[]);assert len(ls[nid])==len(w),(nid,typ,len(ls[nid]),len(w))
|
|
helper=(R/'docs/hel-892/dualloop-document-evidence/build_definition.py').read_text();func=helper[helper.index('def canonical'):helper.index('\ndef build(')]
|
|
header='''"""Scoped exact-declaration reference; parse AST/text only, never upstream imports."""
|
|
import ast
|
|
import copy
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
REPO = Path(__file__).resolve().parents[3]
|
|
OUT = Path(__file__).resolve().parent
|
|
REF = OUT.parent / "scail-reference"
|
|
'''
|
|
header+='PATHS = '+repr([str(p.relative_to(R))])+'\nHOSTS = '+repr(hostids)+'\nBINDINGS = '+repr(bindings)+'\nLAYOUTS = '+repr(ls)+'\n'
|
|
(D/'build_definition.py').write_text(header+'\n'+func+'\n'+'''def scoped_graphs(g):
|
|
return [("", "", g)] + [(HOSTS[s["id"]] + ":", f"/definitions/subgraphs/{i}", s)
|
|
for i, s in enumerate(g["definitions"]["subgraphs"])]
|
|
|
|
|
|
def build(index=0):
|
|
raw = (REPO / PATHS[index]).read_bytes()
|
|
g = json.loads(raw)
|
|
prose = json.loads((OUT / "prose.json").read_bytes())
|
|
editorial = json.loads((OUT / "editorial.json").read_bytes())
|
|
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
|
|
sources, trees = [], {}
|
|
for e in manifest:
|
|
data = (REF / e["local_file"]).read_bytes()
|
|
assert hashlib.sha256(data).hexdigest() == e["sha256"]
|
|
sources.append(dict(e, local_file="../scail-reference/" + e["local_file"],
|
|
lines=[1,len(data.decode().splitlines())],
|
|
claim="准确声明提交/发布成员,仅静态;源码许可不是模型素材许可,目标/恢复未知"))
|
|
if e["file"].endswith(".py"):
|
|
trees[e["local_file"]] = ast.parse(data)
|
|
fields, comments, bindings, empty, flow = [], [], [], [], []
|
|
boundaries = []
|
|
for pre, prefix, graph in scoped_graphs(g):
|
|
scope = "root" if not pre else "宿主" + pre[:-1] + "内部定义"
|
|
edge_by_id = {e[0] if isinstance(e,list) else e["id"]: e for e in graph["links"]}
|
|
for ni,n in enumerate(graph["nodes"]):
|
|
nid, ptr = pre + str(n["id"]), f"{prefix}/nodes/{ni}"
|
|
flow.append(nid + " 原节点完整保存 " + json.dumps(n,ensure_ascii=False))
|
|
if n["type"] in ["Note","MarkdownNote"]:
|
|
comments.append(dict(node_id=nid,pointer=ptr+"/widgets_values/0",
|
|
text=n["widgets_values"][0],meaning=prose["notes"][nid],evidence=[]))
|
|
continue
|
|
key,file,symbol = BINDINGS[nid]
|
|
cl, schema, rs, candidates = None, {}, [], []
|
|
if key not in ["unknown","boundary"]:
|
|
ei = next(i for i,e in enumerate(manifest) if e["id"] == key and e["file"] == file)
|
|
entry = manifest[ei]
|
|
cl = next((c for c in trees[entry["local_file"]].body if isinstance(c,ast.ClassDef) and c.name == symbol),None)
|
|
rs = [i for i,e in enumerate(manifest) if e["id"] == key]
|
|
if cl:
|
|
sources.append(dict(sources[ei],lines=[cl.lineno,cl.end_lineno],claim=f"{nid}准确{key}类{symbol}静态schema/实现;原额外项/协议冲突另列"))
|
|
rs.append(len(sources)-1)
|
|
schema = node_schema(cl)
|
|
candidates = [dict(source=ei,symbol=symbol,lines=[cl.lineno,cl.end_lineno])]
|
|
if n["type"] == "ResizeImageMaskNode":
|
|
# Exact SCALE_DIMENSIONS branch, not a different resize branch.
|
|
method = next(m for m in cl.body if isinstance(m,ast.FunctionDef) and m.name == "define_schema")
|
|
option = next(c for c in ast.walk(method) if isinstance(c,ast.Call) and isinstance(c.func,ast.Attribute) and c.func.attr == "Option" and c.args and isinstance(c.args[0],ast.Attribute) and c.args[0].attr == "SCALE_DIMENSIONS")
|
|
for c in ast.walk(option):
|
|
if isinstance(c,ast.Call) and isinstance(c.func,ast.Attribute) and c.func.attr == "Input" and c.args and isinstance(c.args[0],ast.Constant):
|
|
name = c.args[0].value
|
|
default = next((ast.unparse(k.value) for k in c.keywords if k.arg == "default"),"无显式default")
|
|
schema["resize_type."+name] = (default,ast.unparse(c))
|
|
schema["resize_type.crop"] = schema["crop"]
|
|
source_id = "subgraph-definition" if key == "boundary" else "unknown-no-version" if key == "unknown" else key if cl else "unresolved-"+key
|
|
bindings.append(dict(node_id=nid,class_type=n["type"],source_version=n.get("properties",{}).get("ver","未知:没有准确版本"),source_id=source_id,candidates=candidates,declared_provider=n.get("properties",{}).get("cnr_id"),implementation_verified=cl is not None,scope=scope,
|
|
notice="宿主仅原定义边界,不当后端类" if key == "boundary" else "准确类/具体未匹配/无版本分列,不借同名或后版补实"))
|
|
effect = editorial[nid] + " 原mode=0,不认证执行;无具名保存,不补具名值/双指针。"
|
|
flow.append(effect)
|
|
w = n.get("widgets_values")
|
|
if "widgets_values" not in n or w is None or w == []:
|
|
empty.append(dict(node_id=nid,class_type=n["type"],pointer=ptr,scope=scope,
|
|
state="missing" if "widgets_values" not in n else "null" if w is None else "empty_list",named_state="missing",effect=effect))
|
|
continue
|
|
for j,(name,value) in enumerate(zip(LAYOUTS[nid],w,strict=True)):
|
|
known = name in schema
|
|
inp = next((i for i,x in enumerate(n.get("inputs",[])) if x["name"] == name),None)
|
|
link = n["inputs"][inp].get("link") if inp is not None else None
|
|
e = edge_by_id.get(link)
|
|
boundary_link = pre and isinstance(e,dict) and e["origin_id"] == graph["inputNode"]["id"]
|
|
aux = name == "control_after_generate" or (n["type"] in ["LoadImage","LoadVideo"] and name == "upload") or n["type"] == "Display Any (rgthree)"
|
|
role = "boundary_saved_cache" if known and boundary_link else "linked_override" if known and link is not None else "frontend_only" if aux else "schema_input" if known else "extra_saved"
|
|
default,limits = schema.get(name,("未知:无准确后端字段/额外保存,不借后版补默认","未知:额外保存或准确实现未核准,原位置/控件名不等于后端支持"))
|
|
evidence = rs + ([i for i,e in enumerate(manifest) if e["id"] in ["frontend","litegraph"]] if aux else [])
|
|
fields.append(dict(node_id=nid,definition_node_id=str(n["id"]),scope=scope,class_type=n["type"],field=name,label=prose["labels"].get(name,name+"原保存(映射与额外项分列)"),pointer=ptr+"/widgets_values/"+str(j),value=value,json_type=type(value).__name__,named_state="missing",
|
|
input_pointer=f"{ptr}/inputs/{inp}" if known and inp is not None else "未知:无准确后端字段映射,不由位置/同名补实",input_name=name if known and inp is not None else None,type=limits,role=role,schema_default=default,limits=limits,unit=prose["units"].get(nid+"."+name,"准确schema类型/原JSON类型分列;无明确物理单位则未知"),effect=effect+(" 原边界连接缓存;宿主外线/空口和proxy映射另列,非恢复或生效证明。" if boundary_link else "")+(" 此原保存不在准确schema,不能认证生效/恢复。" if not known and not aux else ""),evidence=evidence,
|
|
execution_note="仅静态保存与源码;未构造prompt/执行插件模型SAM媒体表达式随机循环采样解码I/O清理;转换/执行资格不变。"))
|
|
flow += [scope+" 物理/边界记录 "+json.dumps(e,ensure_ascii=False) for e in graph["links"]]
|
|
if pre:
|
|
host = next(n for n in g["nodes"] if str(n["id"])+":" == pre)
|
|
boundary = dict(host_node_id=str(host["id"]),definition_id=graph["id"],pointer=prefix,
|
|
host=host,inputNode=graph["inputNode"],outputNode=graph["outputNode"],inputs=graph["inputs"],outputs=graph["outputs"],widgets=graph["widgets"],state=graph["state"],extra=graph["extra"],
|
|
proxyWidgets=host["properties"]["proxyWidgets"],proxy_mappings=[])
|
|
for pi,(target,widget) in enumerate(host["properties"]["proxyWidgets"]):
|
|
n = next(n for n in graph["nodes"] if str(n["id"]) == target)
|
|
preview = widget == "$$canvas-image-preview"
|
|
f = next((f for f in fields if f["node_id"] == pre+target and f["field"] == widget),None)
|
|
assert preview or f is not None
|
|
inp = next((x for x in n.get("inputs",[]) if x["name"] == widget),None)
|
|
internal_edge = edge_by_id.get(inp.get("link")) if inp else None
|
|
host_slot = internal_edge["origin_slot"] if isinstance(internal_edge,dict) and internal_edge["origin_id"] == graph["inputNode"]["id"] else None
|
|
mapping = dict(proxy_index=pi,raw=[target,widget],node_id=pre+target,widget=widget,
|
|
preview_only=preview,**(dict(saved_pointer=f["pointer"],saved_value=f["value"]) if f else {}),
|
|
backend_mapping_verified=f["input_name"] is not None if f else False,
|
|
internal_origin_edge=internal_edge,
|
|
definition_input=graph["inputs"][host_slot] if host_slot is not None else None,
|
|
host_input=host["inputs"][host_slot] if host_slot is not None else None,
|
|
scope="原proxy/控件/保存位置/边界origin结构核准;后端schema缺口和宿主恢复另列;预览不造保存项")
|
|
boundary["proxy_mappings"].append(mapping)
|
|
flow.append("宿主"+str(host["id"])+" proxy原映射 "+json.dumps(mapping,ensure_ascii=False))
|
|
boundaries.append(boundary)
|
|
flow.append("宿主"+str(host["id"])+" 三scope原边界 "+json.dumps(boundary,ensure_ascii=False))
|
|
flow += ["根附加属性 "+json.dumps(g["extra"],ensure_ascii=False)] + prose["steps"]
|
|
assert len(fields) == 195 and len(comments) == 10 and len(boundaries) == 3
|
|
return dict(source_path=PATHS[index],source_sha1=hashlib.sha1(raw).hexdigest(),source_sha256=hashlib.sha256(raw).hexdigest(),canonical_sha256=hashlib.sha256(canonical(g)).hexdigest(),notice=prose["notice"],user_overview=prose["overview"],versions=prose["versions"],counts=dict(saved_fields=195,root_saved_fields=sum(f["scope"]=="root" for f in fields),internal_saved_fields=sum(f["scope"]!="root" for f in fields),linked_saved_fields=sum(f["role"]=="linked_override" for f in fields),boundary_saved_fields=sum(f["role"]=="boundary_saved_cache" for f in fields),frontend_only=sum(f["role"]=="frontend_only" for f in fields),source_nodes=149,root_nodes=53,internal_nodes=96,physical_edges=254,source_notes=10,proxy_widgets=48,proxy_saved_references=44,proxy_previews=4,final_scalars=0,final_prompt_constructed=False),node_bindings=bindings,fields=fields,sources=sources,comments=comments,flow=flow,flow_evidence=[],zero_saved_nodes=empty,boundaries=boundaries,steps=[prose["overview"]]+prose["steps"])
|
|
''')
|
|
print('Prepared explicit scoped builder/bindings',len(bindings),'layouts',len(ls))
|