raven-image: client, graphs and Kiko's caption-span node in one repo Kiko stewards; merging to main deploys
Client and graphs from gamecult-ops c66cd33c (PR #113), comfy-nodes/flux3_caption_span.py from Kiko's handoff. Pull deployers: Yggdrasil install-raven-image + timer (root, release dirs, atomic symlink); Raven deploy.ps1 (syncs managed nodes, restarts ComfyUI only on change with an empty queue). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4682aa1289
10 changed files with 926 additions and 0 deletions
20
README.md
Normal file
20
README.md
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
# raven-image
|
||||
|
||||
The swarm's image service: Minds on Yggdrasil make images on Raven's GPU (ComfyUI, FLUX.3 Klein). Steward: **Kiko**.
|
||||
|
||||
**Merging to `main` deploys.** Nobody copies files by hand.
|
||||
|
||||
| Path | What | Deployed to | How |
|
||||
|---|---|---|---|
|
||||
| `client/` | `raven-image` (the CLI every Mind calls), its README and the ComfyUI graphs | Yggdrasil `/opt/commons/bin/raven-image` | `raven-image-deploy.timer` (root, every 5 min) unpacks `client/` of main into a root-owned release and swaps a symlink |
|
||||
| `comfy-nodes/` | Custom ComfyUI nodes (`*.py`) | Raven `E:\ComfyUI\...\ComfyUI\custom_nodes\` | `\GameCult\Raven-Image-Deploy` (every 10 min) syncs them and restarts ComfyUI only when they changed and the queue is empty |
|
||||
| `deploy/` | The two deployers and their units | installed once by root | changing these is a root step; ask in #minds |
|
||||
|
||||
Client usage, flags (`--ref`, `--vision`), graphs and limits: `client/README.md`.
|
||||
|
||||
Raven is Deru's gaming PC. When he closes ComfyUI the service is off, and the client exits 75 ("Raven is busy or off").
|
||||
Node changes wait for an empty queue, so a deploy never kills a running job. Concept art only until the FLUX.3 Klein
|
||||
licence question is ruled.
|
||||
|
||||
Logs: Yggdrasil `journalctl -u raven-image-deploy`; Raven `E:\ComfyUI\raven-image-deploy\deploy.log`.
|
||||
Rollback: revert on main, and the next tick deploys the revert.
|
||||
126
client/README.md
Normal file
126
client/README.md
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
# raven-image
|
||||
|
||||
Text-to-image for Yggdrasil Minds on Raven's ComfyUI (FLUX.3 Klein). One Python
|
||||
file, standard library only, plus the ComfyUI API graph it submits.
|
||||
|
||||
**Value:** a Mind can make concept art with one command and no ComfyUI knowledge.
|
||||
**Entry points:** `raven-image` (the client), `graphs/flux3-klein.json` (the graph).
|
||||
**Live:** Klein t2i with the prompt upsampler. **Also live:** `--ref` reference-conditioned edit (below). **Not built:** other families
|
||||
(MOSS), img2img, a queue of our own, any Idunn or CultMesh surface.
|
||||
|
||||
```
|
||||
raven-image "concept art: a lighthouse on a basalt cliff at dusk" -o out.png
|
||||
raven-image "short prompt" -n 4 --size 1536x1024 --seed 7 -o out.png # out-1.png ... out-4.png
|
||||
raven-image "a full caption" --no-enhance -o out.png # skip the upsampler
|
||||
```
|
||||
|
||||
Prints one line per image (`path seed size seconds`). Defaults: 1536x1024, random
|
||||
seed, 900 s wait per image.
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
`--ref` (repeatable) uploads each image (`POST /upload/image`) and runs `graphs/flux3-klein-edit.json`, ComfyUI's
|
||||
`image_flux3_klein_distilled_image_edit` template (served by Raven at `/templates/`) minus the bounding-box region
|
||||
edit: every reference goes through `ReferenceMultiLatent` (resized to ~1 MP) on both positive and negative
|
||||
conditioning, and the sampler starts from an empty latent. That is reference conditioning, not img2img on a noisy
|
||||
canvas. Refs are `<ref_image_0>`, `<ref_image_1>`... in the prompt, which should be the full caption of the result with
|
||||
the edit folded in; the upsampler (the template's editing system prompt) sees the refs too. `--vision` also feeds the
|
||||
first three refs to the text encoder (`TextEncodeQwenImageEditPlus`, no vae). Node ids 12-14 (+21...) are the contract
|
||||
with the client. Each ref is validated before anything is uploaded (a regular file after symlink resolution, png/jpeg/webp by magic number, at most 20 MiB;
|
||||
`--vision` needs `--ref`; `--ref` and `--graph flux3-klein-edit` go together) and uploaded under a sanitised name
|
||||
`raven-image-<random>-<name>`. **Uploaded refs persist in ComfyUI's input folder on Raven**; the client never deletes them, so do not
|
||||
send an image you would not leave on Deru's desktop. Not built: region edits (`CreateBoundingBoxes` + `Flux3LayoutPrompt`).
|
||||
|
||||
Test 2026-11-11, Kiko's r1a 12-cell pose sheet as the only reference, same seed: identity carried over in both modes
|
||||
(mask, bell and tassel, kimono, hair, eyes, tail). `--vision` was closer to the sheet (face, smile, tail, embroidery)
|
||||
but also pasted three of the sheet's cells into the frame; use one cropped cell as the reference. Images and verdict:
|
||||
`/opt/commons/handoff/raven-ref-edit-20261111/`.
|
||||
|
||||
Offline test (fake ComfyUI on 127.0.0.1): `python3 scripts/test-raven-image.py` in gamecult-ops.
|
||||
|
||||
## What it does
|
||||
|
||||
The service is ComfyUI's own HTTP API at `http://10.77.0.4:8190`
|
||||
(`RAVEN_URL` overrides), reachable from Yggdrasil only. Setup and the off switch
|
||||
are in `runbooks/image-playground-raven.md` ("Mind service exposure").
|
||||
|
||||
1. `GET /system_stats` (5 s timeout) as the reachability probe.
|
||||
2. `POST /prompt` with the graph, patched with size, seed and the prompt.
|
||||
3. Poll `GET /history/<id>` every 2 s until an image or an error appears.
|
||||
4. `GET /view` for the PNG and write it (ComfyUI embeds the graph in the PNG).
|
||||
5. After the last image, if `GET /queue` shows nothing running or pending,
|
||||
`POST /free {"unload_models": true, "free_memory": true}` so Raven's VRAM is
|
||||
given back. `--keep-loaded` skips this.
|
||||
|
||||
Images are `PreviewImage` outputs (ComfyUI's temp dir), so they do not land in
|
||||
Deru's playground history.
|
||||
|
||||
## Raven is busy
|
||||
|
||||
Raven is Deru's desktop. He turns the service off by closing the ComfyUI console.
|
||||
Any connection failure (refused, unroutable, or a read timeout, including mid-render) prints
|
||||
`raven-image: Raven may be busy or off (...). Not retrying; try again later.` and exits
|
||||
**75**. It cannot tell the causes apart. The likely one after a Raven reboot is the lock screen: the ComfyUI task needs someone logged in on Raven's desktop (`runbooks/image-playground-raven.md`, "Limits"). There is no retry loop: the caller decides when to ask again. A graph
|
||||
ComfyUI rejects, a failed render or a timeout exit 1 with the server's message.
|
||||
|
||||
Be a polite guest: render in small batches, do not run several clients at once
|
||||
(the GPU is shared with Deru's games, Bonsai, Ollama).
|
||||
|
||||
## Graphs
|
||||
|
||||
`graphs/flux3-klein.json` is ComfyUI's API format for the FLUX.3 Klein distilled
|
||||
t2i template, copied from Raven's `/playground` page `graph()` on 2026-11-10
|
||||
(euler/simple, 16 steps, cfg 1, empty negative; BFL's prompt upsampler `Pup`
|
||||
with its system prompt; `TARGET CANVAS: w:h` header). The client patches only
|
||||
node 6 (size), 7 (seed) and 11 (upsampler prompt), or removes nodes 10-11 and
|
||||
sets node 4's text for `--no-enhance`. Node ids are the contract between the
|
||||
client and the graph. If the playground's graph changes, re-copy it.
|
||||
|
||||
Graphs are found next to the script (`graphs/`) or in `RAVEN_GRAPHS`.
|
||||
Install: put this directory under `/opt/commons/opt/raven-image/` and symlink
|
||||
`raven-image` into `/opt/commons/bin/` (root-owned; ask `@eureka`).
|
||||
|
||||
## Licence: concept art only until ruled
|
||||
|
||||
Text read 2026-11-10 from `huggingface.co/black-forest-labs/flux-3-image-klein-comfy`
|
||||
(`LICENSE.md`, FLUX Kommunity License v.1.0; the model card is gated, the
|
||||
`resolve/main/LICENSE.md` URL answered 200). Quotes, not legal advice:
|
||||
|
||||
- **Outputs:** "Output does not include any components of the FLUX Model". Outputs are
|
||||
not Derivatives ("Outputs are not considered Derivatives under this License").
|
||||
"We claim no ownership rights in and to the Outputs. You are solely responsible for
|
||||
the Outputs you generate and their subsequent uses in accordance with this License."
|
||||
- **Commercial use of outputs** (2.a): only "solely if you are a Qualifying User, use
|
||||
Outputs ... for commercial purposes". "Qualifying User" means "you, if at any time
|
||||
you together with your affiliates' gross annualized revenue is less than
|
||||
US$5,000,000". Otherwise use is limited to "Non-Commercial Purposes", which excludes
|
||||
"use (a) for revenue-generating activity (including ... in a production
|
||||
environment), (b) in direct interactions with or that has impact on end users".
|
||||
- **Conditions for a Qualifying User** (2.e): "implement and maintain content
|
||||
filtering measures" or "ensure Output undergoes review for unlawful or infringing
|
||||
content before public or non-public distribution", and "ensure Output includes
|
||||
disclosures ... that the Output was generated or modified using artificial
|
||||
intelligence technologies to the extent required under applicable law".
|
||||
- **Training on outputs** (4.b): you will not "use the FLUX Model, any Derivatives, or
|
||||
any Output or results from the FLUX Model or Derivative to improve any other
|
||||
artificial intelligence model that performs any function similar to a FLUX Model".
|
||||
Derivative (iii) also covers models trained on "synthetic-data Outputs".
|
||||
- **Derivatives and distribution:** fine-tunes and the weights may be Distributed only
|
||||
with the licence copy and the Attribution Notice (3.a-b); the licence is
|
||||
"non-transferable, non-sublicensable". Shipping *weights* is not what we do.
|
||||
- **Shipping outputs in a product:** the text has no clause about it. It is commercial
|
||||
use of Outputs, so 2.a and 2.e govern. GameCult's revenue vs the US$5M line, who
|
||||
counts as an affiliate, and what a Mind's concept art feeding a shipped product
|
||||
counts as are not answered by the text and need a ruling from whoever holds the
|
||||
legal root. Termination is automatic on breach (8.a).
|
||||
- Section 4.a also bars "any data produced by the FLUX Model" for "military purposes",
|
||||
surveillance, biometric processing, and for infringing third-party rights,
|
||||
"digital replica" rights included: no likenesses of real people.
|
||||
|
||||
Check run 2026-11-10: `raven-image "concept art: a lighthouse on a basalt cliff at dusk, storm clouds, a small ferry below" -n 2` made two 1536x1024 images (81 s cold, 45 s warm), then freed VRAM.
|
||||
|
||||
Until that ruling: concept art, not shipped assets, and nothing generated here goes
|
||||
into a training set.
|
||||
174
client/graphs/flux3-klein-edit.json
Normal file
174
client/graphs/flux3-klein-edit.json
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
{
|
||||
"1": {
|
||||
"class_type": "UNETLoader",
|
||||
"inputs": {
|
||||
"unet_name": "flux3-image-klein-int8-convrot.safetensors",
|
||||
"weight_dtype": "default"
|
||||
}
|
||||
},
|
||||
"2": {
|
||||
"class_type": "CLIPLoader",
|
||||
"inputs": {
|
||||
"clip_name": "qwen3vl_4b_int8_convrot.safetensors",
|
||||
"type": "flux3",
|
||||
"device": "default"
|
||||
}
|
||||
},
|
||||
"3": {
|
||||
"class_type": "VAELoader",
|
||||
"inputs": {
|
||||
"vae_name": "flux2-vae.safetensors"
|
||||
}
|
||||
},
|
||||
"4": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {
|
||||
"clip": [
|
||||
"2",
|
||||
0
|
||||
],
|
||||
"text": [
|
||||
"11",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"5": {
|
||||
"class_type": "ConditioningZeroOut",
|
||||
"inputs": {
|
||||
"conditioning": [
|
||||
"4",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"6": {
|
||||
"class_type": "EmptyFlux2LatentImage",
|
||||
"inputs": {
|
||||
"width": 1536,
|
||||
"height": 1024,
|
||||
"batch_size": 1
|
||||
}
|
||||
},
|
||||
"7": {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"model": [
|
||||
"1",
|
||||
0
|
||||
],
|
||||
"positive": [
|
||||
"13",
|
||||
0
|
||||
],
|
||||
"negative": [
|
||||
"13",
|
||||
1
|
||||
],
|
||||
"latent_image": [
|
||||
"6",
|
||||
0
|
||||
],
|
||||
"seed": 0,
|
||||
"steps": 16,
|
||||
"cfg": 1,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
"denoise": 1
|
||||
}
|
||||
},
|
||||
"8": {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {
|
||||
"samples": [
|
||||
"7",
|
||||
0
|
||||
],
|
||||
"vae": [
|
||||
"3",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"9": {
|
||||
"class_type": "PreviewImage",
|
||||
"inputs": {
|
||||
"images": [
|
||||
"8",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"10": {
|
||||
"class_type": "CLIPLoader",
|
||||
"inputs": {
|
||||
"clip_name": "qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors",
|
||||
"type": "flux3",
|
||||
"device": "default"
|
||||
}
|
||||
},
|
||||
"11": {
|
||||
"class_type": "TextGenerate",
|
||||
"inputs": {
|
||||
"clip": [
|
||||
"10",
|
||||
0
|
||||
],
|
||||
"prompt": "",
|
||||
"max_length": 3584,
|
||||
"sampling_mode": "on",
|
||||
"sampling_mode.temperature": 1,
|
||||
"sampling_mode.top_k": 1,
|
||||
"sampling_mode.top_p": 0.95,
|
||||
"sampling_mode.min_p": 0,
|
||||
"sampling_mode.repetition_penalty": 1.05,
|
||||
"sampling_mode.seed": 0,
|
||||
"thinking": false,
|
||||
"use_default_template": true,
|
||||
"mtp": "off",
|
||||
"system_prompt": "You are the prompt upsampler of an image-editing model. You see the reference image(s), attached in order (the first image, the second image, ...), and the user's short request. Expand it into ONE detailed, self-contained instruction: the caption the editing model receives together with the same images. Output only the instruction as one continuous English prose block, with no greetings, explanations, Markdown, JSON, coordinates, ids or angle-bracket tokens. Read a vague or conversational request as the most plausible edit of the supplied images.\\n\\nPick the voice by task shape. When one reference stays and gets bounded changes, write an imperative editing instruction on it (\\\"Remove the ...\\\", \\\"Change the ... to ...\\\", \\\"Zoom in on ...\\\"); a whole-image transformation opens with its scope (\\\"Convert the entire image into ...\\\", \\\"Apply a ... filter over the entire scene\\\", \\\"Horizontally flip the entire image so that ...\\\", \\\"Shift the camera viewpoint to ...\\\", then where the major elements should now be). When the references are drawn into a newly composed frame (combining subjects, a new scene, a garment, object or style donor), write a generation request (\\\"Create a photograph of ...\\\", \\\"Create an anime-style illustration of ...\\\", \\\"Generate a new image featuring ...\\\") that says what to take from each image, by ordinal, and what is newly generated.\\n\\nKeep every explicit edit, constraint, count, position, style cue and piece of wording, and decide what is left open as one concrete plan. Ground everything in what is actually visible: identify each referent unambiguously by its real appearance, never mention content that is not there, and use every image the user attached. State every end state concretely (which color, how large, which pose, which material) and give new content enough appearance to be generated. Cover the knock-on effects of the change (shadows, reflections, occlusion, perspective, scale, lighting) and say what fills a removed region. A zoom-in names what stays in frame and which neighbors are cropped out; an outpainting continues the scene in the same medium. Describe the change, not the whole scene, and close an editing instruction with one compact clause naming what stays unchanged; transferred people keep their identity, face and accessories unless asked otherwise. Transcribe on-image text verbatim in its original language inside double quotes, with line breaks as \\\\n, and match the original font, size and color when replacing it. Name recognizable public figures, brands and landmarks you can see. Directions are frame-relative; use no evaluative or quality words. Typical length is 50 to 150 words.\\n\\nOutput only the instruction.",
|
||||
"image": [
|
||||
"14",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"12": {
|
||||
"class_type": "LoadImage",
|
||||
"inputs": {
|
||||
"image": "ref0.png"
|
||||
}
|
||||
},
|
||||
"13": {
|
||||
"class_type": "ReferenceMultiLatent",
|
||||
"inputs": {
|
||||
"positive": [
|
||||
"4",
|
||||
0
|
||||
],
|
||||
"negative": [
|
||||
"5",
|
||||
0
|
||||
],
|
||||
"vae": [
|
||||
"3",
|
||||
0
|
||||
],
|
||||
"resolution": "resize",
|
||||
"resolution.megapixels": 1.0,
|
||||
"images.image0": [
|
||||
"12",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"14": {
|
||||
"class_type": "BatchImagesNode",
|
||||
"inputs": {
|
||||
"images.image0": [
|
||||
"12",
|
||||
0
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
133
client/graphs/flux3-klein.json
Normal file
133
client/graphs/flux3-klein.json
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
{
|
||||
"1": {
|
||||
"class_type": "UNETLoader",
|
||||
"inputs": {
|
||||
"unet_name": "flux3-image-klein-int8-convrot.safetensors",
|
||||
"weight_dtype": "default"
|
||||
}
|
||||
},
|
||||
"2": {
|
||||
"class_type": "CLIPLoader",
|
||||
"inputs": {
|
||||
"clip_name": "qwen3vl_4b_int8_convrot.safetensors",
|
||||
"type": "flux3",
|
||||
"device": "default"
|
||||
}
|
||||
},
|
||||
"3": {
|
||||
"class_type": "VAELoader",
|
||||
"inputs": {
|
||||
"vae_name": "flux2-vae.safetensors"
|
||||
}
|
||||
},
|
||||
"4": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {
|
||||
"clip": [
|
||||
"2",
|
||||
0
|
||||
],
|
||||
"text": [
|
||||
"11",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"5": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {
|
||||
"clip": [
|
||||
"2",
|
||||
0
|
||||
],
|
||||
"text": ""
|
||||
}
|
||||
},
|
||||
"6": {
|
||||
"class_type": "EmptyFlux2LatentImage",
|
||||
"inputs": {
|
||||
"width": 1536,
|
||||
"height": 1024,
|
||||
"batch_size": 1
|
||||
}
|
||||
},
|
||||
"7": {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"model": [
|
||||
"1",
|
||||
0
|
||||
],
|
||||
"positive": [
|
||||
"4",
|
||||
0
|
||||
],
|
||||
"negative": [
|
||||
"5",
|
||||
0
|
||||
],
|
||||
"latent_image": [
|
||||
"6",
|
||||
0
|
||||
],
|
||||
"seed": 0,
|
||||
"steps": 16,
|
||||
"cfg": 1,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
"denoise": 1
|
||||
}
|
||||
},
|
||||
"8": {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {
|
||||
"samples": [
|
||||
"7",
|
||||
0
|
||||
],
|
||||
"vae": [
|
||||
"3",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"9": {
|
||||
"class_type": "PreviewImage",
|
||||
"inputs": {
|
||||
"images": [
|
||||
"8",
|
||||
0
|
||||
]
|
||||
}
|
||||
},
|
||||
"10": {
|
||||
"class_type": "CLIPLoader",
|
||||
"inputs": {
|
||||
"clip_name": "qwen3.5_9b_flux3_prompt_upsampler_w4a8.safetensors",
|
||||
"type": "flux3",
|
||||
"device": "default"
|
||||
}
|
||||
},
|
||||
"11": {
|
||||
"class_type": "TextGenerate",
|
||||
"inputs": {
|
||||
"clip": [
|
||||
"10",
|
||||
0
|
||||
],
|
||||
"prompt": "TARGET CANVAS: 3:2\nPROMPT",
|
||||
"max_length": 3584,
|
||||
"sampling_mode": "on",
|
||||
"sampling_mode.temperature": 1,
|
||||
"sampling_mode.top_k": 1,
|
||||
"sampling_mode.top_p": 0.95,
|
||||
"sampling_mode.min_p": 0,
|
||||
"sampling_mode.repetition_penalty": 1.05,
|
||||
"sampling_mode.seed": 0,
|
||||
"thinking": false,
|
||||
"use_default_template": true,
|
||||
"mtp": "off",
|
||||
"system_prompt": "You are the prompt upsampler of a text-to-image model. Expand the user's short request into ONE detailed, self-contained caption: the exact text the image model receives. Output only the caption, with no greetings, explanations, refusals, questions, Markdown, headings, JSON, coordinates, ids or angle-bracket tokens, and no quotes around it. If the input is not clearly an image request, caption a visualization of its concept. The request may begin with a \"TARGET CANVAS: W:H\" line: compose for that canvas (wide spreads content sideways, tall stacks it) and never mention the ratio or the canvas.\n\nFidelity and planning: keep every explicit subject, attribute, count, spatial constraint, style cue and piece of wording; never contradict, substitute, drop or narrow the request, and keep an abstract concept abstract. Decide everything left open as ONE concrete, consistent plan; never offer alternatives or hedge. Never re-express a stated constraint through another mechanism; add camera optics (depth of field, bokeh, blur) only when asked for or implied. Without a stated style, plan an actual photograph and open with the medium convention (\"Full-color outdoor photograph, ...\", \"Full-color indoor photograph, ...\", \"Studio photograph, ...\", \"Close-up photograph, ...\"); keep \"Photorealistic\" for renders, and turn \"photorealistic\" or \"realistic\" requests for photos into the photograph convention. Give a photograph a few ordinary, non-ideal specifics drawn from the scene's own objects instead of the stock-photo ideal. Do not invent names, brands, logos or celebrities; keep user-named ones. A long request keeps its content but not its wording: drop appraisal and sales vocabulary, turn moods into observable physical facts, and add only new concrete content with positions. Time of day is lighting, not rendered text.\n\nCaption format: one continuous prose block in the generative voice, never \"this image shows\", \"we can see\" or \"is visible\". Lead with medium and style, then scene, lighting and camera, then the subjects with concrete colors, materials and state. Every person in focus gets an observable profile: ethnicity, gender, age range, skin tone (\"fair skin\", \"brown skin\"), hair and clothing. Make the layout reconstructable from words: frame-relative positions (frame-left, frame-right, upper, lower, foreground, midground, background), sentence-initial anchors (\"On the left, ...\", \"In the background, ...\"), relations (holds, faces, behind) and a consistent order; describe up to about ten instances one by one, beyond that give the exact count and arrangement. Out-of-focus or distant planes are shapes, colors and silhouettes, never identities or readable text, and the background takes about a sixth of the caption. Be definite: no hedging adverbs, no quality or emotion judgments, no closing sentence about mood; state negations as what is present. Rendered text: transcribe every wording verbatim inside double quotes in its original language and script, keep the line breaks of multi-line text, and give its typography, color and placement; author concrete, domain-correct wording when the request needs text it does not supply, and name canonical structures (calendar, keyboard, periodic table) exactly with their full layout. All prose is English; only quoted text keeps its language. Typical length is 100 to 350 words, more for complex scenes.\n\nOutput only the caption.\n"
|
||||
}
|
||||
}
|
||||
}
|
||||
201
client/raven-image
Normal file
201
client/raven-image
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
#!/usr/bin/env python3
|
||||
"""raven-image: text-to-image on Raven's ComfyUI (Yggdrasil-only, http://10.77.0.4:8190).
|
||||
|
||||
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, stat, sys, time, urllib.error, urllib.parse, urllib.request
|
||||
|
||||
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
|
||||
MAX_REF = 20 * 2 ** 20 # bytes; refs persist in Raven's input folder, so cap what we put there
|
||||
MAGIC = ((b"\x89PNG\r\n\x1a\n", None), (b"\xff\xd8\xff", None), (b"RIFF", b"WEBP")) # png, jpeg, webp (bytes 8-12)
|
||||
|
||||
|
||||
class Busy(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def graph_dir():
|
||||
here = os.path.dirname(os.path.realpath(__file__))
|
||||
for d in (os.environ.get("RAVEN_GRAPHS"), os.path.join(here, "graphs")):
|
||||
if d and os.path.isdir(d):
|
||||
return d
|
||||
sys.exit("raven-image: no graphs/ directory (set RAVEN_GRAPHS)")
|
||||
|
||||
|
||||
def call(method, path, body=None, timeout=30):
|
||||
req = urllib.request.Request(BASE + path, method=method,
|
||||
data=None if body is None else json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.read()
|
||||
except urllib.error.HTTPError:
|
||||
raise
|
||||
except (urllib.error.URLError, OSError) as e: # refused, timed out, unroutable
|
||||
raise Busy(str(e))
|
||||
|
||||
|
||||
def load_ref(arg):
|
||||
"""Validate a --ref before anything is uploaded; returns the image bytes. Errors name the argument as typed."""
|
||||
p = os.path.realpath(arg)
|
||||
# O_NONBLOCK so a FIFO swapped in after any earlier check cannot hang open(); judge the opened descriptor, not the path.
|
||||
try:
|
||||
fd = os.open(p, os.O_RDONLY | os.O_NONBLOCK)
|
||||
except FileNotFoundError:
|
||||
sys.exit(f"raven-image: --ref {arg!r}: no such file")
|
||||
except OSError as e:
|
||||
sys.exit(f"raven-image: --ref {arg!r}: {e.strerror}")
|
||||
try:
|
||||
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
||||
sys.exit(f"raven-image: --ref {arg!r}: not a regular file")
|
||||
with os.fdopen(fd, "rb") as f:
|
||||
fd = -1
|
||||
data = f.read(MAX_REF + 1)
|
||||
except OSError as e:
|
||||
sys.exit(f"raven-image: --ref {arg!r}: {e.strerror}")
|
||||
finally:
|
||||
if fd >= 0:
|
||||
os.close(fd)
|
||||
if len(data) > MAX_REF:
|
||||
sys.exit(f"raven-image: --ref {arg!r}: larger than {MAX_REF // 2 ** 20} MiB")
|
||||
if not any(data.startswith(m) and (t is None or data[8:12] == t) for m, t in MAGIC):
|
||||
sys.exit(f"raven-image: --ref {arg!r}: not a png, jpeg or webp image")
|
||||
return data
|
||||
|
||||
|
||||
def safe_name(arg):
|
||||
base = os.path.basename(arg) or "ref"
|
||||
return "".join(c if c.isascii() and (c.isalnum() or c in "._-") else "_" for c in base)[-80:]
|
||||
|
||||
|
||||
def upload(arg, data):
|
||||
"""POST /upload/image (multipart); returns the name ComfyUI stored it under."""
|
||||
name = "raven-image-" + os.urandom(4).hex() + "-" + safe_name(arg)
|
||||
b = "----ravenimage" + os.urandom(8).hex()
|
||||
parts = [("--%s\r\nContent-Disposition: form-data; name=\"image\"; filename=\"%s\"\r\n"
|
||||
"Content-Type: application/octet-stream\r\n\r\n" % (b, name)).encode(), data,
|
||||
("\r\n--%s\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n--%s--\r\n" % (b, b)).encode()]
|
||||
req = urllib.request.Request(BASE + "/upload/image", method="POST", data=b"".join(parts),
|
||||
headers={"Content-Type": "multipart/form-data; boundary=" + b})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
return json.loads(r.read())["name"]
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.exit(f"raven-image: Raven rejected the reference upload: {e.read().decode()[:800]}")
|
||||
except (urllib.error.URLError, OSError) as e:
|
||||
raise Busy(str(e))
|
||||
|
||||
|
||||
def build(name, text, w, h, seed, enhance, refs=(), vision=False):
|
||||
with open(os.path.join(graph_dir(), name + ".json")) as f:
|
||||
g = json.load(f)
|
||||
g["6"]["inputs"].update(width=w, height=h)
|
||||
g["7"]["inputs"]["seed"] = seed
|
||||
for i, r in enumerate(refs): # node 12 is ref 0; the rest join the reference latent and the upsampler's view
|
||||
k = "12" if i == 0 else f"2{i}"
|
||||
g[k] = {"class_type": "LoadImage", "inputs": {"image": r}}
|
||||
g["13"]["inputs"][f"images.image{i}"] = [k, 0]
|
||||
g["14"]["inputs"][f"images.image{i}"] = [k, 0]
|
||||
if refs and not enhance:
|
||||
del g["14"]
|
||||
# node 4 (the text encoder) is decided once, here: its prompt is the upsampler's output (a link) or the caption itself
|
||||
prompt = ["11", 0] if enhance else text
|
||||
if vision: # the encoder sees the refs too (vision tower); no vae, so ReferenceMultiLatent stays the only latent path
|
||||
enc = {"clip": ["2", 0], "prompt": prompt}
|
||||
enc.update({f"image{i + 1}": [("12" if i == 0 else f"2{i}"), 0] for i in range(min(len(refs), 3))})
|
||||
g["4"] = {"class_type": "TextEncodeQwenImageEditPlus", "inputs": enc}
|
||||
else:
|
||||
g["4"]["inputs"]["text"] = prompt
|
||||
if enhance:
|
||||
d = math.gcd(w, h)
|
||||
g["11"]["inputs"]["prompt"] = text if refs else f"TARGET CANVAS: {w // d}:{h // d}\n{text}"
|
||||
else:
|
||||
for k in ("10", "11"):
|
||||
del g[k]
|
||||
return g
|
||||
|
||||
|
||||
def render(g, timeout):
|
||||
try:
|
||||
r = json.loads(call("POST", "/prompt", {"prompt": g, "client_id": "raven-image"}))
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.exit(f"raven-image: Raven rejected the graph: {e.read().decode()[:800]}")
|
||||
pid = r["prompt_id"]
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
h = json.loads(call("GET", f"/history/{pid}")).get(pid)
|
||||
if not h:
|
||||
continue
|
||||
st = h.get("status", {})
|
||||
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():
|
||||
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)
|
||||
if st.get("completed"):
|
||||
sys.exit("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 free_if_idle():
|
||||
q = json.loads(call("GET", "/queue"))
|
||||
if not q.get("queue_running") and not q.get("queue_pending"):
|
||||
call("POST", "/free", {"unload_models": True, "free_memory": True})
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("prompt", help="short prompt; the upsampler expands it unless --no-enhance")
|
||||
ap.add_argument("-o", "--out", default="raven.png", help="output file; with -n>1 gets -1, -2... before the extension")
|
||||
ap.add_argument("-n", type=int, default=1, help="images to render, one after another")
|
||||
ap.add_argument("--size", default="1536x1024", help="WxH, multiples of 16")
|
||||
ap.add_argument("--seed", type=int, help="seed of the first image (default random); image i uses seed+i")
|
||||
ap.add_argument("--ref", metavar="IMAGE", action="append", default=[],
|
||||
help="reference image, repeatable; runs graphs/flux3-klein-edit. The prompt cites them as "
|
||||
"<ref_image_0>, <ref_image_1>... in order and is a full caption of the result with the edit folded in")
|
||||
ap.add_argument("--vision", action="store_true",
|
||||
help="with --ref: also feed the first 3 refs to the text encoder (TextEncodeQwenImageEditPlus, no vae)")
|
||||
ap.add_argument("--graph", help="graphs/<name>.json (default flux3-klein, or flux3-klein-edit with --ref)")
|
||||
ap.add_argument("--no-enhance", action="store_true", help="send the prompt as the caption, skip the upsampler")
|
||||
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()
|
||||
if a.vision and not a.ref:
|
||||
ap.error("--vision needs at least one --ref")
|
||||
if a.graph and (a.graph == "flux3-klein-edit") != bool(a.ref):
|
||||
ap.error("--ref and graph flux3-klein-edit go together (the edit graph needs refs, other graphs cannot take them)")
|
||||
a.graph = a.graph or ("flux3-klein-edit" if a.ref else "flux3-klein")
|
||||
ref_data = [load_ref(r) for r in a.ref] # everything refusable is refused before the first request
|
||||
w, h = (int(v) for v in a.size.lower().split("x"))
|
||||
seed0 = a.seed if a.seed is not None else random.randrange(2 ** 48)
|
||||
root, ext = os.path.splitext(a.out)
|
||||
try:
|
||||
call("GET", "/system_stats", timeout=5)
|
||||
refs = [upload(r, d) for r, d in zip(a.ref, ref_data)]
|
||||
for i in range(a.n):
|
||||
seed = seed0 + i
|
||||
t = time.time()
|
||||
png = render(build(a.graph, a.prompt, w, h, seed, not a.no_enhance, refs, a.vision), a.timeout)
|
||||
path = a.out if a.n == 1 else f"{root}-{i + 1}{ext}"
|
||||
with open(path, "wb") as f:
|
||||
f.write(png)
|
||||
print(f"{path} seed={seed} {w}x{h} {time.time() - t:.0f}s", flush=True)
|
||||
if not a.keep_loaded:
|
||||
print("freed Raven's VRAM" if free_if_idle() else "queue not empty, left models loaded")
|
||||
except Busy as e:
|
||||
print(f"raven-image: Raven may be busy or off ({BASE}: {e}). Not retrying; try again later. "
|
||||
"Most likely cause after a Raven reboot: the lock screen (the ComfyUI task needs someone logged in on Raven's desktop). "
|
||||
"A read timeout mid-render also lands here.", file=sys.stderr)
|
||||
sys.exit(EX_BUSY)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
99
comfy-nodes/flux3_caption_span.py
Normal file
99
comfy-nodes/flux3_caption_span.py
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
"""Flux3 caption-span encoder: encode reference image + caption together in the Qwen3-VL encoder, then control how
|
||||
much of the image side of the hidden states reaches the DiT.
|
||||
|
||||
Stock TextEncodeQwenImageEditPlus returns every position, image tokens included. Here the image positions (the
|
||||
vision-tower tokens that replaced <|image_pad|>) are first average-pooled down to pool_tokens positions (0 = keep all),
|
||||
then multiplied by alpha. alpha 1 with no pooling is stock (arm B); alpha 0 drops the positions altogether (arm C:
|
||||
caption-only, image-informed, because the caption and template tokens keep the hidden states they got by attending to
|
||||
the image); alpha > 1 over-weights them. No vae input: reference latents are ReferenceMultiLatent's job, as in arm A.
|
||||
|
||||
One image only. Install: copy this file to ComfyUI/custom_nodes/ on Raven and restart ComfyUI.
|
||||
Written against ComfyUI master 74eb0c4 (0.45.0); Raven runs 0.44.0.
|
||||
"""
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
import comfy.utils
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
|
||||
TEMPLATE = ("<|im_start|>system\nDescribe the key features of the input image (color, shape, size, texture, objects, "
|
||||
"background), then explain how the user's text instruction should alter or modify the image. Generate a new "
|
||||
"image that meets the user's requirements while maintaining consistency with the original input where "
|
||||
"appropriate.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n")
|
||||
IMAGE_PROMPT = "Picture 1: <|vision_start|><|image_pad|><|vision_end|>"
|
||||
|
||||
|
||||
def splice(t, start, n, alpha, pool_tokens=0):
|
||||
"""t [B, L, C]: positions [start, start+n) become alpha * (optionally pooled) positions; alpha 0 removes them."""
|
||||
head, span, tail = t[:, :start], t[:, start:start + n], t[:, start + n:]
|
||||
if alpha == 0:
|
||||
return torch.cat([head, tail], dim=1)
|
||||
if pool_tokens > 0:
|
||||
span = F.adaptive_avg_pool1d(span.transpose(1, 2).float(), pool_tokens).transpose(1, 2).to(t.dtype)
|
||||
return torch.cat([head, span * alpha, tail], dim=1)
|
||||
|
||||
|
||||
def image_span(token_list, out_len):
|
||||
"""(start, n) of the image positions in the encoder output, from the tokenizer's list and the output length."""
|
||||
idx = [i for i, e in enumerate(token_list) if isinstance(e[0], dict) and e[0].get("type") == "image"]
|
||||
if len(idx) != 1:
|
||||
raise ValueError(f"expected exactly one image placeholder in the token list, found {len(idx)}")
|
||||
n = out_len - (len(token_list) - 1)
|
||||
if n <= 0:
|
||||
raise ValueError(f"output length {out_len} leaves no room for image tokens in a list of {len(token_list)}")
|
||||
return idx[0], n
|
||||
|
||||
|
||||
class Flux3CaptionSpanEncode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="Flux3CaptionSpanEncode",
|
||||
display_name="Flux3 Caption Span Encode (image seen, image positions dropped)",
|
||||
category="model/conditioning",
|
||||
inputs=[
|
||||
io.Clip.Input("clip"),
|
||||
io.String.Input("prompt", multiline=True, dynamic_prompts=True),
|
||||
io.Image.Input("image1"),
|
||||
io.Float.Input("alpha", default=1.0, min=0.0, max=4.0, step=0.05,
|
||||
tooltip="Scale of the image positions' hidden states. 0 drops them (arm C), 1 is stock, >1 over-weights."),
|
||||
io.Int.Input("pool_tokens", default=0, min=0, max=64,
|
||||
tooltip="0 keeps every image position; N>0 average-pools them to N first (arm C2)."),
|
||||
],
|
||||
outputs=[io.Conditioning.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, clip, prompt, image1, alpha=1.0, pool_tokens=0) -> io.NodeOutput:
|
||||
samples = image1.movedim(-1, 1)
|
||||
scale = math.sqrt(384 * 384 / (samples.shape[3] * samples.shape[2]))
|
||||
s = comfy.utils.common_upscale(samples, round(samples.shape[3] * scale), round(samples.shape[2] * scale), "area", "disabled")
|
||||
tokens = clip.tokenize(IMAGE_PROMPT + prompt, images=[s.movedim(1, -1)], llama_template=TEMPLATE)
|
||||
groups = next(iter(tokens.values()))
|
||||
if len(groups) != 1:
|
||||
raise ValueError(f"expected one token group, got {len(groups)}")
|
||||
cond = clip.encode_from_tokens_scheduled(tokens)
|
||||
out = []
|
||||
for t, d in cond:
|
||||
full = t.shape[1]
|
||||
start, n = image_span(groups[0], full)
|
||||
d = dict(d)
|
||||
kept = 0 if alpha == 0 else (pool_tokens or n)
|
||||
for k, v in d.items(): # position-indexed extras (attention masks) follow the same cut
|
||||
if torch.is_tensor(v) and v.dim() >= 2 and v.shape[1] == full:
|
||||
d[k] = torch.cat([v[:, :start], v[:, start:start + kept], v[:, start + n:]], dim=1)
|
||||
t2 = splice(t, start, n, alpha, pool_tokens)
|
||||
print(f"Flux3CaptionSpanEncode: {full} positions, image at [{start}, {start + n}) -> {t2.shape[1]} (alpha={alpha}, pool_tokens={pool_tokens})")
|
||||
out.append([t2, d])
|
||||
return io.NodeOutput(out)
|
||||
|
||||
|
||||
class Flux3CaptionSpanExtension(ComfyExtension):
|
||||
async def get_node_list(self):
|
||||
return [Flux3CaptionSpanEncode]
|
||||
|
||||
|
||||
async def comfy_entrypoint():
|
||||
return Flux3CaptionSpanExtension()
|
||||
65
deploy/raven/deploy.ps1
Normal file
65
deploy/raven/deploy.ps1
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
# Deploy GameCult/raven-image comfy-nodes/ to Raven's ComfyUI. Merging to main deploys.
|
||||
# Run every 10 minutes by the scheduled task \GameCult\Raven-Image-Deploy, as the logged-in desktop user.
|
||||
# - Reads main's commit from the forge; does nothing if it is the deployed one.
|
||||
# - Syncs comfy-nodes/*.py into ComfyUI's custom_nodes, and removes the nodes this script installed earlier and main
|
||||
# no longer has (managed.txt). Files it did not install are never touched.
|
||||
# - If a node file changed: restarts ComfyUI only when its queue is empty; otherwise it leaves state unwritten and
|
||||
# tries again next tick. If ComfyUI is not running (Deru closed it), it writes the files and restarts nothing.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Api = 'https://eureka.gamecult.org/forge/api/v1/repos/GameCult/raven-image'
|
||||
$Nodes = 'E:\ComfyUI\ComfyUI_windows_portable\ComfyUI\custom_nodes'
|
||||
$Home_ = 'E:\ComfyUI\raven-image-deploy'
|
||||
$State = Join-Path $Home_ 'deployed.txt'
|
||||
$Managed = Join-Path $Home_ 'managed.txt'
|
||||
$Log = Join-Path $Home_ 'deploy.log'
|
||||
New-Item -ItemType Directory -Force $Home_ | Out-Null
|
||||
function Log($m) { Add-Content -Path $Log -Value ("{0:u} {1}" -f (Get-Date), $m) }
|
||||
|
||||
try {
|
||||
$sha = (Invoke-RestMethod "$Api/branches/main" -TimeoutSec 30).commit.id
|
||||
if ($sha -notmatch '^[0-9a-f]{40}$') { Log "no plain sha from the forge: $sha"; exit 1 }
|
||||
$old = if (Test-Path $State) { (Get-Content $State -Raw).Trim() } else { '' }
|
||||
if ($old -eq $sha) { exit 0 }
|
||||
|
||||
$tmp = Join-Path $env:TEMP ("raven-image-" + $sha.Substring(0, 8))
|
||||
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory $tmp | Out-Null
|
||||
$zip = "$tmp.zip"
|
||||
Invoke-WebRequest "$Api/archive/$sha.zip" -OutFile $zip -TimeoutSec 120 -UseBasicParsing
|
||||
Expand-Archive $zip -DestinationPath $tmp -Force
|
||||
$src = Join-Path $tmp 'raven-image\comfy-nodes'
|
||||
$want = @(if (Test-Path $src) { Get-ChildItem $src -Filter '*.py' -File })
|
||||
|
||||
$prev = @(if (Test-Path $Managed) { Get-Content $Managed | Where-Object { $_ } })
|
||||
$changed = $false
|
||||
foreach ($f in $want) {
|
||||
$dest = Join-Path $Nodes $f.Name
|
||||
if (-not (Test-Path $dest) -or (Get-FileHash $dest).Hash -ne (Get-FileHash $f.FullName).Hash) { $changed = $true }
|
||||
}
|
||||
foreach ($n in $prev) { if ($want.Name -notcontains $n -and (Test-Path (Join-Path $Nodes $n))) { $changed = $true } }
|
||||
|
||||
$listening = Get-NetTCPConnection -LocalPort 8190 -LocalAddress 127.0.0.1 -State Listen -ErrorAction SilentlyContinue
|
||||
if ($changed -and $listening) {
|
||||
$q = Invoke-RestMethod 'http://127.0.0.1:8190/queue' -TimeoutSec 10
|
||||
if (@($q.queue_running).Count -gt 0 -or @($q.queue_pending).Count -gt 0) { Log "$($sha.Substring(0,8)): nodes changed, queue busy, retry next tick"; exit 0 }
|
||||
}
|
||||
|
||||
foreach ($f in $want) { Copy-Item $f.FullName (Join-Path $Nodes $f.Name) -Force }
|
||||
foreach ($n in $prev) { if ($want.Name -notcontains $n) { Remove-Item (Join-Path $Nodes $n) -Force -ErrorAction SilentlyContinue } }
|
||||
Set-Content -Path $Managed -Value ($want | ForEach-Object Name)
|
||||
|
||||
if ($changed -and $listening) {
|
||||
schtasks /end /tn '\GameCult\Image-Playground' | Out-Null
|
||||
Stop-Process -Id $listening.OwningProcess -Force -ErrorAction SilentlyContinue
|
||||
Start-Sleep 2
|
||||
schtasks /run /tn '\GameCult\Image-Playground' | Out-Null
|
||||
Log "$($sha.Substring(0,8)): nodes synced, ComfyUI restarted"
|
||||
} else {
|
||||
Log "$($sha.Substring(0,8)): synced (nodes changed: $changed, ComfyUI running: $([bool]$listening))"
|
||||
}
|
||||
Set-Content -Path $State -Value $sha
|
||||
Remove-Item -Recurse -Force $tmp, $zip -ErrorAction SilentlyContinue
|
||||
} catch {
|
||||
Log "failed: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
84
deploy/yggdrasil/install-raven-image
Normal file
84
deploy/yggdrasil/install-raven-image
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
#!/usr/bin/python3 -I
|
||||
"""Install the raven-image client on Yggdrasil from GameCult/raven-image main. Merging to main deploys.
|
||||
|
||||
Run as root by raven-image-deploy.timer. Reads the forge locally, so it needs no login and no DNS. When main moves,
|
||||
it unpacks `client/` of that commit into /opt/commons/opt/raven-image.releases/<sha8> (root-owned, no group or other
|
||||
write bit), points /opt/commons/opt/raven-image at it in one rename, and keeps the three newest releases. The client
|
||||
in /opt/commons/bin/raven-image is a symlink through that path, so a release swap is atomic for callers.
|
||||
Rollback: `ln -sfn raven-image.releases/<older sha8> /opt/commons/opt/raven-image.new && mv -T ... raven-image`.
|
||||
"""
|
||||
import io, json, os, shutil, sys, tarfile, urllib.request
|
||||
|
||||
FORGE = "http://127.0.0.1:3310/api/v1/repos/GameCult/raven-image"
|
||||
ROOT = "/opt/commons/opt"
|
||||
LINK = os.path.join(ROOT, "raven-image")
|
||||
RELEASES = os.path.join(ROOT, "raven-image.releases")
|
||||
BIN = "/opt/commons/bin/raven-image"
|
||||
KEEP = 3
|
||||
|
||||
|
||||
def get(url):
|
||||
with urllib.request.urlopen(url, timeout=60) as r:
|
||||
return r.read()
|
||||
|
||||
|
||||
def main():
|
||||
sha = json.loads(get(f"{FORGE}/branches/main"))["commit"]["id"]
|
||||
if not (len(sha) == 40 and all(c in "0123456789abcdef" for c in sha)):
|
||||
sys.exit(f"install-raven-image: forge gave no plain sha: {sha!r}")
|
||||
short = sha[:8]
|
||||
target = os.path.join(RELEASES, short)
|
||||
if os.path.islink(LINK) and os.readlink(LINK) == os.path.join("raven-image.releases", short):
|
||||
print(f"install-raven-image: {short} already live")
|
||||
return
|
||||
os.makedirs(RELEASES, exist_ok=True)
|
||||
if not os.path.isdir(target):
|
||||
tmp = target + ".partial"
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
os.makedirs(tmp)
|
||||
with tarfile.open(fileobj=io.BytesIO(get(f"{FORGE}/archive/{sha}.tar.gz")), mode="r:gz") as tf:
|
||||
for m in tf.getmembers():
|
||||
parts = m.name.split("/", 2) # raven-image/client/<path>
|
||||
if len(parts) < 3 or parts[1] != "client" or not parts[2]:
|
||||
continue
|
||||
if not (m.isfile() or m.isdir()) or ".." in parts[2].split("/"):
|
||||
continue
|
||||
dest = os.path.join(tmp, parts[2])
|
||||
if m.isdir():
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
continue
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
with open(dest, "wb") as f:
|
||||
f.write(tf.extractfile(m).read())
|
||||
if not os.path.isfile(os.path.join(tmp, "raven-image")):
|
||||
sys.exit("install-raven-image: commit has no client/raven-image; not installing")
|
||||
for d, dirs, files in os.walk(tmp):
|
||||
os.chmod(d, 0o755)
|
||||
for f in files:
|
||||
p = os.path.join(d, f)
|
||||
os.chmod(p, 0o755 if p == os.path.join(tmp, "raven-image") else 0o644)
|
||||
os.rename(tmp, target)
|
||||
if os.path.isdir(LINK) and not os.path.islink(LINK): # the hand install before this deploy existed
|
||||
os.rename(LINK, os.path.join(RELEASES, "hand-installed"))
|
||||
new = LINK + ".new"
|
||||
if os.path.lexists(new):
|
||||
os.remove(new)
|
||||
os.symlink(os.path.join("raven-image.releases", short), new)
|
||||
os.replace(new, LINK)
|
||||
want = os.path.join(LINK, "raven-image")
|
||||
if not os.path.islink(BIN) or os.readlink(BIN) != want:
|
||||
tmpbin = BIN + ".new"
|
||||
if os.path.lexists(tmpbin):
|
||||
os.remove(tmpbin)
|
||||
os.symlink(want, tmpbin)
|
||||
os.replace(tmpbin, BIN)
|
||||
kept = sorted((e for e in os.scandir(RELEASES) if e.is_dir() and not e.name.endswith(".partial") and e.name != "hand-installed"),
|
||||
key=lambda e: e.stat().st_mtime, reverse=True)
|
||||
for e in kept[KEEP:]:
|
||||
if e.name != short:
|
||||
shutil.rmtree(e.path)
|
||||
print(f"install-raven-image: {short} live")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
15
deploy/yggdrasil/raven-image-deploy.service
Normal file
15
deploy/yggdrasil/raven-image-deploy.service
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
[Unit]
|
||||
Description=Install the raven-image client from GameCult/raven-image main
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/python3 -I /usr/local/sbin/install-raven-image
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/opt/commons/opt /opt/commons/bin
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
NoNewPrivileges=yes
|
||||
RestrictAddressFamilies=AF_INET AF_INET6
|
||||
MemoryMax=256M
|
||||
Nice=10
|
||||
9
deploy/yggdrasil/raven-image-deploy.timer
Normal file
9
deploy/yggdrasil/raven-image-deploy.timer
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
[Unit]
|
||||
Description=Poll GameCult/raven-image main and install the client when it moves
|
||||
|
||||
[Timer]
|
||||
OnBootSec=2min
|
||||
OnUnitActiveSec=5min
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Loading…
Reference in a new issue