raven-image: write each image's exact final prompt beside it; --caption-only previews the upsampled caption
Node 20 (PreviewAny on the upsampler output) puts the caption in history; every written image gets <root>.json with caption and settings. --caption-only runs nodes 10, 11, 20 only. Tests: 185 checks (159 at base). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5dd9642b75
commit
c69ceebb26
3 changed files with 114 additions and 9 deletions
|
|
@ -17,6 +17,21 @@ 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), sanitised `refs`, `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); with `--no-enhance` it 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,40 @@ 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") or [given if isinstance(given, str) else None]
|
||||
caption = text[0]
|
||||
if caption_only and outs.get("20", {}).get("text"):
|
||||
return None, caption
|
||||
for out in () if caption_only else outs.values():
|
||||
for im in out.get("images", []):
|
||||
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):
|
||||
"""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": [safe_name(r) for r in a.ref], "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 +339,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 +350,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 +371,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 +385,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 +402,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)
|
||||
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,12 +1,13 @@
|
|||
#!/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
|
||||
CAPTION = "Full-color photograph, a small private space yacht moored at a dock, soft light."
|
||||
seen = {"uploads": [], "prompts": [], "view": PNG}
|
||||
|
||||
|
||||
|
|
@ -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: 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"{}")
|
||||
|
|
@ -324,6 +327,49 @@ 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"] == ["r0.png"] and rec["graph"] == "flux3-klein-edit", "edit sidecar: sanitised ref name, edit graph")
|
||||
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, "vision edit sidecar: upsampler caption")
|
||||
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.strip() == CAPTION and p.stderr == "", 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")
|
||||
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