saliacoel commited on
Commit
ea13a89
·
verified ·
1 Parent(s): 1233384

Upload salia_chars_upload.py

Browse files
Files changed (1) hide show
  1. salia_chars_upload.py +463 -0
salia_chars_upload.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import re
4
+ from urllib.parse import quote, unquote, urlparse
5
+ from typing import Optional
6
+
7
+ import numpy as np
8
+
9
+ REPO_ID = "saliacoel/chars"
10
+ REPO_TYPE = "model"
11
+ BRANCH = "main"
12
+ BAM_FILENAME = "BAM.txt"
13
+ CATEGORY = "Salia/HuggingFace"
14
+
15
+ _INVALID_PATH_CHARS = re.compile(r'[<>:"\\|?*\x00-\x1F]')
16
+ _BAM_ENTRY_ID_RE = re.compile(r"(?<!\d)(\d{4})\.\s*")
17
+ _FIRST_MP4_RE = re.compile(r"\.mp4\b", re.IGNORECASE)
18
+ _LEADING_PATH_RE = re.compile(r'([A-Za-z]:[\\/]|/|\.{1,2}[\\/])')
19
+
20
+
21
+ # -----------------------------------------------------------------------------
22
+ # Generic helpers
23
+ # -----------------------------------------------------------------------------
24
+
25
+ def _optional_string(value) -> str:
26
+ if value is None:
27
+ return ""
28
+ return str(value).strip()
29
+
30
+
31
+
32
+ def _require_non_empty_string(value, name: str) -> str:
33
+ value = _optional_string(value)
34
+ if not value:
35
+ raise ValueError(f"{name} must not be empty.")
36
+ return value
37
+
38
+
39
+
40
+ def _resolve_hf_token(hf_token: str, *, required: bool) -> Optional[str]:
41
+ token = _optional_string(hf_token)
42
+ if token:
43
+ return token
44
+
45
+ for env_name in ("HF_TOKEN", "HUGGINGFACE_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
46
+ env_value = _optional_string(os.environ.get(env_name))
47
+ if env_value:
48
+ return env_value
49
+
50
+ if required:
51
+ raise ValueError(
52
+ "A Hugging Face token is required. Provide hf_token in the node, or set HF_TOKEN / "
53
+ "HUGGINGFACE_TOKEN / HUGGING_FACE_HUB_TOKEN in the environment."
54
+ )
55
+ return None
56
+
57
+
58
+
59
+ def _import_hf():
60
+ try:
61
+ from huggingface_hub import HfApi, hf_hub_download
62
+ except Exception as exc:
63
+ raise RuntimeError(
64
+ "Missing dependency 'huggingface_hub'. Install it in the ComfyUI Python environment with: "
65
+ "pip install huggingface_hub"
66
+ ) from exc
67
+ return HfApi, hf_hub_download
68
+
69
+
70
+
71
+ def _sanitize_path_component(component: str, label: str) -> str:
72
+ component = _require_non_empty_string(component, label)
73
+ component = component.replace("\\", "/").split("/")[-1]
74
+ component = _INVALID_PATH_CHARS.sub("_", component)
75
+ component = component.strip().strip(".")
76
+ if component in {"", ".", ".."}:
77
+ raise ValueError(f"Invalid {label}: {component!r}")
78
+ return component
79
+
80
+
81
+
82
+ def _sanitize_repo_path(path_in_repo: str) -> str:
83
+ path_in_repo = _require_non_empty_string(path_in_repo, "path_in_repo")
84
+ cleaned_parts = []
85
+ for raw_part in path_in_repo.replace("\\", "/").split("/"):
86
+ part = raw_part.strip()
87
+ if not part or part == ".":
88
+ continue
89
+ if part == "..":
90
+ raise ValueError("path_in_repo must not contain '..'.")
91
+ cleaned_parts.append(_sanitize_path_component(part, "path component"))
92
+ if not cleaned_parts:
93
+ raise ValueError("path_in_repo became empty after sanitization.")
94
+ return "/".join(cleaned_parts)
95
+
96
+
97
+
98
+ def _ensure_extension(filename: str, extension: str) -> str:
99
+ filename = _sanitize_path_component(filename, "filename")
100
+ if filename.lower().endswith(extension.lower()):
101
+ return filename
102
+ return f"{filename}{extension}"
103
+
104
+
105
+
106
+ def _quote_repo_path(path_in_repo: str) -> str:
107
+ return "/".join(quote(part, safe="") for part in path_in_repo.split("/"))
108
+
109
+
110
+
111
+ def _repo_file_url(path_in_repo: str) -> str:
112
+ path_in_repo = _sanitize_repo_path(path_in_repo)
113
+ return f"https://huggingface.co/{REPO_ID}/resolve/{BRANCH}/{_quote_repo_path(path_in_repo)}"
114
+
115
+
116
+
117
+ def _commit_url_from_upload_result(upload_result) -> str:
118
+ commit_url = getattr(upload_result, "commit_url", None)
119
+ if commit_url:
120
+ return str(commit_url)
121
+ return str(upload_result)
122
+
123
+
124
+
125
+ def _make_repo_target(character_name: str, filename: str, extension: str) -> str:
126
+ character_name = _sanitize_path_component(character_name, "character_name")
127
+ filename = _ensure_extension(filename, extension)
128
+ return _sanitize_repo_path(f"{character_name}/{filename}")
129
+
130
+
131
+
132
+ def _normalize_local_path(local_path: str) -> str:
133
+ local_path = _require_non_empty_string(local_path, "local_path")
134
+
135
+ if local_path.lower().startswith("file://"):
136
+ parsed = urlparse(local_path)
137
+ local_path = unquote(parsed.path or "")
138
+ if re.match(r"^/[A-Za-z]:[/\\]", local_path):
139
+ local_path = local_path[1:]
140
+
141
+ local_path = os.path.expandvars(os.path.expanduser(local_path))
142
+ return os.path.normpath(local_path)
143
+
144
+
145
+
146
+ def _read_text_file(file_path: str) -> str:
147
+ with open(file_path, "rb") as handle:
148
+ raw = handle.read()
149
+
150
+ for encoding in ("utf-8-sig", "utf-8", "latin-1"):
151
+ try:
152
+ return raw.decode(encoding)
153
+ except Exception:
154
+ continue
155
+ return raw.decode("utf-8", errors="replace")
156
+
157
+
158
+
159
+ def _upload_bytes(file_bytes: bytes, path_in_repo: str, hf_token: str, commit_message: str):
160
+ token = _resolve_hf_token(hf_token, required=True)
161
+ path_in_repo = _sanitize_repo_path(path_in_repo)
162
+
163
+ HfApi, _ = _import_hf()
164
+ api = HfApi(token=token)
165
+
166
+ upload_result = api.upload_file(
167
+ path_or_fileobj=file_bytes,
168
+ path_in_repo=path_in_repo,
169
+ repo_id=REPO_ID,
170
+ repo_type=REPO_TYPE,
171
+ token=token,
172
+ commit_message=commit_message,
173
+ )
174
+
175
+ return path_in_repo, _repo_file_url(path_in_repo), _commit_url_from_upload_result(upload_result)
176
+
177
+
178
+
179
+ def _upload_local_file(local_path: str, path_in_repo: str, hf_token: str, commit_message: str):
180
+ token = _resolve_hf_token(hf_token, required=True)
181
+ local_path = _normalize_local_path(local_path)
182
+ path_in_repo = _sanitize_repo_path(path_in_repo)
183
+
184
+ if not os.path.isfile(local_path):
185
+ raise ValueError(f"Local file does not exist: {local_path}")
186
+
187
+ HfApi, _ = _import_hf()
188
+ api = HfApi(token=token)
189
+
190
+ upload_result = api.upload_file(
191
+ path_or_fileobj=local_path,
192
+ path_in_repo=path_in_repo,
193
+ repo_id=REPO_ID,
194
+ repo_type=REPO_TYPE,
195
+ token=token,
196
+ commit_message=commit_message,
197
+ )
198
+
199
+ return path_in_repo, _repo_file_url(path_in_repo), _commit_url_from_upload_result(upload_result)
200
+
201
+
202
+ # -----------------------------------------------------------------------------
203
+ # Image helpers
204
+ # -----------------------------------------------------------------------------
205
+
206
+ def _tensor_to_png_bytes(img):
207
+ try:
208
+ from PIL import Image
209
+ except Exception as exc:
210
+ raise RuntimeError(
211
+ "Missing dependency 'Pillow'. Install it in the ComfyUI Python environment with: pip install pillow"
212
+ ) from exc
213
+
214
+ if img is None:
215
+ raise ValueError("img is required.")
216
+
217
+ if hasattr(img, "detach"):
218
+ img = img.detach()
219
+ if hasattr(img, "cpu"):
220
+ img = img.cpu()
221
+ if hasattr(img, "numpy"):
222
+ arr = img.numpy()
223
+ else:
224
+ arr = np.asarray(img)
225
+
226
+ if arr.ndim == 4:
227
+ if arr.shape[0] == 0:
228
+ raise ValueError("Received an empty image batch.")
229
+ if arr.shape[0] != 1:
230
+ raise ValueError(
231
+ f"Expected a single image, but received a batch of {arr.shape[0]}. Use an image selector/split node first."
232
+ )
233
+ arr = arr[0]
234
+
235
+ if arr.ndim != 3:
236
+ raise ValueError(f"Expected image tensor with 3 dimensions after batch removal, got shape {arr.shape}.")
237
+
238
+ channels = int(arr.shape[2])
239
+ if channels not in (3, 4):
240
+ raise ValueError(f"Expected 3 channels (RGB) or 4 channels (RGBA), but got {channels} channels.")
241
+
242
+ if np.issubdtype(arr.dtype, np.floating):
243
+ arr = np.clip(arr, 0.0, 1.0)
244
+ arr = np.rint(arr * 255.0).astype(np.uint8)
245
+ else:
246
+ arr = np.clip(arr, 0, 255).astype(np.uint8)
247
+
248
+ mode = "RGBA" if channels == 4 else "RGB"
249
+ pil_image = Image.fromarray(arr, mode=mode)
250
+
251
+ buffer = io.BytesIO()
252
+ pil_image.save(buffer, format="PNG")
253
+ return buffer.getvalue(), mode
254
+
255
+
256
+ # -----------------------------------------------------------------------------
257
+ # BAM parsing helpers
258
+ # -----------------------------------------------------------------------------
259
+
260
+ def _download_bam_text(hf_token: str) -> str:
261
+ token = _resolve_hf_token(hf_token, required=False)
262
+ _, hf_hub_download = _import_hf()
263
+
264
+ cached_path = hf_hub_download(
265
+ repo_id=REPO_ID,
266
+ filename=BAM_FILENAME,
267
+ repo_type=REPO_TYPE,
268
+ revision=BRANCH,
269
+ token=token,
270
+ )
271
+ return _read_text_file(cached_path)
272
+
273
+
274
+
275
+ def _iter_bam_entries(bam_text: str):
276
+ bam_text = "" if bam_text is None else str(bam_text)
277
+ matches = list(_BAM_ENTRY_ID_RE.finditer(bam_text))
278
+ for index, match in enumerate(matches):
279
+ start = match.end()
280
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(bam_text)
281
+ entry_id = int(match.group(1))
282
+ entry_text = bam_text[start:end].strip()
283
+ yield entry_id, entry_text
284
+
285
+
286
+
287
+ def _extract_name_from_bam_entry(entry_text: str) -> str:
288
+ entry_text = "" if entry_text is None else str(entry_text)
289
+ return entry_text.split(",", 1)[0].strip().strip(",")
290
+
291
+
292
+
293
+ def _lookup_bam_name(character_id: int, bam_text: str) -> str:
294
+ try:
295
+ character_id = int(character_id)
296
+ except Exception as exc:
297
+ raise ValueError("id must be an integer.") from exc
298
+
299
+ if character_id < 0 or character_id > 9999:
300
+ raise ValueError("id must be between 0 and 9999.")
301
+
302
+ for entry_id, entry_text in _iter_bam_entries(bam_text):
303
+ if entry_id != character_id:
304
+ continue
305
+ name = _extract_name_from_bam_entry(entry_text)
306
+ if not name:
307
+ raise ValueError(f"Found ID {character_id:04d} in BAM.txt, but the name field is empty.")
308
+ return name
309
+
310
+ raise ValueError(f"Could not find ID {character_id:04d} in {BAM_FILENAME}.")
311
+
312
+
313
+ # -----------------------------------------------------------------------------
314
+ # MP4 path parsing helpers
315
+ # -----------------------------------------------------------------------------
316
+
317
+ def _strip_wrappers(text: str) -> str:
318
+ text = "" if text is None else str(text)
319
+ text = text.strip()
320
+ while text and text[0] in '"\'([{<':
321
+ text = text[1:].lstrip()
322
+ while text and text[-1] in '"\')]}>,':
323
+ text = text[:-1].rstrip()
324
+ return text
325
+
326
+
327
+
328
+ def _extract_mp4_path(mp4_path: str) -> str:
329
+ raw = _require_non_empty_string(mp4_path, "MP4_PATH")
330
+
331
+ first_mp4 = _FIRST_MP4_RE.search(raw)
332
+ if not first_mp4:
333
+ raise ValueError("MP4_PATH did not contain a .mp4 path.")
334
+
335
+ end = first_mp4.end()
336
+ semicolon_index = raw.rfind(";", 0, first_mp4.start())
337
+ candidate = raw[semicolon_index + 1 : end] if semicolon_index != -1 else raw[:end]
338
+ candidate = _strip_wrappers(candidate)
339
+
340
+ prefix_match = _LEADING_PATH_RE.search(candidate)
341
+ if prefix_match:
342
+ candidate = candidate[prefix_match.start() :]
343
+ candidate = _strip_wrappers(candidate)
344
+
345
+ if not candidate.lower().endswith(".mp4"):
346
+ fallback = re.search(r'([^\s;]+\.mp4)\b', candidate, re.IGNORECASE)
347
+ if fallback:
348
+ candidate = fallback.group(1)
349
+
350
+ candidate = candidate.strip()
351
+ if not candidate or not candidate.lower().endswith(".mp4"):
352
+ raise ValueError(f"Could not isolate a valid .mp4 path from MP4_PATH: {raw!r}")
353
+
354
+ return candidate
355
+
356
+
357
+ # -----------------------------------------------------------------------------
358
+ # Node classes
359
+ # -----------------------------------------------------------------------------
360
+
361
+ class Salia_BAM_ID_to_Name:
362
+ CATEGORY = CATEGORY
363
+ FUNCTION = "lookup"
364
+ RETURN_TYPES = ("STRING",)
365
+ RETURN_NAMES = ("character_name",)
366
+ DESCRIPTION = (
367
+ "Downloads BAM.txt from saliacoel/chars, finds the 4-digit ID like 0004., and returns the text "
368
+ "between the ID and the first comma."
369
+ )
370
+ SEARCH_ALIASES = ["bam id to name", "character id to bam name"]
371
+
372
+ @classmethod
373
+ def INPUT_TYPES(cls):
374
+ return {
375
+ "required": {
376
+ "id": ("INT", {"default": 1, "min": 0, "max": 9999, "step": 1}),
377
+ "hf_token": ("STRING", {"default": "", "multiline": False, "placeholder": "hf_... (optional for public BAM.txt)"}),
378
+ }
379
+ }
380
+
381
+ def lookup(self, id, hf_token):
382
+ bam_text = _download_bam_text(hf_token)
383
+ character_name = _lookup_bam_name(id, bam_text)
384
+ return (character_name,)
385
+
386
+
387
+ class _SaliaCharsUploadBase:
388
+ CATEGORY = CATEGORY
389
+ OUTPUT_NODE = True
390
+ RETURN_TYPES = ("STRING", "STRING", "STRING")
391
+ RETURN_NAMES = ("path_in_repo", "file_url", "commit_url")
392
+
393
+
394
+ class Salia_Upload_to_Chars_IMG(_SaliaCharsUploadBase):
395
+ FUNCTION = "upload"
396
+ DESCRIPTION = "Uploads a single RGB or RGBA ComfyUI image tensor as CHARACTER_NAME/FILENAME.png to saliacoel/chars."
397
+ SEARCH_ALIASES = ["upload png to chars", "salia chars image upload"]
398
+
399
+ @classmethod
400
+ def INPUT_TYPES(cls):
401
+ return {
402
+ "required": {
403
+ "img": ("IMAGE", {}),
404
+ "character_name": ("STRING", {"default": "Adali", "multiline": False}),
405
+ "filename": ("STRING", {"default": "image", "multiline": False}),
406
+ "hf_token": ("STRING", {"default": "", "multiline": False, "placeholder": "hf_..."}),
407
+ }
408
+ }
409
+
410
+ def upload(self, img, character_name, filename, hf_token):
411
+ path_in_repo = _make_repo_target(character_name, filename, ".png")
412
+ png_bytes, mode = _tensor_to_png_bytes(img)
413
+ return _upload_bytes(
414
+ png_bytes,
415
+ path_in_repo,
416
+ hf_token,
417
+ f"ComfyUI upload {path_in_repo} ({mode})",
418
+ )
419
+
420
+
421
+ class Salia_Upload_to_Chars_MP4(_SaliaCharsUploadBase):
422
+ FUNCTION = "upload"
423
+ DESCRIPTION = (
424
+ "Parses the first .mp4 path out of MP4_PATH by scanning backward to the previous semicolon, then uploads that "
425
+ "local file as CHARACTER_NAME/FILENAME.mp4 to saliacoel/chars."
426
+ )
427
+ SEARCH_ALIASES = ["upload mp4 to chars", "salia chars mp4 upload"]
428
+
429
+ @classmethod
430
+ def INPUT_TYPES(cls):
431
+ return {
432
+ "required": {
433
+ "MP4_PATH": ("STRING", {"default": "", "multiline": True}),
434
+ "character_name": ("STRING", {"default": "Adali", "multiline": False}),
435
+ "filename": ("STRING", {"default": "video", "multiline": False}),
436
+ "hf_token": ("STRING", {"default": "", "multiline": False, "placeholder": "hf_..."}),
437
+ }
438
+ }
439
+
440
+ def upload(self, MP4_PATH, character_name, filename, hf_token):
441
+ local_mp4_path = _extract_mp4_path(MP4_PATH)
442
+ path_in_repo = _make_repo_target(character_name, filename, ".mp4")
443
+ return _upload_local_file(
444
+ local_mp4_path,
445
+ path_in_repo,
446
+ hf_token,
447
+ f"ComfyUI upload {path_in_repo} (MP4)",
448
+ )
449
+
450
+
451
+ NODE_CLASS_MAPPINGS = {
452
+ "Salia_BAM_ID_to_Name": Salia_BAM_ID_to_Name,
453
+ "Salia_Upload_to_Chars_IMG": Salia_Upload_to_Chars_IMG,
454
+ "Salia_Upload_to_Chars_MP4": Salia_Upload_to_Chars_MP4,
455
+ }
456
+
457
+ NODE_DISPLAY_NAME_MAPPINGS = {
458
+ "Salia_BAM_ID_to_Name": "Salia_BAM_ID_to_Name",
459
+ "Salia_Upload_to_Chars_IMG": "Salia_Upload_to_Chars_IMG",
460
+ "Salia_Upload_to_Chars_MP4": "Salia_Upload_to_Chars_MP4",
461
+ }
462
+
463
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]