spine-parts 2.28.0 → 2.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.ts +28 -9
- package/docs/AUTHORING.md +12 -5
- package/docs/STABILITY.md +29 -5
- package/package.json +1 -1
- package/src/comfy/plate.ts +32 -15
- package/src/plate.ts +155 -11
package/cli.ts
CHANGED
|
@@ -25,7 +25,7 @@ import { parseAltArg } from './tools/alternate-cli.ts';
|
|
|
25
25
|
import { type AlternateCliInput, assembleStage, build, checkStage, ERROR_MAP_FILE, loopStage, readRuns, readSource, rigStage, suppliedCheckFlag } from './src/build.ts';
|
|
26
26
|
import { ACCEPTABLE_BARS, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, findRigc, PACK_SHAPES, rigcRunnerAt, type PackShape, PAGE_EDGES, type PageEdges, PARTS_HOME_SENTENCE, RIGC_GEOMETRY_VERSION, rigcRanClause, type RigcRunner, NO_PARTS_SENTENCE, SEAM_MEAN_BAR, SOURCE_SENTENCE, SEAM_PX_BAR, SEAM_PX_LEVEL, SPINEBOY_YARDSTICK, TEXTURE_STRETCH_CEILING } from './src/check.ts';
|
|
27
27
|
import { ComfyClient, resolveHost, runBackground, runMatte, runPainting, runSeeThrough } from './src/comfy/index.ts';
|
|
28
|
-
import { DEFAULT_GROW_PX, runForeground } from './src/plate.ts';
|
|
28
|
+
import { coreCfg, DEFAULT_GROW_PX, runForeground } from './src/plate.ts';
|
|
29
29
|
import { type CharacterConfig, loadClothConfig, loadConfig, loadEarlyConfig, loadPaintConfig } from './src/config.ts';
|
|
30
30
|
import { configWriteLines, readConfigWriteTarget, separateConfigWriteTarget, stageConfigWrite, type StagedConfigWrite } from './tools/configwrite.ts';
|
|
31
31
|
import { failLine, guidePointer, PartsError } from './src/errors.ts';
|
|
@@ -880,7 +880,7 @@ usage:
|
|
|
880
880
|
rig-parts comfy plate --mode background|foreground --painting <png>
|
|
881
881
|
--mask-from seethrough:<dir>|figure-mask:<dir>|matte:<dir> --out <dir>
|
|
882
882
|
[--graph lama|core] [--model <name>] [--checkpoint-sha256 <hex>]
|
|
883
|
-
[--seed 0] [--grow 8] [--steps 30] [--prompt <text>] [--negative <text>]
|
|
883
|
+
[--seed 0] [--grow 8] [--steps 30] [--cfg 6] [--prompt <text>] [--negative <text>]
|
|
884
884
|
[--host <url>] [--wait 1800] [--timeout 3600] [--poll 3]
|
|
885
885
|
A step-4 plate with a receipt: <out>/plate.png, mask.png and receipt.json
|
|
886
886
|
(spec rig-parts-plate-receipt/1). The mask comes from a source only — the
|
|
@@ -1181,7 +1181,7 @@ const TAKES = {
|
|
|
1181
1181
|
'comfy seethrough': { valued: ['--image', '--out', '--resolution', '--steps', '--seed', '--prefix', '--host', '--wait', '--timeout', '--poll', '--config', '--depth-run'], switches: ['--offload', '--no-offload', '--lama', '--nf4'] },
|
|
1182
1182
|
'comfy paint': { valued: ['--config', '--out', '--seeds', '--seed0', '--host', '--wait', '--timeout', '--poll'], switches: [] },
|
|
1183
1183
|
'comfy matte': { valued: ['--painting', '--out', '--node', '--model', '--checkpoint-sha256', '--resolution', '--threshold', '--host', '--wait', '--timeout', '--poll'], switches: [] },
|
|
1184
|
-
'comfy plate': { valued: ['--mode', '--painting', '--mask-from', '--out', '--graph', '--model', '--checkpoint-sha256', '--seed', '--grow', '--steps', '--prompt', '--negative', '--host', '--wait', '--timeout', '--poll'], switches: [] },
|
|
1184
|
+
'comfy plate': { valued: ['--mode', '--painting', '--mask-from', '--out', '--graph', '--model', '--checkpoint-sha256', '--seed', '--grow', '--steps', '--cfg', '--prompt', '--negative', '--host', '--wait', '--timeout', '--poll'], switches: [] },
|
|
1185
1185
|
inputs: { valued: ['--source', '--config', '--out'], switches: [] },
|
|
1186
1186
|
build: { valued: ['--config', '--source', '--full', '--head', '--out', '--seam', '--project', '--page-edges', '--pack-shape', '--requirements', '--idle-keys', '--lead-in', '--alt', '--set', '--environment', '--wind-band'], switches: ['--loop', '--seam-pairs', '--keep-stills', '--all-sets', '--no-extremes'] },
|
|
1187
1187
|
compose: { valued: ['--scene', '--out', '--requirements', '--accept'], switches: [] },
|
|
@@ -1342,7 +1342,23 @@ function isPackShape(v: PackShape | string): v is PackShape {
|
|
|
1342
1342
|
return (PACK_SHAPES as readonly string[]).includes(v);
|
|
1343
1343
|
}
|
|
1344
1344
|
|
|
1345
|
+
/** Resolve the optional stamp clock before either command touches output. */
|
|
1346
|
+
function runStampClock(): string | undefined {
|
|
1347
|
+
const value = process.env.SOURCE_DATE_EPOCH;
|
|
1348
|
+
if (value === undefined) return undefined;
|
|
1349
|
+
const millis = Number(value) * 1000;
|
|
1350
|
+
if (!/^(0|[1-9][0-9]*)$/.test(value) || !Number.isSafeInteger(millis) || Number(value) > 253402300799) {
|
|
1351
|
+
throw new PartsError([{
|
|
1352
|
+
code: 'RUN_STAMP_EPOCH', object: 'environment variable SOURCE_DATE_EPOCH',
|
|
1353
|
+
detail: `${JSON.stringify(value)} found; canonical non-negative integer seconds <= 253402300799 (9999-12-31T23:59:59Z) are required`,
|
|
1354
|
+
}]);
|
|
1355
|
+
}
|
|
1356
|
+
return new Date(millis).toISOString();
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1345
1359
|
function cmdRig(args: string[]): number {
|
|
1360
|
+
let fixedClock: string | undefined;
|
|
1361
|
+
try { fixedClock = runStampClock(); } catch (err) { return printRefusal(err); }
|
|
1346
1362
|
let config: string | null = null;
|
|
1347
1363
|
let partsDir: string | null = null;
|
|
1348
1364
|
let out: string | null = null;
|
|
@@ -1385,11 +1401,11 @@ function cmdRig(args: string[]): number {
|
|
|
1385
1401
|
return printRefusal(err);
|
|
1386
1402
|
}
|
|
1387
1403
|
const scratch = mkdtempSync(join(tmpdir(), 'rig-parts-rig-'));
|
|
1388
|
-
const startedAt = new Date().toISOString();
|
|
1404
|
+
const startedAt = fixedClock ?? new Date().toISOString();
|
|
1389
1405
|
try {
|
|
1390
1406
|
const pkg = readPackageIdentity(join(import.meta.dir, 'package.json'));
|
|
1391
1407
|
const rig = rigStage({ config, parts: partsDir, out, idleKeys: keys, pageEdges: edges, packShape: shape }, rigcRunner(bin), scratch, console.log);
|
|
1392
|
-
const finishedAt = new Date().toISOString();
|
|
1408
|
+
const finishedAt = fixedClock ?? new Date().toISOString();
|
|
1393
1409
|
writeRunStamp({ pkg, command: 'rig', startedAt, finishedAt, outDir: out, configPath: config, outputPaths: rigOutputFiles(rig) });
|
|
1394
1410
|
return EXIT_OK;
|
|
1395
1411
|
} catch (err) {
|
|
@@ -1846,6 +1862,8 @@ function cmdLoop(args: string[]): number {
|
|
|
1846
1862
|
}
|
|
1847
1863
|
|
|
1848
1864
|
function cmdAssemble(args: string[]): number {
|
|
1865
|
+
let fixedClock: string | undefined;
|
|
1866
|
+
try { fixedClock = runStampClock(); } catch (err) { return printRefusal(err); }
|
|
1849
1867
|
const flags = new Map<string, string>();
|
|
1850
1868
|
const alts: AlternateCliInput[] = [];
|
|
1851
1869
|
let propose = false;
|
|
@@ -1912,13 +1930,13 @@ function cmdAssemble(args: string[]): number {
|
|
|
1912
1930
|
const out = flags.get('--out') as string;
|
|
1913
1931
|
clearRunStamp(out);
|
|
1914
1932
|
const pkg = readPackageIdentity(join(import.meta.dir, 'package.json'));
|
|
1915
|
-
const startedAt = new Date().toISOString();
|
|
1933
|
+
const startedAt = fixedClock ?? new Date().toISOString();
|
|
1916
1934
|
const result = assembleStage(
|
|
1917
1935
|
{ source, full, head, config, ...(flags.has('--requirements') ? { requirements: flags.get('--requirements') as string } : {}), ...(seam === undefined ? {} : { seam: seam as SeamRule }), ...(project === undefined ? {} : { project: project as ProjectRule }), ...(alts.length === 0 ? {} : { alts }) },
|
|
1918
1936
|
{ partsJson: join(out, 'rig', 'parts.json'), partsDir: join(out, 'rig', 'parts'), recomposite: join(out, 'render', 'recomposite_rig.png'), errorMap: join(out, 'render', ERROR_MAP_FILE) },
|
|
1919
1937
|
console.log,
|
|
1920
1938
|
);
|
|
1921
|
-
const finishedAt = new Date().toISOString();
|
|
1939
|
+
const finishedAt = fixedClock ?? new Date().toISOString();
|
|
1922
1940
|
writeRunStamp({ pkg, command: 'assemble', startedAt, finishedAt, outDir: out, configPath: config, outputPaths: assembleOutputFiles(out, result) });
|
|
1923
1941
|
return EXIT_OK;
|
|
1924
1942
|
} catch (err) {
|
|
@@ -1969,7 +1987,7 @@ function secondsFlag(v: Map<string, string>, flag: string, fallback: number): nu
|
|
|
1969
1987
|
}
|
|
1970
1988
|
|
|
1971
1989
|
/** Flags `comfy plate --mode foreground` does not take: it runs no box and no model. */
|
|
1972
|
-
const PLATE_BOX_FLAGS = ['--graph', '--model', '--checkpoint-sha256', '--seed', '--grow', '--steps', '--prompt', '--negative', '--host', '--wait', '--timeout', '--poll'];
|
|
1990
|
+
const PLATE_BOX_FLAGS = ['--graph', '--model', '--checkpoint-sha256', '--seed', '--grow', '--steps', '--cfg', '--prompt', '--negative', '--host', '--wait', '--timeout', '--poll'];
|
|
1973
1991
|
|
|
1974
1992
|
async function cmdComfyPlate(v: Map<string, string>): Promise<number> {
|
|
1975
1993
|
const mode = v.get('--mode');
|
|
@@ -1999,11 +2017,12 @@ async function cmdComfyPlate(v: Map<string, string>): Promise<number> {
|
|
|
1999
2017
|
const steps = intFlag(v, '--steps', 30, 1);
|
|
2000
2018
|
for (const x of [seed, grow, steps]) if (typeof x === 'string') return usage(x);
|
|
2001
2019
|
if (graph === 'lama') for (const x of ['--steps', '--prompt', '--negative']) if (v.has(x)) return usage(`${x} is for --graph core; the lama graph takes no prompt and no steps`);
|
|
2020
|
+
const cfg = coreCfg(v.get('--cfg'), graph);
|
|
2002
2021
|
console.log(`rig-parts comfy plate: background (${graph}) ${painting} -> ${out}`);
|
|
2003
2022
|
// Every local refusal (no source mask, the checksum, the grid) comes before the host is resolved.
|
|
2004
2023
|
const r = await runBackground(
|
|
2005
2024
|
() => new ComfyClient(resolveHost(v.get('--host'), process.env.COMFY_HOST), { poll: poll as number, request: 30 }),
|
|
2006
|
-
{ painting, maskFrom: v.get('--mask-from'), out, graph, model: v.get('--model'), checkpointSha256: v.get('--checkpoint-sha256'), seed: seed as number, growPx: grow as number, steps: steps as number, prompt: v.get('--prompt'), negative: v.get('--negative'), wait: wait as number, timeout: timeout as number },
|
|
2025
|
+
{ painting, maskFrom: v.get('--mask-from'), out, graph, model: v.get('--model'), checkpointSha256: v.get('--checkpoint-sha256'), seed: seed as number, growPx: grow as number, steps: steps as number, ...(v.has('--cfg') ? { cfg } : {}), prompt: v.get('--prompt'), negative: v.get('--negative'), wait: wait as number, timeout: timeout as number },
|
|
2007
2026
|
(l) => console.log(l),
|
|
2008
2027
|
);
|
|
2009
2028
|
console.log(` wrote ${join(out, r.output.path)} (sha256 ${r.output.sha256}), ${r.mask.path} and receipt.json; model ${r.model?.name} (checkpoint sha256 declared), GPU ${r.gpu}`);
|
package/docs/AUTHORING.md
CHANGED
|
@@ -5133,6 +5133,7 @@ row in this page's `rule` and `line` tables; the selftest holds that (`TY16`).
|
|
|
5133
5133
|
|
|
5134
5134
|
| rule | means | change |
|
|
5135
5135
|
| --- | --- | --- |
|
|
5136
|
+
| <a id="RUN_STAMP_EPOCH"></a>`RUN_STAMP_EPOCH` | SOURCE_DATE_EPOCH is not canonical non-negative integer seconds at most 253402300799 (9999-12-31T23:59:59Z) | unset the variable for wall-clock stamps or supply integer seconds at most 253402300799 for four-digit-year ISO stamps; 253402300800 and above, empty, signs, fractions, whitespace and leading zeroes are refused before any output is touched |
|
|
5136
5137
|
| <a id="CONFIG_HYBRID_SOURCE"></a>`CONFIG_HYBRID_SOURCE` | the two hybrid neighbours name different source parts | use a single continuous source layer for the joint band |
|
|
5137
5138
|
| <a id="CONFIG_HYBRID_CUT"></a>`CONFIG_HYBRID_CUT` | a hybrid joint also declares a cut-cap option | remove cap, cap_shape, edge and cut_band at that joint |
|
|
5138
5139
|
| <a id="ASSEMBLE_HYBRID_SOURCE"></a>`ASSEMBLE_HYBRID_SOURCE` | effective alternate layer selection gives a band different upper and lower source layers | select the same continuous layer for both rigid neighbours |
|
|
@@ -5355,8 +5356,12 @@ or a joint.
|
|
|
5355
5356
|
inpaints it on a ComfyUI box. `--graph lama` (the default) uses the
|
|
5356
5357
|
comfyui-inpaint-nodes pack and its LaMa model (`--model`, default
|
|
5357
5358
|
`big-lama.pt`). `--graph core` uses ComfyUI's own nodes and the checkpoint
|
|
5358
|
-
`--model` names, with `--steps`, `--prompt` and `--negative`;
|
|
5359
|
-
|
|
5359
|
+
`--model` names, with `--steps`, `--cfg` (default 6), `--prompt` and `--negative`; when a painting's
|
|
5360
|
+
width or height is not a multiple of 8, it pads the uploaded painting (`edge-replicate`)
|
|
5361
|
+
and grown mask (`zero`, kept as context) on the right and bottom (`pad: [0, 0]`)
|
|
5362
|
+
to the next multiple of 8, crops the box's output back at `[0, 0]` before
|
|
5363
|
+
pasting inside the mask, and records `grid_transform` in `receipt.json`
|
|
5364
|
+
(on-grid paintings run unpadded and omit `grid_transform`). Every node, input and model of the
|
|
5360
5365
|
graph is checked against the box's `/object_info` before anything is
|
|
5361
5366
|
uploaded, so a box without the pack refuses `lama` and still runs `core`. The
|
|
5362
5367
|
job is appended behind any other job: never put in front, nothing reordered,
|
|
@@ -5400,10 +5405,12 @@ recorded transform. The record fields and sampling formula are specified in
|
|
|
5400
5405
|
| <a id="PLATE_MASK_SOURCE"></a><a id="PLATE_MASK_GRID"></a><a id="PLATE_MASK_VALUES"></a><a id="PLATE_MASK_EMPTY"></a>`PLATE_MASK_SOURCE`, `PLATE_MASK_GRID`, `PLATE_MASK_VALUES`, `PLATE_MASK_EMPTY` | no `--mask-from`, or a source directory holding no See-through run or no scene figure mask; a source on another grid without a valid recorded `input_transform`; a `figure_rig.png` holding other than opaque white and black; a mask with no figure pixel | run `comfy seethrough` on the original painting to record its input transform, or `assemble` with `config.scene` at the painting grid |
|
|
5401
5406
|
| <a id="PLATE_MASK_RUN"></a>`PLATE_MASK_RUN` | the figure source has no readable `rig-run/1` assemble `run.json`, or its `figure_rig.png`, `parts.json` or declared `painting_in_rig.png` lacks exactly one matching output hash; or the See-through source has no readable `meta.json` with `image_sha256` and `layers` hashes, or a layer PNG on disk lacks a matching `layers` entry | re-run `assemble` with the source config to regenerate `run.json` and its `rig/` files together, or re-run `comfy seethrough` on the painting to regenerate `meta.json` and `parts/` together |
|
|
5402
5407
|
| <a id="PLATE_MASK_PAINTING"></a>`PLATE_MASK_PAINTING` | `parts.json` has an invalid `painting_in_rig` declaration, its recorded painting is missing, undecodable or differs from its declared hash, or the supplied painting differs from the recorded opaque RGB; or the supplied painting's SHA-256 differs from a See-through source's `meta.json` `image_sha256` | use the original `--painting` file for this source, or re-run `assemble` or `comfy seethrough` on this painting |
|
|
5403
|
-
| <a id="PLATE_CHECKPOINT_SHA256"></a><a id="PLATE_MODEL_GIVEN"></a
|
|
5408
|
+
| <a id="PLATE_CHECKPOINT_SHA256"></a><a id="PLATE_MODEL_GIVEN"></a>`PLATE_CHECKPOINT_SHA256`, `PLATE_MODEL_GIVEN` | `--checkpoint-sha256` absent or not 64 hex characters; `--graph core` without `--model` | the flag |
|
|
5409
|
+
| <a id="PLATE_CORE_CFG"></a>`PLATE_CORE_CFG` | `--cfg` given with `--graph lama`, or not a finite number above 0 | `--cfg`, `--graph` |
|
|
5410
|
+
| <a id="PLATE_CORE_GRID"></a>PLATE_CORE_GRID *(retired)* | retired in 2.x: off-grid `core` now pads to the next multiple of 8 and records `grid_transform`; see [STABILITY](STABILITY.md#plate-receipt) | none |
|
|
5404
5411
|
| <a id="PLATE_PAINTING_PRESENT"></a><a id="PLATE_OUT_EMPTY"></a>`PLATE_PAINTING_PRESENT`, `PLATE_OUT_EMPTY` | no `--painting` file, or an `--out` that already holds entries | `--painting`, `--out` |
|
|
5405
|
-
| <a id="COMFY_GPU_NAMED"></a><a id="COMFY_PLATE_SIZE"></a>`COMFY_GPU_NAMED`, `COMFY_PLATE_SIZE` | `/system_stats` does not name exactly one device; the box's image is not the painting's size | the box |
|
|
5406
|
-
| <a id="PLATE_RECEIPT_READ"></a><a id="PLATE_RECEIPT_SPEC"></a><a id="PLATE_RECEIPT_KEYS"></a><a id="PLATE_RECEIPT_FILE"></a><a id="PLATE_RECEIPT_HASH"></a>`PLATE_RECEIPT_READ`, `PLATE_RECEIPT_SPEC`, `PLATE_RECEIPT_KEYS`, `PLATE_RECEIPT_FILE`, `PLATE_RECEIPT_HASH` | the receipt read back before it is published is not JSON, not this spec, not in its key order, names a file that is gone,
|
|
5412
|
+
| <a id="COMFY_GPU_NAMED"></a><a id="COMFY_PLATE_SIZE"></a>`COMFY_GPU_NAMED`, `COMFY_PLATE_SIZE` | `/system_stats` does not name exactly one device; the box's image is not the painting's size (or, for off-grid `core`, the padded size) | the box |
|
|
5413
|
+
| <a id="PLATE_RECEIPT_READ"></a><a id="PLATE_RECEIPT_SPEC"></a><a id="PLATE_RECEIPT_KEYS"></a><a id="PLATE_RECEIPT_FILE"></a><a id="PLATE_RECEIPT_HASH"></a><a id="PLATE_RECEIPT_GRID_TRANSFORM"></a>`PLATE_RECEIPT_READ`, `PLATE_RECEIPT_SPEC`, `PLATE_RECEIPT_KEYS`, `PLATE_RECEIPT_FILE`, `PLATE_RECEIPT_HASH`, `PLATE_RECEIPT_GRID_TRANSFORM` | the receipt read back before it is published is not JSON, not this spec, not in its key order, names a file that is gone, records a sha256 that is not the file's, or has a missing, unexpected, malformed or mismatched `grid_transform` | nothing to change by hand: the run is refused and `<out>` is not written |
|
|
5407
5414
|
| <a id="MATTE_MODEL"></a><a id="MATTE_MODEL_INSTALLED"></a>`MATTE_MODEL`, `MATTE_MODEL_INSTALLED` | absent or unsupported explicit node/model, or the supported weight file is absent from the server model listing | use `--node BiRefNetRMBG --model BiRefNet-HR-matting` with installed weights |
|
|
5408
5415
|
| <a id="MATTE_PARAMS"></a>`MATTE_PARAMS` | resolution is outside [64,2048] or not a multiple of 8, or threshold is outside integer [0,254] | set `--resolution` and `--threshold` within these bounds |
|
|
5409
5416
|
| <a id="MATTE_RECEIPT"></a><a id="MATTE_PAINTING"></a><a id="MATTE_HASH"></a>`MATTE_RECEIPT`, `MATTE_PAINTING`, `MATTE_HASH` | `matte:<dir>` lacks a complete ordered receipt, names another painting, or raw/final mask bytes differ from their recorded hashes | re-run `comfy matte` on the supplied painting and keep its receipt and both masks together |
|
package/docs/STABILITY.md
CHANGED
|
@@ -214,7 +214,7 @@ defaults are the help's too, and none is guessed from the art.
|
|
|
214
214
|
| `inputs` | `--source`, `--config`, `--out` |
|
|
215
215
|
| `comfy` | `paint`: `--config`, `--out`; optional `--seeds`, `--seed0`, `--host`, `--wait`, `--timeout`, `--poll` |
|
|
216
216
|
| `comfy` | `matte`: `--painting`, `--out`, `--node` (`BiRefNetRMBG`), `--model` (`BiRefNet-HR-matting`), `--checkpoint-sha256` (declared, required); optional `--resolution`, `--threshold`, `--host`, `--wait`, `--timeout`, `--poll` (issue #1204) |
|
|
217
|
-
| `comfy` | `plate`: `--mode` (`background` or `foreground`), `--painting`, `--mask-from` (`seethrough:<dir>`, `figure-mask:<dir>` or `matte:<dir>`), `--out`; with `--mode background` also `--checkpoint-sha256` (required) and optional `--graph` (`lama` or `core`), `--model` (required with `core`), `--seed`, `--grow`, `--steps`, `--prompt`, `--negative` (the last
|
|
217
|
+
| `comfy` | `plate`: `--mode` (`background` or `foreground`), `--painting`, `--mask-from` (`seethrough:<dir>`, `figure-mask:<dir>` or `matte:<dir>`), `--out`; with `--mode background` also `--checkpoint-sha256` (required) and optional `--graph` (`lama` or `core`), `--model` (required with `core`), `--seed`, `--grow`, `--steps`, `--cfg`, `--prompt`, `--negative` (the last four with `core` only), `--host`, `--wait`, `--timeout`, `--poll` (issue #1183, additive) |
|
|
218
218
|
| `comfy` | `seethrough`: `--image`, `--out`; optional `--resolution`, `--steps`, `--seed`, `--prefix`, `--offload`, `--no-offload`, `--lama`, `--nf4`, `--host`, `--wait`, `--timeout`, `--poll`, `--config` (See-through settings and optional depth block), `--depth-run` (`full` or `head`, required with the block) |
|
|
219
219
|
| `assemble` | `--propose-plan` with `--source`, `--full`, `--config`, optional `--head`, `--write-config` (must name `--config` itself, issue #356); or `--source`, `--full`, `--config`, `--out`, optional `--head` (without it, one run: issue #359), `--seam` (near-white, silhouette), `--project` (core, visible), `--alt` (repeatable `<name>=<source>:<full>[:<head>]`, issue #454), `--requirements` (source-bound cut-material evidence only when the file declares `cut_material`, issue #888) |
|
|
220
220
|
| `head-crop-preflight` | `--full`, `--canvas`, `--head-box` (JSON coordinate array); read-only advice before the head run, original alpha > 8 samples (issue #1082) |
|
|
@@ -448,13 +448,25 @@ new spec version. Every path in it is relative to the receipt's directory.
|
|
|
448
448
|
| `painting` | `{ path, sha256 }` of the painting read |
|
|
449
449
|
| `mask` | `{ source, from, path, sha256 }`: `source` is `"seethrough"`, `"figure-mask"` or `"matte"`, `from` the source directory, `path` the mask actually used (`mask.png`, opaque white inside) |
|
|
450
450
|
| `model` | `{ name, checkpoint_sha256, checkpoint_sha256_from }`, or null for `foreground`. `checkpoint_sha256` is the `--checkpoint-sha256` value, lower-cased; `checkpoint_sha256_from` is `"declared"`: the box reports no hash, so this field is **declared, not measured** |
|
|
451
|
-
| `params` | every parameter of the run, the seed included, in a fixed order per graph: `lama` — `seed`, `grow_px`, `mask_alpha_above`; `core` — `seed`, `grow_px`, `steps`, `cfg`, `sampler`, `scheduler`, `denoise`, `prompt`, `negative`, `mask_alpha_above`; `foreground` — `mask_alpha_above` |
|
|
451
|
+
| `params` | every parameter of the run, the seed included, in a fixed order per graph: `lama` — `seed`, `grow_px`, `mask_alpha_above`; `core` — `seed`, `grow_px`, `steps`, `cfg` (`--cfg`, default `6`), `sampler`, `scheduler`, `denoise`, `prompt`, `negative`, `mask_alpha_above`; `foreground` — `mask_alpha_above` |
|
|
452
452
|
| `graph` | `"rig-parts/plate-background-lama/1"`, `"rig-parts/plate-background-core/1"`, or the fixed local id `"rig-parts/plate-foreground/1"` |
|
|
453
453
|
| `gpu` | the device `/system_stats` names (the same seed gives other pixels on another GPU), or null for `foreground` |
|
|
454
|
+
| `grid_transform` | present only when `mode` is `"background"`, `graph` is `"rig-parts/plate-background-core/1"`, and the painting's width or height is not a multiple of 8 (issue #1209, additive): `{ source: [width, height], padded: [ceil(width/8)*8, ceil(height/8)*8], pad: [0, 0], pad_fill: "edge-replicate", mask_pad_fill: "zero", inverse: "crop" }` in that key order. Omitted for on-grid `core`, `lama`, and `foreground` |
|
|
454
455
|
| `output` | `{ path, sha256 }` of `plate.png` |
|
|
455
456
|
|
|
456
457
|
The receipt is read back against the bytes on disk before `<out>` is published;
|
|
457
|
-
a hash that is not its file's refuses the run.
|
|
458
|
+
a hash that is not its file's refuses the run. `verifyPlateReceipt` also
|
|
459
|
+
re-derives `grid_transform` from the decoded painting, `mode` and `graph`, and
|
|
460
|
+
refuses a missing, unexpected, malformed or mismatched transform as
|
|
461
|
+
`PLATE_RECEIPT_GRID_TRANSFORM`. For off-grid `--graph core` paintings, the
|
|
462
|
+
uploaded painting is padded on the right and bottom by replicating its edge
|
|
463
|
+
pixels (`pad_fill: "edge-replicate"`), the uploaded grown mask is padded with
|
|
464
|
+
zero (`mask_pad_fill: "zero"`, kept as context outside the hole), the box's
|
|
465
|
+
output is required at `padded` dimensions (`COMFY_PLATE_SIZE` otherwise) and
|
|
466
|
+
cropped at `[0, 0]` back to `source` before pasting inside the native mask, so
|
|
467
|
+
pixels outside the hole equal the painting byte for byte. On-grid `core`
|
|
468
|
+
paintings retain their original upload bytes, graph and 9-key receipt. Because
|
|
469
|
+
every painting grid is covered by this transform, `PLATE_CORE_GRID` is retired.
|
|
458
470
|
|
|
459
471
|
### Matte source receipt
|
|
460
472
|
|
|
@@ -676,12 +688,24 @@ Key order is fixed as shown; `outputs` is sorted by `/`-separated `path` in UTF-
|
|
|
676
688
|
code-unit order. Every `path` in `config` and `outputs` is relative to the `--out`
|
|
677
689
|
directory (`../`-prefixed when `--config` sits outside `--out`; never an absolute or
|
|
678
690
|
home path). Every `sha256` is computed from the bytes on disk after writing. A refused
|
|
679
|
-
run writes no `run.json`.
|
|
680
|
-
time read in `cli.ts` (`src/` remains pure), `run.json` is outside
|
|
691
|
+
run writes no `run.json`. By default, `started_at` and `finished_at` record wall-clock
|
|
692
|
+
time read in `cli.ts` (`src/` remains pure). With that default, `run.json` is outside
|
|
693
|
+
the byte-for-byte
|
|
681
694
|
determinism comparisons (`RG03`, `RG19`, `AS07`); for the same input at the same
|
|
682
695
|
relative `--config` layout, two `run.json` files differ only in `started_at` and
|
|
683
696
|
`finished_at`.
|
|
684
697
|
|
|
698
|
+
Set `SOURCE_DATE_EPOCH` to opt into a fixed clock: both timestamps equal that
|
|
699
|
+
instant in UTC ISO format, without adding a stamp field. The value must match
|
|
700
|
+
`^(0|[1-9][0-9]*)$` and be at most 253402300799 seconds
|
|
701
|
+
(9999-12-31T23:59:59Z), preserving the four-digit-year ISO form.
|
|
702
|
+
253402300800 and above are refused. Empty, negative,
|
|
703
|
+
fractional, non-numeric, noncanonical and out-of-range values refuse
|
|
704
|
+
`RUN_STAMP_EPOCH`, naming the variable, found value and requirement before any
|
|
705
|
+
output is written or an existing stamp is removed. Unset preserves the existing
|
|
706
|
+
wall-clock path and stamp format. Fixed clocks make stamps byte-identical for
|
|
707
|
+
identical inputs and the same relative config layout.
|
|
708
|
+
|
|
685
709
|
`outputs` lists exactly the files the stage wrote in this run, derived from what the
|
|
686
710
|
stage returns, not from a walk of `--out`: a stray or earlier file under `--out` is
|
|
687
711
|
neither hashed nor listed. Before the stage starts, the command removes an earlier
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "spine-parts",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.30.0",
|
|
4
4
|
"description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/comfy/plate.ts
CHANGED
|
@@ -6,17 +6,20 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 1. the source mask is read (`src/plate.ts`); with none, the run is refused
|
|
8
8
|
* before anything is written and before the host is reached;
|
|
9
|
-
* 2. the declared checkpoint sha256 and, for `core`, the
|
|
9
|
+
* 2. the declared checkpoint sha256 and, for `core`, the checkpoint name are
|
|
10
10
|
* checked;
|
|
11
11
|
* 3. the box answers `/system_stats` and names its GPU;
|
|
12
12
|
* 4. every node, input and model of the chosen graph is on the box's
|
|
13
13
|
* `/object_info` (`checkGraph`) — a box without the inpaint pack is refused
|
|
14
14
|
* here for `lama`, before anything is uploaded;
|
|
15
|
-
* 5. the painting and the grown mask
|
|
15
|
+
* 5. the painting and the grown mask (for off-grid `core`, padded to the next
|
|
16
|
+
* multiple of 8 on the right and bottom with `grid_transform` recorded) are
|
|
17
|
+
* uploaded and the graph is appended
|
|
16
18
|
* to the queue: behind every other job, never in front, nothing reordered
|
|
17
19
|
* and nothing cancelled; a wait past `--wait` while pending is refused
|
|
18
20
|
* naming the job's place (`COMFY_QUEUE_BEHIND`);
|
|
19
|
-
* 6. the box's image is read back, required at the
|
|
21
|
+
* 6. the box's image is read back, required at the uploaded size (then cropped
|
|
22
|
+
* at `[0, 0]` back to the painting's size for off-grid `core`), pasted
|
|
20
23
|
* into the painting inside the mask only, and written with its receipt
|
|
21
24
|
* through `publishPlate` (staged, read back, then moved).
|
|
22
25
|
*/
|
|
@@ -25,9 +28,10 @@ import { checkGraph, type Graph } from '../graphs.ts';
|
|
|
25
28
|
import {
|
|
26
29
|
assertPlateOutFree,
|
|
27
30
|
CORE_DEFAULTS,
|
|
31
|
+
coreCfg,
|
|
28
32
|
type CoreParams,
|
|
29
|
-
coreGridProblem,
|
|
30
33
|
corePlateGraph,
|
|
34
|
+
cropCoreGrid,
|
|
31
35
|
declaredChecksum,
|
|
32
36
|
type FigureMask,
|
|
33
37
|
growMask,
|
|
@@ -40,6 +44,7 @@ import {
|
|
|
40
44
|
PLATE_GRAPH_IDS,
|
|
41
45
|
type PlateGraph,
|
|
42
46
|
type PlateReceipt,
|
|
47
|
+
prepareCoreGrid,
|
|
43
48
|
publishPlate,
|
|
44
49
|
readPlatePainting,
|
|
45
50
|
readSourceMask,
|
|
@@ -59,6 +64,7 @@ export interface BackgroundRun {
|
|
|
59
64
|
seed: number;
|
|
60
65
|
growPx: number;
|
|
61
66
|
steps: number;
|
|
67
|
+
cfg?: number | string | undefined;
|
|
62
68
|
prompt: string | undefined;
|
|
63
69
|
negative: string | undefined;
|
|
64
70
|
wait: number;
|
|
@@ -77,22 +83,24 @@ export function gpuName(stats: Record<string, unknown>, host: string): string {
|
|
|
77
83
|
|
|
78
84
|
/** `connect` is called only after every local check has passed, so a refused run never resolves a host or reaches a box. */
|
|
79
85
|
export async function runBackground(connect: () => ComfyClient, run: BackgroundRun, say: (line: string) => void): Promise<PlateReceipt> {
|
|
80
|
-
// Local first: no source mask, a bad checksum or
|
|
86
|
+
// Local first: no source mask, a bad checksum or a missing checkpoint is refused before the box is reached.
|
|
87
|
+
const cfg = coreCfg(run.cfg, run.graph);
|
|
81
88
|
const from = parseMaskFrom(run.maskFrom);
|
|
82
89
|
const painting = readPlatePainting(run.painting);
|
|
83
90
|
const { width: W, height: H } = painting.raster;
|
|
84
91
|
const source: FigureMask = readSourceMask(from.source, from.dir, W, H, painting.raster, painting.bytes);
|
|
85
92
|
const checkpoint = declaredChecksum(run.checkpointSha256);
|
|
86
|
-
if (run.graph === 'core') {
|
|
87
|
-
|
|
88
|
-
const grid = coreGridProblem(W, H, run.painting);
|
|
89
|
-
if (grid !== null) refuseIfAny([grid]);
|
|
93
|
+
if (run.graph === 'core' && run.model === undefined) {
|
|
94
|
+
refuse('PLATE_MODEL_GIVEN', '--model', 'is absent; the core graph needs the checkpoint the box loads, by its name on the box — there is no default checkpoint');
|
|
90
95
|
}
|
|
91
96
|
assertPlateOutFree(run.out);
|
|
92
97
|
const mask = growMask(source, run.growPx);
|
|
98
|
+
const prepared = run.graph === 'core' ? prepareCoreGrid(painting.raster, mask) : { painting: painting.raster, mask };
|
|
99
|
+
const uploadPaintingBytes = prepared.transform === undefined ? painting.bytes : encodePngBytes(prepared.painting);
|
|
100
|
+
const uploadMaskBytes = encodePngBytes(maskImage(prepared.mask));
|
|
93
101
|
const model = run.model ?? LAMA_MODEL;
|
|
94
102
|
const lama: LamaParams = { seed: run.seed, grow_px: run.growPx };
|
|
95
|
-
const core: CoreParams = { seed: run.seed, grow_px: run.growPx, steps: run.steps, cfg
|
|
103
|
+
const core: CoreParams = { seed: run.seed, grow_px: run.growPx, steps: run.steps, cfg, sampler: CORE_DEFAULTS.sampler, scheduler: CORE_DEFAULTS.scheduler, denoise: CORE_DEFAULTS.denoise, prompt: run.prompt ?? CORE_DEFAULTS.prompt, negative: run.negative ?? CORE_DEFAULTS.negative };
|
|
96
104
|
const prefix = `rig_parts_plate_${crypto.randomUUID().slice(0, 8)}`;
|
|
97
105
|
const build = (p: string, m: string): Graph => (run.graph === 'lama' ? lamaPlateGraph(p, m, model, lama, prefix) : corePlateGraph(p, m, model, core, prefix));
|
|
98
106
|
|
|
@@ -102,9 +110,9 @@ export async function runBackground(connect: () => ComfyClient, run: BackgroundR
|
|
|
102
110
|
refuseIfAny(checkGraph(build(`${prefix}_painting.png`, `${prefix}_mask.png`), info, client.host, new Set(['1.image', '2.image'])));
|
|
103
111
|
say(` box: every node, input and model of the ${run.graph} graph is on its /object_info; GPU ${gpu}`);
|
|
104
112
|
|
|
105
|
-
const paintingRef = await client.uploadImage(
|
|
106
|
-
const maskRef = await client.uploadImage(
|
|
107
|
-
say(` uploaded ${run.painting} (${
|
|
113
|
+
const paintingRef = await client.uploadImage(uploadPaintingBytes, `${prefix}_painting.png`);
|
|
114
|
+
const maskRef = await client.uploadImage(uploadMaskBytes, `${prefix}_mask.png`);
|
|
115
|
+
say(` uploaded ${run.painting} (${prepared.painting.width}x${prepared.painting.height}) and its mask (${mask.inside.reduce((a, b) => a + b, 0)} px, grown ${run.growPx} px)`);
|
|
108
116
|
const id = await client.submit(build(paintingRef, maskRef), 'rig-parts');
|
|
109
117
|
say(` appended prompt ${id} to the queue (behind any other job; nothing reordered or cancelled)`);
|
|
110
118
|
const { entry, elapsed } = await client.waitBehind(id, run.wait, run.timeout, say);
|
|
@@ -112,7 +120,15 @@ export async function runBackground(connect: () => ComfyClient, run: BackgroundR
|
|
|
112
120
|
const images = historyImages(entry);
|
|
113
121
|
if (images.length !== 1) refuse('COMFY_HISTORY_OUTPUTS', `prompt ${id}`, `lists ${images.length} image(s); the graph's one SaveImage is required to have saved exactly one`);
|
|
114
122
|
const got = decodePngBytes(await client.view(images[0].filename, images[0].subfolder, images[0].type), images[0].filename);
|
|
115
|
-
|
|
123
|
+
const [expectedW, expectedH] = prepared.transform === undefined ? [W, H] : prepared.transform.padded;
|
|
124
|
+
if (got.width !== expectedW || got.height !== expectedH) {
|
|
125
|
+
refuse(
|
|
126
|
+
'COMFY_PLATE_SIZE',
|
|
127
|
+
`prompt ${id} ${images[0].filename}`,
|
|
128
|
+
`is ${got.width}x${got.height}; ${prepared.transform === undefined ? `the painting's ${W}x${H}` : `the padded core grid ${expectedW}x${expectedH} (for painting ${W}x${H})`} is required — the plate is pasted into the painting pixel for pixel, never resized`,
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
const inpainted = prepared.transform === undefined ? got : cropCoreGrid(got, prepared.transform);
|
|
116
132
|
|
|
117
133
|
return publishPlate({
|
|
118
134
|
out: run.out,
|
|
@@ -123,10 +139,11 @@ export async function runBackground(connect: () => ComfyClient, run: BackgroundR
|
|
|
123
139
|
source: from.source,
|
|
124
140
|
sourceDir: from.dir,
|
|
125
141
|
mask,
|
|
126
|
-
plate: pasteInside(painting.raster,
|
|
142
|
+
plate: pasteInside(painting.raster, inpainted, mask),
|
|
127
143
|
model: { name: model, checkpoint_sha256: checkpoint, checkpoint_sha256_from: 'declared' },
|
|
128
144
|
params: run.graph === 'lama' ? { ...lama, mask_alpha_above: OPAQUE_ALPHA_ABOVE } : { ...core, mask_alpha_above: OPAQUE_ALPHA_ABOVE },
|
|
129
145
|
graph: PLATE_GRAPH_IDS[run.graph],
|
|
130
146
|
gpu,
|
|
147
|
+
gridTransform: prepared.transform,
|
|
131
148
|
});
|
|
132
149
|
}
|
package/src/plate.ts
CHANGED
|
@@ -46,13 +46,26 @@ export const PLATE_RECEIPT_FILE = 'receipt.json';
|
|
|
46
46
|
export const PLATE_MASK_FILE = 'mask.png';
|
|
47
47
|
export const PLATE_OUTPUT_FILE = 'plate.png';
|
|
48
48
|
|
|
49
|
-
/** The receipt's top-level keys, in the order they are written. */
|
|
49
|
+
/** The receipt's top-level keys when `grid_transform` is absent, in the order they are written. */
|
|
50
50
|
export const PLATE_RECEIPT_KEYS = ['spec', 'mode', 'painting', 'mask', 'model', 'params', 'graph', 'gpu', 'output'] as const;
|
|
51
|
+
/** The receipt's top-level keys when `grid_transform` is present (off-grid `core`), in the order they are written. */
|
|
52
|
+
export const PLATE_RECEIPT_GRID_TRANSFORM_KEYS = ['spec', 'mode', 'painting', 'mask', 'model', 'params', 'graph', 'gpu', 'grid_transform', 'output'] as const;
|
|
53
|
+
/** The `grid_transform` object's keys, in the order they are written. */
|
|
54
|
+
export const CORE_GRID_TRANSFORM_KEYS = ['source', 'padded', 'pad', 'pad_fill', 'mask_pad_fill', 'inverse'] as const;
|
|
51
55
|
|
|
52
56
|
export type PlateMode = 'background' | 'foreground';
|
|
53
57
|
export type PlateGraph = 'lama' | 'core';
|
|
54
58
|
export type MaskSource = 'seethrough' | 'figure-mask' | 'matte';
|
|
55
59
|
|
|
60
|
+
export interface CoreGridTransform {
|
|
61
|
+
source: [number, number];
|
|
62
|
+
padded: [number, number];
|
|
63
|
+
pad: [0, 0];
|
|
64
|
+
pad_fill: 'edge-replicate';
|
|
65
|
+
mask_pad_fill: 'zero';
|
|
66
|
+
inverse: 'crop';
|
|
67
|
+
}
|
|
68
|
+
|
|
56
69
|
/** The graph ids a receipt names: one per background graph, and the fixed local id of the foreground derivation. */
|
|
57
70
|
export const PLATE_GRAPH_IDS = {
|
|
58
71
|
lama: 'rig-parts/plate-background-lama/1',
|
|
@@ -74,6 +87,7 @@ export interface PlateReceipt {
|
|
|
74
87
|
params: Record<string, string | number | boolean>;
|
|
75
88
|
graph: string;
|
|
76
89
|
gpu: string | null;
|
|
90
|
+
grid_transform?: CoreGridTransform;
|
|
77
91
|
output: { path: string; sha256: string };
|
|
78
92
|
}
|
|
79
93
|
|
|
@@ -92,6 +106,21 @@ export function declaredChecksum(value: string | undefined): string {
|
|
|
92
106
|
return value.toLowerCase();
|
|
93
107
|
}
|
|
94
108
|
|
|
109
|
+
/** `--cfg <number>` for `--graph core`: a finite number above 0, or `CORE_DEFAULTS.cfg` when absent; refused on `lama`. */
|
|
110
|
+
export function coreCfg(value: number | string | undefined, graph: PlateGraph): number {
|
|
111
|
+
if (graph !== 'core') {
|
|
112
|
+
if (value !== undefined) fail('PLATE_CORE_CFG', '--cfg', 'is for --graph core; the lama graph takes no CFG parameter');
|
|
113
|
+
return CORE_DEFAULTS.cfg;
|
|
114
|
+
}
|
|
115
|
+
if (value === undefined) return CORE_DEFAULTS.cfg;
|
|
116
|
+
const trimmed = typeof value === 'string' ? value.trim() : '';
|
|
117
|
+
const n = typeof value === 'number' ? value : /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(trimmed) ? Number(trimmed) : NaN;
|
|
118
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
119
|
+
fail('PLATE_CORE_CFG', '--cfg', `is ${typeof value === 'number' ? String(value) : JSON.stringify(value)}; a finite number above 0 is required`);
|
|
120
|
+
}
|
|
121
|
+
return n;
|
|
122
|
+
}
|
|
123
|
+
|
|
95
124
|
/** `--mask-from <source>:<dir>`, parsed; an absent or unknown source is refused by name. */
|
|
96
125
|
export function parseMaskFrom(value: string | undefined): { source: MaskSource; dir: string } {
|
|
97
126
|
if (value === undefined) {
|
|
@@ -412,19 +441,91 @@ export function corePlateGraph(painting: string, mask: string, checkpoint: strin
|
|
|
412
441
|
};
|
|
413
442
|
}
|
|
414
443
|
|
|
415
|
-
/** The
|
|
416
|
-
export function
|
|
417
|
-
|
|
444
|
+
/** The pad-to-8 transform for an off-grid painting on the `core` background graph; `undefined` when already a multiple of 8. */
|
|
445
|
+
export function coreGridTransform(width: number, height: number): CoreGridTransform | undefined {
|
|
446
|
+
if (width % 8 === 0 && height % 8 === 0) return undefined;
|
|
447
|
+
return {
|
|
448
|
+
source: [width, height],
|
|
449
|
+
padded: [Math.ceil(width / 8) * 8, Math.ceil(height / 8) * 8],
|
|
450
|
+
pad: [0, 0],
|
|
451
|
+
pad_fill: 'edge-replicate',
|
|
452
|
+
mask_pad_fill: 'zero',
|
|
453
|
+
inverse: 'crop',
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Validate a recorded `grid_transform` against the bound painting's `width`x`height` and key order. */
|
|
458
|
+
export function isCoreGridTransform(value: unknown, width: number, height: number): value is CoreGridTransform {
|
|
459
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
460
|
+
const v = value as Record<string, unknown>;
|
|
461
|
+
if (Object.keys(v).join(',') !== CORE_GRID_TRANSFORM_KEYS.join(',')) return false;
|
|
462
|
+
const pair = (p: unknown): p is [number, number] => Array.isArray(p) && p.length === 2 && p.every((n) => Number.isSafeInteger(n));
|
|
463
|
+
if (!pair(v.source) || !pair(v.padded) || !pair(v.pad)) return false;
|
|
464
|
+
const expected = coreGridTransform(width, height);
|
|
465
|
+
if (expected === undefined) return false;
|
|
466
|
+
return (
|
|
467
|
+
v.source[0] === expected.source[0] &&
|
|
468
|
+
v.source[1] === expected.source[1] &&
|
|
469
|
+
v.padded[0] === expected.padded[0] &&
|
|
470
|
+
v.padded[1] === expected.padded[1] &&
|
|
471
|
+
v.pad[0] === 0 &&
|
|
472
|
+
v.pad[1] === 0 &&
|
|
473
|
+
v.pad_fill === 'edge-replicate' &&
|
|
474
|
+
v.mask_pad_fill === 'zero' &&
|
|
475
|
+
v.inverse === 'crop'
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Pad an off-grid painting and its grown mask to the next multiple of 8 on
|
|
481
|
+
* the right and bottom (`pad: [0, 0]`): the painting replicates its right and
|
|
482
|
+
* bottom edges (`edge-replicate`), and the mask pads with `0` (kept as
|
|
483
|
+
* context, never inside the hole). On-grid paintings return unchanged with no
|
|
484
|
+
* transform.
|
|
485
|
+
*/
|
|
486
|
+
export function prepareCoreGrid(painting: Raster, mask: FigureMask): { painting: Raster; mask: FigureMask; transform?: CoreGridTransform } {
|
|
487
|
+
const transform = coreGridTransform(painting.width, painting.height);
|
|
488
|
+
if (transform === undefined) return { painting, mask };
|
|
489
|
+
const [W, H] = transform.source;
|
|
490
|
+
const [paddedW, paddedH] = transform.padded;
|
|
491
|
+
const paddedPainting = newRaster(paddedW, paddedH);
|
|
492
|
+
for (let y = 0; y < paddedH; y++) {
|
|
493
|
+
const sy = Math.min(y, H - 1);
|
|
494
|
+
for (let x = 0; x < paddedW; x++) {
|
|
495
|
+
const sx = Math.min(x, W - 1);
|
|
496
|
+
const src = (sy * W + sx) * 4;
|
|
497
|
+
const dst = (y * paddedW + x) * 4;
|
|
498
|
+
paddedPainting.data.set(painting.data.subarray(src, src + 4), dst);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const paddedMask: FigureMask = { width: paddedW, height: paddedH, inside: new Uint8Array(paddedW * paddedH) };
|
|
502
|
+
for (let y = 0; y < H; y++) {
|
|
503
|
+
paddedMask.inside.set(mask.inside.subarray(y * W, (y + 1) * W), y * paddedW);
|
|
504
|
+
}
|
|
505
|
+
return { painting: paddedPainting, mask: paddedMask, transform };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Crop a padded `core` output back to the painting's exact `source` grid at `transform.pad` (`[0, 0]`). */
|
|
509
|
+
export function cropCoreGrid(padded: Raster, transform: CoreGridTransform): Raster {
|
|
510
|
+
const [W, H] = transform.source;
|
|
511
|
+
const [padX, padY] = transform.pad;
|
|
512
|
+
const out = newRaster(W, H);
|
|
513
|
+
for (let y = 0; y < H; y++) {
|
|
514
|
+
const src = ((y + padY) * padded.width + padX) * 4;
|
|
515
|
+
out.data.set(padded.data.subarray(src, src + W * 4), y * W * 4);
|
|
516
|
+
}
|
|
517
|
+
return out;
|
|
418
518
|
}
|
|
419
519
|
|
|
420
520
|
// ---------------------------------------------------------------------------
|
|
421
521
|
// the receipt
|
|
422
522
|
// ---------------------------------------------------------------------------
|
|
423
523
|
|
|
424
|
-
/** The receipt's JSON text, its keys in `PLATE_RECEIPT_KEYS` order. */
|
|
524
|
+
/** The receipt's JSON text, its keys in `PLATE_RECEIPT_KEYS` (or `PLATE_RECEIPT_GRID_TRANSFORM_KEYS` when `grid_transform` is present) order. */
|
|
425
525
|
export function receiptText(r: PlateReceipt): string {
|
|
426
526
|
const ordered: Record<string, unknown> = {};
|
|
427
|
-
|
|
527
|
+
const keys = r.grid_transform === undefined ? PLATE_RECEIPT_KEYS : PLATE_RECEIPT_GRID_TRANSFORM_KEYS;
|
|
528
|
+
for (const k of keys) ordered[k] = r[k];
|
|
428
529
|
return `${JSON.stringify(ordered, null, 2)}\n`;
|
|
429
530
|
}
|
|
430
531
|
|
|
@@ -435,21 +536,28 @@ export function receiptPath(receiptDir: string, path: string): string {
|
|
|
435
536
|
|
|
436
537
|
/**
|
|
437
538
|
* Every problem between a receipt and the bytes on disk: its spec and key
|
|
438
|
-
* order,
|
|
439
|
-
* the file it names (or whose file is gone)
|
|
539
|
+
* order, each of the painting, mask and output whose sha256 is not that of
|
|
540
|
+
* the file it names (or whose file is gone), and `grid_transform` re-derived
|
|
541
|
+
* from the decoded painting, mode and graph.
|
|
440
542
|
*/
|
|
441
543
|
export function verifyPlateReceipt(receiptFile: string): Problem[] {
|
|
442
544
|
const problems: Problem[] = [];
|
|
443
545
|
let r: Record<string, unknown>;
|
|
444
546
|
try {
|
|
445
|
-
|
|
547
|
+
const parsed: unknown = JSON.parse(readFileSync(receiptFile, 'utf8'));
|
|
548
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
549
|
+
return [{ code: 'PLATE_RECEIPT_READ', object: receiptFile, detail: 'does not parse as a JSON object' }];
|
|
550
|
+
}
|
|
551
|
+
r = parsed as Record<string, unknown>;
|
|
446
552
|
} catch (err) {
|
|
447
553
|
return [{ code: 'PLATE_RECEIPT_READ', object: receiptFile, detail: `does not parse as JSON (${(err as Error).message})` }];
|
|
448
554
|
}
|
|
449
555
|
if (r.spec !== PLATE_RECEIPT_SPEC) problems.push({ code: 'PLATE_RECEIPT_SPEC', object: receiptFile, detail: `has spec ${JSON.stringify(r.spec)}; "${PLATE_RECEIPT_SPEC}" is required` });
|
|
450
556
|
const keys = Object.keys(r).join(',');
|
|
451
|
-
|
|
557
|
+
const expectedKeys = 'grid_transform' in r ? PLATE_RECEIPT_GRID_TRANSFORM_KEYS : PLATE_RECEIPT_KEYS;
|
|
558
|
+
if (keys !== expectedKeys.join(',')) problems.push({ code: 'PLATE_RECEIPT_KEYS', object: receiptFile, detail: `has keys ${keys}; ${expectedKeys.join(',')} in that order is required` });
|
|
452
559
|
const base = dirname(receiptFile);
|
|
560
|
+
let paintingRaster: Raster | undefined;
|
|
453
561
|
for (const field of ['painting', 'mask', 'output'] as const) {
|
|
454
562
|
const f = r[field] as { path?: unknown; sha256?: unknown } | undefined;
|
|
455
563
|
if (typeof f?.path !== 'string' || typeof f.sha256 !== 'string') {
|
|
@@ -461,8 +569,42 @@ export function verifyPlateReceipt(receiptFile: string): Problem[] {
|
|
|
461
569
|
problems.push({ code: 'PLATE_RECEIPT_FILE', object: `${receiptFile} ${field}`, detail: `names ${f.path}, which does not exist` });
|
|
462
570
|
continue;
|
|
463
571
|
}
|
|
464
|
-
const
|
|
572
|
+
const bytes = new Uint8Array(readFileSync(file));
|
|
573
|
+
const found = sha256(bytes);
|
|
465
574
|
if (found !== f.sha256) problems.push({ code: 'PLATE_RECEIPT_HASH', object: `${receiptFile} ${field}`, detail: `records sha256 ${f.sha256} for ${f.path}; the file on disk has ${found}` });
|
|
575
|
+
if (field === 'painting') {
|
|
576
|
+
try { paintingRaster = decodePngBytes(bytes, file); } catch { /* hash/read already covers invalid bytes */ }
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
if (paintingRaster !== undefined) {
|
|
580
|
+
const expectedTransform = r.mode === 'background' && r.graph === PLATE_GRAPH_IDS.core ? coreGridTransform(paintingRaster.width, paintingRaster.height) : undefined;
|
|
581
|
+
if (expectedTransform !== undefined) {
|
|
582
|
+
if (!('grid_transform' in r) || r.grid_transform === undefined) {
|
|
583
|
+
problems.push({
|
|
584
|
+
code: 'PLATE_RECEIPT_GRID_TRANSFORM',
|
|
585
|
+
object: `${receiptFile} grid_transform`,
|
|
586
|
+
detail: `is absent; off-grid core painting (${paintingRaster.width}x${paintingRaster.height}) requires ${JSON.stringify(expectedTransform)}`,
|
|
587
|
+
});
|
|
588
|
+
} else if (!isCoreGridTransform(r.grid_transform, paintingRaster.width, paintingRaster.height)) {
|
|
589
|
+
problems.push({
|
|
590
|
+
code: 'PLATE_RECEIPT_GRID_TRANSFORM',
|
|
591
|
+
object: `${receiptFile} grid_transform`,
|
|
592
|
+
detail: `is ${JSON.stringify(r.grid_transform)}; off-grid core painting (${paintingRaster.width}x${paintingRaster.height}) requires ${JSON.stringify(expectedTransform)} in ${CORE_GRID_TRANSFORM_KEYS.join(',')} order`,
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
} else if ('grid_transform' in r) {
|
|
596
|
+
problems.push({
|
|
597
|
+
code: 'PLATE_RECEIPT_GRID_TRANSFORM',
|
|
598
|
+
object: `${receiptFile} grid_transform`,
|
|
599
|
+
detail: `is ${JSON.stringify(r.grid_transform)}; no grid_transform is permitted for ${r.mode === 'background' && r.graph === PLATE_GRAPH_IDS.core ? `on-grid painting ${paintingRaster.width}x${paintingRaster.height}` : `mode ${JSON.stringify(r.mode)} graph ${JSON.stringify(r.graph)}`}`,
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
} else if ('grid_transform' in r && (typeof r.grid_transform !== 'object' || r.grid_transform === null || Array.isArray(r.grid_transform) || Object.keys(r.grid_transform as object).join(',') !== CORE_GRID_TRANSFORM_KEYS.join(','))) {
|
|
603
|
+
problems.push({
|
|
604
|
+
code: 'PLATE_RECEIPT_GRID_TRANSFORM',
|
|
605
|
+
object: `${receiptFile} grid_transform`,
|
|
606
|
+
detail: `is ${JSON.stringify(r.grid_transform)}; a valid grid_transform in ${CORE_GRID_TRANSFORM_KEYS.join(',')} order is required`,
|
|
607
|
+
});
|
|
466
608
|
}
|
|
467
609
|
return problems;
|
|
468
610
|
}
|
|
@@ -500,6 +642,7 @@ export interface PlateWrite {
|
|
|
500
642
|
params: PlateReceipt['params'];
|
|
501
643
|
graph: string;
|
|
502
644
|
gpu: string | null;
|
|
645
|
+
gridTransform?: CoreGridTransform;
|
|
503
646
|
}
|
|
504
647
|
|
|
505
648
|
let foregroundStageSeq = 0;
|
|
@@ -528,6 +671,7 @@ export function publishPlate(w: PlateWrite): PlateReceipt {
|
|
|
528
671
|
params: w.params,
|
|
529
672
|
graph: w.graph,
|
|
530
673
|
gpu: w.gpu,
|
|
674
|
+
...(w.gridTransform === undefined ? {} : { grid_transform: w.gridTransform }),
|
|
531
675
|
output: { path: PLATE_OUTPUT_FILE, sha256: plate.sha256 },
|
|
532
676
|
};
|
|
533
677
|
writeFileSync(join(stage, PLATE_RECEIPT_FILE), receiptText(receipt));
|