forked from no8d/ComfyUI-NO8D-controls
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslider_lora_stack.py
More file actions
163 lines (142 loc) · 5.47 KB
/
Copy pathslider_lora_stack.py
File metadata and controls
163 lines (142 loc) · 5.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
from __future__ import annotations
import hashlib
import json
import math
import comfy.sd
import comfy.utils
import folder_paths
import nodes as comfy_nodes
_NO_LORA = "None"
_WEIGHT_EPSILON = 0.000001
def _lora_names():
return [_NO_LORA] + folder_paths.get_filename_list("loras")
def _parse_entries(stack_json):
try:
entries = json.loads(stack_json or "[]")
except (TypeError, json.JSONDecodeError) as exc:
raise ValueError("NO8D-LoRA stack: stack data is not valid JSON") from exc
if not isinstance(entries, list):
raise ValueError("NO8D-LoRA stack: stack data must be a list")
return entries
def _effective_entry_signature(entries):
signature = []
for entry in entries:
if not isinstance(entry, dict):
continue
enabled = bool(entry.get("enabled", True))
name = str(entry.get("name", _NO_LORA))
try:
weight = float(entry.get("weight", 0.0))
except (TypeError, ValueError):
weight = 0.0
if not enabled:
signature.append({"enabled": False})
elif name == _NO_LORA:
signature.append({"enabled": True, "name": _NO_LORA})
elif abs(weight) <= _WEIGHT_EPSILON:
signature.append({"enabled": True, "name": name, "weight": 0.0})
else:
signature.append(
{
"enabled": True,
"name": name,
"weight": round(weight, 6),
"trigger": str(entry.get("trigger", "")).strip(),
}
)
return signature
def _trigger_words_from_entries(validated_entries):
triggers = []
seen = set()
for enabled, name, weight, _path, _index, trigger in validated_entries:
if not enabled or name == _NO_LORA or abs(weight) <= _WEIGHT_EPSILON:
continue
trigger = str(trigger or "").strip()
if not trigger:
continue
key = trigger.casefold()
if key in seen:
continue
seen.add(key)
triggers.append(trigger)
return ", ".join(triggers)
class NO8DLoraStack:
@classmethod
def INPUT_TYPES(cls):
native_inputs = comfy_nodes.UNETLoader.INPUT_TYPES()
inputs = {
section: dict(values) if isinstance(values, dict) else values
for section, values in native_inputs.items()
}
required = dict(inputs.get("required", {}))
required["lora_picker"] = (_lora_names(),)
required["stack_json"] = ("STRING", {"default": "[]", "multiline": True})
inputs["required"] = required
return inputs
RETURN_TYPES = ("MODEL", "STRING")
RETURN_NAMES = ("model", "trigger_words")
FUNCTION = "run"
CATEGORY = "NO8D-control"
@classmethod
def IS_CHANGED(cls, lora_picker, stack_json, **unet_inputs):
entries = _parse_entries(stack_json)
h = hashlib.sha1()
h.update(
json.dumps(
unet_inputs,
ensure_ascii=False,
sort_keys=True,
default=str,
).encode("utf-8")
)
h.update(
json.dumps(
_effective_entry_signature(entries),
ensure_ascii=False,
sort_keys=True,
).encode("utf-8")
)
return h.hexdigest()
def run(self, lora_picker, stack_json, **unet_inputs):
native_loader = comfy_nodes.UNETLoader()
load_function = getattr(native_loader, comfy_nodes.UNETLoader.FUNCTION)
model = load_function(**unet_inputs)[0]
entries = _parse_entries(stack_json)
validated_entries = []
for index, entry in enumerate(entries):
if not isinstance(entry, dict):
raise ValueError(f"NO8D-LoRA stack: entry {index + 1} must be an object")
name = str(entry.get("name", _NO_LORA))
try:
weight = float(entry.get("weight", 0.0))
except (TypeError, ValueError) as exc:
raise ValueError(
f"NO8D-LoRA stack: invalid weight for entry {index + 1} ({name})"
) from exc
if not math.isfinite(weight):
raise ValueError(
f"NO8D-LoRA stack: weight must be finite for entry {index + 1} ({name})"
)
path = None
if name != _NO_LORA:
path = folder_paths.get_full_path("loras", name)
trigger = str(entry.get("trigger", "")).strip()
validated_entries.append((bool(entry.get("enabled", True)), name, weight, path, index, trigger))
loras_for_run = {}
for enabled, name, weight, path, index, _trigger in validated_entries:
if not enabled:
continue
if name == _NO_LORA or abs(weight) <= _WEIGHT_EPSILON:
continue
if path is None:
raise FileNotFoundError(
f"NO8D-LoRA stack: LoRA file not found for entry {index + 1}: {name}"
)
lora = loras_for_run.get(path)
if lora is None:
lora = comfy.utils.load_torch_file(path, safe_load=True)
loras_for_run[path] = lora
model, _ = comfy.sd.load_lora_for_models(model, None, lora, weight, 0.0)
return (model, _trigger_words_from_entries(validated_entries))
NODE_CLASS_MAPPINGS = {"NO8DLoraStack": NO8DLoraStack}
NODE_DISPLAY_NAME_MAPPINGS = {"NO8DLoraStack": "NO8D-LoRA stack"}