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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Standalone ComfyUI custom nodes for the Facing Each Other pose catalogue.
|
| 3 |
+
|
| 4 |
+
Install:
|
| 5 |
+
Put this ONE file in ComfyUI/custom_nodes/ and restart ComfyUI.
|
| 6 |
+
Hugging Face publishing needs huggingface_hub in ComfyUI's Python env:
|
| 7 |
+
python -m pip install huggingface_hub
|
| 8 |
+
No OpenAI Python SDK or copy of the prototype node is needed.
|
| 9 |
+
|
| 10 |
+
Nodes:
|
| 11 |
+
Salia Facing Each Other: Astra Batch
|
| 12 |
+
Paste the horizontal-slice JSON, enter the two keys, and queue once.
|
| 13 |
+
start_or_check submits one Batch containing one request per pose-pair.
|
| 14 |
+
Queue again to check the same Batch; it never automatically resubmits.
|
| 15 |
+
prepare_only writes prompts/JSONL locally without calling either API.
|
| 16 |
+
check/download can use an explicit batch_id, even with an empty JSON.
|
| 17 |
+
|
| 18 |
+
Salia Facing Each Other: Astra Release
|
| 19 |
+
Enter/connect batch_id and enter both keys. Queue again while pending.
|
| 20 |
+
When terminal, download output/errors, extract assistant text, and
|
| 21 |
+
publish Markdown, companion JSON, raw JSONL, and a combined TXT.
|
| 22 |
+
Failed, refused, missing, and incomplete answers are reported in JSON
|
| 23 |
+
and TXT, and are never presented as completed Markdown catalogues.
|
| 24 |
+
Release NEVER submits new generation requests.
|
| 25 |
+
|
| 26 |
+
Fixed generation settings:
|
| 27 |
+
model=gpt-6-astra; reasoning={effort: high, mode: standard, summary: null}
|
| 28 |
+
text={format: {type: text}, verbosity: medium}; store=false; tools=[]
|
| 29 |
+
service_tier=default; stream=false; endpoint=/v1/responses; window=24h
|
| 30 |
+
No artificial max_output_tokens limit is added.
|
| 31 |
+
|
| 32 |
+
HF destination (a model repository): saliacoel/poses, branch main.
|
| 33 |
+
<original output_filename>.md
|
| 34 |
+
<original output_filename without .md>.json
|
| 35 |
+
FacingEachOther_AllOutputs.txt
|
| 36 |
+
Batches/<batch_id>/... input, output, errors, manifest, release report
|
| 37 |
+
|
| 38 |
+
Every job in the JSON is included, even reference_complete jobs. The supplied
|
| 39 |
+
example has 81 jobs, IDs 0-80. There is no hardcoded count or pose combination.
|
| 40 |
+
Prompt wording comes from FacingEachOtherPromptFromJSON, with the output
|
| 41 |
+
contract changed to ordinary response text. Reference filenames are listed;
|
| 42 |
+
the three example .md contents are not supplied by the horizontal-slice JSON
|
| 43 |
+
and are not automatically invented or fetched.
|
| 44 |
+
|
| 45 |
+
Local state: ComfyUI/output/Salia_FacingEachOther_Astra_Batch/.
|
| 46 |
+
Keys are never written into generated files or batch state. Blank key widgets
|
| 47 |
+
may use OPENAI_API_KEY and HF_TOKEN/HUGGING_FACE_HUB_TOKEN respectively.
|
| 48 |
+
An uncertain Batch-creation network failure is recovered by listing Batches
|
| 49 |
+
or by an explicit batch_id, rather than automatically charging for a duplicate.
|
| 50 |
+
|
| 51 |
+
API references:
|
| 52 |
+
https://developers.openai.com/api/docs/guides/batch
|
| 53 |
+
https://developers.openai.com/api/docs/models/gpt-6-astra
|
| 54 |
+
https://huggingface.co/docs/huggingface_hub/en/package_reference/hf_api
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
from __future__ import annotations
|
| 58 |
+
|
| 59 |
+
import hashlib
|
| 60 |
+
import json
|
| 61 |
+
import os
|
| 62 |
+
import re
|
| 63 |
+
import secrets
|
| 64 |
+
import shutil
|
| 65 |
+
import tempfile
|
| 66 |
+
from contextlib import contextmanager
|
| 67 |
+
from copy import deepcopy
|
| 68 |
+
from datetime import datetime, timezone
|
| 69 |
+
from pathlib import Path
|
| 70 |
+
from typing import Any, Dict, List, Tuple
|
| 71 |
+
from urllib.error import HTTPError, URLError
|
| 72 |
+
from urllib.parse import quote, unquote, urlparse
|
| 73 |
+
from urllib.request import Request, url2pathname, urlopen
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
NODE_VERSION = "1.0.0"
|
| 77 |
+
PURPOSE = "salia-facing-each-other-astra-batch"
|
| 78 |
+
OPENAI_MODEL = "gpt-6-astra"
|
| 79 |
+
OPENAI_BATCH_ENDPOINT = "/v1/responses"
|
| 80 |
+
OPENAI_REASONING = {"effort": "high", "mode": "standard", "summary": None}
|
| 81 |
+
HF_REPO_ID = "saliacoel/poses"
|
| 82 |
+
HF_REPO_TYPE = "model"
|
| 83 |
+
HF_REVISION = "main"
|
| 84 |
+
HF_URL = "https://huggingface.co/saliacoel/poses/tree/main"
|
| 85 |
+
ALL_OUTPUTS_FILENAME = "FacingEachOther_AllOutputs.txt"
|
| 86 |
+
MAX_JSON_BYTES = 8 * 1024 * 1024
|
| 87 |
+
MAX_BATCH_BYTES = 200_000_000
|
| 88 |
+
MAX_BATCH_REQUESTS = 50_000
|
| 89 |
+
URL_TIMEOUT_SECONDS = 30
|
| 90 |
+
TERMINAL_STATUSES = {"completed", "failed", "expired", "cancelled"}
|
| 91 |
+
PENDING_STATUSES = {"validating", "in_progress", "finalizing", "cancelling"}
|
| 92 |
+
SAFE_BATCH_ID = re.compile(r"batch_[A-Za-z0-9_-]+\Z")
|
| 93 |
+
SAFE_FILE_ID = re.compile(r"file[-_][A-Za-z0-9_-]+\Z")
|
| 94 |
+
SAFE_MD_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*\.md\Z", re.IGNORECASE)
|
| 95 |
+
REFERENCE_FILES = (
|
| 96 |
+
"FacingEachOther_CharStanding_UserStanding.md",
|
| 97 |
+
"FacingEachOther_CharStanding_UserSupine.md",
|
| 98 |
+
"FacingEachOther_CharStanding_UserProne.md",
|
| 99 |
+
)
|
| 100 |
+
TEXT_OUTPUT_CONTRACT = (
|
| 101 |
+
"Write the output directly into the response instead of sending a file. "
|
| 102 |
+
"Simply output it via text. Provide the full Markdown catalogue as output. "
|
| 103 |
+
"Return no second file, preface, apology, progress note, or unrelated commentary."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class _PosePromptBuilder:
|
| 108 |
+
"""Prompt/JSON helpers embedded from the supplied prototype."""
|
| 109 |
+
|
| 110 |
+
@classmethod
|
| 111 |
+
def _load_json_source(cls, json_source: str) -> Any:
|
| 112 |
+
if not isinstance(json_source, str) or not json_source.strip():
|
| 113 |
+
raise ValueError(
|
| 114 |
+
"json_source is empty. Paste raw JSON or provide an http(s) URL, "
|
| 115 |
+
"file:// URI, or local JSON path."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
source = json_source.strip()
|
| 119 |
+
if cls._looks_like_inline_json(source):
|
| 120 |
+
text = source.lstrip("\ufeff")
|
| 121 |
+
elif source.lower().startswith(("http://", "https://")):
|
| 122 |
+
text = cls._read_url(source)
|
| 123 |
+
elif source.lower().startswith("file://"):
|
| 124 |
+
text = cls._read_file_uri(source)
|
| 125 |
+
else:
|
| 126 |
+
text = cls._read_local_path(source)
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
return json.loads(text)
|
| 130 |
+
except json.JSONDecodeError as exc:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
"Invalid JSON at line "
|
| 133 |
+
f"{exc.lineno}, column {exc.colno}: {exc.msg}"
|
| 134 |
+
) from exc
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@staticmethod
|
| 138 |
+
def _looks_like_inline_json(source: str) -> bool:
|
| 139 |
+
candidate = source.lstrip("\ufeff \t\r\n")
|
| 140 |
+
return candidate.startswith("{") or candidate.startswith("[")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@classmethod
|
| 144 |
+
def _read_url(cls, source: str) -> str:
|
| 145 |
+
request = Request(
|
| 146 |
+
source,
|
| 147 |
+
headers={"User-Agent": "ComfyUI-FacingEachOtherPromptFromJSON/1.0"},
|
| 148 |
+
)
|
| 149 |
+
try:
|
| 150 |
+
with urlopen(request, timeout=URL_TIMEOUT_SECONDS) as response:
|
| 151 |
+
declared_length = response.headers.get("Content-Length")
|
| 152 |
+
if declared_length:
|
| 153 |
+
try:
|
| 154 |
+
length = int(declared_length)
|
| 155 |
+
except ValueError:
|
| 156 |
+
length = None
|
| 157 |
+
if length is not None and length > MAX_JSON_BYTES:
|
| 158 |
+
raise ValueError(
|
| 159 |
+
f"Remote JSON exceeds the {MAX_JSON_BYTES}-byte limit."
|
| 160 |
+
)
|
| 161 |
+
raw = response.read(MAX_JSON_BYTES + 1)
|
| 162 |
+
except ValueError:
|
| 163 |
+
raise
|
| 164 |
+
except (HTTPError, URLError, TimeoutError, OSError) as exc:
|
| 165 |
+
raise RuntimeError(f"Could not read JSON URL '{source}': {exc}") from exc
|
| 166 |
+
return cls._decode_json_bytes(raw, source)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@classmethod
|
| 170 |
+
def _read_file_uri(cls, source: str) -> str:
|
| 171 |
+
parsed = urlparse(source)
|
| 172 |
+
path_text = url2pathname(unquote(parsed.path))
|
| 173 |
+
if parsed.netloc:
|
| 174 |
+
path_text = f"//{parsed.netloc}{path_text}"
|
| 175 |
+
return cls._read_local_path(path_text)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@classmethod
|
| 179 |
+
def _read_local_path(cls, source: str) -> str:
|
| 180 |
+
path = Path(os.path.expandvars(source)).expanduser()
|
| 181 |
+
try:
|
| 182 |
+
size = path.stat().st_size
|
| 183 |
+
except OSError as exc:
|
| 184 |
+
raise RuntimeError(f"Could not access JSON path '{path}': {exc}") from exc
|
| 185 |
+
|
| 186 |
+
if size > MAX_JSON_BYTES:
|
| 187 |
+
raise ValueError(
|
| 188 |
+
f"JSON file '{path}' exceeds the {MAX_JSON_BYTES}-byte limit."
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
raw = path.read_bytes()
|
| 193 |
+
except OSError as exc:
|
| 194 |
+
raise RuntimeError(f"Could not read JSON path '{path}': {exc}") from exc
|
| 195 |
+
return cls._decode_json_bytes(raw, str(path))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@staticmethod
|
| 199 |
+
def _decode_json_bytes(raw: bytes, source_name: str) -> str:
|
| 200 |
+
if len(raw) > MAX_JSON_BYTES:
|
| 201 |
+
raise ValueError(
|
| 202 |
+
f"JSON source '{source_name}' exceeds the {MAX_JSON_BYTES}-byte limit."
|
| 203 |
+
)
|
| 204 |
+
try:
|
| 205 |
+
return raw.decode("utf-8-sig")
|
| 206 |
+
except UnicodeDecodeError as exc:
|
| 207 |
+
raise ValueError(
|
| 208 |
+
f"JSON source '{source_name}' is not valid UTF-8."
|
| 209 |
+
) from exc
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def _split_context_and_jobs(data: Any) -> Tuple[Dict[str, Any], List[Any]]:
|
| 214 |
+
if isinstance(data, list):
|
| 215 |
+
return {}, data
|
| 216 |
+
|
| 217 |
+
if not isinstance(data, dict):
|
| 218 |
+
raise ValueError(
|
| 219 |
+
"The JSON root must be an object containing 'pair_pose_states' "
|
| 220 |
+
"or a list of pose-pair jobs."
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
jobs = data.get("pair_pose_states")
|
| 224 |
+
if not isinstance(jobs, list):
|
| 225 |
+
raise ValueError(
|
| 226 |
+
"The JSON object must contain a 'pair_pose_states' array."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
context = dict(data)
|
| 230 |
+
context.pop("pair_pose_states", None)
|
| 231 |
+
return context, jobs
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
@staticmethod
|
| 235 |
+
def _validate_and_select_job(
|
| 236 |
+
jobs: List[Any], pair_pose_id: int
|
| 237 |
+
) -> Dict[str, Any]:
|
| 238 |
+
required = (
|
| 239 |
+
"id",
|
| 240 |
+
"char_pose",
|
| 241 |
+
"user_pose",
|
| 242 |
+
"output_filename",
|
| 243 |
+
"base_pose_sentence",
|
| 244 |
+
)
|
| 245 |
+
by_id: Dict[int, Dict[str, Any]] = {}
|
| 246 |
+
|
| 247 |
+
for position, job in enumerate(jobs):
|
| 248 |
+
if not isinstance(job, dict):
|
| 249 |
+
raise ValueError(
|
| 250 |
+
f"pair_pose_states[{position}] must be a JSON object."
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
missing = [key for key in required if key not in job]
|
| 254 |
+
if missing:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
f"pair_pose_states[{position}] is missing: {', '.join(missing)}."
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
job_id = job["id"]
|
| 260 |
+
if isinstance(job_id, bool) or not isinstance(job_id, int):
|
| 261 |
+
raise ValueError(
|
| 262 |
+
f"pair_pose_states[{position}].id must be an integer."
|
| 263 |
+
)
|
| 264 |
+
if job_id in by_id:
|
| 265 |
+
raise ValueError(f"Duplicate pose-pair ID: {job_id}.")
|
| 266 |
+
|
| 267 |
+
for key in required[1:]:
|
| 268 |
+
if not isinstance(job[key], str) or not job[key].strip():
|
| 269 |
+
raise ValueError(
|
| 270 |
+
f"Pose-pair ID {job_id} has an empty or non-string '{key}'."
|
| 271 |
+
)
|
| 272 |
+
by_id[job_id] = job
|
| 273 |
+
|
| 274 |
+
if pair_pose_id not in by_id:
|
| 275 |
+
available = sorted(by_id)
|
| 276 |
+
if not available:
|
| 277 |
+
description = "none"
|
| 278 |
+
elif len(available) <= 20:
|
| 279 |
+
description = ", ".join(str(value) for value in available)
|
| 280 |
+
else:
|
| 281 |
+
description = (
|
| 282 |
+
f"{available[0]}-{available[-1]} "
|
| 283 |
+
f"({len(available)} IDs total)"
|
| 284 |
+
)
|
| 285 |
+
raise ValueError(
|
| 286 |
+
f"Pose-pair ID {pair_pose_id} was not found. Available IDs: "
|
| 287 |
+
f"{description}."
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
return by_id[pair_pose_id]
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@staticmethod
|
| 294 |
+
def _validate_declared_queue(
|
| 295 |
+
context: Dict[str, Any], jobs: List[Any]
|
| 296 |
+
) -> None:
|
| 297 |
+
semantics = context.get("queue_semantics")
|
| 298 |
+
if not isinstance(semantics, dict):
|
| 299 |
+
return
|
| 300 |
+
|
| 301 |
+
declared_count = semantics.get("pair_count")
|
| 302 |
+
if declared_count is not None:
|
| 303 |
+
if isinstance(declared_count, bool) or not isinstance(
|
| 304 |
+
declared_count, int
|
| 305 |
+
):
|
| 306 |
+
raise ValueError("queue_semantics.pair_count must be an integer.")
|
| 307 |
+
if len(jobs) != declared_count:
|
| 308 |
+
raise ValueError(
|
| 309 |
+
"The JSON declares "
|
| 310 |
+
f"{declared_count} jobs but contains {len(jobs)}."
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
declared_range = semantics.get("id_range")
|
| 314 |
+
if isinstance(declared_range, str) and "-" in declared_range:
|
| 315 |
+
start_text, end_text = declared_range.split("-", 1)
|
| 316 |
+
try:
|
| 317 |
+
start, end = int(start_text), int(end_text)
|
| 318 |
+
except ValueError:
|
| 319 |
+
return
|
| 320 |
+
if end < start or end - start + 1 != len(jobs):
|
| 321 |
+
raise ValueError("queue_semantics.id_range length does not match the queue.")
|
| 322 |
+
expected = set(range(start, end + 1))
|
| 323 |
+
actual = {job["id"] for job in jobs if isinstance(job, dict)}
|
| 324 |
+
if actual != expected:
|
| 325 |
+
missing = sorted(expected - actual)
|
| 326 |
+
extra = sorted(actual - expected)
|
| 327 |
+
raise ValueError(
|
| 328 |
+
"Pose-pair IDs do not match the declared id_range. "
|
| 329 |
+
f"Missing: {missing or 'none'}; extra: {extra or 'none'}."
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
def _reference_names(context: Dict[str, Any]) -> List[str]:
|
| 335 |
+
names: List[str] = list(REFERENCE_FILES)
|
| 336 |
+
references = context.get("reference_files", [])
|
| 337 |
+
if isinstance(references, list):
|
| 338 |
+
for item in references:
|
| 339 |
+
if isinstance(item, dict):
|
| 340 |
+
filename = item.get("filename")
|
| 341 |
+
else:
|
| 342 |
+
filename = item
|
| 343 |
+
if (
|
| 344 |
+
isinstance(filename, str)
|
| 345 |
+
and filename.strip()
|
| 346 |
+
and filename not in names
|
| 347 |
+
):
|
| 348 |
+
names.append(filename)
|
| 349 |
+
return names
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@classmethod
|
| 353 |
+
def _compose_prompt(
|
| 354 |
+
cls, context: Dict[str, Any], selected: Dict[str, Any]
|
| 355 |
+
) -> str:
|
| 356 |
+
filename = selected["output_filename"].strip()
|
| 357 |
+
reference_lines = "\n".join(
|
| 358 |
+
f"- {name}" for name in cls._reference_names(context)
|
| 359 |
+
)
|
| 360 |
+
selected_json = json.dumps(selected, indent=2, ensure_ascii=False)
|
| 361 |
+
context_json = json.dumps(context, indent=2, ensure_ascii=False)
|
| 362 |
+
|
| 363 |
+
return f"""You are a new GPT instance with zero access to the conversation that created this job.
|
| 364 |
+
|
| 365 |
+
# TASK
|
| 366 |
+
|
| 367 |
+
Create exactly one complete, hand-authored Markdown physical-state catalogue for the selected ordered pose pair.
|
| 368 |
+
|
| 369 |
+
This ID selects one WHOLE pose-pair catalogue file. It does not select one individual contact state. The file you create must enumerate all materially distinct resolved distance, placement, contact, visibility, restraint, control, and release states that preserve both selected base poses.
|
| 370 |
+
|
| 371 |
+
# TARGET JOB
|
| 372 |
+
|
| 373 |
+
- Pair-pose ID: {selected["id"]}
|
| 374 |
+
- {{{{char}}}} base pose: {selected["char_pose"]}
|
| 375 |
+
- {{{{user}}}} base pose: {selected["user_pose"]}
|
| 376 |
+
- Required output filename: {filename}
|
| 377 |
+
- Base pose sentence: {selected["base_pose_sentence"]}
|
| 378 |
+
|
| 379 |
+
The base pose sentence fixes only the actor identities, facing family, and two base poses. It is a neutral seed, not the only state to write. Size, precise placement, contact, line of sight, restraint, and control must be enumerated inside the catalogue.
|
| 380 |
+
|
| 381 |
+
Selected job as JSON:
|
| 382 |
+
|
| 383 |
+
~~~json
|
| 384 |
+
{selected_json}
|
| 385 |
+
~~~
|
| 386 |
+
|
| 387 |
+
# THREE REFERENCE FILES
|
| 388 |
+
|
| 389 |
+
These are the completed examples:
|
| 390 |
+
|
| 391 |
+
{reference_lines}
|
| 392 |
+
|
| 393 |
+
If the reference files are supplied with this prompt, read all three before writing. Use them for structure, directive grammar, precision, and level of detail. Do not copy their anatomy mechanically into a different pose pair.
|
| 394 |
+
|
| 395 |
+
# AUTHORITATIVE PROJECT CONTEXT
|
| 396 |
+
|
| 397 |
+
The following JSON contains the complete project handoff, pose definitions, language rules, file contract, tag policy, size system, and validation checklist. Follow it literally.
|
| 398 |
+
|
| 399 |
+
~~~json
|
| 400 |
+
{context_json}
|
| 401 |
+
~~~
|
| 402 |
+
|
| 403 |
+
# NON-NEGOTIABLE REMINDERS
|
| 404 |
+
|
| 405 |
+
1. Always write the literal actor tokens {{{{char}}}}, {{{{char}}}}'s, {{{{user}}}}, and {{{{user}}}}'s. Never replace either actor with a character pronoun.
|
| 406 |
+
2. Supine means lying on the back. Prone means lying on the belly/front torso. Never interchange them.
|
| 407 |
+
3. Straddle means legs on opposite sides like straddling a horse. Never describe straddling one isolated arm or one isolated leg.
|
| 408 |
+
4. Describe exact anatomy. Do not write vague phrases such as "high clamp", "upper-body control", "dominant position", or "nearby target" without exact physical placement.
|
| 409 |
+
5. Touching, standing astride, supporting, occupying, or being close does not automatically mean restraint. Disable a limb only when the described geometry prevents its use.
|
| 410 |
+
6. Explicitly state line of sight. "Facing Each Other" describes facing directions and does not guarantee that both actors can see each other in every state.
|
| 411 |
+
7. Each resolved state must contain these sections in this exact order:
|
| 412 |
+
- State
|
| 413 |
+
- {{{{user}}}} Pose Info
|
| 414 |
+
- {{{{char}}}} Pose Info
|
| 415 |
+
- Size Info
|
| 416 |
+
- Grappling Info
|
| 417 |
+
- Struggle And Release Info
|
| 418 |
+
- State Transitions
|
| 419 |
+
8. Each actor's Pose Info must contain exact prose followed by Enabled Tags and Disabled Tags.
|
| 420 |
+
9. Every resolved state needs all five size cases: towering, larger, same, smaller, and mini. Each case needs one useful anatomical explanation and exactly one directive using this fixed field order:
|
| 421 |
+
{{{{char==towering|char.enable=Tag A,Tag B|char.disable=Tag C|user.enable=Tag D|user.disable=none}}}};
|
| 422 |
+
10. Define every tag that you use. Add a tag on the fly only when a genuinely new physical distinction needs one.
|
| 423 |
+
11. Enable Struggle only for an actor actually under control. Enable Release only for the actor actually maintaining that control.
|
| 424 |
+
12. An enabled attack, grapple, smother, or transition tag means the action can be attempted; it does not mean its result already exists.
|
| 425 |
+
13. Assume both actors temporarily possess every supported anatomy, including large breasts and sensitive genitals. A later anatomy parser removes inapplicable tags.
|
| 426 |
+
14. Do not add numeric combat formulas, Unity code, IK code, LLM API code, or runtime battle-system code.
|
| 427 |
+
15. Mark applicable content precisely with NSFW, Smothering, Dangerous, Lethal, or Blinding as defined in the project context.
|
| 428 |
+
|
| 429 |
+
# WORK METHOD
|
| 430 |
+
|
| 431 |
+
1. Read the selected pair, all pose definitions, and all rules.
|
| 432 |
+
2. Decide the exact orientation implied by Facing Each Other for this pair.
|
| 433 |
+
3. Enumerate the physically distinct stable placements from separated states through close contact and actual controls.
|
| 434 |
+
4. Split any state whose mechanics change because of body region, distance, trapped side, controlling actor, visibility, or size.
|
| 435 |
+
5. Write exact actor-specific permissions, tag deltas, all five size cases, grappling facts, struggle/release facts, and transitions for every state.
|
| 436 |
+
6. Run the entire validation checklist before returning the result.
|
| 437 |
+
|
| 438 |
+
# OUTPUT CONTRACT
|
| 439 |
+
|
| 440 |
+
Write the output directly into the response instead of sending a file. Simply output it via text.
|
| 441 |
+
|
| 442 |
+
Provide the full Markdown catalogue as output. The publishing node will save the response as {filename}.
|
| 443 |
+
|
| 444 |
+
Do not merely print the filename. Do not wrap the entire catalogue in a code fence. Return no second file, preface, apology, progress note, or unrelated commentary.
|
| 445 |
+
"""
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def _utc_now() -> str:
|
| 449 |
+
return datetime.now(timezone.utc).isoformat()
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _work_root() -> Path:
|
| 453 |
+
try:
|
| 454 |
+
import folder_paths
|
| 455 |
+
output = Path(folder_paths.get_output_directory())
|
| 456 |
+
except ImportError:
|
| 457 |
+
output = Path.cwd() / "output"
|
| 458 |
+
root = output / "Salia_FacingEachOther_Astra_Batch"
|
| 459 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 460 |
+
return root.resolve()
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
@contextmanager
|
| 464 |
+
def _workflow_lock(root: Path):
|
| 465 |
+
"""OS lock releases automatically on process exit, including crashes."""
|
| 466 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 467 |
+
handle = (root / "workflow.lock").open("a+b")
|
| 468 |
+
locked = False
|
| 469 |
+
try:
|
| 470 |
+
if os.name == "nt":
|
| 471 |
+
import msvcrt
|
| 472 |
+
if handle.seek(0, 2) == 0:
|
| 473 |
+
handle.write(b"0")
|
| 474 |
+
handle.flush()
|
| 475 |
+
handle.seek(0)
|
| 476 |
+
try:
|
| 477 |
+
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
| 478 |
+
except OSError as exc:
|
| 479 |
+
raise RuntimeError("Another Astra pose operation is running. Queue again after it finishes.") from exc
|
| 480 |
+
else:
|
| 481 |
+
import fcntl
|
| 482 |
+
try:
|
| 483 |
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 484 |
+
except BlockingIOError as exc:
|
| 485 |
+
raise RuntimeError("Another Astra pose operation is running. Queue again after it finishes.") from exc
|
| 486 |
+
locked = True
|
| 487 |
+
yield
|
| 488 |
+
finally:
|
| 489 |
+
if locked:
|
| 490 |
+
if os.name == "nt":
|
| 491 |
+
handle.seek(0)
|
| 492 |
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
| 493 |
+
else:
|
| 494 |
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
| 495 |
+
handle.close()
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
@contextmanager
|
| 499 |
+
def _atomic_file(path: Path, mode: str = "w"):
|
| 500 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 501 |
+
options = {"encoding": "utf-8", "newline": "\n"} if mode == "w" else {}
|
| 502 |
+
with tempfile.NamedTemporaryFile(mode=mode, dir=path.parent, delete=False, **options) as handle:
|
| 503 |
+
temporary = Path(handle.name)
|
| 504 |
+
try:
|
| 505 |
+
yield handle
|
| 506 |
+
handle.flush()
|
| 507 |
+
os.fsync(handle.fileno())
|
| 508 |
+
except BaseException:
|
| 509 |
+
handle.close()
|
| 510 |
+
temporary.unlink(missing_ok=True)
|
| 511 |
+
raise
|
| 512 |
+
try:
|
| 513 |
+
os.replace(temporary, path)
|
| 514 |
+
finally:
|
| 515 |
+
temporary.unlink(missing_ok=True)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def _write_json(path: Path, data: Any) -> None:
|
| 519 |
+
with _atomic_file(path) as handle:
|
| 520 |
+
json.dump(data, handle, ensure_ascii=False, indent=2)
|
| 521 |
+
handle.write("\n")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _read_json(path: Path) -> Dict[str, Any]:
|
| 525 |
+
value = json.loads(path.read_text(encoding="utf-8-sig"))
|
| 526 |
+
if not isinstance(value, dict):
|
| 527 |
+
raise ValueError(f"Expected a JSON object in {path}.")
|
| 528 |
+
return value
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def _file_hash(path: Path) -> str:
|
| 532 |
+
digest = hashlib.sha256()
|
| 533 |
+
with path.open("rb") as handle:
|
| 534 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 535 |
+
digest.update(chunk)
|
| 536 |
+
return digest.hexdigest()
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _settings() -> Dict[str, Any]:
|
| 540 |
+
return {
|
| 541 |
+
"model": OPENAI_MODEL,
|
| 542 |
+
"service_tier": "default",
|
| 543 |
+
"text": {"format": {"type": "text"}, "verbosity": "medium"},
|
| 544 |
+
"reasoning": dict(OPENAI_REASONING),
|
| 545 |
+
"tools": [],
|
| 546 |
+
"stream": False,
|
| 547 |
+
"store": False,
|
| 548 |
+
"include": ["reasoning.encrypted_content", "web_search_call.action.sources"],
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def _validate_filename(filename: Any) -> str:
|
| 553 |
+
if not isinstance(filename, str) or not SAFE_MD_NAME.fullmatch(filename) or ".." in filename:
|
| 554 |
+
raise ValueError(f"output_filename must be a safe, single .md filename: {filename!r}.")
|
| 555 |
+
if len(filename) > 180:
|
| 556 |
+
raise ValueError("output_filename is too long (maximum 180 characters).")
|
| 557 |
+
return filename
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _prepare(source: str, root: Path) -> Dict[str, Any]:
|
| 561 |
+
if len((source or "").encode("utf-8")) > MAX_JSON_BYTES:
|
| 562 |
+
raise ValueError("Horizontal-slice input exceeds the 8 MiB limit.")
|
| 563 |
+
data = _PosePromptBuilder._load_json_source(source)
|
| 564 |
+
context, jobs = _PosePromptBuilder._split_context_and_jobs(data)
|
| 565 |
+
if not jobs or len(jobs) > MAX_BATCH_REQUESTS:
|
| 566 |
+
raise ValueError("The JSON must contain between 1 and 50,000 pose-pair jobs.")
|
| 567 |
+
first_id = jobs[0].get("id", -1) if isinstance(jobs[0], dict) else -1
|
| 568 |
+
_PosePromptBuilder._validate_and_select_job(jobs, first_id)
|
| 569 |
+
_PosePromptBuilder._validate_declared_queue(context, jobs)
|
| 570 |
+
filenames = set()
|
| 571 |
+
for job in jobs:
|
| 572 |
+
if job["id"] < 0:
|
| 573 |
+
raise ValueError("Pose-pair IDs must be non-negative.")
|
| 574 |
+
filename = _validate_filename(job["output_filename"])
|
| 575 |
+
if filename.casefold() in filenames:
|
| 576 |
+
raise ValueError(f"Duplicate output_filename: {filename}.")
|
| 577 |
+
filenames.add(filename.casefold())
|
| 578 |
+
|
| 579 |
+
# Change the embedded context too, so it cannot contradict the final
|
| 580 |
+
# text-only output contract. Preserve all authoring and anatomy rules.
|
| 581 |
+
prompt_context = deepcopy(context)
|
| 582 |
+
if isinstance(prompt_context.get("file_contract"), dict):
|
| 583 |
+
prompt_context["file_contract"]["return_contract"] = TEXT_OUTPUT_CONTRACT
|
| 584 |
+
canonical = json.dumps(
|
| 585 |
+
{"data": data, "settings": _settings(), "version": NODE_VERSION},
|
| 586 |
+
ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
| 587 |
+
).encode("utf-8")
|
| 588 |
+
fingerprint = hashlib.sha256(canonical).hexdigest()
|
| 589 |
+
run_root = root / "runs" / fingerprint
|
| 590 |
+
state_path = run_root / "batch_state.json"
|
| 591 |
+
if state_path.is_file():
|
| 592 |
+
state = _read_json(state_path)
|
| 593 |
+
if state.get("fingerprint") != fingerprint:
|
| 594 |
+
raise ValueError("Saved state does not match this horizontal-slice input.")
|
| 595 |
+
return state
|
| 596 |
+
|
| 597 |
+
input_path = run_root / "input_requests.jsonl"
|
| 598 |
+
entries = []
|
| 599 |
+
with _atomic_file(input_path) as handle:
|
| 600 |
+
for job in jobs:
|
| 601 |
+
prompt = _PosePromptBuilder._compose_prompt(prompt_context, job)
|
| 602 |
+
custom_id = f"pose_{job['id']}"
|
| 603 |
+
body = _settings()
|
| 604 |
+
body["input"] = [{"role": "user", "content": [{"type": "input_text", "text": prompt}]}]
|
| 605 |
+
line = {"custom_id": custom_id, "method": "POST", "url": OPENAI_BATCH_ENDPOINT, "body": body}
|
| 606 |
+
handle.write(json.dumps(line, ensure_ascii=False, separators=(",", ":")) + "\n")
|
| 607 |
+
entries.append({
|
| 608 |
+
"id": job["id"], "custom_id": custom_id,
|
| 609 |
+
"output_filename": job["output_filename"], "job": deepcopy(job),
|
| 610 |
+
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
|
| 611 |
+
})
|
| 612 |
+
if input_path.stat().st_size > MAX_BATCH_BYTES:
|
| 613 |
+
raise ValueError("Generated JSONL exceeds OpenAI's 200 MB Batch input limit.")
|
| 614 |
+
source_path = run_root / "horizontal_slice.json"
|
| 615 |
+
_write_json(source_path, data)
|
| 616 |
+
manifest = {
|
| 617 |
+
"format_version": 1, "node_version": NODE_VERSION, "purpose": PURPOSE,
|
| 618 |
+
"created_at": _utc_now(), "fingerprint": fingerprint,
|
| 619 |
+
"model": OPENAI_MODEL, "endpoint": OPENAI_BATCH_ENDPOINT,
|
| 620 |
+
"settings": _settings(), "repo_id": HF_REPO_ID, "revision": HF_REVISION,
|
| 621 |
+
"job_count": len(entries), "jobs": entries, "input_sha256": _file_hash(input_path),
|
| 622 |
+
"reference_contents_included": False,
|
| 623 |
+
}
|
| 624 |
+
manifest_path = run_root / "request_manifest.json"
|
| 625 |
+
_write_json(manifest_path, manifest)
|
| 626 |
+
state = {
|
| 627 |
+
**manifest, "phase": "prepared", "batch_id": "", "input_file_id": "",
|
| 628 |
+
"run_root": str(run_root), "manifest_path": str(manifest_path),
|
| 629 |
+
"state_path": str(state_path), "input_path": str(input_path),
|
| 630 |
+
"source_path": str(source_path), "downloads": {},
|
| 631 |
+
}
|
| 632 |
+
_save_state(state, root)
|
| 633 |
+
return state
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def _save_state(state: Dict[str, Any], root: Path) -> None:
|
| 637 |
+
_write_json(Path(state["state_path"]), state)
|
| 638 |
+
batch_id = str(state.get("batch_id") or "")
|
| 639 |
+
if SAFE_BATCH_ID.fullmatch(batch_id):
|
| 640 |
+
_write_json(root / "by_batch" / (batch_id + ".json"), {"state_path": state["state_path"]})
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def _key(value: str, env_names: Tuple[str, ...], label: str) -> str:
|
| 644 |
+
result = (value or "").strip()
|
| 645 |
+
if not result:
|
| 646 |
+
result = next((os.environ[name].strip() for name in env_names if os.environ.get(name, "").strip()), "")
|
| 647 |
+
if not result or result.lower() in {"sk-xxx", "hf_xxx", "sk-...", "hf_..."}:
|
| 648 |
+
raise ValueError(f"Enter a valid {label}, or set {' / '.join(env_names)} in ComfyUI's environment.")
|
| 649 |
+
if "\n" in result or "\r" in result:
|
| 650 |
+
raise ValueError(f"{label} contains a newline.")
|
| 651 |
+
return result
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
class _OpenAIHTTPError(RuntimeError):
|
| 655 |
+
def __init__(self, status_code: int, message: str):
|
| 656 |
+
self.status_code = status_code
|
| 657 |
+
super().__init__(message)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def _http_error(exc: HTTPError, key: str) -> _OpenAIHTTPError:
|
| 661 |
+
raw = exc.read(8192).decode("utf-8", errors="replace")
|
| 662 |
+
try:
|
| 663 |
+
parsed = json.loads(raw)
|
| 664 |
+
error = parsed.get("error", parsed) if isinstance(parsed, dict) else parsed
|
| 665 |
+
detail = error.get("message", str(error)) if isinstance(error, dict) else str(error)
|
| 666 |
+
except ValueError:
|
| 667 |
+
detail = raw or str(exc)
|
| 668 |
+
return _OpenAIHTTPError(exc.code, f"OpenAI HTTP {exc.code}: {detail[:1600].replace(key, '[redacted]')}")
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def _openai_json(method: str, path: str, key: str, payload: Any = None) -> Dict[str, Any]:
|
| 672 |
+
headers = {"Authorization": "Bearer " + key, "User-Agent": "Salia-Pose-Astra-Batch/" + NODE_VERSION}
|
| 673 |
+
data = None
|
| 674 |
+
if payload is not None:
|
| 675 |
+
headers["Content-Type"] = "application/json"
|
| 676 |
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
| 677 |
+
request = Request("https://api.openai.com" + path, data=data, headers=headers, method=method)
|
| 678 |
+
try:
|
| 679 |
+
with urlopen(request, timeout=180) as response:
|
| 680 |
+
result = json.loads(response.read().decode("utf-8"))
|
| 681 |
+
except HTTPError as exc:
|
| 682 |
+
raise _http_error(exc, key) from None
|
| 683 |
+
except (URLError, TimeoutError, OSError) as exc:
|
| 684 |
+
raise RuntimeError(f"OpenAI {method} network failure: {str(exc).replace(key, '[redacted]')}") from None
|
| 685 |
+
if not isinstance(result, dict):
|
| 686 |
+
raise RuntimeError("OpenAI returned a non-object response.")
|
| 687 |
+
return result
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def _upload_input(path: Path, key: str) -> str:
|
| 691 |
+
boundary = "----SaliaPoseAstra" + secrets.token_hex(16)
|
| 692 |
+
data = (
|
| 693 |
+
f'--{boundary}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\nbatch\r\n'
|
| 694 |
+
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="input_requests.jsonl"\r\n'
|
| 695 |
+
'Content-Type: application/jsonl\r\n\r\n'
|
| 696 |
+
).encode("utf-8") + path.read_bytes() + f"\r\n--{boundary}--\r\n".encode("ascii")
|
| 697 |
+
request = Request("https://api.openai.com/v1/files", data=data, method="POST", headers={
|
| 698 |
+
"Authorization": "Bearer " + key,
|
| 699 |
+
"Content-Type": "multipart/form-data; boundary=" + boundary,
|
| 700 |
+
"User-Agent": "Salia-Pose-Astra-Batch/" + NODE_VERSION,
|
| 701 |
+
})
|
| 702 |
+
try:
|
| 703 |
+
with urlopen(request, timeout=300) as response:
|
| 704 |
+
result = json.loads(response.read().decode("utf-8"))
|
| 705 |
+
except HTTPError as exc:
|
| 706 |
+
raise _http_error(exc, key) from None
|
| 707 |
+
file_id = str(result.get("id") or "") if isinstance(result, dict) else ""
|
| 708 |
+
if not SAFE_FILE_ID.fullmatch(file_id):
|
| 709 |
+
raise RuntimeError("OpenAI file upload did not return a valid input_file_id.")
|
| 710 |
+
return file_id
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def _download_file(file_id: str, path: Path, key: str) -> Path:
|
| 714 |
+
if not SAFE_FILE_ID.fullmatch(file_id):
|
| 715 |
+
raise ValueError("Invalid OpenAI file ID.")
|
| 716 |
+
request = Request("https://api.openai.com/v1/files/" + quote(file_id, safe="") + "/content", headers={
|
| 717 |
+
"Authorization": "Bearer " + key,
|
| 718 |
+
"User-Agent": "Salia-Pose-Astra-Batch/" + NODE_VERSION,
|
| 719 |
+
})
|
| 720 |
+
try:
|
| 721 |
+
with urlopen(request, timeout=300) as response, _atomic_file(path, "wb") as handle:
|
| 722 |
+
shutil.copyfileobj(response, handle, length=1024 * 1024)
|
| 723 |
+
except HTTPError as exc:
|
| 724 |
+
raise _http_error(exc, key) from None
|
| 725 |
+
return path
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def _get_batch(batch_id: str, key: str) -> Dict[str, Any]:
|
| 729 |
+
if not SAFE_BATCH_ID.fullmatch(batch_id):
|
| 730 |
+
raise ValueError("batch_id must be an OpenAI Batch ID beginning with batch_.")
|
| 731 |
+
batch = _openai_json("GET", "/v1/batches/" + quote(batch_id, safe=""), key)
|
| 732 |
+
if batch.get("id") != batch_id or batch.get("endpoint") != OPENAI_BATCH_ENDPOINT:
|
| 733 |
+
raise ValueError("The requested Batch ID does not identify a /v1/responses batch.")
|
| 734 |
+
return batch
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def _hf_tools():
|
| 738 |
+
try:
|
| 739 |
+
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
|
| 740 |
+
except ImportError as exc:
|
| 741 |
+
raise ImportError("Install huggingface_hub in ComfyUI's Python environment: python -m pip install huggingface_hub") from exc
|
| 742 |
+
return CommitOperationAdd, HfApi, hf_hub_download
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def _hf_commit(files: List[Tuple[Path, str]], key: str, message: str) -> str:
|
| 746 |
+
Add, HfApi, _ = _hf_tools()
|
| 747 |
+
api = HfApi(endpoint="https://huggingface.co", token=key)
|
| 748 |
+
info = api.repo_info(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, revision=HF_REVISION, token=key)
|
| 749 |
+
operations = [Add(path_in_repo=remote, path_or_fileobj=str(local)) for local, remote in files]
|
| 750 |
+
commit = api.create_commit(
|
| 751 |
+
repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, revision=HF_REVISION,
|
| 752 |
+
operations=operations, commit_message=message, parent_commit=info.sha, token=key,
|
| 753 |
+
)
|
| 754 |
+
oid = str(getattr(commit, "oid", "") or "")
|
| 755 |
+
if not oid:
|
| 756 |
+
raise RuntimeError("Hugging Face did not return a commit ID.")
|
| 757 |
+
return oid
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def _archive_files(state: Dict[str, Any], prefix: str, include_state: bool = False) -> List[Tuple[Path, str]]:
|
| 761 |
+
files = [(Path(state["input_path"]), prefix + "/input_requests.jsonl"),
|
| 762 |
+
(Path(state["manifest_path"]), prefix + "/request_manifest.json")]
|
| 763 |
+
if state.get("source_path") and Path(state["source_path"]).is_file():
|
| 764 |
+
files.append((Path(state["source_path"]), prefix + "/horizontal_slice.json"))
|
| 765 |
+
if include_state:
|
| 766 |
+
files.append((Path(state["state_path"]), prefix + "/batch_state.json"))
|
| 767 |
+
return files
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def _backup_batch(state: Dict[str, Any], root: Path, hf_key: str) -> str:
|
| 771 |
+
if state.get("hf_batch_backup_commit"):
|
| 772 |
+
return ""
|
| 773 |
+
try:
|
| 774 |
+
state["hf_batch_backup_commit"] = _hf_commit(
|
| 775 |
+
_archive_files(state, "Batches/" + state["batch_id"], True), hf_key,
|
| 776 |
+
"Archive Astra pose batch " + state["batch_id"],
|
| 777 |
+
)
|
| 778 |
+
state.pop("hf_backup_error", None)
|
| 779 |
+
_save_state(state, root)
|
| 780 |
+
return ""
|
| 781 |
+
except Exception as exc:
|
| 782 |
+
error = str(exc).replace(hf_key, "[redacted]")[:1600]
|
| 783 |
+
state["hf_backup_error"] = error
|
| 784 |
+
_save_state(state, root)
|
| 785 |
+
return " HF backup needs another attempt: " + error
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _adopt_batch(state: Dict[str, Any], batch: Dict[str, Any], root: Path) -> None:
|
| 789 |
+
batch_id = str(batch.get("id") or "")
|
| 790 |
+
if not SAFE_BATCH_ID.fullmatch(batch_id) or batch.get("endpoint") != OPENAI_BATCH_ENDPOINT:
|
| 791 |
+
raise ValueError("OpenAI returned an invalid Responses Batch object.")
|
| 792 |
+
if state.get("input_file_id") and state["input_file_id"] != batch.get("input_file_id"):
|
| 793 |
+
raise ValueError("Batch input_file_id does not match the saved request manifest.")
|
| 794 |
+
state.update({"batch_id": batch_id, "input_file_id": batch.get("input_file_id"),
|
| 795 |
+
"phase": "submitted", "batch": batch, "last_checked_at": _utc_now()})
|
| 796 |
+
_save_state(state, root)
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def _recover_creation(state: Dict[str, Any], key: str, root: Path) -> None:
|
| 800 |
+
after = ""
|
| 801 |
+
for _ in range(10):
|
| 802 |
+
suffix = "?limit=100" + ("&after=" + quote(after, safe="") if after else "")
|
| 803 |
+
page = _openai_json("GET", "/v1/batches" + suffix, key)
|
| 804 |
+
matches = [b for b in page.get("data", []) if isinstance(b, dict)
|
| 805 |
+
and b.get("input_file_id") == state.get("input_file_id")
|
| 806 |
+
and b.get("endpoint") == OPENAI_BATCH_ENDPOINT]
|
| 807 |
+
if len(matches) == 1:
|
| 808 |
+
_adopt_batch(state, matches[0], root)
|
| 809 |
+
return
|
| 810 |
+
if len(matches) > 1:
|
| 811 |
+
raise RuntimeError("Multiple Batches use this input file. Set batch_id explicitly to select one.")
|
| 812 |
+
if not page.get("has_more") or not page.get("last_id"):
|
| 813 |
+
break
|
| 814 |
+
after = page["last_id"]
|
| 815 |
+
raise RuntimeError(
|
| 816 |
+
"The previous Batch-creation result is uncertain and no matching Batch was found yet. "
|
| 817 |
+
"Queue again later, or set batch_id from the OpenAI Batches dashboard. "
|
| 818 |
+
"No second Batch was submitted. Local state: " + state["state_path"]
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def _start(state: Dict[str, Any], key: str, hf_key: str, root: Path) -> Dict[str, Any]:
|
| 823 |
+
if state.get("batch_id"):
|
| 824 |
+
return _get_batch(state["batch_id"], key)
|
| 825 |
+
if state.get("phase") in {"creating_batch", "creation_uncertain"}:
|
| 826 |
+
_recover_creation(state, key, root)
|
| 827 |
+
return state["batch"]
|
| 828 |
+
input_path = Path(state["input_path"])
|
| 829 |
+
if not input_path.is_file() or _file_hash(input_path) != state["input_sha256"]:
|
| 830 |
+
raise ValueError("Prepared input JSONL is missing or has changed. Restore it before submitting the Batch.")
|
| 831 |
+
if not state.get("hf_prepared_commit"):
|
| 832 |
+
# Verify HF publishing access and preserve requests before generation.
|
| 833 |
+
state["hf_prepared_commit"] = _hf_commit(
|
| 834 |
+
_archive_files(state, "Batches/prepared_" + state["fingerprint"]), hf_key,
|
| 835 |
+
f"Prepare {state['job_count']} Astra pose requests",
|
| 836 |
+
)
|
| 837 |
+
_save_state(state, root)
|
| 838 |
+
if not state.get("input_file_id"):
|
| 839 |
+
state["input_file_id"] = _upload_input(input_path, key)
|
| 840 |
+
state["phase"] = "input_uploaded"
|
| 841 |
+
_save_state(state, root)
|
| 842 |
+
state["phase"] = "creating_batch"
|
| 843 |
+
_save_state(state, root)
|
| 844 |
+
try:
|
| 845 |
+
batch = _openai_json("POST", "/v1/batches", key, {
|
| 846 |
+
"input_file_id": state["input_file_id"], "endpoint": OPENAI_BATCH_ENDPOINT,
|
| 847 |
+
"completion_window": "24h", "metadata": {
|
| 848 |
+
"purpose": PURPOSE, "node_version": NODE_VERSION,
|
| 849 |
+
"fingerprint": state["fingerprint"], "job_count": str(state["job_count"]),
|
| 850 |
+
},
|
| 851 |
+
})
|
| 852 |
+
_adopt_batch(state, batch, root)
|
| 853 |
+
except Exception as exc:
|
| 854 |
+
state["phase"] = "create_rejected" if isinstance(exc, _OpenAIHTTPError) and exc.status_code < 500 else "creation_uncertain"
|
| 855 |
+
state["creation_error"] = str(exc).replace(key, "[redacted]")[:1600]
|
| 856 |
+
_save_state(state, root)
|
| 857 |
+
raise
|
| 858 |
+
return batch
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def _cached_download(state: Dict[str, Any], file_id: str, name: str, key: str, root: Path) -> Path:
|
| 862 |
+
path = Path(state["run_root"]) / name
|
| 863 |
+
previous = state.setdefault("downloads", {}).get(name, {})
|
| 864 |
+
if not (previous.get("file_id") == file_id and path.is_file() and previous.get("sha256") == _file_hash(path)):
|
| 865 |
+
_download_file(file_id, path, key)
|
| 866 |
+
state["downloads"][name] = {"file_id": file_id, "sha256": _file_hash(path)}
|
| 867 |
+
_save_state(state, root)
|
| 868 |
+
return path
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def _download_results(state: Dict[str, Any], batch: Dict[str, Any], key: str, root: Path) -> List[Path]:
|
| 872 |
+
state["batch"] = batch
|
| 873 |
+
_write_json(Path(state["run_root"]) / "batch_status.json", batch)
|
| 874 |
+
paths = []
|
| 875 |
+
for field, filename in (("output_file_id", "output.jsonl"), ("error_file_id", "errors.jsonl")):
|
| 876 |
+
if batch.get(field):
|
| 877 |
+
paths.append(_cached_download(state, str(batch[field]), filename, key, root))
|
| 878 |
+
_save_state(state, root)
|
| 879 |
+
return paths
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
def _validate_manifest(state: Dict[str, Any], batch: Dict[str, Any]) -> None:
|
| 883 |
+
if state.get("purpose") != PURPOSE or state.get("model") != OPENAI_MODEL or state.get("endpoint") != OPENAI_BATCH_ENDPOINT:
|
| 884 |
+
raise ValueError("The manifest is not an Astra Facing Each Other Responses manifest.")
|
| 885 |
+
if state.get("batch_id") and state["batch_id"] != batch["id"]:
|
| 886 |
+
raise ValueError("The manifest belongs to a different Batch ID.")
|
| 887 |
+
if state.get("input_file_id") and state["input_file_id"] != batch.get("input_file_id"):
|
| 888 |
+
raise ValueError("The manifest belongs to a different Batch input file.")
|
| 889 |
+
jobs = state.get("jobs")
|
| 890 |
+
if not isinstance(jobs, list) or not jobs or len(jobs) != state.get("job_count"):
|
| 891 |
+
raise ValueError("The manifest's job list/count is invalid.")
|
| 892 |
+
seen_ids, seen_names = set(), set()
|
| 893 |
+
for entry in jobs:
|
| 894 |
+
if not isinstance(entry, dict) or isinstance(entry.get("id"), bool) or not isinstance(entry.get("id"), int) or entry["id"] < 0:
|
| 895 |
+
raise ValueError("The manifest contains an invalid job.")
|
| 896 |
+
custom_id = entry.get("custom_id")
|
| 897 |
+
name = _validate_filename(entry.get("output_filename"))
|
| 898 |
+
if custom_id != f"pose_{entry['id']}" or custom_id in seen_ids or name.casefold() in seen_names:
|
| 899 |
+
raise ValueError("The manifest has duplicate or invalid job identifiers/filenames.")
|
| 900 |
+
seen_ids.add(custom_id)
|
| 901 |
+
seen_names.add(name.casefold())
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def _recover_input(input_path: Path) -> Dict[str, Any]:
|
| 905 |
+
"""Rebuild ID-to-filename mapping from the actual uploaded prompts."""
|
| 906 |
+
entries, context = [], None
|
| 907 |
+
with input_path.open(encoding="utf-8-sig") as handle:
|
| 908 |
+
for number, line in enumerate(handle, 1):
|
| 909 |
+
if not line.strip():
|
| 910 |
+
continue
|
| 911 |
+
request = json.loads(line)
|
| 912 |
+
body = request.get("body", {})
|
| 913 |
+
if request.get("url") != OPENAI_BATCH_ENDPOINT or body.get("model") != OPENAI_MODEL:
|
| 914 |
+
raise ValueError("This Batch input was not created for gpt-6-astra /v1/responses.")
|
| 915 |
+
if request.get("method") != "POST":
|
| 916 |
+
raise ValueError("The Batch input contains an unexpected HTTP method.")
|
| 917 |
+
parts = [p.get("text", "") for msg in body.get("input", []) if isinstance(msg, dict)
|
| 918 |
+
for p in msg.get("content", []) if isinstance(p, dict) and p.get("type") == "input_text"]
|
| 919 |
+
prompt = "\n".join(parts)
|
| 920 |
+
match = re.search(r"Selected job as JSON:\s*~~~json\s*\n(.*?)\n~~~", prompt, re.DOTALL)
|
| 921 |
+
if not match:
|
| 922 |
+
raise ValueError(f"Cannot recover pose metadata from Batch input line {number}. Provide batch_manifest from the Batch node.")
|
| 923 |
+
job = json.loads(match.group(1))
|
| 924 |
+
entries.append({"id": job["id"], "custom_id": request["custom_id"],
|
| 925 |
+
"output_filename": _validate_filename(job["output_filename"]), "job": job,
|
| 926 |
+
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest()})
|
| 927 |
+
if context is None:
|
| 928 |
+
match_context = re.search(r"# AUTHORITATIVE PROJECT CONTEXT\s*.*?~~~json\s*\n(.*?)\n~~~", prompt, re.DOTALL)
|
| 929 |
+
context = json.loads(match_context.group(1)) if match_context else {}
|
| 930 |
+
return {"format_version": 1, "node_version": NODE_VERSION, "purpose": PURPOSE,
|
| 931 |
+
"model": OPENAI_MODEL, "endpoint": OPENAI_BATCH_ENDPOINT, "settings": _settings(),
|
| 932 |
+
"repo_id": HF_REPO_ID, "revision": HF_REVISION, "job_count": len(entries), "jobs": entries,
|
| 933 |
+
"input_sha256": _file_hash(input_path), "reference_contents_included": False,
|
| 934 |
+
"recovered_horizontal_slice": {**(context or {}), "pair_pose_states": [e["job"] for e in entries]}}
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def _resolve_state(batch: Dict[str, Any], key: str, hf_key: str, root: Path, manifest_path: str = "") -> Dict[str, Any]:
|
| 938 |
+
batch_id = batch["id"]
|
| 939 |
+
provided = None
|
| 940 |
+
if (manifest_path or "").strip():
|
| 941 |
+
provided = _read_json(Path(os.path.expandvars(manifest_path.strip())).expanduser())
|
| 942 |
+
_validate_manifest(provided, batch)
|
| 943 |
+
index_path = root / "by_batch" / (batch_id + ".json")
|
| 944 |
+
if index_path.is_file():
|
| 945 |
+
path = Path(_read_json(index_path)["state_path"])
|
| 946 |
+
if path.is_file():
|
| 947 |
+
state = _read_json(path)
|
| 948 |
+
_validate_manifest(state, batch)
|
| 949 |
+
if provided and (provided.get("input_sha256") != state.get("input_sha256") or provided.get("jobs") != state["jobs"]):
|
| 950 |
+
raise ValueError("batch_manifest does not match this Batch's saved state.")
|
| 951 |
+
input_path = Path(state["input_path"])
|
| 952 |
+
if input_path.is_file() and _file_hash(input_path) == state.get("input_sha256"):
|
| 953 |
+
_adopt_batch(state, batch, root)
|
| 954 |
+
return state
|
| 955 |
+
|
| 956 |
+
run_root = root / "recovered" / batch_id
|
| 957 |
+
run_root.mkdir(parents=True, exist_ok=True)
|
| 958 |
+
state = provided or {}
|
| 959 |
+
if not state:
|
| 960 |
+
try:
|
| 961 |
+
_, _, hf_download = _hf_tools()
|
| 962 |
+
remote = hf_download(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, revision=HF_REVISION,
|
| 963 |
+
filename="Batches/" + batch_id + "/request_manifest.json", token=hf_key or False)
|
| 964 |
+
state = _read_json(Path(remote))
|
| 965 |
+
except Exception:
|
| 966 |
+
# The archive can be absent after a failed HF backup. The original
|
| 967 |
+
# OpenAI input is authoritative and permits recovery without it.
|
| 968 |
+
state = {}
|
| 969 |
+
input_path = run_root / "input_requests.jsonl"
|
| 970 |
+
_download_file(str(batch.get("input_file_id") or ""), input_path, key)
|
| 971 |
+
recovered = _recover_input(input_path)
|
| 972 |
+
if state:
|
| 973 |
+
_validate_manifest(state, batch)
|
| 974 |
+
if state.get("input_sha256") != recovered["input_sha256"]:
|
| 975 |
+
raise ValueError("The saved manifest does not match the actual OpenAI Batch input JSONL.")
|
| 976 |
+
if state.get("jobs") != recovered["jobs"]:
|
| 977 |
+
raise ValueError("The saved manifest's filenames/jobs differ from the actual submitted prompts.")
|
| 978 |
+
else:
|
| 979 |
+
state = {k: v for k, v in recovered.items() if k != "recovered_horizontal_slice"}
|
| 980 |
+
_validate_manifest(state, batch)
|
| 981 |
+
source_path = run_root / "horizontal_slice.json"
|
| 982 |
+
_write_json(source_path, recovered["recovered_horizontal_slice"])
|
| 983 |
+
recovered_manifest = run_root / "request_manifest.json"
|
| 984 |
+
_write_json(recovered_manifest, {k: v for k, v in state.items() if k not in {
|
| 985 |
+
"run_root", "state_path", "input_path", "manifest_path", "downloads", "source_path",
|
| 986 |
+
}})
|
| 987 |
+
state.update({"batch_id": batch_id, "input_file_id": batch["input_file_id"],
|
| 988 |
+
"run_root": str(run_root), "state_path": str(run_root / "batch_state.json"),
|
| 989 |
+
"input_path": str(input_path), "manifest_path": str(recovered_manifest),
|
| 990 |
+
"source_path": str(source_path), "downloads": {}, "phase": "submitted"})
|
| 991 |
+
_adopt_batch(state, batch, root)
|
| 992 |
+
return state
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def _batch_message(batch: Dict[str, Any], count: int) -> str:
|
| 996 |
+
counts = batch.get("request_counts") or {}
|
| 997 |
+
detail = f"{counts.get('completed', 0)} completed, {counts.get('failed', 0)} failed; {count} expected"
|
| 998 |
+
message = f"Astra Batch {batch['id']}: {batch.get('status', 'unknown')} ({detail})."
|
| 999 |
+
if batch.get("errors"):
|
| 1000 |
+
message += " Batch errors: " + json.dumps(batch["errors"], ensure_ascii=False)[:2000]
|
| 1001 |
+
return message
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
def _node_result(values: Tuple[Any, ...]) -> Dict[str, Any]:
|
| 1005 |
+
return {"ui": {"text": [str(values[0])]}, "result": values}
|
| 1006 |
+
|
| 1007 |
+
|
| 1008 |
+
def _analyse_row(row: Dict[str, Any]) -> Dict[str, Any]:
|
| 1009 |
+
response = row.get("response")
|
| 1010 |
+
body = response.get("body", {}) if isinstance(response, dict) else {}
|
| 1011 |
+
if not isinstance(body, dict):
|
| 1012 |
+
body = {}
|
| 1013 |
+
messages, refusals = [], []
|
| 1014 |
+
for item in body.get("output", []) or []:
|
| 1015 |
+
if not isinstance(item, dict) or item.get("type") != "message" or item.get("role", "assistant") != "assistant":
|
| 1016 |
+
continue
|
| 1017 |
+
pieces = []
|
| 1018 |
+
for part in item.get("content", []) or []:
|
| 1019 |
+
if not isinstance(part, dict):
|
| 1020 |
+
continue
|
| 1021 |
+
if part.get("type") == "output_text" and isinstance(part.get("text"), str):
|
| 1022 |
+
pieces.append(part["text"])
|
| 1023 |
+
elif part.get("type") == "refusal":
|
| 1024 |
+
refusals.append(str(part.get("refusal") or part.get("text") or "Model refusal."))
|
| 1025 |
+
if pieces:
|
| 1026 |
+
messages.append("".join(pieces))
|
| 1027 |
+
text = "\n\n".join(messages)
|
| 1028 |
+
if not text.strip() and isinstance(body.get("output_text"), str):
|
| 1029 |
+
text = body["output_text"]
|
| 1030 |
+
error, status = "", "completed"
|
| 1031 |
+
if row.get("error"):
|
| 1032 |
+
status, error = "failed", json.dumps(row["error"], ensure_ascii=False)
|
| 1033 |
+
elif not isinstance(response, dict) or response.get("status_code") != 200:
|
| 1034 |
+
status, error = "failed", f"Request HTTP status: {response.get('status_code') if isinstance(response, dict) else 'missing'}; " + json.dumps(body.get("error", {}), ensure_ascii=False)
|
| 1035 |
+
elif body.get("error"):
|
| 1036 |
+
status, error = "failed", json.dumps(body["error"], ensure_ascii=False)
|
| 1037 |
+
elif refusals:
|
| 1038 |
+
status, error = "refused", "\n".join(refusals)
|
| 1039 |
+
elif body.get("status") != "completed":
|
| 1040 |
+
status = "incomplete" if body.get("status") == "incomplete" else "failed"
|
| 1041 |
+
error = f"Responses status: {body.get('status', 'missing')}; " + json.dumps(body.get("incomplete_details") or {}, ensure_ascii=False)
|
| 1042 |
+
elif not text.strip():
|
| 1043 |
+
status, error = "failed", "Response contains no non-empty assistant output_text."
|
| 1044 |
+
return {"status": status, "markdown": text, "error": error, "refusals": refusals}
|
| 1045 |
+
|
| 1046 |
+
|
| 1047 |
+
def _collect_records(paths: List[Path], jobs: List[Dict[str, Any]], records_root: Path) -> set:
|
| 1048 |
+
"""Parse JSONL incrementally; keep at most one response in memory."""
|
| 1049 |
+
expected = {entry["custom_id"] for entry in jobs}
|
| 1050 |
+
seen = set()
|
| 1051 |
+
for path in paths:
|
| 1052 |
+
with path.open(encoding="utf-8-sig") as handle:
|
| 1053 |
+
for number, line in enumerate(handle, 1):
|
| 1054 |
+
if not line.strip():
|
| 1055 |
+
continue
|
| 1056 |
+
try:
|
| 1057 |
+
row = json.loads(line)
|
| 1058 |
+
except ValueError as exc:
|
| 1059 |
+
raise ValueError(f"Invalid result JSONL in {path.name}, line {number}.") from exc
|
| 1060 |
+
if not isinstance(row, dict) or row.get("custom_id") not in expected:
|
| 1061 |
+
raise ValueError(f"Unexpected custom_id in {path.name}, line {number}. No release was uploaded.")
|
| 1062 |
+
custom_id = row["custom_id"]
|
| 1063 |
+
if custom_id in seen:
|
| 1064 |
+
raise ValueError(f"Duplicate result for {custom_id}. No release was uploaded.")
|
| 1065 |
+
seen.add(custom_id)
|
| 1066 |
+
_write_json(records_root / (custom_id + ".json"), row)
|
| 1067 |
+
return seen
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
def _build_release(state: Dict[str, Any], batch: Dict[str, Any], paths: List[Path]) -> Tuple[List[Tuple[Path, str]], Dict[str, Any]]:
|
| 1071 |
+
release_root = Path(state["run_root"]) / "release"
|
| 1072 |
+
records_root = release_root / "records"
|
| 1073 |
+
jobs = sorted(state["jobs"], key=lambda entry: entry["id"])
|
| 1074 |
+
seen = _collect_records(paths, jobs, records_root)
|
| 1075 |
+
files, successes, failures = [], [], []
|
| 1076 |
+
all_path = release_root / ALL_OUTPUTS_FILENAME
|
| 1077 |
+
with _atomic_file(all_path) as all_handle:
|
| 1078 |
+
for entry in jobs:
|
| 1079 |
+
custom_id, name = entry["custom_id"], entry["output_filename"]
|
| 1080 |
+
if custom_id in seen:
|
| 1081 |
+
row = _read_json(records_root / (custom_id + ".json"))
|
| 1082 |
+
result = _analyse_row(row)
|
| 1083 |
+
else:
|
| 1084 |
+
row = None
|
| 1085 |
+
result = {"status": "missing", "markdown": "", "error": "No result/error row was returned for this job.", "refusals": []}
|
| 1086 |
+
document = {
|
| 1087 |
+
"format_version": 1, "batch_id": batch["id"], "pair_pose_id": entry["id"],
|
| 1088 |
+
"custom_id": custom_id, "output_filename": name, "job": entry["job"],
|
| 1089 |
+
**result, "openai_batch_result": row,
|
| 1090 |
+
}
|
| 1091 |
+
json_name = name[:-3] + ".json"
|
| 1092 |
+
json_path = release_root / json_name
|
| 1093 |
+
_write_json(json_path, document)
|
| 1094 |
+
files.append((json_path, json_name))
|
| 1095 |
+
all_handle.write(f"[Pair-pose ID {entry['id']}] {name}\n\n")
|
| 1096 |
+
if result["status"] == "completed":
|
| 1097 |
+
md_path = release_root / name
|
| 1098 |
+
with _atomic_file(md_path) as md_handle:
|
| 1099 |
+
md_handle.write(result["markdown"])
|
| 1100 |
+
if not result["markdown"].endswith("\n"):
|
| 1101 |
+
md_handle.write("\n")
|
| 1102 |
+
files.append((md_path, name))
|
| 1103 |
+
successes.append({"id": entry["id"], "custom_id": custom_id, "filename": name})
|
| 1104 |
+
else:
|
| 1105 |
+
failures.append({"id": entry["id"], "custom_id": custom_id, "filename": name,
|
| 1106 |
+
"status": result["status"], "error": result["error"]})
|
| 1107 |
+
all_handle.write(f"[{result['status'].upper()}] {result['error']}\n\n")
|
| 1108 |
+
if result["markdown"]:
|
| 1109 |
+
all_handle.write(result["markdown"])
|
| 1110 |
+
all_handle.write("\n\n")
|
| 1111 |
+
prefix = "Batches/" + batch["id"]
|
| 1112 |
+
report = {
|
| 1113 |
+
"format_version": 1, "batch_id": batch["id"], "batch_status": batch["status"],
|
| 1114 |
+
"created_at": _utc_now(), "model": OPENAI_MODEL, "reasoning": dict(OPENAI_REASONING),
|
| 1115 |
+
"expected_count": len(jobs), "complete_count": len(successes), "failure_count": len(failures),
|
| 1116 |
+
"all_jobs_complete": not failures, "batch_request_counts": batch.get("request_counts"),
|
| 1117 |
+
"successes": successes, "failures": failures, "all_outputs_filename": ALL_OUTPUTS_FILENAME,
|
| 1118 |
+
"reference_contents_included": False,
|
| 1119 |
+
}
|
| 1120 |
+
report_path = release_root / "release_report.json"
|
| 1121 |
+
_write_json(report_path, report)
|
| 1122 |
+
files.extend([(all_path, ALL_OUTPUTS_FILENAME), (all_path, prefix + "/" + ALL_OUTPUTS_FILENAME),
|
| 1123 |
+
(report_path, prefix + "/release_report.json"),
|
| 1124 |
+
(Path(state["run_root"]) / "batch_status.json", prefix + "/batch_status.json")])
|
| 1125 |
+
files.extend(_archive_files(state, prefix))
|
| 1126 |
+
files.extend((path, prefix + "/" + path.name) for path in paths)
|
| 1127 |
+
report["all_outputs_path"] = str(all_path)
|
| 1128 |
+
report["report_path"] = str(report_path)
|
| 1129 |
+
return files, report
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
def _release_message(batch_id: str, report: Dict[str, Any], repeated: bool = False) -> str:
|
| 1133 |
+
prefix = "Already released" if repeated else "Released"
|
| 1134 |
+
text = f"{prefix} Astra Batch {batch_id}: {report['complete_count']}/{report['expected_count']} complete Markdown catalogues, {report['failure_count']} failures."
|
| 1135 |
+
text += " Companion JSON, raw results, and " + ALL_OUTPUTS_FILENAME + " are in " + HF_REPO_ID + "."
|
| 1136 |
+
if report["failure_count"]:
|
| 1137 |
+
text += " The combined TXT and release_report.json identify failures and preserve any partial text."
|
| 1138 |
+
return text
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def _release(state: Dict[str, Any], batch: Dict[str, Any], key: str, hf_key: str, root: Path) -> Tuple[Any, ...]:
|
| 1142 |
+
status = batch.get("status")
|
| 1143 |
+
if status in PENDING_STATUSES:
|
| 1144 |
+
return (_batch_message(batch, state["job_count"]) + " Queue Release again later.", batch["id"], 0, 0, HF_URL, "")
|
| 1145 |
+
if status not in TERMINAL_STATUSES:
|
| 1146 |
+
raise ValueError(f"Unknown OpenAI Batch status: {status!r}.")
|
| 1147 |
+
counts = batch.get("request_counts") or {}
|
| 1148 |
+
if status == "completed" and counts.get("total") != state["job_count"]:
|
| 1149 |
+
raise ValueError("Completed Batch request count does not match the saved manifest. No release was uploaded.")
|
| 1150 |
+
previous = state.get("release") or {}
|
| 1151 |
+
signature = [status, batch.get("output_file_id"), batch.get("error_file_id")]
|
| 1152 |
+
if previous.get("commit_oid") and previous.get("signature") == signature and Path(previous.get("all_outputs_path", "")).is_file():
|
| 1153 |
+
return (_release_message(batch["id"], previous, True), batch["id"],
|
| 1154 |
+
previous["complete_count"], previous["failure_count"], HF_URL, previous["all_outputs_path"])
|
| 1155 |
+
paths = _download_results(state, batch, key, root)
|
| 1156 |
+
files, report = _build_release(state, batch, paths)
|
| 1157 |
+
# Save all derived files before uploading so a failed upload can be retried.
|
| 1158 |
+
state["release"] = {**report, "signature": signature, "commit_oid": ""}
|
| 1159 |
+
_save_state(state, root)
|
| 1160 |
+
commit_oid = _hf_commit(files, hf_key, f"Release {report['complete_count']}/{report['expected_count']} Astra pose catalogues ({batch['id']})")
|
| 1161 |
+
state["release"].update({"commit_oid": commit_oid, "published_at": _utc_now()})
|
| 1162 |
+
_save_state(state, root)
|
| 1163 |
+
return (_release_message(batch["id"], report), batch["id"], report["complete_count"],
|
| 1164 |
+
report["failure_count"], HF_URL, report["all_outputs_path"])
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
class Salia_FacingEachOther_Astra_Batch:
|
| 1168 |
+
@classmethod
|
| 1169 |
+
def INPUT_TYPES(cls):
|
| 1170 |
+
return {"required": {
|
| 1171 |
+
"horizontal-slice-json": ("STRING", {"default": "", "multiline": True,
|
| 1172 |
+
"tooltip": "Paste the complete horizontal-slice JSON. Raw JSON, a JSON path, or an HTTP(S) URL is accepted."}),
|
| 1173 |
+
"openAI_key": ("STRING", {"default": "", "multiline": False}),
|
| 1174 |
+
"hf_key": ("STRING", {"default": "", "multiline": False}),
|
| 1175 |
+
"action": (["start_or_check", "prepare_only", "check", "download"], {"default": "start_or_check"}),
|
| 1176 |
+
}, "optional": {
|
| 1177 |
+
"batch_id": ("STRING", {"default": "", "multiline": False,
|
| 1178 |
+
"tooltip": "Leave blank to resume this JSON's saved Batch. An explicit ID checks/downloads an existing Batch and never submits another."}),
|
| 1179 |
+
}}
|
| 1180 |
+
|
| 1181 |
+
RETURN_TYPES = ("STRING", "STRING", "INT", "STRING", "STRING", "STRING")
|
| 1182 |
+
RETURN_NAMES = ("status", "batch_id", "request_count", "batch_manifest", "input_jsonl", "output_jsonl")
|
| 1183 |
+
FUNCTION = "run"
|
| 1184 |
+
CATEGORY = "Salia/Pose Catalogue"
|
| 1185 |
+
OUTPUT_NODE = True
|
| 1186 |
+
DESCRIPTION = "Prepare, submit, check, or download a text-only Astra Responses Batch, one request per pose pair."
|
| 1187 |
+
|
| 1188 |
+
@classmethod
|
| 1189 |
+
def IS_CHANGED(cls, **kwargs):
|
| 1190 |
+
return float("nan")
|
| 1191 |
+
|
| 1192 |
+
def run(self, openAI_key: str, hf_key: str, action: str = "start_or_check", batch_id: str = "", **kwargs):
|
| 1193 |
+
if action not in {"start_or_check", "prepare_only", "check", "download"}:
|
| 1194 |
+
raise ValueError("Unknown Batch action.")
|
| 1195 |
+
source = kwargs.get("horizontal-slice-json", "")
|
| 1196 |
+
root = _work_root()
|
| 1197 |
+
with _workflow_lock(root):
|
| 1198 |
+
if action == "prepare_only":
|
| 1199 |
+
state = _prepare(source, root)
|
| 1200 |
+
return _node_result((f"Prepared {state['job_count']} Astra requests. No API call was made.",
|
| 1201 |
+
str(state.get("batch_id") or ""), state["job_count"], state["manifest_path"], state["input_path"], ""))
|
| 1202 |
+
key = _key(openAI_key, ("OPENAI_API_KEY",), "openAI_key")
|
| 1203 |
+
hf_token = (hf_key or "").strip() or os.environ.get("HF_TOKEN", "").strip() or os.environ.get("HUGGING_FACE_HUB_TOKEN", "").strip()
|
| 1204 |
+
explicit_id = (batch_id or "").strip()
|
| 1205 |
+
if explicit_id:
|
| 1206 |
+
batch = _get_batch(explicit_id, key)
|
| 1207 |
+
state = _resolve_state(batch, key, hf_token, root)
|
| 1208 |
+
else:
|
| 1209 |
+
state = _prepare(source, root)
|
| 1210 |
+
if action in {"check", "download"}:
|
| 1211 |
+
if not state.get("batch_id"):
|
| 1212 |
+
if state.get("phase") in {"creating_batch", "creation_uncertain"}:
|
| 1213 |
+
_recover_creation(state, key, root)
|
| 1214 |
+
else:
|
| 1215 |
+
raise ValueError("No Batch has been started for this JSON. Use start_or_check or enter batch_id.")
|
| 1216 |
+
batch = _get_batch(state["batch_id"], key)
|
| 1217 |
+
else:
|
| 1218 |
+
hf_token = _key(hf_key, ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"), "hf_key")
|
| 1219 |
+
batch = _start(state, key, hf_token, root)
|
| 1220 |
+
_adopt_batch(state, batch, root)
|
| 1221 |
+
status = _batch_message(batch, state["job_count"])
|
| 1222 |
+
if hf_token:
|
| 1223 |
+
status += _backup_batch(state, root, hf_token)
|
| 1224 |
+
output_path = ""
|
| 1225 |
+
if action == "download":
|
| 1226 |
+
if batch.get("status") in TERMINAL_STATUSES:
|
| 1227 |
+
paths = _download_results(state, batch, key, root)
|
| 1228 |
+
output_path = next((str(path) for path in paths if path.name == "output.jsonl"), "")
|
| 1229 |
+
status += f" Downloaded {len(paths)} raw result/error JSONL files. Use Astra Release to publish."
|
| 1230 |
+
else:
|
| 1231 |
+
status += " Results are not ready. Queue again later."
|
| 1232 |
+
elif batch.get("status") in TERMINAL_STATUSES:
|
| 1233 |
+
status += " Queue Astra Release to download and publish results."
|
| 1234 |
+
else:
|
| 1235 |
+
status += " Queue again later to check progress."
|
| 1236 |
+
return _node_result((status, state["batch_id"], state["job_count"], state["manifest_path"], state["input_path"], output_path))
|
| 1237 |
+
|
| 1238 |
+
|
| 1239 |
+
class Salia_FacingEachOther_Astra_Release:
|
| 1240 |
+
@classmethod
|
| 1241 |
+
def INPUT_TYPES(cls):
|
| 1242 |
+
return {"required": {
|
| 1243 |
+
"batch_id": ("STRING", {"default": "", "multiline": False,
|
| 1244 |
+
"tooltip": "Connect batch_id from Astra Batch, or paste the Batch ID."}),
|
| 1245 |
+
"openAI_key": ("STRING", {"default": "", "multiline": False}),
|
| 1246 |
+
"hf_key": ("STRING", {"default": "", "multiline": False}),
|
| 1247 |
+
}, "optional": {
|
| 1248 |
+
"batch_manifest": ("STRING", {"default": "", "multiline": False,
|
| 1249 |
+
"tooltip": "Optional: connect batch_manifest from Astra Batch. Otherwise recover from local state, HF archive, or OpenAI's original input file."}),
|
| 1250 |
+
}}
|
| 1251 |
+
|
| 1252 |
+
RETURN_TYPES = ("STRING", "STRING", "INT", "INT", "STRING", "STRING")
|
| 1253 |
+
RETURN_NAMES = ("status", "batch_id", "complete_count", "failure_count", "repository_url", "all_outputs_txt")
|
| 1254 |
+
FUNCTION = "run"
|
| 1255 |
+
CATEGORY = "Salia/Pose Catalogue"
|
| 1256 |
+
OUTPUT_NODE = True
|
| 1257 |
+
DESCRIPTION = "Download an Astra pose Batch and publish Markdown, JSON, raw JSONL, and one combined TXT to saliacoel/poses."
|
| 1258 |
+
|
| 1259 |
+
@classmethod
|
| 1260 |
+
def IS_CHANGED(cls, **kwargs):
|
| 1261 |
+
return float("nan")
|
| 1262 |
+
|
| 1263 |
+
def run(self, batch_id: str, openAI_key: str, hf_key: str, batch_manifest: str = ""):
|
| 1264 |
+
key = _key(openAI_key, ("OPENAI_API_KEY",), "openAI_key")
|
| 1265 |
+
hf_token = _key(hf_key, ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"), "hf_key")
|
| 1266 |
+
root = _work_root()
|
| 1267 |
+
with _workflow_lock(root):
|
| 1268 |
+
batch = _get_batch((batch_id or "").strip(), key)
|
| 1269 |
+
state = _resolve_state(batch, key, hf_token, root, batch_manifest)
|
| 1270 |
+
return _node_result(_release(state, batch, key, hf_token, root))
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
+
NODE_CLASS_MAPPINGS = {
|
| 1274 |
+
"Salia_FacingEachOther_Astra_Batch": Salia_FacingEachOther_Astra_Batch,
|
| 1275 |
+
"Salia_FacingEachOther_Astra_Release": Salia_FacingEachOther_Astra_Release,
|
| 1276 |
+
}
|
| 1277 |
+
|
| 1278 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 1279 |
+
"Salia_FacingEachOther_Astra_Batch": "Salia Facing Each Other: Astra Batch",
|
| 1280 |
+
"Salia_FacingEachOther_Astra_Release": "Salia Facing Each Other: Astra Release",
|
| 1281 |
+
}
|