saliacoel commited on
Commit
98ac894
·
verified ·
1 Parent(s): 5d2a0b7

Upload salia_repo_lora_loader_background.py

Browse files
Files changed (1) hide show
  1. salia_repo_lora_loader_background.py +171 -0
salia_repo_lora_loader_background.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import urllib.parse
6
+ import urllib.request
7
+
8
+ import comfy.sd
9
+ import comfy.utils
10
+ import folder_paths
11
+
12
+
13
+ HF_REPO_BASE = "https://huggingface.co/saliacoel/background/resolve/main"
14
+
15
+
16
+ class Salia_Repo_Lora_Loader_Background:
17
+ """
18
+ Downloads a single LoRA from the fixed public Hugging Face repo
19
+ `saliacoel/background` when missing, then applies it model-only.
20
+
21
+ Input examples that all resolve to the same file:
22
+ - cars
23
+ - cars.safetensors
24
+ """
25
+
26
+ CATEGORY = "loaders/saliacoel"
27
+ FUNCTION = "load_single_lora"
28
+ RETURN_TYPES = ("MODEL",)
29
+ RETURN_NAMES = ("loaded_out",)
30
+ DESCRIPTION = (
31
+ "Downloads a missing LoRA from saliacoel/background and applies it "
32
+ "with model-only LoRA loading."
33
+ )
34
+ OUTPUT_TOOLTIPS = (
35
+ "model_in with the requested LoRA applied.",
36
+ )
37
+
38
+ def __init__(self):
39
+ self.loaded_lora = None
40
+
41
+ @classmethod
42
+ def INPUT_TYPES(cls):
43
+ return {
44
+ "required": {
45
+ "name": (
46
+ "STRING",
47
+ {
48
+ "default": "",
49
+ "multiline": False,
50
+ "placeholder": "cars",
51
+ "tooltip": (
52
+ "LoRA name from saliacoel/background. "
53
+ "The node resolves it to <name>.safetensors."
54
+ ),
55
+ },
56
+ ),
57
+ "model_in": (
58
+ "MODEL",
59
+ {"tooltip": "The MODEL input that will receive the LoRA."},
60
+ ),
61
+ "strength": (
62
+ "FLOAT",
63
+ {
64
+ "default": 1.0,
65
+ "min": -100.0,
66
+ "max": 100.0,
67
+ "step": 0.01,
68
+ "tooltip": "Strength used when applying the LoRA.",
69
+ },
70
+ ),
71
+ }
72
+ }
73
+
74
+ @staticmethod
75
+ def _normalize_name(name: str) -> str:
76
+ base = (name or "").strip()
77
+ if not base:
78
+ raise ValueError("name cannot be empty.")
79
+
80
+ # Prevent path traversal or accidental subfolders.
81
+ base = os.path.basename(base)
82
+
83
+ if base.lower().endswith(".safetensors"):
84
+ base = base[: -len(".safetensors")]
85
+
86
+ if not base:
87
+ raise ValueError("name resolves to an empty base name.")
88
+
89
+ return base
90
+
91
+ @classmethod
92
+ def _build_filename(cls, name: str) -> str:
93
+ return f"{cls._normalize_name(name)}.safetensors"
94
+
95
+ @staticmethod
96
+ def _download_file(url: str, target_path: str) -> None:
97
+ os.makedirs(os.path.dirname(target_path), exist_ok=True)
98
+ tmp_path = target_path + ".download"
99
+
100
+ if os.path.exists(tmp_path):
101
+ os.remove(tmp_path)
102
+
103
+ wget_path = shutil.which("wget")
104
+
105
+ try:
106
+ if wget_path:
107
+ subprocess.run(
108
+ [wget_path, "-O", tmp_path, url],
109
+ check=True,
110
+ cwd=os.path.dirname(target_path),
111
+ )
112
+ else:
113
+ request = urllib.request.Request(
114
+ url,
115
+ headers={"User-Agent": "ComfyUI-SaliacoelSingleRepoLoraModelOnly/1.0"},
116
+ )
117
+ with urllib.request.urlopen(request) as response, open(tmp_path, "wb") as out_file:
118
+ shutil.copyfileobj(response, out_file)
119
+
120
+ os.replace(tmp_path, target_path)
121
+ except Exception:
122
+ if os.path.exists(tmp_path):
123
+ os.remove(tmp_path)
124
+ raise
125
+
126
+ @classmethod
127
+ def _ensure_lora_available(cls, lora_name: str) -> str:
128
+ existing_path = folder_paths.get_full_path("loras", lora_name)
129
+ if existing_path is not None:
130
+ return existing_path
131
+
132
+ lora_dirs = folder_paths.get_folder_paths("loras")
133
+ if not lora_dirs:
134
+ raise RuntimeError("No ComfyUI 'loras' folder is configured.")
135
+
136
+ target_dir = lora_dirs[0]
137
+ target_path = os.path.join(target_dir, lora_name)
138
+ url = f"{HF_REPO_BASE}/{urllib.parse.quote(lora_name)}"
139
+
140
+ logging.info("[SaliacoelSingleRepoLoraModelOnly] Downloading missing LoRA: %s", url)
141
+ cls._download_file(url, target_path)
142
+
143
+ resolved_path = folder_paths.get_full_path("loras", lora_name)
144
+ return resolved_path if resolved_path is not None else target_path
145
+
146
+ def _get_or_load_lora(self, lora_path: str):
147
+ if self.loaded_lora is not None and self.loaded_lora[0] == lora_path:
148
+ return self.loaded_lora[1]
149
+
150
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
151
+ self.loaded_lora = (lora_path, lora)
152
+ return lora
153
+
154
+ def load_single_lora(self, name, model_in, strength):
155
+ if strength == 0:
156
+ return (model_in,)
157
+
158
+ lora_name = self._build_filename(name)
159
+ lora_path = self._ensure_lora_available(lora_name)
160
+ lora = self._get_or_load_lora(lora_path)
161
+ model_out, _ = comfy.sd.load_lora_for_models(model_in, None, lora, strength, 0)
162
+ return (model_out,)
163
+
164
+
165
+ NODE_CLASS_MAPPINGS = {
166
+ "Salia_Repo_Lora_Loader_Background": Salia_Repo_Lora_Loader_Background,
167
+ }
168
+
169
+ NODE_DISPLAY_NAME_MAPPINGS = {
170
+ "Salia_Repo_Lora_Loader_Background": "Salia Repo LoRA Loader (Background)",
171
+ }