saliacoel commited on
Commit
355a7af
·
verified ·
1 Parent(s): 143d3cc

Update salia_get_lora_x.py

Browse files
Files changed (1) hide show
  1. salia_get_lora_x.py +527 -319
salia_get_lora_x.py CHANGED
@@ -1,320 +1,528 @@
1
- import logging
2
- import os
3
- import shutil
4
- import urllib.parse
5
- import urllib.request
6
-
7
- import comfy.controlnet
8
- import comfy.sd
9
- import comfy.utils
10
- import folder_paths
11
-
12
-
13
- HF_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
14
- HF_LORA_REPO_BASE = HF_REPO_BASE
15
- HF_CHECKPOINT_REPO_BASE = HF_REPO_BASE
16
- HF_CONTROLNET_REPO_BASE = HF_REPO_BASE
17
-
18
-
19
- class _SaliaRepoFileMixin:
20
- @staticmethod
21
- def _normalize_safetensors_name(name: str) -> str:
22
- base = os.path.basename((name or "").strip())
23
- if not base:
24
- raise ValueError("filename cannot be empty.")
25
-
26
- if base.lower().endswith(".safetensors"):
27
- base = base[: -len(".safetensors")]
28
-
29
- if not base:
30
- raise ValueError("filename resolves to an empty name.")
31
-
32
- return f"{base}.safetensors"
33
-
34
- @staticmethod
35
- def _download_file(url: str, target_path: str) -> None:
36
- os.makedirs(os.path.dirname(target_path), exist_ok=True)
37
- tmp_path = target_path + ".download"
38
-
39
- if os.path.exists(tmp_path):
40
- os.remove(tmp_path)
41
-
42
- try:
43
- request = urllib.request.Request(
44
- url,
45
- headers={"User-Agent": "ComfyUI-SaliacoelRepoModelLoader/1.0"},
46
- )
47
- with urllib.request.urlopen(request) as response, open(tmp_path, "wb") as out_file:
48
- shutil.copyfileobj(response, out_file)
49
-
50
- os.replace(tmp_path, target_path)
51
- except Exception:
52
- if os.path.exists(tmp_path):
53
- os.remove(tmp_path)
54
- raise
55
-
56
- @staticmethod
57
- def _preferred_model_dir(folder_name: str, default_subdir: str) -> str:
58
- models_dir = getattr(folder_paths, "models_dir", None)
59
- if models_dir:
60
- return os.path.join(models_dir, default_subdir)
61
-
62
- folder_dirs = folder_paths.get_folder_paths(folder_name)
63
- if not folder_dirs:
64
- raise RuntimeError(f"No ComfyUI '{folder_name}' folder is configured.")
65
-
66
- return folder_dirs[0]
67
-
68
- @classmethod
69
- def _ensure_file_available(
70
- cls,
71
- folder_name: str,
72
- default_subdir: str,
73
- repo_base: str,
74
- file_name: str,
75
- log_prefix: str,
76
- ) -> str:
77
- preferred_dir = cls._preferred_model_dir(folder_name, default_subdir)
78
- preferred_path = os.path.join(preferred_dir, file_name)
79
-
80
- if os.path.isfile(preferred_path):
81
- return preferred_path
82
-
83
- existing_path = folder_paths.get_full_path(folder_name, file_name)
84
- if existing_path is not None:
85
- return existing_path
86
-
87
- url = f"{repo_base}/{urllib.parse.quote(file_name)}"
88
- logging.info("[%s] Downloading missing file: %s", log_prefix, url)
89
- cls._download_file(url, preferred_path)
90
-
91
- return preferred_path
92
-
93
-
94
- class Salia_Get_Lora_X(_SaliaRepoFileMixin):
95
- """
96
- Loads a single LoRA from the public Hugging Face repo `saliacoel/x`.
97
-
98
- Behavior:
99
- - Takes a single base name, e.g. `Fade_to_Black`
100
- - Normalizes it to `Fade_to_Black.safetensors`
101
- - Checks if it already exists in ComfyUI's loras folder
102
- - If missing, downloads it
103
- - Loads it and applies it model-only to one MODEL input
104
- """
105
-
106
- CATEGORY = "loaders/saliacoel"
107
- FUNCTION = "load_lora"
108
- RETURN_TYPES = ("MODEL",)
109
- RETURN_NAMES = ("loaded_model",)
110
- DESCRIPTION = (
111
- "Loads a single LoRA from saliacoel/x. If missing locally, it is "
112
- "downloaded first, then applied model-only."
113
- )
114
- OUTPUT_TOOLTIPS = (
115
- "model_in with the LoRA applied.",
116
- )
117
-
118
- def __init__(self):
119
- self.loaded_lora = None
120
-
121
- @classmethod
122
- def INPUT_TYPES(cls):
123
- return {
124
- "required": {
125
- "filename": (
126
- "STRING",
127
- {
128
- "default": "",
129
- "multiline": False,
130
- "placeholder": "Fade_to_Black",
131
- "tooltip": "LoRA name without .safetensors",
132
- },
133
- ),
134
- "model_in": (
135
- "MODEL",
136
- {"tooltip": "The MODEL input that will receive the LoRA."},
137
- ),
138
- "strength": (
139
- "FLOAT",
140
- {
141
- "default": 1.0,
142
- "min": -100.0,
143
- "max": 100.0,
144
- "step": 0.01,
145
- "tooltip": "Strength used when applying the LoRA.",
146
- },
147
- ),
148
- }
149
- }
150
-
151
- @classmethod
152
- def _ensure_lora_available(cls, lora_name: str) -> str:
153
- return cls._ensure_file_available(
154
- folder_name="loras",
155
- default_subdir="loras",
156
- repo_base=HF_LORA_REPO_BASE,
157
- file_name=lora_name,
158
- log_prefix="SaliacoelSingleRepoLora",
159
- )
160
-
161
- def _get_or_load_lora(self, lora_path: str):
162
- if self.loaded_lora is not None and self.loaded_lora[0] == lora_path:
163
- return self.loaded_lora[1]
164
-
165
- lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
166
- self.loaded_lora = (lora_path, lora)
167
- return lora
168
-
169
- def _apply_lora_model_only(self, model, lora_path: str, strength: float):
170
- if strength == 0:
171
- return model
172
-
173
- lora = self._get_or_load_lora(lora_path)
174
- model_lora, _ = comfy.sd.load_lora_for_models(model, None, lora, strength, 0)
175
- return model_lora
176
-
177
- def load_lora(self, filename, model_in, strength):
178
- lora_name = self._normalize_safetensors_name(filename)
179
- lora_path = self._ensure_lora_available(lora_name)
180
- loaded_model = self._apply_lora_model_only(model_in, lora_path, strength)
181
- return (loaded_model,)
182
-
183
-
184
- class Salia_Get_Checkpoint_X(_SaliaRepoFileMixin):
185
- """
186
- Loads a single checkpoint from the public Hugging Face repo `saliacoel/x`.
187
-
188
- Behavior:
189
- - Takes a single base name, e.g. `my_model`
190
- - Normalizes it to `my_model.safetensors`
191
- - Checks ComfyUI's checkpoints folder first
192
- - If missing, downloads it to /ComfyUI/models/checkpoints
193
- - Loads it with the same core loader path used by CheckpointLoaderSimple
194
- """
195
-
196
- CATEGORY = "loaders/saliacoel"
197
- FUNCTION = "load_checkpoint"
198
- RETURN_TYPES = ("MODEL", "CLIP", "VAE")
199
- RETURN_NAMES = ("model", "clip", "vae")
200
- DESCRIPTION = (
201
- "Loads a single checkpoint from saliacoel/x. If missing locally, it is "
202
- "downloaded first, then loaded like ComfyUI's CheckpointLoaderSimple."
203
- )
204
- OUTPUT_TOOLTIPS = (
205
- "The model used for denoising latents.",
206
- "The CLIP model used for encoding text prompts.",
207
- "The VAE model used for encoding and decoding images to and from latent space.",
208
- )
209
- SEARCH_ALIASES = ["load model", "checkpoint", "model loader", "load checkpoint", "ckpt", "model"]
210
-
211
- @classmethod
212
- def INPUT_TYPES(cls):
213
- return {
214
- "required": {
215
- "filename": (
216
- "STRING",
217
- {
218
- "default": "",
219
- "multiline": False,
220
- "placeholder": "your_checkpoint",
221
- "tooltip": "Checkpoint name without .safetensors",
222
- },
223
- ),
224
- }
225
- }
226
-
227
- @classmethod
228
- def _ensure_checkpoint_available(cls, ckpt_name: str) -> str:
229
- return cls._ensure_file_available(
230
- folder_name="checkpoints",
231
- default_subdir="checkpoints",
232
- repo_base=HF_CHECKPOINT_REPO_BASE,
233
- file_name=ckpt_name,
234
- log_prefix="SaliacoelSingleRepoCheckpoint",
235
- )
236
-
237
- def load_checkpoint(self, filename):
238
- ckpt_name = self._normalize_safetensors_name(filename)
239
- ckpt_path = self._ensure_checkpoint_available(ckpt_name)
240
- out = comfy.sd.load_checkpoint_guess_config(
241
- ckpt_path,
242
- output_vae=True,
243
- output_clip=True,
244
- embedding_directory=folder_paths.get_folder_paths("embeddings"),
245
- )
246
- return out[:3]
247
-
248
-
249
- class Salia_Get_ControlNet_Model_X(_SaliaRepoFileMixin):
250
- """
251
- Loads a single ControlNet model from the public Hugging Face repo `saliacoel/x`.
252
-
253
- Behavior:
254
- - Takes a single base name, e.g. `depth_controlnet`
255
- - Normalizes it to `depth_controlnet.safetensors`
256
- - Checks ComfyUI's controlnet folder first
257
- - If missing, downloads it to /ComfyUI/models/controlnet
258
- - Loads it with the same core loader path used by ControlNetLoader
259
- """
260
-
261
- CATEGORY = "loaders/saliacoel"
262
- FUNCTION = "load_controlnet"
263
- RETURN_TYPES = ("CONTROL_NET",)
264
- RETURN_NAMES = ("control_net",)
265
- DESCRIPTION = (
266
- "Loads a single ControlNet model from saliacoel/x. If missing locally, "
267
- "it is downloaded first, then loaded like ComfyUI's ControlNetLoader."
268
- )
269
- SEARCH_ALIASES = ["controlnet", "control net", "cn", "load controlnet", "controlnet loader"]
270
-
271
- @classmethod
272
- def INPUT_TYPES(cls):
273
- return {
274
- "required": {
275
- "filename": (
276
- "STRING",
277
- {
278
- "default": "",
279
- "multiline": False,
280
- "placeholder": "your_controlnet",
281
- "tooltip": "ControlNet model name without .safetensors",
282
- },
283
- ),
284
- }
285
- }
286
-
287
- @classmethod
288
- def _ensure_controlnet_available(cls, controlnet_name: str) -> str:
289
- return cls._ensure_file_available(
290
- folder_name="controlnet",
291
- default_subdir="controlnet",
292
- repo_base=HF_CONTROLNET_REPO_BASE,
293
- file_name=controlnet_name,
294
- log_prefix="SaliacoelSingleRepoControlNet",
295
- )
296
-
297
- def load_controlnet(self, filename):
298
- controlnet_name = self._normalize_safetensors_name(filename)
299
- controlnet_path = self._ensure_controlnet_available(controlnet_name)
300
- controlnet = comfy.controlnet.load_controlnet(controlnet_path)
301
-
302
- if controlnet is None:
303
- raise RuntimeError(
304
- "ERROR: controlnet file is invalid and does not contain a valid controlnet model."
305
- )
306
-
307
- return (controlnet,)
308
-
309
-
310
- NODE_CLASS_MAPPINGS = {
311
- "Salia_Get_Lora_X": Salia_Get_Lora_X,
312
- "Salia_Get_Checkpoint_X": Salia_Get_Checkpoint_X,
313
- "Salia_Get_ControlNet_Model_X": Salia_Get_ControlNet_Model_X,
314
- }
315
-
316
- NODE_DISPLAY_NAME_MAPPINGS = {
317
- "Salia_Get_Lora_X": "Salia Get LoRa and Load LoRa X (1)",
318
- "Salia_Get_Checkpoint_X": "Salia Get Checkpoint and Load Checkpoint X",
319
- "Salia_Get_ControlNet_Model_X": "Salia Get ControlNet and Load ControlNet Model X",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  }
 
1
+ import logging
2
+ import os
3
+ import time
4
+ import urllib.error
5
+ import urllib.parse
6
+ import urllib.request
7
+
8
+ from safetensors import safe_open
9
+
10
+ import comfy.controlnet
11
+ import comfy.sd
12
+ import comfy.utils
13
+ import folder_paths
14
+
15
+
16
+ HF_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
17
+ HF_LORA_REPO_BASE = HF_REPO_BASE
18
+ HF_CHECKPOINT_REPO_BASE = HF_REPO_BASE
19
+ HF_CONTROLNET_REPO_BASE = HF_REPO_BASE
20
+
21
+
22
+ class _SaliaRepoFileMixin:
23
+ DOWNLOAD_CHUNK_SIZE = 8 * 1024 * 1024
24
+ DOWNLOAD_TIMEOUT_SECONDS = 300
25
+ MAX_DOWNLOAD_ATTEMPTS = 3
26
+ MIN_SAFETENSORS_SIZE = 16
27
+
28
+ @staticmethod
29
+ def _normalize_safetensors_name(name: str) -> str:
30
+ raw = str(name or "").strip().strip('"').strip("'").replace("\\", "/")
31
+ base = os.path.basename(raw).strip()
32
+
33
+ if not base:
34
+ raise ValueError("filename cannot be empty.")
35
+
36
+ if base.lower().endswith(".safetensors"):
37
+ base = base[: -len(".safetensors")].strip()
38
+
39
+ if not base:
40
+ raise ValueError("filename resolves to an empty name.")
41
+
42
+ return f"{base}.safetensors"
43
+
44
+ @classmethod
45
+ def _validate_safetensors_file(cls, path: str):
46
+ if not os.path.isfile(path):
47
+ return False, "file does not exist"
48
+
49
+ try:
50
+ size = os.path.getsize(path)
51
+ except OSError as e:
52
+ return False, f"cannot stat file: {e}"
53
+
54
+ if size < cls.MIN_SAFETENSORS_SIZE:
55
+ return False, f"file is too small: {size} bytes"
56
+
57
+ try:
58
+ with safe_open(path, framework="pt", device="cpu") as f:
59
+ # Force header parsing. This does not load tensor payloads.
60
+ _ = list(f.keys())
61
+ return True, ""
62
+ except Exception as e:
63
+ return False, f"{type(e).__name__}: {e}"
64
+
65
+ @staticmethod
66
+ def _unique_invalid_path(path: str) -> str:
67
+ stamp = time.strftime("%Y%m%d-%H%M%S")
68
+ candidate = f"{path}.invalid-{stamp}"
69
+ counter = 1
70
+
71
+ while os.path.exists(candidate):
72
+ candidate = f"{path}.invalid-{stamp}.{counter}"
73
+ counter += 1
74
+
75
+ return candidate
76
+
77
+ @classmethod
78
+ def _quarantine_invalid_file(cls, path: str, reason: str, log_prefix: str) -> None:
79
+ if not os.path.isfile(path):
80
+ return
81
+
82
+ bad_path = cls._unique_invalid_path(path)
83
+
84
+ try:
85
+ os.replace(path, bad_path)
86
+ logging.warning(
87
+ "[%s] Existing safetensors file is invalid and was moved to: %s. Reason: %s",
88
+ log_prefix,
89
+ bad_path,
90
+ reason,
91
+ )
92
+ except Exception:
93
+ logging.warning(
94
+ "[%s] Existing safetensors file is invalid but could not be moved: %s. "
95
+ "Reason: %s",
96
+ log_prefix,
97
+ path,
98
+ reason,
99
+ exc_info=True,
100
+ )
101
+
102
+ @classmethod
103
+ def _download_file(cls, url: str, target_path: str) -> int:
104
+ os.makedirs(os.path.dirname(target_path), exist_ok=True)
105
+
106
+ tmp_path = f"{target_path}.download.{os.getpid()}"
107
+ if os.path.exists(tmp_path):
108
+ os.remove(tmp_path)
109
+
110
+ bytes_written = 0
111
+
112
+ try:
113
+ request = urllib.request.Request(
114
+ url,
115
+ headers={
116
+ "User-Agent": "ComfyUI-SaliacoelRepoModelLoader/2.0",
117
+ "Accept": "application/octet-stream,*/*",
118
+ },
119
+ )
120
+
121
+ with urllib.request.urlopen(
122
+ request,
123
+ timeout=cls.DOWNLOAD_TIMEOUT_SECONDS,
124
+ ) as response:
125
+ status = getattr(response, "status", None) or response.getcode()
126
+ if status < 200 or status >= 300:
127
+ raise RuntimeError(f"HTTP status {status}")
128
+
129
+ expected_raw = response.headers.get("Content-Length")
130
+ expected_size = None
131
+ if expected_raw:
132
+ try:
133
+ expected_size = int(expected_raw)
134
+ except ValueError:
135
+ expected_size = None
136
+
137
+ with open(tmp_path, "wb") as out_file:
138
+ while True:
139
+ chunk = response.read(cls.DOWNLOAD_CHUNK_SIZE)
140
+ if not chunk:
141
+ break
142
+
143
+ bytes_written += len(chunk)
144
+ out_file.write(chunk)
145
+
146
+ out_file.flush()
147
+ os.fsync(out_file.fileno())
148
+
149
+ if expected_size is not None and bytes_written != expected_size:
150
+ raise RuntimeError(
151
+ f"incomplete HTTP download: got {bytes_written} bytes, "
152
+ f"expected {expected_size} bytes"
153
+ )
154
+
155
+ if bytes_written < cls.MIN_SAFETENSORS_SIZE:
156
+ raise RuntimeError(f"downloaded file is too small: {bytes_written} bytes")
157
+
158
+ os.replace(tmp_path, target_path)
159
+ return bytes_written
160
+
161
+ except Exception:
162
+ if os.path.exists(tmp_path):
163
+ try:
164
+ os.remove(tmp_path)
165
+ except OSError:
166
+ pass
167
+ raise
168
+
169
+ @staticmethod
170
+ def _preferred_model_dir(folder_name: str, default_subdir: str) -> str:
171
+ models_dir = getattr(folder_paths, "models_dir", None)
172
+ if models_dir:
173
+ return os.path.join(models_dir, default_subdir)
174
+
175
+ folder_dirs = folder_paths.get_folder_paths(folder_name)
176
+ if not folder_dirs:
177
+ raise RuntimeError(f"No ComfyUI '{folder_name}' folder is configured.")
178
+
179
+ return folder_dirs[0]
180
+
181
+ @staticmethod
182
+ def _candidate_paths(folder_name: str, preferred_path: str, file_name: str):
183
+ paths = []
184
+
185
+ def add(path):
186
+ if path and path not in paths:
187
+ paths.append(path)
188
+
189
+ add(preferred_path)
190
+
191
+ existing_path = folder_paths.get_full_path(folder_name, file_name)
192
+ add(existing_path)
193
+
194
+ return paths
195
+
196
+ @classmethod
197
+ def _download_and_validate(
198
+ cls,
199
+ repo_base: str,
200
+ file_name: str,
201
+ target_path: str,
202
+ log_prefix: str,
203
+ ) -> str:
204
+ url = f"{repo_base.rstrip('/')}/{urllib.parse.quote(file_name, safe='')}"
205
+ last_error = None
206
+
207
+ for attempt in range(1, cls.MAX_DOWNLOAD_ATTEMPTS + 1):
208
+ try:
209
+ logging.info(
210
+ "[%s] Downloading %s to %s (attempt %s/%s)",
211
+ log_prefix,
212
+ url,
213
+ target_path,
214
+ attempt,
215
+ cls.MAX_DOWNLOAD_ATTEMPTS,
216
+ )
217
+
218
+ bytes_written = cls._download_file(url, target_path)
219
+ valid, reason = cls._validate_safetensors_file(target_path)
220
+
221
+ if valid:
222
+ logging.info(
223
+ "[%s] Downloaded and validated %s (%s bytes)",
224
+ log_prefix,
225
+ target_path,
226
+ bytes_written,
227
+ )
228
+ return target_path
229
+
230
+ last_error = RuntimeError(reason)
231
+ cls._quarantine_invalid_file(target_path, reason, log_prefix)
232
+
233
+ except urllib.error.HTTPError as e:
234
+ last_error = e
235
+ logging.warning(
236
+ "[%s] HTTP error while downloading %s: %s",
237
+ log_prefix,
238
+ url,
239
+ e,
240
+ )
241
+ except Exception as e:
242
+ last_error = e
243
+ logging.warning(
244
+ "[%s] Error while downloading/validating %s: %s",
245
+ log_prefix,
246
+ url,
247
+ e,
248
+ )
249
+
250
+ if attempt < cls.MAX_DOWNLOAD_ATTEMPTS:
251
+ time.sleep(1.0)
252
+
253
+ raise RuntimeError(
254
+ f"[{log_prefix}] Could not download a valid safetensors file named "
255
+ f"'{file_name}' from {repo_base}. Last error: {last_error}"
256
+ ) from last_error
257
+
258
+ @classmethod
259
+ def _ensure_file_available(
260
+ cls,
261
+ folder_name: str,
262
+ default_subdir: str,
263
+ repo_base: str,
264
+ file_name: str,
265
+ log_prefix: str,
266
+ ) -> str:
267
+ preferred_dir = cls._preferred_model_dir(folder_name, default_subdir)
268
+ preferred_path = os.path.join(preferred_dir, file_name)
269
+
270
+ for path in cls._candidate_paths(folder_name, preferred_path, file_name):
271
+ if not os.path.isfile(path):
272
+ continue
273
+
274
+ valid, reason = cls._validate_safetensors_file(path)
275
+ if valid:
276
+ logging.info("[%s] Using existing valid file: %s", log_prefix, path)
277
+ return path
278
+
279
+ cls._quarantine_invalid_file(path, reason, log_prefix)
280
+
281
+ return cls._download_and_validate(
282
+ repo_base=repo_base,
283
+ file_name=file_name,
284
+ target_path=preferred_path,
285
+ log_prefix=log_prefix,
286
+ )
287
+
288
+
289
+ class Salia_Get_Lora_X(_SaliaRepoFileMixin):
290
+ """
291
+ Loads a single LoRA from the public Hugging Face repo `saliacoel/x`.
292
+
293
+ Behavior:
294
+ - Takes a single base name, e.g. `Fade_to_Black`
295
+ - Normalizes it to `Fade_to_Black.safetensors`
296
+ - Validates any existing local file
297
+ - If missing or invalid, downloads it atomically
298
+ - Loads it and applies it model-only to one MODEL input
299
+ """
300
+
301
+ CATEGORY = "loaders/saliacoel"
302
+ FUNCTION = "load_lora"
303
+ RETURN_TYPES = ("MODEL",)
304
+ RETURN_NAMES = ("loaded_model",)
305
+ DESCRIPTION = (
306
+ "Loads a single LoRA from saliacoel/x. If missing or invalid locally, "
307
+ "it is downloaded first, then applied model-only."
308
+ )
309
+ OUTPUT_TOOLTIPS = ("model_in with the LoRA applied.",)
310
+
311
+ def __init__(self):
312
+ self.loaded_lora = None
313
+
314
+ @classmethod
315
+ def INPUT_TYPES(cls):
316
+ return {
317
+ "required": {
318
+ "filename": (
319
+ "STRING",
320
+ {
321
+ "default": "",
322
+ "multiline": False,
323
+ "placeholder": "Fade_to_Black",
324
+ "tooltip": "LoRA name without .safetensors",
325
+ },
326
+ ),
327
+ "model_in": (
328
+ "MODEL",
329
+ {"tooltip": "The MODEL input that will receive the LoRA."},
330
+ ),
331
+ "strength": (
332
+ "FLOAT",
333
+ {
334
+ "default": 1.0,
335
+ "min": -100.0,
336
+ "max": 100.0,
337
+ "step": 0.01,
338
+ "tooltip": "Strength used when applying the LoRA.",
339
+ },
340
+ ),
341
+ }
342
+ }
343
+
344
+ @classmethod
345
+ def _ensure_lora_available(cls, lora_name: str) -> str:
346
+ return cls._ensure_file_available(
347
+ folder_name="loras",
348
+ default_subdir="loras",
349
+ repo_base=HF_LORA_REPO_BASE,
350
+ file_name=lora_name,
351
+ log_prefix="SaliacoelSingleRepoLora",
352
+ )
353
+
354
+ def _get_or_load_lora(self, lora_path: str):
355
+ if self.loaded_lora is not None and self.loaded_lora[0] == lora_path:
356
+ return self.loaded_lora[1]
357
+
358
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
359
+ self.loaded_lora = (lora_path, lora)
360
+ return lora
361
+
362
+ def _apply_lora_model_only(self, model, lora_path: str, strength: float):
363
+ if strength == 0:
364
+ return model
365
+
366
+ lora = self._get_or_load_lora(lora_path)
367
+ model_lora, _ = comfy.sd.load_lora_for_models(model, None, lora, strength, 0)
368
+ return model_lora
369
+
370
+ def load_lora(self, filename, model_in, strength):
371
+ lora_name = self._normalize_safetensors_name(filename)
372
+ lora_path = self._ensure_lora_available(lora_name)
373
+ loaded_model = self._apply_lora_model_only(model_in, lora_path, strength)
374
+ return (loaded_model,)
375
+
376
+
377
+ class Salia_Get_Checkpoint_X(_SaliaRepoFileMixin):
378
+ """
379
+ Loads a single checkpoint from the public Hugging Face repo `saliacoel/x`.
380
+
381
+ Behavior:
382
+ - Takes a single base name, e.g. `my_model`
383
+ - Normalizes it to `my_model.safetensors`
384
+ - Validates any existing local file
385
+ - If missing or invalid, downloads it to /ComfyUI/models/checkpoints
386
+ - Loads it with the same core loader path used by CheckpointLoaderSimple
387
+ """
388
+
389
+ CATEGORY = "loaders/saliacoel"
390
+ FUNCTION = "load_checkpoint"
391
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
392
+ RETURN_NAMES = ("model", "clip", "vae")
393
+ DESCRIPTION = (
394
+ "Loads a single checkpoint from saliacoel/x. If missing or invalid locally, "
395
+ "it is downloaded first, then loaded like ComfyUI's CheckpointLoaderSimple."
396
+ )
397
+ OUTPUT_TOOLTIPS = (
398
+ "The model used for denoising latents.",
399
+ "The CLIP model used for encoding text prompts.",
400
+ "The VAE model used for encoding and decoding images to and from latent space.",
401
+ )
402
+ SEARCH_ALIASES = [
403
+ "load model",
404
+ "checkpoint",
405
+ "model loader",
406
+ "load checkpoint",
407
+ "ckpt",
408
+ "model",
409
+ ]
410
+
411
+ @classmethod
412
+ def INPUT_TYPES(cls):
413
+ return {
414
+ "required": {
415
+ "filename": (
416
+ "STRING",
417
+ {
418
+ "default": "",
419
+ "multiline": False,
420
+ "placeholder": "your_checkpoint",
421
+ "tooltip": "Checkpoint name without .safetensors",
422
+ },
423
+ ),
424
+ }
425
+ }
426
+
427
+ @classmethod
428
+ def _ensure_checkpoint_available(cls, ckpt_name: str) -> str:
429
+ return cls._ensure_file_available(
430
+ folder_name="checkpoints",
431
+ default_subdir="checkpoints",
432
+ repo_base=HF_CHECKPOINT_REPO_BASE,
433
+ file_name=ckpt_name,
434
+ log_prefix="SaliacoelSingleRepoCheckpoint",
435
+ )
436
+
437
+ def load_checkpoint(self, filename):
438
+ ckpt_name = self._normalize_safetensors_name(filename)
439
+ ckpt_path = self._ensure_checkpoint_available(ckpt_name)
440
+
441
+ out = comfy.sd.load_checkpoint_guess_config(
442
+ ckpt_path,
443
+ output_vae=True,
444
+ output_clip=True,
445
+ embedding_directory=folder_paths.get_folder_paths("embeddings"),
446
+ )
447
+
448
+ return out[:3]
449
+
450
+
451
+ class Salia_Get_ControlNet_Model_X(_SaliaRepoFileMixin):
452
+ """
453
+ Loads a single ControlNet model from the public Hugging Face repo `saliacoel/x`.
454
+
455
+ Behavior:
456
+ - Takes a single base name, e.g. `depth_controlnet`
457
+ - Normalizes it to `depth_controlnet.safetensors`
458
+ - Validates any existing local file
459
+ - If missing or invalid, downloads it to /ComfyUI/models/controlnet
460
+ - Loads it with the same core loader path used by ControlNetLoader
461
+ """
462
+
463
+ CATEGORY = "loaders/saliacoel"
464
+ FUNCTION = "load_controlnet"
465
+ RETURN_TYPES = ("CONTROL_NET",)
466
+ RETURN_NAMES = ("control_net",)
467
+ DESCRIPTION = (
468
+ "Loads a single ControlNet model from saliacoel/x. If missing or invalid locally, "
469
+ "it is downloaded first, then loaded like ComfyUI's ControlNetLoader."
470
+ )
471
+ SEARCH_ALIASES = [
472
+ "controlnet",
473
+ "control net",
474
+ "cn",
475
+ "load controlnet",
476
+ "controlnet loader",
477
+ ]
478
+
479
+ @classmethod
480
+ def INPUT_TYPES(cls):
481
+ return {
482
+ "required": {
483
+ "filename": (
484
+ "STRING",
485
+ {
486
+ "default": "",
487
+ "multiline": False,
488
+ "placeholder": "your_controlnet",
489
+ "tooltip": "ControlNet model name without .safetensors",
490
+ },
491
+ ),
492
+ }
493
+ }
494
+
495
+ @classmethod
496
+ def _ensure_controlnet_available(cls, controlnet_name: str) -> str:
497
+ return cls._ensure_file_available(
498
+ folder_name="controlnet",
499
+ default_subdir="controlnet",
500
+ repo_base=HF_CONTROLNET_REPO_BASE,
501
+ file_name=controlnet_name,
502
+ log_prefix="SaliacoelSingleRepoControlNet",
503
+ )
504
+
505
+ def load_controlnet(self, filename):
506
+ controlnet_name = self._normalize_safetensors_name(filename)
507
+ controlnet_path = self._ensure_controlnet_available(controlnet_name)
508
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path)
509
+
510
+ if controlnet is None:
511
+ raise RuntimeError(
512
+ "ERROR: controlnet file is invalid and does not contain a valid controlnet model."
513
+ )
514
+
515
+ return (controlnet,)
516
+
517
+
518
+ NODE_CLASS_MAPPINGS = {
519
+ "Salia_Get_Lora_X": Salia_Get_Lora_X,
520
+ "Salia_Get_Checkpoint_X": Salia_Get_Checkpoint_X,
521
+ "Salia_Get_ControlNet_Model_X": Salia_Get_ControlNet_Model_X,
522
+ }
523
+
524
+ NODE_DISPLAY_NAME_MAPPINGS = {
525
+ "Salia_Get_Lora_X": "Salia Get LoRa and Load LoRa X (1)",
526
+ "Salia_Get_Checkpoint_X": "Salia Get Checkpoint and Load Checkpoint X",
527
+ "Salia_Get_ControlNet_Model_X": "Salia Get ControlNet and Load ControlNet Model X",
528
  }