orlecampos's picture
Upload folder using huggingface_hub
adbeee5 verified
Raw History Blame Contribute Delete
5.32 kB
#!/usr/bin/env python3
"""UI/graph -> API/prompt converter usando /object_info. Server-side."""
import json, sys, urllib.request
WF=sys.argv[1]; OBJ=sys.argv[2]; OUT=sys.argv[3]
CHAR=sys.argv[4] if len(sys.argv)>4 else "awa"
PROMPT=sys.argv[5] if len(sys.argv)>5 else None
g=json.load(open(WF))
oi=json.load(open(OBJ))
nodes={n["id"]:n for n in g["nodes"]}
# ---- EDITS (PhotoFlow-specific; guard p/ outros workflows como LTX) ----
if 289 in nodes:
ls=nodes[289]; wv=ls["widgets_values"]
b=3+(8-1)*4 # loraStack slot 8
wv[b]=f"{CHAR}_identity_v1.safetensors"; wv[b+1]=1.0; wv[b+2]=1; wv[b+3]=1
if PROMPT and 529 in nodes:
nodes[529]["widgets_values"][0]=PROMPT
# ---- link map ----
links={}
for l in g.get("links",[]):
# [id, src_node, src_slot, dst_node, dst_slot, type]
links[l[0]]=(l[1],l[2])
NOTE_TYPES={"MarkdownNote","Note","Reroute"}
def widget_groups(class_type):
"""[(name, has_control)] dos inputs widget-capable, na ordem de declaracao."""
info=oi.get(class_type)
if not info: return None
groups=[]
inp=info.get("input",{})
for sect in ("required","optional"):
for name,spec in inp.get(sect,{}).items():
t=spec[0]
opts=spec[1] if len(spec)>1 and isinstance(spec[1],dict) else {}
# COMBO aparece como lista de opcoes OU como a string "COMBO" (varia por nó)
is_widget = isinstance(t,list) or t in ("INT","FLOAT","STRING","BOOLEAN","COMBO")
if is_widget:
# seed/noise_seed sempre ganham control_after_generate no frontend
hc = (name in ("seed","noise_seed")) or bool(opts.get("control_after_generate"))
groups.append((name,hc))
return groups
# Tipos descartados de proposito (pass-through): upscaler SeedVR2 pesado/idiossincratico
FORCE_DROP=set() # versão fiel: converte tudo (nós ausentes no object_info auto-dropam via pass-through)
# kept = nós que viram nó de API (ativos, no object_info, não-nota, não force-drop)
kept=set(n["id"] for n in g["nodes"]
if n.get("mode",0)==0 and n["type"] not in NOTE_TYPES
and n["type"] in oi and n["type"] not in FORCE_DROP)
def resolve(node_id, slot, seen=None):
"""resolve uma conexão; passa através de nó não-kept casando o TIPO do output."""
seen=seen or set()
n=nodes.get(node_id)
if n is None: return [str(node_id), slot]
if node_id not in kept and node_id not in seen:
seen.add(node_id)
outs=n.get("outputs",[])
otype=outs[slot].get("type") if slot<len(outs) else None
linked=[i for i in n.get("inputs",[]) if i.get("link") is not None]
pick=None
for i in linked: # prefere input do mesmo tipo do output
if otype and i.get("type")==otype: pick=i; break
if pick is None and linked: pick=linked[min(slot,len(linked)-1)]
if pick:
src=links.get(pick["link"])
if src: return resolve(src[0],src[1],seen)
return [str(node_id), slot]
api={}
skipped=[]
for n in g["nodes"]:
if n.get("mode",0)!=0: continue
ct=n["type"]
if ct in NOTE_TYPES: continue
if ct not in oi:
skipped.append((n["id"],ct)); continue
inputs={}
# linked inputs
for inp in n.get("inputs",[]):
if inp.get("link") is not None:
src=links.get(inp["link"])
if src: inputs[inp["name"]]=resolve(src[0],src[1])
# widget inputs — detecta esquema (full=mantém fantasma de widget linkado / compact=não)
groups=widget_groups(ct)
wvv=n.get("widgets_values",[])
if groups is not None and isinstance(wvv,list):
linkedset={i["name"] for i in n.get("inputs",[]) if i.get("link") is not None}
# ComfyUI mantém SEMPRE o valor-fantasma de widgets convertidos em link (esquema "full").
# Widgets novos (adicionados à classe depois do save) ficam além de len(wvv) -> usam default.
wi=0
for nm,hc in groups:
if nm in linkedset: # widget convertido em link
if wi<len(wvv): wi+=1 # consome fantasma
if hc and wi<len(wvv): wi+=1 # consome control fantasma
continue # mantém o link já gravado
if wi<len(wvv):
inputs[nm]=wvv[wi]; wi+=1
if hc and wi<len(wvv):
wi+=1 # pula control_after_generate
# preenche widgets REQUIRED faltantes (params novos pós-save) com default do object_info
linkedset={i["name"] for i in n.get("inputs",[]) if i.get("link") is not None}
for name,spec in oi[ct]["input"].get("required",{}).items():
if name in inputs or name in linkedset: continue
t=spec[0]; opts=spec[1] if len(spec)>1 and isinstance(spec[1],dict) else {}
is_widget = isinstance(t,list) or t in ("INT","FLOAT","STRING","BOOLEAN","COMBO")
if not is_widget: continue
d=opts.get("default")
if d is None and isinstance(t,list) and t: d=t[0] # combo-lista: 1a opção
if d is not None: inputs[name]=d
api[str(n["id"])]={"class_type":ct,"inputs":inputs,"_meta":{"title":n.get("title") or ct}}
json.dump(api,open(OUT,"w"),indent=1)
print("API nodes:",len(api),"| skipped:",skipped)