Prompt record: sidecar of the exact caption, and --caption-only #2
3 changed files with 139 additions and 13 deletions
|
|
@ -17,6 +17,22 @@ raven-image "a full caption" --no-enhance -o out.png # skip the
|
|||
Prints one line per image (`path seed size seconds`). Defaults: 1536x1024, random
|
||||
seed, 900 s wait per image.
|
||||
|
||||
**Record.** Next to every image the client writes `<image>.json` (`out.png` gets `out.json`; `-n 4` gets one per image), in
|
||||
every mode: client and graph sha256, model file names, size, seed, steps, cfg, sampler, scheduler, `enhance`, `prompt` (as
|
||||
typed), `caption` (the exact text the encoder saw), `vision` (whether `--vision` fed the refs to the encoder), `encoder` (the node id and class
|
||||
that consumed the prompt: `CLIPTextEncode` or `TextEncodeQwenImageEditPlus`), `refs` (each as `{name, sha256}` of its content), `margin`, `bg`, seconds, UTC time. With the upsampler on
|
||||
the caption is read from ComfyUI's `PreviewAny` output (node 20, on the upsampler's output), and a render whose history lacks it
|
||||
fails without writing; with `--no-enhance` the caption is the prompt. `--out` may not end in `.json`.
|
||||
|
||||
```
|
||||
raven-image --caption-only "small private space yacht" --size 1536x1024 # prints the caption, renders nothing, writes nothing
|
||||
```
|
||||
|
||||
`--caption-only` runs only nodes 10, 11 and 20 (about 9 s, no image) and prints what the upsampler made of the prompt, so a
|
||||
person or a model can read it before Raven spends a render. It matters: that prompt came back as a boat on open water, an
|
||||
attractor visible only in the caption. It refuses `--no-enhance`, `--ref` and `--margin`; exit codes are as for a render.
|
||||
Images stay `PreviewImage`; the client never saves into Raven's output history.
|
||||
|
||||
```
|
||||
raven-image --ref sheet.png "Using the character from <ref_image_0>, show her seated at a desk typing, ..." --size 1024x1024 -o out.png
|
||||
raven-image --ref a.png --ref b.png --vision "<ref_image_0> ... <ref_image_1> ..." -o out.png
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ Talks to ComfyUI's own API: POST /prompt, poll GET /history/<id>, GET /view,
|
|||
POST /free when the queue is empty. No retry loop: an unreachable Raven exits 75
|
||||
with "Raven may be busy or off". See README.md next to this file.
|
||||
"""
|
||||
import argparse, json, math, os, random, re, stat, struct, sys, time, urllib.error, urllib.parse, urllib.request, zlib
|
||||
import argparse, datetime, hashlib, json, math, os, random, re, stat, struct, sys, time, urllib.error, urllib.parse, urllib.request, zlib
|
||||
|
||||
BASE = os.environ.get("RAVEN_URL", "http://10.77.0.4:8190")
|
||||
EX_BUSY = 75 # EX_TEMPFAIL: no answer from Raven (off, busy, a read timeout mid-render, or a lock screen after a reboot); try again later, by hand
|
||||
|
|
@ -115,6 +115,7 @@ def build(name, text, w, h, seed, enhance, refs=(), vision=False):
|
|||
if enhance:
|
||||
d = math.gcd(w, h)
|
||||
g["11"]["inputs"]["prompt"] = text if refs else f"TARGET CANVAS: {w // d}:{h // d}\n{text}"
|
||||
g["20"] = {"class_type": "PreviewAny", "inputs": {"source": ["11", 0]}} # the caption, in history beside the image
|
||||
else:
|
||||
for k in ("10", "11"):
|
||||
del g[k]
|
||||
|
|
@ -256,7 +257,11 @@ def clear_edges(png, pct, alpha=False, bg=None):
|
|||
return png_encode(w, h, bpp, rows, keep), back, clip, band
|
||||
|
||||
|
||||
def render(g, timeout):
|
||||
def render(g, timeout, caption_only=False):
|
||||
"""Run graph g; returns (png, caption). The caption is node 20's PreviewAny text, the upsampler's exact output, else the
|
||||
text node 4 was given. caption_only: g holds no image node, png is None."""
|
||||
enc = g.get("4", {}).get("inputs", {})
|
||||
given = enc.get("text", enc.get("prompt"))
|
||||
try:
|
||||
r = json.loads(call("POST", "/prompt", {"prompt": g, "client_id": "raven-image"}))
|
||||
except urllib.error.HTTPError as e:
|
||||
|
|
@ -272,15 +277,43 @@ def render(g, timeout):
|
|||
if st.get("status_str") == "error":
|
||||
msgs = [m for m in st.get("messages", []) if m[0] == "execution_error"]
|
||||
sys.exit(f"raven-image: render failed: {json.dumps(msgs[-1][1] if msgs else st)[:800]}")
|
||||
for out in h.get("outputs", {}).values():
|
||||
outs = h.get("outputs", {})
|
||||
text = outs.get("20", {}).get("text")
|
||||
caption = text[0] if text else None if "20" in g else given if isinstance(given, str) else None
|
||||
if caption_only and caption is not None:
|
||||
return None, caption
|
||||
for out in () if caption_only else outs.values():
|
||||
for im in out.get("images", []):
|
||||
if caption is None: # the record must hold the exact prompt: no caption, no image
|
||||
sys.exit("raven-image: history has no caption from the upsampler (node 20); nothing written")
|
||||
q = urllib.parse.urlencode({"filename": im["filename"], "subfolder": im["subfolder"], "type": im["type"]})
|
||||
return call("GET", "/view?" + q, timeout=120)
|
||||
return call("GET", "/view?" + q, timeout=120), caption
|
||||
if st.get("completed"):
|
||||
sys.exit("raven-image: render completed with no image")
|
||||
sys.exit("raven-image: completed with no caption" if caption_only else "raven-image: render completed with no image")
|
||||
sys.exit(f"raven-image: no image after {timeout}s (prompt {pid} may still be running on Raven)")
|
||||
|
||||
|
||||
def sha256(path):
|
||||
with open(path, "rb") as f:
|
||||
return hashlib.sha256(f.read()).hexdigest()
|
||||
|
||||
|
||||
def write_record(path, a, g, seed, w, h, caption, bg, seconds, ref_data):
|
||||
"""The image's record, beside it: what Raven was asked and the exact text its encoder saw."""
|
||||
s = g["7"]["inputs"]
|
||||
rec = {"client_sha256": sha256(os.path.realpath(__file__)), "graph": a.graph,
|
||||
"graph_sha256": sha256(os.path.join(graph_dir(), a.graph + ".json")),
|
||||
"models": {k: n["inputs"][f] for k, n in g.items() for f in ("unet_name", "clip_name", "vae_name") if f in n.get("inputs", {})},
|
||||
"size": f"{w}x{h}", "seed": seed, "steps": s["steps"], "cfg": s["cfg"], "sampler": s["sampler_name"], "scheduler": s["scheduler"],
|
||||
"enhance": "11" in g, "prompt": a.prompt, "caption": caption, "refs": [{"name": safe_name(r), "sha256": hashlib.sha256(d).hexdigest()} for r, d in zip(a.ref, ref_data)],
|
||||
"vision": a.vision, "encoder": {"node": "4", "class_type": g["4"]["class_type"]}, "margin": a.margin,
|
||||
"bg": "%06x" % bg if a.margin else None, "seconds": round(seconds, 1),
|
||||
"utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(rec, f, ensure_ascii=False, indent=1)
|
||||
f.write(chr(10))
|
||||
|
||||
|
||||
def free_if_idle():
|
||||
q = json.loads(call("GET", "/queue"))
|
||||
if not q.get("queue_running") and not q.get("queue_pending"):
|
||||
|
|
@ -309,6 +342,8 @@ def main():
|
|||
ap.add_argument("--alpha", action="store_true", help="--margin: key the backdrop connected to the band to transparent (RGBA output)")
|
||||
ap.add_argument("--max-clip", type=float, default=0.5, metavar="PCT", help="--margin: largest %% of the band that may need clearing (default 0.5)")
|
||||
ap.add_argument("--no-enhance", action="store_true", help="send the prompt as the caption, skip the upsampler")
|
||||
ap.add_argument("--caption-only", action="store_true",
|
||||
help="run only the upsampler, print the caption it makes of the prompt and render nothing (no file written)")
|
||||
ap.add_argument("--timeout", type=int, default=900, help="seconds to wait per image")
|
||||
ap.add_argument("--keep-loaded", action="store_true", help="skip POST /free at the end")
|
||||
a = ap.parse_args()
|
||||
|
|
@ -318,6 +353,10 @@ def main():
|
|||
ap.error("--ref and graph flux3-klein-edit go together (the edit graph needs refs, other graphs cannot take them)")
|
||||
if a.margin is not None and not 0 < a.margin <= 40:
|
||||
ap.error("--margin is a percentage above 0 and at most 40")
|
||||
if a.caption_only and (a.no_enhance or a.ref or a.margin is not None):
|
||||
ap.error("--caption-only previews the upsampler and cannot be combined with --no-enhance, --ref or --margin")
|
||||
if os.path.splitext(a.out)[1].lower() == ".json":
|
||||
ap.error("--out must not end in .json: that name is the image's record")
|
||||
if a.alpha and not a.margin:
|
||||
ap.error("--alpha needs --margin")
|
||||
if not re.fullmatch(r"#?[0-9a-fA-F]{6}", a.bg):
|
||||
|
|
@ -335,6 +374,13 @@ def main():
|
|||
dirty = broken = 0
|
||||
try:
|
||||
call("GET", "/system_stats", timeout=5)
|
||||
if a.caption_only:
|
||||
g = build(a.graph, a.prompt, w, h, seed0, True)
|
||||
_, caption = render({k: g[k] for k in ("10", "11", "20")}, a.timeout, True)
|
||||
print(caption)
|
||||
if not a.keep_loaded:
|
||||
print("freed Raven's VRAM" if free_if_idle() else "queue not empty, left models loaded", file=sys.stderr)
|
||||
return
|
||||
refs = [upload(r, d) for r, d in zip(a.ref, ref_data)]
|
||||
for i in range(a.n):
|
||||
seed = seed0 + i
|
||||
|
|
@ -342,7 +388,7 @@ def main():
|
|||
g = build(a.graph, a.prompt, w, h, seed, not a.no_enhance, refs, a.vision)
|
||||
if a.margin:
|
||||
pin_edges(g, w, h, a.margin, bg)
|
||||
png = render(g, a.timeout)
|
||||
png, caption = render(g, a.timeout)
|
||||
note = ""
|
||||
if a.margin:
|
||||
try:
|
||||
|
|
@ -359,6 +405,7 @@ def main():
|
|||
path = a.out if a.n == 1 else f"{root}-{i + 1}{ext}"
|
||||
with open(path, "wb") as f:
|
||||
f.write(png)
|
||||
write_record(os.path.splitext(path)[0] + ".json", a, g, seed, w, h, caption, bg, time.time() - t, ref_data)
|
||||
print(f"{path} seed={seed} {w}x{h} {time.time() - t:.0f}s{note}", flush=True)
|
||||
if not a.keep_loaded:
|
||||
print("freed Raven's VRAM" if free_if_idle() else "queue not empty, left models loaded")
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Offline test of client/raven-image against an in-process fake ComfyUI on 127.0.0.1.
|
||||
Asserts on the POSTed /prompt graph and the multipart upload. Needs only python3. Usage: test-raven-image.py [repo-root]"""
|
||||
import json, os, subprocess, sys, tempfile, threading
|
||||
import hashlib, json, os, re, subprocess, sys, tempfile, threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
root = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
tool = os.path.join(root, "client", "raven-image")
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"\0" * 32
|
||||
seen = {"uploads": [], "prompts": [], "view": PNG}
|
||||
CAPTION = "Full-color photograph, a small private space yacht moored at a dock, soft light."
|
||||
seen = {"uploads": [], "prompts": [], "view": PNG, "drop20": False, "free": 0}
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
|
|
@ -17,8 +18,10 @@ class H(BaseHTTPRequestHandler):
|
|||
self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/history/"):
|
||||
self.send(json.dumps({self.path[9:]: {"status": {"completed": True}, "outputs": {"9": {"images": [
|
||||
{"filename": "x.png", "subfolder": "", "type": "temp"}]}}}}).encode())
|
||||
g, outs = seen["prompts"][-1], {} # like ComfyUI, report only the output nodes the posted graph has
|
||||
if "9" in g: outs["9"] = {"images": [{"filename": "x.png", "subfolder": "", "type": "temp"}]}
|
||||
if "20" in g and not seen["drop20"]: outs["20"] = {"text": [CAPTION]}
|
||||
self.send(json.dumps({self.path[9:]: {"status": {"completed": True}, "outputs": outs}}).encode())
|
||||
elif self.path.startswith("/view"): self.send(seen["view"], "image/png")
|
||||
elif self.path == "/queue": self.send(b'{"queue_running":[],"queue_pending":[]}')
|
||||
else: self.send(b"{}")
|
||||
|
|
@ -26,6 +29,7 @@ class H(BaseHTTPRequestHandler):
|
|||
body = self.rfile.read(int(self.headers["Content-Length"]))
|
||||
if self.path == "/upload/image":
|
||||
seen["uploads"].append(body); self.send(json.dumps({"name": "stored%d.png" % len(seen["uploads"])}).encode())
|
||||
elif self.path == "/free": seen["free"] += 1; self.send(b"{}")
|
||||
elif self.path == "/prompt":
|
||||
seen["prompts"].append(json.loads(body)["prompt"]); self.send(b'{"prompt_id":"p1"}')
|
||||
else: self.send(b"{}")
|
||||
|
|
@ -45,11 +49,13 @@ def check(cond, what):
|
|||
fails.append(what); print("FAIL:", what)
|
||||
|
||||
|
||||
def run(*args, url=url):
|
||||
seen["uploads"].clear(); seen["prompts"].clear()
|
||||
def run(*args, url=url, keep=True):
|
||||
seen["uploads"].clear(); seen["prompts"].clear(); seen["free"] = 0
|
||||
env = dict(os.environ, RAVEN_URL=url)
|
||||
p = subprocess.run([sys.executable, "-I", tool, "--keep-loaded", "-o", os.path.join(tmp, "o.png"), *args],
|
||||
p = subprocess.run([sys.executable, "-I", tool, *(["--keep-loaded"] if keep else []), "-o", os.path.join(tmp, "o.png"), *args],
|
||||
capture_output=True, text=True, env=env, timeout=120)
|
||||
for g in seen["prompts"]: # images stay PreviewImage and never reach Deru's playground history
|
||||
check(all(n["class_type"] != "SaveImage" for n in g.values()), f"no SaveImage in the posted graph ({' '.join(args)[:60]})")
|
||||
return p, (seen["prompts"][0] if seen["prompts"] else None)
|
||||
|
||||
|
||||
|
|
@ -324,6 +330,63 @@ seen["view"] = mkpng(160, 160, lambda x, y: RED if x < 12 else BG)
|
|||
p, g = run("--margin", "6", "--bg", "1ec85a", "-n", "2", "--size", "160x160", "--no-enhance", "cap")
|
||||
check(p.returncode == 65 and p.stdout.count("DIRTY") == 2, f"-n 2 both dirty: two reports, exit 65 ({p.returncode})")
|
||||
|
||||
# the record beside each image, and --caption-only
|
||||
side = os.path.join(tmp, "o.json")
|
||||
def has(name): return name in os.listdir(tmp) # os.path.exists is stubbed earlier in this file
|
||||
def record(*args):
|
||||
if has("o.json"): os.remove(side)
|
||||
p, g = run(*args)
|
||||
return p, g, (json.load(open(side, encoding="utf-8")) if has("o.json") else None)
|
||||
p, g, rec = record("--seed", "42", "--size", "512x768", "yacht")
|
||||
check(p.returncode == 0 and rec is not None and "20" in g, f"sidecar: written beside the image ({p.stderr[-200:]})")
|
||||
if rec:
|
||||
check(g["20"] == {"class_type": "PreviewAny", "inputs": {"source": ["11", 0]}}, "sidecar: node 20 is PreviewAny on the upsampler")
|
||||
check(rec["caption"] == CAPTION and rec["prompt"] == "yacht", "sidecar: caption is the upsampler's text, prompt the argument")
|
||||
check(rec["seed"] == 42 and rec["size"] == "512x768" and rec["enhance"] is True, "sidecar: seed, size, enhance")
|
||||
check((rec["steps"], rec["cfg"], rec["sampler"], rec["scheduler"]) == (16, 1, "euler", "simple"), "sidecar: sampler settings")
|
||||
check(rec["graph"] == "flux3-klein" and rec["graph_sha256"] == hashlib.sha256(open(os.path.join(root, "client", "graphs", "flux3-klein.json"), "rb").read()).hexdigest(), "sidecar: graph name and sha256")
|
||||
check(rec["client_sha256"] == hashlib.sha256(open(tool, "rb").read()).hexdigest(), "sidecar: client sha256")
|
||||
check(rec["models"] == {"1": "flux3-image-klein-int8-convrot.safetensors", "2": "qwen3vl_4b_int8_convrot.safetensors",
|
||||
"3": "flux2-vae.safetensors", "10": "qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors"}, "sidecar: models from the loader nodes")
|
||||
check(rec["refs"] == [] and rec["margin"] is None and re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", rec["utc"]), "sidecar: no refs, no margin, utc stamp")
|
||||
p, g, rec = record("--no-enhance", "--seed", "7", "plain cap")
|
||||
check(rec is not None and rec["caption"] == "plain cap" and rec["enhance"] is False and "20" not in g and "10" not in rec["models"], "no-enhance sidecar: caption is the prompt, no node 20")
|
||||
p, g, rec = record("--ref", refs[0], "--no-enhance", "cap <ref_image_0>")
|
||||
check(rec is not None and rec["refs"] == [{"name": "r0.png", "sha256": hashlib.sha256(PNG).hexdigest()}] and rec["graph"] == "flux3-klein-edit"
|
||||
and rec["vision"] is False and rec["encoder"] == {"node": "4", "class_type": "CLIPTextEncode"}, "edit sidecar: ref name and content hash, edit graph, no vision")
|
||||
p, g, rec = record("--ref", refs[0], "--vision", "cap <ref_image_0>")
|
||||
check(rec is not None and rec["caption"] == CAPTION and "20" in g and rec["vision"] is True
|
||||
and rec["encoder"] == {"node": "4", "class_type": "TextEncodeQwenImageEditPlus"}, "vision edit sidecar: upsampler caption, vision on, vision encoder")
|
||||
check(rec is not None and 2 <= rec["seconds"] < 120, f"sidecar: seconds recorded ({rec and rec.get('seconds')})")
|
||||
# upsampler on but node 20 missing from history: fail loudly, write nothing
|
||||
seen["drop20"] = True
|
||||
for f in ("o.png", "o.json"):
|
||||
if has(f): os.remove(os.path.join(tmp, f))
|
||||
p, g = run("yacht")
|
||||
check(p.returncode != 0 and "no caption" in p.stderr and not has("o.png") and not has("o.json") and "Traceback" not in p.stderr, f"no caption in history: fails, writes nothing ({p.returncode} {p.stderr[-160:]})")
|
||||
p, g = run("--caption-only", "yacht")
|
||||
check(p.returncode != 0 and p.stdout == "", "caption-only with no caption in history: fails")
|
||||
seen["drop20"] = False
|
||||
p, g = run("-n", "2", "--no-enhance", "cap")
|
||||
check(has("o-1.json") and has("o-2.json"), "-n 2: one sidecar per image")
|
||||
refused(["-o", os.path.join(tmp, "x.json"), "cap"], "must not end in .json", "--out .json")
|
||||
for f in ("o.png", "o.json"):
|
||||
if has(f): os.remove(os.path.join(tmp, f))
|
||||
p, g = run("--caption-only", "--seed", "3", "yacht")
|
||||
check(p.returncode == 0 and p.stdout == CAPTION + chr(10) and p.stderr == "" and seen["free"] == 0, f"caption-only: stdout is the caption ({p.stdout!r} {p.stderr[-200:]})")
|
||||
check(g is not None and sorted(g) == ["10", "11", "20"], f"caption-only: graph is nodes 10, 11, 20 only ({sorted(g or [])})")
|
||||
check(g is not None and g["11"]["inputs"]["prompt"] == "TARGET CANVAS: 3:2\nyacht", "caption-only: upsampler prompt as a render would send it")
|
||||
check(not has("o.png") and not has("o.json"), "caption-only: no file written")
|
||||
p, g = run("--caption-only", "yacht", keep=False)
|
||||
check(p.returncode == 0 and p.stdout == CAPTION + chr(10) and seen["free"] == 1 and "freed" in p.stderr, f"caption-only frees Raven's VRAM, on stderr ({seen['free']} {p.stderr[-100:]})")
|
||||
for args, w in ((["--no-enhance"], "--no-enhance"), (["--ref", refs[0]], "--ref"), (["--margin", "5"], "--margin")):
|
||||
refused(["--caption-only", *args, "cap"], "cannot be combined", "caption-only with " + w)
|
||||
|
||||
# a margin render records its margin and backdrop beside the cleared image
|
||||
seen["view"] = mkpng(160, 160, lambda x, y: BG)
|
||||
p, g, rec = record("--margin", "6", "--bg", "1ec85a", "--size", "160x160", "cap")
|
||||
check(p.returncode == 0 and rec is not None and rec["margin"] == 6 and rec["bg"] == "1ec85a", f"margin sidecar: margin and bg ({p.stderr[-200:]})")
|
||||
|
||||
srv.shutdown()
|
||||
print(f"{count[0] - len(fails)}/{count[0]} checks passed")
|
||||
sys.exit(1 if fails else 0)
|
||||
|
|
|
|||
Loading…
Reference in a new issue