saliacoel commited on
Commit
6848282
·
verified ·
1 Parent(s): f0a4e6c

Upload Salia_Save_Speak_And_Upload_Zip.py

Browse files
Files changed (1) hide show
  1. Salia_Save_Speak_And_Upload_Zip.py +378 -0
Salia_Save_Speak_And_Upload_Zip.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ComfyUI nodes for saving a portrait/SPEAK set and uploading its folder ZIP.
2
+
3
+ Install this file directly in ComfyUI/custom_nodes/ and restart ComfyUI.
4
+ The uploader additionally needs huggingface_hub in ComfyUI's Python environment.
5
+
6
+ Nodes (category: Salia/SPEAK):
7
+ Salia Save SPEAK
8
+ Saves EXACT filenames, replacing an existing set with the same Filename.
9
+ Relative Main_Folder_name values are relative to ComfyUI's output directory;
10
+ absolute folder paths are also accepted. Returns the absolute main PNG path.
11
+ Each IMAGE input must contain one image; RGB/RGBA channels are preserved.
12
+ Images are not cropped, resized, or composited. Coordinates are written as
13
+ supplied, independently of the actual image dimensions.
14
+
15
+ UPLOAD_ZIP
16
+ Recursively zips that folder, including the named folder at the ZIP root.
17
+ Defaults match the supplied uploader: model repo saliacoel/tmp, revision main,
18
+ path_in_repo img.zip, ZIP compression level 6. The repository must exist.
19
+ Returns the resolved Hugging Face URL and the local ZIP path.
20
+ Optional after_save: connect the first node's main_file_path here to ensure
21
+ saving completes before this node takes its folder snapshot. To wait for
22
+ several saves, chain their optional after_save inputs, then connect the last
23
+ save to UPLOAD_ZIP. The ZIP includes all files already in the chosen folder.
24
+
25
+ Example output (Main_Folder_name=Bust_Batch_1, Filename=Fine_M):
26
+ ComfyUI/output/Bust_Batch_1/Fine_M.png
27
+ ComfyUI/output/Bust_Batch_1/SPEAK/Fine_M_SPEAK_A.png
28
+ ComfyUI/output/Bust_Batch_1/SPEAK/Fine_M_SPEAK_A_Coords.txt
29
+ ComfyUI/output/Bust_Batch_1/SPEAK/Fine_M_SPEAK_B.png
30
+ ComfyUI/output/Bust_Batch_1/SPEAK/Fine_M_SPEAK_B_Coords.txt
31
+ """
32
+
33
+ import io
34
+ import os
35
+ import tempfile
36
+ import threading
37
+ import zipfile
38
+ from datetime import datetime, timezone
39
+ from pathlib import Path, PurePosixPath
40
+ from urllib.parse import quote
41
+
42
+ import numpy as np
43
+ from PIL import Image
44
+
45
+ try:
46
+ import folder_paths
47
+ except ImportError:
48
+ folder_paths = None
49
+
50
+
51
+ # Keep this module's save operations and ZIP snapshots from overlapping.
52
+ _FOLDER_LOCK = threading.RLock()
53
+ _INT_MAX = 2147483647
54
+
55
+
56
+ def _main_folder(Main_Folder_name):
57
+ name = str(Main_Folder_name).strip()
58
+ if not name:
59
+ raise ValueError("Main_Folder_name cannot be empty.")
60
+ if any(ord(char) < 32 for char in name):
61
+ raise ValueError("Main_Folder_name contains a control character.")
62
+ folder = Path(name).expanduser()
63
+ if not folder.is_absolute():
64
+ if ".." in folder.parts or folder == Path("."):
65
+ raise ValueError("Use a folder name under output, or an absolute folder path.")
66
+ output = (
67
+ folder_paths.get_output_directory()
68
+ if folder_paths is not None
69
+ else os.path.join(os.getcwd(), "output")
70
+ )
71
+ folder = Path(output) / folder
72
+ folder = folder.resolve()
73
+ if folder == Path(folder.anchor):
74
+ raise ValueError("Main_Folder_name must name a folder, not a filesystem root.")
75
+ return folder
76
+
77
+
78
+ def _filename_stem(Filename):
79
+ name = str(Filename).strip()
80
+ if name.lower().endswith(".png"):
81
+ name = name[:-4]
82
+ if (
83
+ not name
84
+ or name in (".", "..")
85
+ or name.endswith((" ", "."))
86
+ or any(char in '\\/:*?"<>|' or ord(char) < 32 for char in name)
87
+ ):
88
+ raise ValueError("Filename must be a plain filename, e.g. Fine_M or Fine_M.png.")
89
+ return name
90
+
91
+
92
+ def _png_bytes(image, input_name):
93
+ # ComfyUI passes torch tensors. Avoid importing torch just to serialize one.
94
+ if not callable(getattr(image, "detach", None)):
95
+ raise TypeError(f"{input_name} must be a ComfyUI IMAGE tensor.")
96
+ shape = tuple(image.shape)
97
+ if len(shape) == 4:
98
+ if shape[0] != 1:
99
+ raise ValueError(
100
+ f"{input_name} contains a batch of {shape[0]} images. "
101
+ "Supply exactly one image per input and Filename."
102
+ )
103
+ image = image[0]
104
+ shape = tuple(image.shape)
105
+ if len(shape) != 3 or min(shape[:2]) < 1 or shape[-1] not in (1, 3, 4):
106
+ raise ValueError(
107
+ f"{input_name} has shape {shape}; expected [1,H,W,C] or [H,W,C], "
108
+ "with 1, 3, or 4 channels."
109
+ )
110
+ pixels = image.detach().cpu().float().numpy()
111
+ if not np.isfinite(pixels).all():
112
+ raise ValueError(f"{input_name} contains NaN or infinite pixel values.")
113
+ pixels = np.rint(np.clip(pixels, 0.0, 1.0) * 255.0).astype(np.uint8)
114
+ if shape[-1] == 1:
115
+ pixels = pixels[:, :, 0]
116
+ with Image.fromarray(pixels) as png, io.BytesIO() as buffer:
117
+ png.save(buffer, format="PNG", compress_level=6)
118
+ return buffer.getvalue()
119
+
120
+
121
+ def _coords_bytes(x, y, w, h, label):
122
+ values = (x, y, w, h)
123
+ if any(isinstance(value, bool) or not isinstance(value, (int, np.integer)) for value in values):
124
+ raise ValueError(f"{label} coordinates must be integers.")
125
+ if w < 1 or h < 1:
126
+ raise ValueError(f"{label} W and H must be at least 1.")
127
+ return f"X {x}\nY {y}\nW {w}\nH {h}\n".encode("utf-8")
128
+
129
+
130
+ def _write_files(files):
131
+ # Prepare every file first. Each replacement is atomic, and the main PNG is
132
+ # committed last. No automatic numbering or timestamp suffixes are added.
133
+ staged = []
134
+ try:
135
+ for destination, content in files:
136
+ destination.parent.mkdir(parents=True, exist_ok=True)
137
+ fd, temporary_name = tempfile.mkstemp(
138
+ prefix=".salia_speak_", suffix=".tmp", dir=str(destination.parent)
139
+ )
140
+ temporary_path = Path(temporary_name)
141
+ staged.append((temporary_path, destination))
142
+ with os.fdopen(fd, "wb") as stream:
143
+ stream.write(content)
144
+ for temporary_path, destination in staged:
145
+ os.replace(str(temporary_path), str(destination))
146
+ finally:
147
+ for temporary_path, _ in staged:
148
+ if temporary_path.exists():
149
+ temporary_path.unlink()
150
+
151
+
152
+ def _hf_token(hf_key):
153
+ token = str(hf_key or "").strip()
154
+ if not token or token == "hf_???":
155
+ token = (
156
+ os.environ.get("HF_TOKEN", "").strip()
157
+ or os.environ.get("HUGGINGFACEHUB_API_TOKEN", "").strip()
158
+ )
159
+ if not token:
160
+ raise ValueError(
161
+ "Provide a Hugging Face write token in hf_key, or set HF_TOKEN / "
162
+ "HUGGINGFACEHUB_API_TOKEN in ComfyUI's environment."
163
+ )
164
+ if not token.startswith("hf_"):
165
+ raise ValueError("The Hugging Face token must start with hf_.")
166
+ return token
167
+
168
+
169
+ def _remote_path(path_in_repo):
170
+ value = str(path_in_repo).strip().replace("\\", "/")
171
+ path = PurePosixPath(value)
172
+ if not value or path.is_absolute() or ".." in path.parts or not path.name:
173
+ raise ValueError("path_in_repo must be a relative ZIP filename, e.g. img.zip.")
174
+ if any(ord(char) < 32 for char in value):
175
+ raise ValueError("path_in_repo contains a control character.")
176
+ if path.suffix.lower() != ".zip":
177
+ raise ValueError("path_in_repo must end in .zip.")
178
+ return path.as_posix()
179
+
180
+
181
+ def _zip_folder(folder, compresslevel):
182
+ # ComfyUI's temp directory normally sits alongside output. If the chosen
183
+ # source contains it, put the ZIP beside the source instead (never inside it).
184
+ temp_dir = Path(
185
+ folder_paths.get_temp_directory()
186
+ if folder_paths is not None
187
+ else tempfile.gettempdir()
188
+ ).resolve()
189
+ if temp_dir == folder or folder in temp_dir.parents:
190
+ temp_dir = folder.parent
191
+ temp_dir.mkdir(parents=True, exist_ok=True)
192
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
193
+ fd, local_zip_path = tempfile.mkstemp(
194
+ prefix=f"{folder.name}_{timestamp}_", suffix=".zip", dir=str(temp_dir)
195
+ )
196
+ os.close(fd)
197
+ count = 0
198
+
199
+ def walk_error(error):
200
+ raise error
201
+
202
+ try:
203
+ with zipfile.ZipFile(
204
+ local_zip_path, "w", compression=zipfile.ZIP_DEFLATED,
205
+ compresslevel=compresslevel, allowZip64=True,
206
+ ) as archive:
207
+ for root, directories, filenames in os.walk(folder, onerror=walk_error):
208
+ directories.sort()
209
+ filenames.sort()
210
+ root_path = Path(root)
211
+ # Do not accidentally package files outside the selected folder.
212
+ if any((root_path / name).is_symlink() for name in directories + filenames):
213
+ raise ValueError("The selected upload folder contains a symbolic link.")
214
+ archive.write(root_path, arcname=root_path.relative_to(folder.parent).as_posix())
215
+ for name in filenames:
216
+ source = root_path / name
217
+ if not source.is_file():
218
+ raise ValueError(f"Cannot ZIP a non-regular file: {source}")
219
+ archive.write(source, arcname=source.relative_to(folder.parent).as_posix())
220
+ count += 1
221
+ if count == 0:
222
+ raise ValueError(f"The selected upload folder contains no files: {folder}")
223
+ except BaseException:
224
+ Path(local_zip_path).unlink(missing_ok=True)
225
+ raise
226
+ return local_zip_path, count
227
+
228
+
229
+ class Salia_Save_Speak_Images:
230
+ CATEGORY = "Salia/SPEAK"
231
+ DESCRIPTION = "Save one main PNG, two SPEAK PNGs, and their X/Y/W/H text files."
232
+ RETURN_TYPES = ("STRING",)
233
+ RETURN_NAMES = ("main_file_path",)
234
+ FUNCTION = "save"
235
+ OUTPUT_NODE = True
236
+
237
+ @classmethod
238
+ def IS_CHANGED(cls, **kwargs):
239
+ return float("nan")
240
+
241
+ @classmethod
242
+ def INPUT_TYPES(cls):
243
+ return {
244
+ "required": {
245
+ "Main_Folder_name": ("STRING", {"default": "Bust_Batch_1", "multiline": False}),
246
+ "Filename": ("STRING", {"default": "Fine_M", "multiline": False}),
247
+ "Main_Img": ("IMAGE",),
248
+ "Speak_A_Img": ("IMAGE",),
249
+ "Speak_B_Img": ("IMAGE",),
250
+ "SPEAK_A_X": ("INT", {"default": 0, "min": -_INT_MAX, "max": _INT_MAX, "step": 1}),
251
+ "SPEAK_A_Y": ("INT", {"default": 0, "min": -_INT_MAX, "max": _INT_MAX, "step": 1}),
252
+ "SPEAK_A_W": ("INT", {"default": 200, "min": 1, "max": _INT_MAX, "step": 1}),
253
+ "SPEAK_A_H": ("INT", {"default": 200, "min": 1, "max": _INT_MAX, "step": 1}),
254
+ "SPEAK_B_X": ("INT", {"default": 0, "min": -_INT_MAX, "max": _INT_MAX, "step": 1}),
255
+ "SPEAK_B_Y": ("INT", {"default": 0, "min": -_INT_MAX, "max": _INT_MAX, "step": 1}),
256
+ "SPEAK_B_W": ("INT", {"default": 200, "min": 1, "max": _INT_MAX, "step": 1}),
257
+ "SPEAK_B_H": ("INT", {"default": 200, "min": 1, "max": _INT_MAX, "step": 1}),
258
+ },
259
+ "optional": {
260
+ "after_save": ("STRING", {
261
+ "forceInput": True,
262
+ "tooltip": "Optional: connect a previous save's path to run this save after it.",
263
+ }),
264
+ },
265
+ }
266
+
267
+ def save(
268
+ self, Main_Folder_name, Filename, Main_Img, Speak_A_Img, Speak_B_Img,
269
+ SPEAK_A_X, SPEAK_A_Y, SPEAK_A_W, SPEAK_A_H,
270
+ SPEAK_B_X, SPEAK_B_Y, SPEAK_B_W, SPEAK_B_H, after_save=None,
271
+ ):
272
+ folder = _main_folder(Main_Folder_name)
273
+ stem = _filename_stem(Filename)
274
+ speak = folder / "SPEAK"
275
+ main_path = folder / f"{stem}.png"
276
+ # Validate and encode all inputs before touching the destination files.
277
+ files = [
278
+ (speak / f"{stem}_SPEAK_A.png", _png_bytes(Speak_A_Img, "Speak_A_Img")),
279
+ (speak / f"{stem}_SPEAK_A_Coords.txt", _coords_bytes(
280
+ SPEAK_A_X, SPEAK_A_Y, SPEAK_A_W, SPEAK_A_H, "SPEAK_A")),
281
+ (speak / f"{stem}_SPEAK_B.png", _png_bytes(Speak_B_Img, "Speak_B_Img")),
282
+ (speak / f"{stem}_SPEAK_B_Coords.txt", _coords_bytes(
283
+ SPEAK_B_X, SPEAK_B_Y, SPEAK_B_W, SPEAK_B_H, "SPEAK_B")),
284
+ (main_path, _png_bytes(Main_Img, "Main_Img")),
285
+ ]
286
+ with _FOLDER_LOCK:
287
+ _write_files(files)
288
+ print(f"[Salia Save SPEAK] Saved 5 files: {main_path}")
289
+ return (str(main_path),)
290
+
291
+
292
+ class Salia_UPLOAD_ZIP:
293
+ CATEGORY = "Salia/SPEAK"
294
+ DESCRIPTION = "ZIP an existing main folder and upload it to Hugging Face (model repository)."
295
+ RETURN_TYPES = ("STRING", "STRING")
296
+ RETURN_NAMES = ("hf_url", "local_zip_path")
297
+ FUNCTION = "zip_and_upload"
298
+ OUTPUT_NODE = True
299
+
300
+ @classmethod
301
+ def IS_CHANGED(cls, **kwargs):
302
+ return float("nan")
303
+
304
+ @classmethod
305
+ def INPUT_TYPES(cls):
306
+ return {
307
+ "required": {
308
+ "hf_key": ("STRING", {"default": "hf_???", "multiline": False}),
309
+ "Main_Folder_name": ("STRING", {"default": "Bust_Batch_1", "multiline": False}),
310
+ },
311
+ "optional": {
312
+ "repo_id": ("STRING", {"default": "saliacoel/tmp"}),
313
+ "revision": ("STRING", {"default": "main"}),
314
+ "path_in_repo": ("STRING", {"default": "img.zip"}),
315
+ "zip_compresslevel": ("INT", {"default": 6, "min": 0, "max": 9, "step": 1}),
316
+ "after_save": ("STRING", {
317
+ "forceInput": True,
318
+ "tooltip": "Connect the save node's main_file_path to wait for its files before uploading.",
319
+ }),
320
+ },
321
+ }
322
+
323
+ def zip_and_upload(
324
+ self, hf_key, Main_Folder_name="Bust_Batch_1", repo_id="saliacoel/tmp",
325
+ revision="main", path_in_repo="img.zip", zip_compresslevel=6, after_save=None,
326
+ ):
327
+ try:
328
+ from huggingface_hub import HfApi
329
+ except ImportError as error:
330
+ raise ImportError(
331
+ "Install huggingface_hub in ComfyUI's Python environment: "
332
+ "python -m pip install -U huggingface_hub"
333
+ ) from error
334
+
335
+ token = _hf_token(hf_key)
336
+ folder = _main_folder(Main_Folder_name)
337
+ if not folder.is_dir():
338
+ raise FileNotFoundError(f"Main folder not found: {folder}. Run the save node first.")
339
+ repo_id = str(repo_id).strip()
340
+ revision = str(revision).strip()
341
+ if not repo_id or not revision:
342
+ raise ValueError("repo_id and revision cannot be empty.")
343
+ path_in_repo = _remote_path(path_in_repo)
344
+ compresslevel = int(zip_compresslevel)
345
+ if not 0 <= compresslevel <= 9:
346
+ raise ValueError("zip_compresslevel must be between 0 and 9.")
347
+ with _FOLDER_LOCK:
348
+ local_zip_path, file_count = _zip_folder(folder, compresslevel)
349
+
350
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
351
+ api = HfApi(token=token)
352
+ # Same upload method and model repository type as the supplied uploader.
353
+ # Keep the local archive available if authentication/network upload fails.
354
+ api.upload_file(
355
+ path_or_fileobj=local_zip_path,
356
+ path_in_repo=path_in_repo,
357
+ repo_id=repo_id,
358
+ repo_type="model",
359
+ revision=revision,
360
+ commit_message=f"ComfyUI upload {path_in_repo} ({file_count} files) @ {timestamp}Z",
361
+ )
362
+ hf_url = (
363
+ f"https://huggingface.co/{quote(repo_id, safe='/')}/resolve/"
364
+ f"{quote(revision, safe='')}/{quote(path_in_repo, safe='/')}"
365
+ )
366
+ print(f"[Salia UPLOAD_ZIP] Uploaded {local_zip_path} -> {hf_url}")
367
+ return (hf_url, local_zip_path)
368
+
369
+
370
+ NODE_CLASS_MAPPINGS = {
371
+ "Salia_Save_Speak_Images": Salia_Save_Speak_Images,
372
+ "Salia_UPLOAD_ZIP": Salia_UPLOAD_ZIP,
373
+ }
374
+
375
+ NODE_DISPLAY_NAME_MAPPINGS = {
376
+ "Salia_Save_Speak_Images": "Salia Save SPEAK",
377
+ "Salia_UPLOAD_ZIP": "UPLOAD_ZIP",
378
+ }