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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import re
|
| 3 |
+
import zipfile
|
| 4 |
+
import urllib.request
|
| 5 |
+
from pathlib import PurePosixPath
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
DEFAULT_ZIP_URL = "https://huggingface.co/saliacoel/tmp/resolve/main/prompts.zip"
|
| 10 |
+
MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024 # 100 MiB safety cap
|
| 11 |
+
FILENAME_RE = re.compile(r"^(\d+)_.*\.txt$", re.IGNORECASE)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TMPSCRIPT_ZipPromptPushBuilder:
|
| 15 |
+
"""
|
| 16 |
+
Downloads a zip containing text files named like:
|
| 17 |
+
001_rogueboy_prompt.txt
|
| 18 |
+
2_Warrior_normal.txt
|
| 19 |
+
03_healergirl.txt
|
| 20 |
+
|
| 21 |
+
It parses the leading numeric ID, normalizes leading zeroes, removes linebreaks
|
| 22 |
+
from each text file, and returns one STRING containing lines like:
|
| 23 |
+
prompts.Push("...") ; 1
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
@classmethod
|
| 27 |
+
def INPUT_TYPES(cls):
|
| 28 |
+
return {
|
| 29 |
+
"required": {
|
| 30 |
+
"zip_url": (
|
| 31 |
+
"STRING",
|
| 32 |
+
{
|
| 33 |
+
"default": DEFAULT_ZIP_URL,
|
| 34 |
+
"multiline": False,
|
| 35 |
+
},
|
| 36 |
+
),
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
RETURN_TYPES = ("STRING",)
|
| 41 |
+
RETURN_NAMES = ("prompts_text",)
|
| 42 |
+
FUNCTION = "build_prompts_text"
|
| 43 |
+
CATEGORY = "text/prompts"
|
| 44 |
+
SEARCH_ALIASES = ["zip prompts", "prompt zip", "prompts push"]
|
| 45 |
+
|
| 46 |
+
# The remote file can change while the URL stays the same. This forces ComfyUI
|
| 47 |
+
# to re-run the node each queue execution instead of using a stale cached value.
|
| 48 |
+
@classmethod
|
| 49 |
+
def IS_CHANGED(cls, zip_url):
|
| 50 |
+
return float("NaN")
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def VALIDATE_INPUTS(cls, zip_url):
|
| 54 |
+
parsed = urlparse(zip_url)
|
| 55 |
+
if parsed.scheme not in ("http", "https"):
|
| 56 |
+
return "zip_url must start with http:// or https://"
|
| 57 |
+
if not parsed.netloc:
|
| 58 |
+
return "zip_url is missing a host"
|
| 59 |
+
return True
|
| 60 |
+
|
| 61 |
+
def build_prompts_text(self, zip_url):
|
| 62 |
+
zip_bytes = self._download_zip(zip_url)
|
| 63 |
+
rows = self._extract_prompt_rows(zip_bytes)
|
| 64 |
+
|
| 65 |
+
if not rows:
|
| 66 |
+
raise ValueError(
|
| 67 |
+
"No matching .txt files found in the zip. "
|
| 68 |
+
"Expected filenames like '001_name.txt': leading digits, underscore, then name."
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
output_text = self._format_rows(rows)
|
| 72 |
+
|
| 73 |
+
# The tuple in result is the actual STRING output. The ui field helps some
|
| 74 |
+
# ComfyUI frontends/extensions display the generated text in the node result.
|
| 75 |
+
return {"ui": {"text": [output_text]}, "result": (output_text,)}
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def _download_zip(zip_url):
|
| 79 |
+
request = urllib.request.Request(
|
| 80 |
+
zip_url,
|
| 81 |
+
headers={"User-Agent": "ComfyUI-ZipPromptPushBuilder/1.0"},
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
with urllib.request.urlopen(request, timeout=60) as response:
|
| 86 |
+
status = getattr(response, "status", 200)
|
| 87 |
+
if status >= 400:
|
| 88 |
+
raise ValueError(f"Download failed with HTTP status {status}")
|
| 89 |
+
|
| 90 |
+
chunks = []
|
| 91 |
+
total = 0
|
| 92 |
+
while True:
|
| 93 |
+
chunk = response.read(1024 * 1024)
|
| 94 |
+
if not chunk:
|
| 95 |
+
break
|
| 96 |
+
total += len(chunk)
|
| 97 |
+
if total > MAX_DOWNLOAD_BYTES:
|
| 98 |
+
raise ValueError(
|
| 99 |
+
f"Zip download exceeded {MAX_DOWNLOAD_BYTES // (1024 * 1024)} MiB"
|
| 100 |
+
)
|
| 101 |
+
chunks.append(chunk)
|
| 102 |
+
return b"".join(chunks)
|
| 103 |
+
except Exception as exc:
|
| 104 |
+
raise RuntimeError(f"Could not download zip from {zip_url!r}: {exc}") from exc
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def _extract_prompt_rows(cls, zip_bytes):
|
| 108 |
+
try:
|
| 109 |
+
archive = zipfile.ZipFile(io.BytesIO(zip_bytes))
|
| 110 |
+
except zipfile.BadZipFile as exc:
|
| 111 |
+
raise ValueError("Downloaded file is not a valid zip archive") from exc
|
| 112 |
+
|
| 113 |
+
rows = []
|
| 114 |
+
with archive:
|
| 115 |
+
for info in archive.infolist():
|
| 116 |
+
if info.is_dir():
|
| 117 |
+
continue
|
| 118 |
+
|
| 119 |
+
# Zip paths always use forward slashes. Only the basename matters.
|
| 120 |
+
filename = PurePosixPath(info.filename).name
|
| 121 |
+
match = FILENAME_RE.match(filename)
|
| 122 |
+
if not match:
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
prompt_id = int(match.group(1)) # 02 and 002 both become 2.
|
| 126 |
+
raw_text = archive.read(info)
|
| 127 |
+
decoded_text = cls._decode_text(raw_text)
|
| 128 |
+
prompt_text = cls._remove_linebreaks(decoded_text)
|
| 129 |
+
|
| 130 |
+
rows.append((prompt_id, filename, prompt_text))
|
| 131 |
+
|
| 132 |
+
# Sort by the normalized numeric ID, then by filename for stable output.
|
| 133 |
+
rows.sort(key=lambda row: (row[0], row[1].casefold()))
|
| 134 |
+
return rows
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def _decode_text(raw_text):
|
| 138 |
+
# UTF-8 with BOM support first. The fallbacks make Windows-authored prompt
|
| 139 |
+
# files less likely to fail.
|
| 140 |
+
for encoding in ("utf-8-sig", "utf-16", "cp1252"):
|
| 141 |
+
try:
|
| 142 |
+
return raw_text.decode(encoding)
|
| 143 |
+
except UnicodeError:
|
| 144 |
+
pass
|
| 145 |
+
return raw_text.decode("utf-8", errors="replace")
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def _remove_linebreaks(text):
|
| 149 |
+
# Converts all whitespace runs, including CR/LF linebreaks, tabs, and repeated
|
| 150 |
+
# spaces, into one normal space.
|
| 151 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def _escape_for_double_quoted_string(text):
|
| 155 |
+
# Keeps generated prompts.Push("...") lines syntactically safe when the prompt
|
| 156 |
+
# itself contains quotes or backslashes.
|
| 157 |
+
return text.replace("\\", "\\\\").replace('"', '\\"')
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def _format_rows(cls, rows):
|
| 161 |
+
prefixes = []
|
| 162 |
+
for prompt_id, _filename, prompt_text in rows:
|
| 163 |
+
escaped_prompt = cls._escape_for_double_quoted_string(prompt_text)
|
| 164 |
+
prefixes.append((prompt_id, f'prompts.Push("{escaped_prompt}")'))
|
| 165 |
+
|
| 166 |
+
# Align the ID comments/readouts after the semicolon.
|
| 167 |
+
width = max(len(prefix) for _prompt_id, prefix in prefixes)
|
| 168 |
+
return "\n".join(
|
| 169 |
+
f"{prefix.ljust(width)} ; {prompt_id}"
|
| 170 |
+
for prompt_id, prefix in prefixes
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
NODE_CLASS_MAPPINGS = {
|
| 175 |
+
"TMPSCRIPT_ZipPromptPushBuilder": TMPSCRIPT_ZipPromptPushBuilder,
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 179 |
+
"TMPSCRIPT_ZipPromptPushBuilder": "TMPSCRIPT_ZipPromptPushBuilder",
|
| 180 |
+
}
|