dsh-dungeon-master 0.5.2 → 0.7.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/CHANGELOG.md +24 -2
- package/CHANGELOG_EN.md +24 -2
- package/README.md +203 -198
- package/README_EN.md +203 -198
- package/cordis.patch.yml +32 -32
- package/cordis.yml +112 -112
- package/dist/commands/dnd.d.ts.map +1 -1
- package/dist/commands/dnd.js +4 -3
- package/dist/commands/dnd.js.map +1 -1
- package/dist/config.d.ts +2 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +2 -0
- package/dist/config.js.map +1 -1
- package/dist/dnd/battle-image.d.ts +11 -4
- package/dist/dnd/battle-image.d.ts.map +1 -1
- package/dist/dnd/battle-image.js +86 -7
- package/dist/dnd/battle-image.js.map +1 -1
- package/dist/dnd/battlefield.d.ts +39 -3
- package/dist/dnd/battlefield.d.ts.map +1 -1
- package/dist/dnd/battlefield.js +378 -88
- package/dist/dnd/battlefield.js.map +1 -1
- package/dist/dnd/campaign.d.ts +192 -16
- package/dist/dnd/campaign.d.ts.map +1 -1
- package/dist/dnd/campaign.js +645 -92
- package/dist/dnd/campaign.js.map +1 -1
- package/dist/dnd/combat-agent.d.ts +53 -5
- package/dist/dnd/combat-agent.d.ts.map +1 -1
- package/dist/dnd/combat-agent.js +612 -62
- package/dist/dnd/combat-agent.js.map +1 -1
- package/dist/dnd/combat-context.d.ts +74 -2
- package/dist/dnd/combat-context.d.ts.map +1 -1
- package/dist/dnd/combat-context.js +62 -21
- package/dist/dnd/combat-context.js.map +1 -1
- package/dist/dnd/conditions.d.ts +217 -0
- package/dist/dnd/conditions.d.ts.map +1 -0
- package/dist/dnd/conditions.js +1216 -0
- package/dist/dnd/conditions.js.map +1 -0
- package/dist/dnd/custom-effects.d.ts +121 -0
- package/dist/dnd/custom-effects.d.ts.map +1 -0
- package/dist/dnd/custom-effects.js +446 -0
- package/dist/dnd/custom-effects.js.map +1 -0
- package/dist/dnd/dice.d.ts +5 -1
- package/dist/dnd/dice.d.ts.map +1 -1
- package/dist/dnd/dice.js +4 -3
- package/dist/dnd/dice.js.map +1 -1
- package/dist/dnd/dnd-service.d.ts +8 -6
- package/dist/dnd/dnd-service.d.ts.map +1 -1
- package/dist/dnd/dnd-service.js +43 -7
- package/dist/dnd/dnd-service.js.map +1 -1
- package/dist/dnd/dnd-tools.d.ts.map +1 -1
- package/dist/dnd/dnd-tools.js +2 -0
- package/dist/dnd/dnd-tools.js.map +1 -1
- package/dist/dnd/formula.d.ts +40 -0
- package/dist/dnd/formula.d.ts.map +1 -0
- package/dist/dnd/formula.js +219 -0
- package/dist/dnd/formula.js.map +1 -0
- package/dist/dnd/map-view.d.ts +3 -1
- package/dist/dnd/map-view.d.ts.map +1 -1
- package/dist/dnd/map-view.js +33 -10
- package/dist/dnd/map-view.js.map +1 -1
- package/dist/dnd/movement.d.ts +3 -3
- package/dist/dnd/movement.d.ts.map +1 -1
- package/dist/dnd/movement.js +14 -8
- package/dist/dnd/movement.js.map +1 -1
- package/dist/dnd/pending-attack.d.ts +23 -13
- package/dist/dnd/pending-attack.d.ts.map +1 -1
- package/dist/dnd/pending-attack.js +198 -27
- package/dist/dnd/pending-attack.js.map +1 -1
- package/dist/dnd/save-effect.d.ts +12 -0
- package/dist/dnd/save-effect.d.ts.map +1 -1
- package/dist/dnd/save-effect.js +72 -8
- package/dist/dnd/save-effect.js.map +1 -1
- package/dist/dnd/spell-links.d.ts +32 -11
- package/dist/dnd/spell-links.d.ts.map +1 -1
- package/dist/dnd/spell-links.js +105 -20
- package/dist/dnd/spell-links.js.map +1 -1
- package/dist/dnd/srd-lookup.d.ts.map +1 -1
- package/dist/dnd/srd-lookup.js +23 -0
- package/dist/dnd/srd-lookup.js.map +1 -1
- package/dist/dnd/terrain.d.ts +8 -2
- package/dist/dnd/terrain.d.ts.map +1 -1
- package/dist/dnd/terrain.js +13 -8
- package/dist/dnd/terrain.js.map +1 -1
- package/dist/dnd/tool-scope.d.ts.map +1 -1
- package/dist/dnd/tool-scope.js +1 -1
- package/dist/dnd/tool-scope.js.map +1 -1
- package/dist/dnd/tool-views.js +4 -4
- package/dist/dnd/tool-views.js.map +1 -1
- package/dist/dnd/tools/character.d.ts.map +1 -1
- package/dist/dnd/tools/character.js +223 -21
- package/dist/dnd/tools/character.js.map +1 -1
- package/dist/dnd/tools/combat.d.ts.map +1 -1
- package/dist/dnd/tools/combat.js +222 -32
- package/dist/dnd/tools/combat.js.map +1 -1
- package/dist/dnd/tools/dice.d.ts.map +1 -1
- package/dist/dnd/tools/dice.js +406 -53
- package/dist/dnd/tools/dice.js.map +1 -1
- package/dist/dnd/tools/explore.d.ts.map +1 -1
- package/dist/dnd/tools/explore.js +3 -2
- package/dist/dnd/tools/explore.js.map +1 -1
- package/dist/dnd/tools/rules.d.ts +3 -0
- package/dist/dnd/tools/rules.d.ts.map +1 -0
- package/dist/dnd/tools/rules.js +190 -0
- package/dist/dnd/tools/rules.js.map +1 -0
- package/dist/dnd/tools/saves.d.ts.map +1 -1
- package/dist/dnd/tools/saves.js +23 -6
- package/dist/dnd/tools/saves.js.map +1 -1
- package/dist/dnd/tools/shared.d.ts +8 -2
- package/dist/dnd/tools/shared.d.ts.map +1 -1
- package/dist/dnd/tools/shared.js +239 -39
- package/dist/dnd/tools/shared.js.map +1 -1
- package/dist/dnd/turn-buttons.d.ts +4 -0
- package/dist/dnd/turn-buttons.d.ts.map +1 -1
- package/dist/dnd/turn-buttons.js +49 -25
- package/dist/dnd/turn-buttons.js.map +1 -1
- package/dist/dnd/zones.d.ts +123 -0
- package/dist/dnd/zones.d.ts.map +1 -0
- package/dist/dnd/zones.js +545 -0
- package/dist/dnd/zones.js.map +1 -0
- package/dist/features/button-utils.d.ts +2 -1
- package/dist/features/button-utils.d.ts.map +1 -1
- package/dist/features/button-utils.js.map +1 -1
- package/dist/features/note-judge.d.ts +24 -7
- package/dist/features/note-judge.d.ts.map +1 -1
- package/dist/features/note-judge.js +112 -24
- package/dist/features/note-judge.js.map +1 -1
- package/dist/features/reply-judge.d.ts.map +1 -1
- package/dist/features/reply-judge.js +22 -4
- package/dist/features/reply-judge.js.map +1 -1
- package/dist/gateway/bootstrap.d.ts.map +1 -1
- package/dist/gateway/bootstrap.js +28 -1
- package/dist/gateway/bootstrap.js.map +1 -1
- package/dist/gateway/middleware-setup.d.ts +3 -1
- package/dist/gateway/middleware-setup.d.ts.map +1 -1
- package/dist/gateway/middleware-setup.js +24 -5
- package/dist/gateway/middleware-setup.js.map +1 -1
- package/dist/middleware/reply-decider.d.ts +8 -1
- package/dist/middleware/reply-decider.d.ts.map +1 -1
- package/dist/middleware/reply-decider.js +22 -8
- package/dist/middleware/reply-decider.js.map +1 -1
- package/dist/middleware/serial-merge.d.ts +7 -3
- package/dist/middleware/serial-merge.d.ts.map +1 -1
- package/dist/middleware/serial-merge.js +125 -9
- package/dist/middleware/serial-merge.js.map +1 -1
- package/dist/model/status-watch.d.ts +4 -0
- package/dist/model/status-watch.d.ts.map +1 -1
- package/dist/model/status-watch.js +6 -2
- package/dist/model/status-watch.js.map +1 -1
- package/dist/session/index.d.ts +1 -1
- package/dist/session/index.d.ts.map +1 -1
- package/dist/session/index.js.map +1 -1
- package/dist/session/session-manager.d.ts +21 -5
- package/dist/session/session-manager.d.ts.map +1 -1
- package/dist/session/session-manager.js +141 -18
- package/dist/session/session-manager.js.map +1 -1
- package/dist/session/types.d.ts +8 -0
- package/dist/session/types.d.ts.map +1 -1
- package/dist/setup/bind-routes.d.ts.map +1 -1
- package/dist/setup/bind-routes.js +2 -1
- package/dist/setup/bind-routes.js.map +1 -1
- package/dist/transport/agent-turn.d.ts +7 -3
- package/dist/transport/agent-turn.d.ts.map +1 -1
- package/dist/transport/agent-turn.js +20 -2
- package/dist/transport/agent-turn.js.map +1 -1
- package/dist/transport/events.d.ts +6 -1
- package/dist/transport/events.d.ts.map +1 -1
- package/dist/transport/events.js +1 -0
- package/dist/transport/events.js.map +1 -1
- package/dist/transport/inbound.d.ts +6 -0
- package/dist/transport/inbound.d.ts.map +1 -1
- package/dist/transport/inbound.js +66 -13
- package/dist/transport/inbound.js.map +1 -1
- package/dist/transport/outbound-buffer.d.ts +6 -0
- package/dist/transport/outbound-buffer.d.ts.map +1 -1
- package/dist/transport/outbound-buffer.js +13 -0
- package/dist/transport/outbound-buffer.js.map +1 -1
- package/dist/transport/outbound.d.ts.map +1 -1
- package/dist/transport/outbound.js +95 -21
- package/dist/transport/outbound.js.map +1 -1
- package/dist/transport/turn-steer.d.ts +70 -0
- package/dist/transport/turn-steer.d.ts.map +1 -0
- package/dist/transport/turn-steer.js +206 -0
- package/dist/transport/turn-steer.js.map +1 -0
- package/lib/client.js +10 -0
- package/lib/client.js.map +1 -1
- package/package.json +143 -137
- package/skills/dnd-module-authoring/SKILL.md +91 -0
- package/skills/dnd-module-authoring/guide.md +76 -47
- package/skills/dnd-rule-extension/SKILL.md +126 -0
- package/skills/qqbot-sticker-maker/SKILL.md +87 -0
- package/skills/qqbot-sticker-maker/references/character-specs.md +94 -0
- package/skills/qqbot-sticker-maker/references/meme-adaptation-notes.md +46 -0
- package/skills/qqbot-sticker-maker/resources/zipzippipe/sources.json +105 -0
- package/skills/qqbot-sticker-maker/scripts/sticker-cli.cjs +1158 -0
- package/skills/qqbot-sticker-maker/scripts/sticker-export.cjs +147 -0
|
@@ -0,0 +1,1158 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* sticker-cli.cjs
|
|
4
|
+
* Deterministic local image alignment, splicing, matting, previewing, and
|
|
5
|
+
* index.json registration CLI for cat, fish, Gemini, Claude, and GPT stickers.
|
|
6
|
+
*
|
|
7
|
+
* Zero network calls. Powered by `dsh-qqbot/node_modules/sharp`.
|
|
8
|
+
* Always writes full structured results to `--output <json-path>` to keep stdout concise.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
'use strict';
|
|
12
|
+
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const crypto = require('crypto');
|
|
16
|
+
const { exportSticker } = require('./sticker-export.cjs');
|
|
17
|
+
|
|
18
|
+
const SKILL_ROOT = path.resolve(__dirname, '..');
|
|
19
|
+
const PKG_OR_PARENT_ROOT = path.resolve(SKILL_ROOT, '../..');
|
|
20
|
+
const OUTER_ROOT = path.resolve(SKILL_ROOT, '../../..');
|
|
21
|
+
|
|
22
|
+
function resolveDefaultStickersDir() {
|
|
23
|
+
const candidates = [
|
|
24
|
+
process.env.DSH_CWD ? path.join(path.resolve(process.env.DSH_CWD), 'stickers') : null,
|
|
25
|
+
path.join(process.cwd(), 'stickers'),
|
|
26
|
+
path.join(PKG_OR_PARENT_ROOT, 'stickers'),
|
|
27
|
+
path.join(OUTER_ROOT, 'dsh-qqbot', 'stickers'),
|
|
28
|
+
].filter(Boolean);
|
|
29
|
+
for (const dir of candidates) {
|
|
30
|
+
if (fs.existsSync(dir)) return dir;
|
|
31
|
+
}
|
|
32
|
+
return path.join(process.cwd(), 'stickers');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function loadSharp() {
|
|
36
|
+
const candidates = [
|
|
37
|
+
path.join(PKG_OR_PARENT_ROOT, 'node_modules', 'sharp'),
|
|
38
|
+
path.join(OUTER_ROOT, 'sharp'),
|
|
39
|
+
path.join(OUTER_ROOT, 'dsh-qqbot', 'node_modules', 'sharp'),
|
|
40
|
+
path.join(process.cwd(), 'node_modules', 'sharp'),
|
|
41
|
+
path.join(process.cwd(), 'dsh-qqbot', 'node_modules', 'sharp'),
|
|
42
|
+
'sharp',
|
|
43
|
+
];
|
|
44
|
+
for (const modPath of candidates) {
|
|
45
|
+
try {
|
|
46
|
+
return require(modPath);
|
|
47
|
+
} catch (_) {
|
|
48
|
+
// try next candidate
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
throw new Error(
|
|
52
|
+
`Cannot resolve 'sharp'. Install optional dependency 'sharp' in your project or under ${PKG_OR_PARENT_ROOT}.`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseArgs(argv) {
|
|
57
|
+
const args = { _: [] };
|
|
58
|
+
for (let i = 0; i < argv.length; i++) {
|
|
59
|
+
const token = argv[i];
|
|
60
|
+
if (token === '--help' || token === '-h') {
|
|
61
|
+
args.help = true;
|
|
62
|
+
} else if (token.startsWith('--')) {
|
|
63
|
+
const eqIdx = token.indexOf('=');
|
|
64
|
+
if (eqIdx !== -1) {
|
|
65
|
+
const k = token.slice(2, eqIdx);
|
|
66
|
+
args[k] = token.slice(eqIdx + 1);
|
|
67
|
+
} else {
|
|
68
|
+
const k = token.slice(2);
|
|
69
|
+
const next = argv[i + 1];
|
|
70
|
+
if (next === undefined || next.startsWith('--')) {
|
|
71
|
+
args[k] = true;
|
|
72
|
+
} else {
|
|
73
|
+
args[k] = next;
|
|
74
|
+
i++;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
args._.push(token);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return args;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function ensureParentDir(filePath) {
|
|
85
|
+
fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function writeJsonReport(outPath, payload) {
|
|
89
|
+
const abs = path.resolve(outPath);
|
|
90
|
+
ensureParentDir(abs);
|
|
91
|
+
fs.writeFileSync(abs, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
|
92
|
+
return abs;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function fail(message, outPath, extra = {}) {
|
|
96
|
+
if (outPath && typeof outPath === 'string') {
|
|
97
|
+
try {
|
|
98
|
+
writeJsonReport(outPath, { ok: false, error: message, ...extra });
|
|
99
|
+
} catch (_) {
|
|
100
|
+
// ignore secondary report error
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
console.error(`ERROR: ${message}`);
|
|
104
|
+
process.exit(1);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function parseIntList(spec, expectedLen, label) {
|
|
108
|
+
const nums = String(spec)
|
|
109
|
+
.split(',')
|
|
110
|
+
.map((s) => Number(s.trim()));
|
|
111
|
+
if (nums.length !== expectedLen || nums.some((n) => !Number.isFinite(n))) {
|
|
112
|
+
throw new Error(`Invalid ${label} "${spec}" (expected ${expectedLen} comma-separated numbers).`);
|
|
113
|
+
}
|
|
114
|
+
return nums.map((n) => Math.round(n));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function parseBoxes(spec, label = 'box list') {
|
|
118
|
+
if (!spec || typeof spec !== 'string') return [];
|
|
119
|
+
return spec
|
|
120
|
+
.split(';')
|
|
121
|
+
.map((s) => s.trim())
|
|
122
|
+
.filter(Boolean)
|
|
123
|
+
.map((entry) => {
|
|
124
|
+
const [x0, y0, x1, y1] = parseIntList(entry, 4, label);
|
|
125
|
+
return {
|
|
126
|
+
x0: Math.min(x0, x1),
|
|
127
|
+
y0: Math.min(y0, y1),
|
|
128
|
+
x1: Math.max(x0, x1),
|
|
129
|
+
y1: Math.max(y0, y1),
|
|
130
|
+
};
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function parseSeeds(spec) {
|
|
135
|
+
if (!spec || typeof spec !== 'string') return [];
|
|
136
|
+
return spec
|
|
137
|
+
.split(';')
|
|
138
|
+
.map((s) => s.trim())
|
|
139
|
+
.filter(Boolean)
|
|
140
|
+
.map((entry) => {
|
|
141
|
+
const [x, y] = parseIntList(entry, 2, 'seed coordinate');
|
|
142
|
+
return { x, y };
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function printHelp(subcmd) {
|
|
147
|
+
const general = `Usage: node sticker-cli.cjs <subcommand> [options]
|
|
148
|
+
|
|
149
|
+
Subcommands:
|
|
150
|
+
align-guide Normalize source meme to 1024x1024, overlay coordinate grid, measure proportions, and optionally diff against a draft
|
|
151
|
+
splice Composite a newly polished local patch into a locked 1024x1024 base without global proportion drift
|
|
152
|
+
process Flood-fill white background to RGBA, detect enclosed white pockets, protect light fills, and export 1024 + target PNG + dark/light preview
|
|
153
|
+
export Preserve native alpha, export 1024 + target PNG, validate content/size, and preview final PNG pixels at 1:1
|
|
154
|
+
register Validate transparent PNG, copy to stickers/, compute sha256, and atomically update index.json
|
|
155
|
+
|
|
156
|
+
Run "node sticker-cli.cjs <subcommand> --help" for subcommand options.`;
|
|
157
|
+
|
|
158
|
+
const helps = {
|
|
159
|
+
'align-guide': `Usage: node sticker-cli.cjs align-guide --ref <path> --out-dir <dir> --output <json> [options]
|
|
160
|
+
|
|
161
|
+
Options:
|
|
162
|
+
--ref <path> Source meme reference image (single meme or sticker sheet)
|
|
163
|
+
--crop "x,y,w,h" Optional pixel crop on --ref before normalizing to 1024x1024
|
|
164
|
+
--compare <path> Optional generated draft to compare against normalized --ref (builds 3-panel overlay strip)
|
|
165
|
+
--out-dir <dir> Output directory for *_ref_1024.png, *_ref_grid.png, and *_align_compare.png
|
|
166
|
+
--tag <label> Optional filename prefix/tag (defaults to --ref basename)
|
|
167
|
+
--output <json> Required path to write JSON proportion metrics & file paths`,
|
|
168
|
+
|
|
169
|
+
splice: `Usage: node sticker-cli.cjs splice --base <path> --patch <path> --patch-crop "x,y,w,h" --target-box "x,y,w,h" --out <png> --output <json> [options]
|
|
170
|
+
|
|
171
|
+
Options:
|
|
172
|
+
--base <path> Locked base image (normalized to 1024x1024 white canvas if not already 1024x1024)
|
|
173
|
+
--patch <path> Newly generated image containing the polished detail region
|
|
174
|
+
--patch-crop "x,y,w,h" Crop box in 1024x1024 normalized patch coordinates (or raw patch pixels if --raw-patch-coords is passed)
|
|
175
|
+
--target-box "x,y,w,h" Destination box on the 1024x1024 base canvas
|
|
176
|
+
--clear-box "x0,y0,x1,y1;..." Optional 1024x1024 base regions filled with #FFFFFF prior to compositing (removes ghost outlines)
|
|
177
|
+
--raw-patch-coords Interpret --patch-crop in raw unscaled --patch pixel coordinates instead of 1024x1024
|
|
178
|
+
--out <png> Output path for spliced 1024x1024 PNG
|
|
179
|
+
--output <json> Required path to write JSON splice report`,
|
|
180
|
+
|
|
181
|
+
process: `Usage: node sticker-cli.cjs process --input <path> --name <cat_xxx|fish_xxx> --out-dir <dir> --output <json> [options]
|
|
182
|
+
|
|
183
|
+
Options:
|
|
184
|
+
--input <path> White-background illustration (.jpg/.png)
|
|
185
|
+
--name <stem> Sticker stem (e.g. cat_看书, fish_盯着你, gpt_夸夸我)
|
|
186
|
+
--out-dir <dir> Directory for <name>_1024.png and <name>.png
|
|
187
|
+
--preview-dir <dir> Directory for dark/light preview PNG (defaults to --out-dir)
|
|
188
|
+
--size <int> Final square sticker size in px (default: 256)
|
|
189
|
+
--tag <vN> Optional version tag to also emit <name>_<tag>_preview.png (avoids UI cache)
|
|
190
|
+
--bg-hard <int> Min RGB channel value treated as pure background white (default: 248)
|
|
191
|
+
--bg-soft <int> Min RGB channel value for 2px edge unpremultiply ramp (default: 226)
|
|
192
|
+
--extra-seeds "x,y;..." Extra 1024x1024 flood-fill seeds for enclosed background pockets
|
|
193
|
+
--protect-boxes "x0,y0,x1,y1;..." 1024x1024 rectangles shielded from flood-fill (protects sclera, book pages, pale skirt pleats, maid frills)
|
|
194
|
+
--gap-close-radius <int> Dilate dark outlines by N px (0-4) when computing flood barrier to seal tiny crayon line gaps (default: 0)
|
|
195
|
+
--white-border <int> Optional outer solid #FFFFFF sticker border radius on 1024 master (default: 0 = no white border)
|
|
196
|
+
--output <json> Required path to write JSON matting & pocket-inspection report`,
|
|
197
|
+
|
|
198
|
+
export: `Usage: node sticker-cli.cjs export --input <transparent-png> --name <stem> --out-dir <dir> --output <json> [options]
|
|
199
|
+
|
|
200
|
+
Options:
|
|
201
|
+
--input <png> Static transparent PNG (native alpha is preserved; no white flood-fill)
|
|
202
|
+
--name <stem> Output filename stem (e.g. gpt_夸夸我; optional .png suffix)
|
|
203
|
+
--out-dir <dir> Directory for <stem>_1024.png master and <stem>.png sticker
|
|
204
|
+
--preview-dir <dir> Directory for <stem>_preview.png (defaults to --out-dir)
|
|
205
|
+
--size <int> Final square sticker size, 64..2048 (default: 256)
|
|
206
|
+
--tag <label> Append a version label to ALL output image filenames
|
|
207
|
+
--max-kb <number> Max final PNG size in KiB (default: 300)
|
|
208
|
+
--force Replace existing export artifacts/report; never replace the input
|
|
209
|
+
--output <json> Required report path, distinct from input and exported images
|
|
210
|
+
|
|
211
|
+
Non-square inputs are padded transparently without stretching. Preview tiles decode
|
|
212
|
+
the exact final PNG at its native pixel size. Existing outputs are kept by default.`,
|
|
213
|
+
|
|
214
|
+
register: `Usage: node sticker-cli.cjs register --input <png> --emotion <str> --look <str> --note <str> --output <json> [options]
|
|
215
|
+
|
|
216
|
+
Options:
|
|
217
|
+
--input <png> Approved transparent RGBA sticker PNG
|
|
218
|
+
--file <filename> Target filename in stickers/ (defaults to basename of --input)
|
|
219
|
+
--allow-custom-prefix Allow another prefix; basename/path validation still applies
|
|
220
|
+
--emotion <str> Short emotion/intent label
|
|
221
|
+
--look <str> Objective visual description of the sticker
|
|
222
|
+
--note <str> When/why the bot should pick this sticker
|
|
223
|
+
--stickers-dir <dir> Target stickers directory (auto-detects <cwd>/stickers or plugin stickers/)
|
|
224
|
+
--init Create stickers/ and initialize an empty index.json if missing
|
|
225
|
+
--auto <true|false> Set "auto" boolean field in index.json (default: false)
|
|
226
|
+
--max-kb <number> Max allowed file size in KB before failing (default: 300)
|
|
227
|
+
--allow-large Allow registering files larger than --max-kb
|
|
228
|
+
--dry-run Validate and compute sha256 without writing to stickers/ or index.json
|
|
229
|
+
--output <json> Required path to write JSON registration report`,
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
console.log(helps[subcmd] || general);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Estimate border background RGB by taking per-channel median along the 4 edges of an RGBA buffer.
|
|
237
|
+
*/
|
|
238
|
+
function detectBorderBgRgb(raw, width, height) {
|
|
239
|
+
const rs = [];
|
|
240
|
+
const gs = [];
|
|
241
|
+
const bs = [];
|
|
242
|
+
const pushPx = (x, y) => {
|
|
243
|
+
const idx = (y * width + x) * 4;
|
|
244
|
+
if (raw[idx + 3] < 25) {
|
|
245
|
+
rs.push(255);
|
|
246
|
+
gs.push(255);
|
|
247
|
+
bs.push(255);
|
|
248
|
+
} else {
|
|
249
|
+
rs.push(raw[idx]);
|
|
250
|
+
gs.push(raw[idx + 1]);
|
|
251
|
+
bs.push(raw[idx + 2]);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
for (let x = 0; x < width; x += Math.max(1, Math.floor(width / 128))) {
|
|
255
|
+
pushPx(x, 0);
|
|
256
|
+
pushPx(x, height - 1);
|
|
257
|
+
}
|
|
258
|
+
for (let y = 0; y < height; y += Math.max(1, Math.floor(height / 128))) {
|
|
259
|
+
pushPx(0, y);
|
|
260
|
+
pushPx(width - 1, y);
|
|
261
|
+
}
|
|
262
|
+
const median = (arr) => {
|
|
263
|
+
const sorted = arr.slice().sort((a, b) => a - b);
|
|
264
|
+
return sorted[Math.floor(sorted.length / 2)] ?? 255;
|
|
265
|
+
};
|
|
266
|
+
return { r: median(rs), g: median(gs), b: median(bs) };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Normalize an image (with optional crop) onto a 1024x1024 solid #FFFFFF RGB/RGBA buffer
|
|
271
|
+
* (or auto-detected border background color when preserveBorderBg=true for sticker sheets).
|
|
272
|
+
*/
|
|
273
|
+
async function normalizeTo1024White(sharp, inputPath, cropSpec, preserveBorderBg = false) {
|
|
274
|
+
let pipeline = sharp(path.resolve(inputPath));
|
|
275
|
+
const origMeta = await pipeline.metadata();
|
|
276
|
+
if (cropSpec) {
|
|
277
|
+
const [left, top, width, height] = parseIntList(cropSpec, 4, '--crop');
|
|
278
|
+
pipeline = sharp(path.resolve(inputPath)).extract({ left, top, width, height });
|
|
279
|
+
}
|
|
280
|
+
let bg = { r: 255, g: 255, b: 255 };
|
|
281
|
+
if (preserveBorderBg) {
|
|
282
|
+
const { data: probeRaw, info: probeInfo } = await pipeline
|
|
283
|
+
.clone()
|
|
284
|
+
.ensureAlpha()
|
|
285
|
+
.raw()
|
|
286
|
+
.toBuffer({ resolveWithObject: true });
|
|
287
|
+
bg = detectBorderBgRgb(probeRaw, probeInfo.width, probeInfo.height);
|
|
288
|
+
}
|
|
289
|
+
const buf = await pipeline
|
|
290
|
+
.flatten({ background: bg })
|
|
291
|
+
.resize(1024, 1024, {
|
|
292
|
+
fit: 'contain',
|
|
293
|
+
background: bg,
|
|
294
|
+
})
|
|
295
|
+
.ensureAlpha()
|
|
296
|
+
.raw()
|
|
297
|
+
.toBuffer();
|
|
298
|
+
return { raw: buf, origWidth: origMeta.width, origHeight: origMeta.height, bg };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Measure foreground bounding box and 10-band horizontal width profile on a 1024x1024 buffer
|
|
303
|
+
* relative to its background color `bg` (handles white, dark-gray sticker sheets, etc.).
|
|
304
|
+
*/
|
|
305
|
+
function measureProportions1024(raw, bg = { r: 255, g: 255, b: 255 }) {
|
|
306
|
+
const W = 1024;
|
|
307
|
+
const H = 1024;
|
|
308
|
+
let minX = W,
|
|
309
|
+
minY = H,
|
|
310
|
+
maxX = -1,
|
|
311
|
+
maxY = -1;
|
|
312
|
+
let fgPixels = 0;
|
|
313
|
+
|
|
314
|
+
const isFg = (idx) => {
|
|
315
|
+
const r = raw[idx];
|
|
316
|
+
const g = raw[idx + 1];
|
|
317
|
+
const b = raw[idx + 2];
|
|
318
|
+
const a = raw[idx + 3];
|
|
319
|
+
if (a < 25) return false;
|
|
320
|
+
const dist = Math.max(Math.abs(r - bg.r), Math.abs(g - bg.g), Math.abs(b - bg.b));
|
|
321
|
+
return dist > 22;
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const bands = [];
|
|
325
|
+
for (let b = 0; b < 10; b++) {
|
|
326
|
+
const yStart = Math.round((b * H) / 10);
|
|
327
|
+
const yEnd = Math.round(((b + 1) * H) / 10) - 1;
|
|
328
|
+
let bMinX = W,
|
|
329
|
+
bMaxX = -1,
|
|
330
|
+
bCount = 0;
|
|
331
|
+
for (let y = yStart; y <= yEnd; y++) {
|
|
332
|
+
for (let x = 0; x < W; x++) {
|
|
333
|
+
const idx = (y * W + x) * 4;
|
|
334
|
+
if (isFg(idx)) {
|
|
335
|
+
fgPixels++;
|
|
336
|
+
if (x < minX) minX = x;
|
|
337
|
+
if (x > maxX) maxX = x;
|
|
338
|
+
if (y < minY) minY = y;
|
|
339
|
+
if (y > maxY) maxY = y;
|
|
340
|
+
if (x < bMinX) bMinX = x;
|
|
341
|
+
if (x > bMaxX) bMaxX = x;
|
|
342
|
+
bCount++;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
bands.push({
|
|
347
|
+
yRangePx: [yStart, yEnd],
|
|
348
|
+
yRangePct: `${b * 10}%-${(b + 1) * 10}%`,
|
|
349
|
+
leftPx: bMaxX >= bMinX ? bMinX : null,
|
|
350
|
+
rightPx: bMaxX >= bMinX ? bMaxX : null,
|
|
351
|
+
spanPx: bMaxX >= bMinX ? bMaxX - bMinX + 1 : 0,
|
|
352
|
+
spanPct: bMaxX >= bMinX ? Number((((bMaxX - bMinX + 1) / W) * 100).toFixed(1)) : 0,
|
|
353
|
+
fgPixels: bCount,
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (maxX < minX) {
|
|
358
|
+
return { empty: true, fgPixels: 0, bands };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const widthPx = maxX - minX + 1;
|
|
362
|
+
const heightPx = maxY - minY + 1;
|
|
363
|
+
return {
|
|
364
|
+
empty: false,
|
|
365
|
+
fgPixels,
|
|
366
|
+
bboxPx: { x0: minX, y0: minY, x1: maxX, y1: maxY, width: widthPx, height: heightPx },
|
|
367
|
+
bboxPct: {
|
|
368
|
+
left: Number(((minX / W) * 100).toFixed(1)),
|
|
369
|
+
top: Number(((minY / H) * 100).toFixed(1)),
|
|
370
|
+
right: Number(((maxX / W) * 100).toFixed(1)),
|
|
371
|
+
bottom: Number(((maxY / H) * 100).toFixed(1)),
|
|
372
|
+
width: Number(((widthPx / W) * 100).toFixed(1)),
|
|
373
|
+
height: Number(((heightPx / H) * 100).toFixed(1)),
|
|
374
|
+
centerX: Number(((((minX + maxX) / 2 / W) * 100)).toFixed(1)),
|
|
375
|
+
centerY: Number(((((minY + maxY) / 2 / H) * 100)).toFixed(1)),
|
|
376
|
+
},
|
|
377
|
+
edgeBleed: {
|
|
378
|
+
touchesLeft: minX <= 8,
|
|
379
|
+
touchesRight: maxX >= W - 9,
|
|
380
|
+
touchesTop: minY <= 8,
|
|
381
|
+
touchesBottom: maxY >= H - 9,
|
|
382
|
+
},
|
|
383
|
+
horizontalBands: bands,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function buildGridSvg1024(metrics, boxColor = '#E11D48', titleText = '') {
|
|
388
|
+
const lines = [];
|
|
389
|
+
for (let i = 1; i < 10; i++) {
|
|
390
|
+
const pos = Math.round((i * 1024) / 10);
|
|
391
|
+
const pct = i * 10;
|
|
392
|
+
const isMid = i === 5;
|
|
393
|
+
const stroke = isMid ? 'rgba(37,99,235,0.55)' : 'rgba(59,130,246,0.32)';
|
|
394
|
+
const width = isMid ? 2 : 1;
|
|
395
|
+
lines.push(`<line x1="${pos}" y1="0" x2="${pos}" y2="1024" stroke="${stroke}" stroke-width="${width}" />`);
|
|
396
|
+
lines.push(`<line x1="0" y1="${pos}" x2="1024" y2="${pos}" stroke="${stroke}" stroke-width="${width}" />`);
|
|
397
|
+
lines.push(
|
|
398
|
+
`<rect x="${pos + 2}" y="4" width="66" height="20" rx="3" fill="rgba(255,255,255,0.82)" />`,
|
|
399
|
+
`<text x="${pos + 5}" y="18" font-family="Consolas, monospace" font-size="12" fill="#1E3A8A">${pct}%/${pos}</text>`,
|
|
400
|
+
`<rect x="4" y="${pos + 2}" width="66" height="20" rx="3" fill="rgba(255,255,255,0.82)" />`,
|
|
401
|
+
`<text x="7" y="${pos + 16}" font-family="Consolas, monospace" font-size="12" fill="#1E3A8A">${pct}%/${pos}</text>`
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
if (metrics && !metrics.empty) {
|
|
405
|
+
const { x0, y0, width, height } = metrics.bboxPx;
|
|
406
|
+
lines.push(
|
|
407
|
+
`<rect x="${x0}" y="${y0}" width="${width}" height="${height}" fill="none" stroke="${boxColor}" stroke-width="3" stroke-dasharray="10,6" />`
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
if (titleText) {
|
|
411
|
+
lines.push(
|
|
412
|
+
`<rect x="330" y="986" width="364" height="32" rx="6" fill="rgba(15,23,42,0.82)" />`,
|
|
413
|
+
`<text x="512" y="1007" text-anchor="middle" font-family="Consolas, sans-serif" font-size="15" font-weight="bold" fill="#F8FAFC">${titleText}</text>`
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
return Buffer.from(`<svg width="1024" height="1024" xmlns="http://www.w3.org/2000/svg">${lines.join('\n')}</svg>`);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function cmdAlignGuide(sharp, args) {
|
|
420
|
+
const outReport = args.output;
|
|
421
|
+
if (!outReport) fail('Missing required --output <json-path>.');
|
|
422
|
+
if (!args.ref) fail('Missing required --ref <source-meme-path>.', outReport);
|
|
423
|
+
if (!args['out-dir']) fail('Missing required --out-dir <dir>.', outReport);
|
|
424
|
+
if (!fs.existsSync(path.resolve(args.ref))) {
|
|
425
|
+
fail(`Reference file not found: ${args.ref}`, outReport);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const outDir = path.resolve(args['out-dir']);
|
|
429
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
430
|
+
const prefix = args.tag || path.parse(args.ref).name;
|
|
431
|
+
|
|
432
|
+
const refNorm = await normalizeTo1024White(sharp, args.ref, args.crop, true);
|
|
433
|
+
const refMetrics = measureProportions1024(refNorm.raw, refNorm.bg);
|
|
434
|
+
|
|
435
|
+
const ref1024Path = path.join(outDir, `${prefix}_ref_1024.png`);
|
|
436
|
+
const refGridPath = path.join(outDir, `${prefix}_ref_grid.png`);
|
|
437
|
+
|
|
438
|
+
await sharp(refNorm.raw, { raw: { width: 1024, height: 1024, channels: 4 } })
|
|
439
|
+
.png()
|
|
440
|
+
.toFile(ref1024Path);
|
|
441
|
+
|
|
442
|
+
const refGridSvg = buildGridSvg1024(refMetrics, '#E11D48', 'SOURCE MEME (1024 GRID)');
|
|
443
|
+
const refGridPng = await sharp(refNorm.raw, { raw: { width: 1024, height: 1024, channels: 4 } })
|
|
444
|
+
.composite([{ input: refGridSvg, top: 0, left: 0 }])
|
|
445
|
+
.png()
|
|
446
|
+
.toBuffer();
|
|
447
|
+
fs.writeFileSync(refGridPath, refGridPng);
|
|
448
|
+
|
|
449
|
+
const result = {
|
|
450
|
+
ok: true,
|
|
451
|
+
command: 'align-guide',
|
|
452
|
+
refInput: path.resolve(args.ref),
|
|
453
|
+
detectedRefBgRgb: refNorm.bg,
|
|
454
|
+
crop: args.crop || null,
|
|
455
|
+
files: {
|
|
456
|
+
ref1024: ref1024Path,
|
|
457
|
+
refGrid: refGridPath,
|
|
458
|
+
alignCompare: null,
|
|
459
|
+
},
|
|
460
|
+
refMetrics,
|
|
461
|
+
compareMetrics: null,
|
|
462
|
+
proportionDiff: null,
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
if (args.compare) {
|
|
466
|
+
if (!fs.existsSync(path.resolve(args.compare))) {
|
|
467
|
+
fail(`Compare draft file not found: ${args.compare}`, outReport);
|
|
468
|
+
}
|
|
469
|
+
const cmpNorm = await normalizeTo1024White(sharp, args.compare, null, true);
|
|
470
|
+
const cmpMetrics = measureProportions1024(cmpNorm.raw, cmpNorm.bg);
|
|
471
|
+
|
|
472
|
+
// Build tinted 50/50 overlay on clean white base: source meme fg -> rose-red, draft fg -> teal-blue
|
|
473
|
+
const overlayRaw = Buffer.alloc(1024 * 1024 * 4);
|
|
474
|
+
for (let i = 0; i < 1024 * 1024; i++) {
|
|
475
|
+
const idx = i * 4;
|
|
476
|
+
const rDist = Math.max(
|
|
477
|
+
Math.abs(refNorm.raw[idx] - refNorm.bg.r),
|
|
478
|
+
Math.abs(refNorm.raw[idx + 1] - refNorm.bg.g),
|
|
479
|
+
Math.abs(refNorm.raw[idx + 2] - refNorm.bg.b)
|
|
480
|
+
);
|
|
481
|
+
const cDist = Math.max(
|
|
482
|
+
Math.abs(cmpNorm.raw[idx] - cmpNorm.bg.r),
|
|
483
|
+
Math.abs(cmpNorm.raw[idx + 1] - cmpNorm.bg.g),
|
|
484
|
+
Math.abs(cmpNorm.raw[idx + 2] - cmpNorm.bg.b)
|
|
485
|
+
);
|
|
486
|
+
const refSig = rDist <= 18 ? 0 : Math.min(1, (rDist - 18) / 145);
|
|
487
|
+
const cmpSig = cDist <= 18 ? 0 : Math.min(1, (cDist - 18) / 145);
|
|
488
|
+
const r = Math.round(255 * (1 - 0.78 * cmpSig));
|
|
489
|
+
const g = Math.round(255 * (1 - 0.75 * refSig - 0.22 * cmpSig));
|
|
490
|
+
const b = Math.round(255 * (1 - 0.65 * refSig));
|
|
491
|
+
overlayRaw[idx] = Math.max(0, Math.min(255, r));
|
|
492
|
+
overlayRaw[idx + 1] = Math.max(0, Math.min(255, g));
|
|
493
|
+
overlayRaw[idx + 2] = Math.max(0, Math.min(255, b));
|
|
494
|
+
overlayRaw[idx + 3] = 255;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const overlaySvg = buildGridSvg1024(refMetrics, '#E11D48', 'OVERLAY: RED=REF / CYAN=DRAFT');
|
|
498
|
+
const overlayPng = await sharp(overlayRaw, { raw: { width: 1024, height: 1024, channels: 4 } })
|
|
499
|
+
.composite([{ input: overlaySvg, top: 0, left: 0 }])
|
|
500
|
+
.png()
|
|
501
|
+
.toBuffer();
|
|
502
|
+
|
|
503
|
+
const cmpSvg = buildGridSvg1024(cmpMetrics, '#0284C7', 'DRAFT (1024 GRID)');
|
|
504
|
+
const cmpGridPng = await sharp(cmpNorm.raw, { raw: { width: 1024, height: 1024, channels: 4 } })
|
|
505
|
+
.composite([{ input: cmpSvg, top: 0, left: 0 }])
|
|
506
|
+
.png()
|
|
507
|
+
.toBuffer();
|
|
508
|
+
|
|
509
|
+
const comparePath = path.join(outDir, `${prefix}_align_compare.png`);
|
|
510
|
+
await sharp({
|
|
511
|
+
create: {
|
|
512
|
+
width: 1024 * 3 + 32,
|
|
513
|
+
height: 1024,
|
|
514
|
+
channels: 4,
|
|
515
|
+
background: { r: 30, g: 41, b: 59, alpha: 1 },
|
|
516
|
+
},
|
|
517
|
+
})
|
|
518
|
+
.composite([
|
|
519
|
+
{ input: refGridPng, left: 0, top: 0 },
|
|
520
|
+
{ input: overlayPng, left: 1040, top: 0 },
|
|
521
|
+
{ input: cmpGridPng, left: 2080, top: 0 },
|
|
522
|
+
])
|
|
523
|
+
.png()
|
|
524
|
+
.toFile(comparePath);
|
|
525
|
+
|
|
526
|
+
result.files.alignCompare = comparePath;
|
|
527
|
+
result.compareMetrics = cmpMetrics;
|
|
528
|
+
if (!refMetrics.empty && !cmpMetrics.empty) {
|
|
529
|
+
result.proportionDiff = {
|
|
530
|
+
widthPctDelta: Number((cmpMetrics.bboxPct.width - refMetrics.bboxPct.width).toFixed(1)),
|
|
531
|
+
heightPctDelta: Number((cmpMetrics.bboxPct.height - refMetrics.bboxPct.height).toFixed(1)),
|
|
532
|
+
centerXPctDelta: Number((cmpMetrics.bboxPct.centerX - refMetrics.bboxPct.centerX).toFixed(1)),
|
|
533
|
+
centerYPctDelta: Number((cmpMetrics.bboxPct.centerY - refMetrics.bboxPct.centerY).toFixed(1)),
|
|
534
|
+
topPxDelta: cmpMetrics.bboxPx.y0 - refMetrics.bboxPx.y0,
|
|
535
|
+
bottomPxDelta: cmpMetrics.bboxPx.y1 - refMetrics.bboxPx.y1,
|
|
536
|
+
bandSpanPctDeltas: refMetrics.horizontalBands.map((rb, idx) => ({
|
|
537
|
+
yRangePct: rb.yRangePct,
|
|
538
|
+
refSpanPct: rb.spanPct,
|
|
539
|
+
draftSpanPct: cmpMetrics.horizontalBands[idx].spanPct,
|
|
540
|
+
deltaPct: Number((cmpMetrics.horizontalBands[idx].spanPct - rb.spanPct).toFixed(1)),
|
|
541
|
+
})),
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const reportAbs = writeJsonReport(outReport, result);
|
|
547
|
+
console.log(`align-guide OK -> grid: ${refGridPath} | report: ${reportAbs}`);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async function cmdSplice(sharp, args) {
|
|
551
|
+
const outReport = args.output;
|
|
552
|
+
if (!outReport) fail('Missing required --output <json-path>.');
|
|
553
|
+
for (const req of ['base', 'patch', 'patch-crop', 'target-box', 'out']) {
|
|
554
|
+
if (!args[req]) fail(`Missing required --${req}.`, outReport);
|
|
555
|
+
}
|
|
556
|
+
if (!fs.existsSync(path.resolve(args.base))) fail(`Base image not found: ${args.base}`, outReport);
|
|
557
|
+
if (!fs.existsSync(path.resolve(args.patch))) fail(`Patch image not found: ${args.patch}`, outReport);
|
|
558
|
+
|
|
559
|
+
const baseNorm = await normalizeTo1024White(sharp, args.base, null);
|
|
560
|
+
const baseRaw = Buffer.from(baseNorm.raw);
|
|
561
|
+
|
|
562
|
+
const clearBoxes = parseBoxes(args['clear-box'], '--clear-box');
|
|
563
|
+
for (const box of clearBoxes) {
|
|
564
|
+
const x0 = Math.max(0, box.x0);
|
|
565
|
+
const y0 = Math.max(0, box.y0);
|
|
566
|
+
const x1 = Math.min(1023, box.x1);
|
|
567
|
+
const y1 = Math.min(1023, box.y1);
|
|
568
|
+
for (let y = y0; y <= y1; y++) {
|
|
569
|
+
for (let x = x0; x <= x1; x++) {
|
|
570
|
+
const idx = (y * 1024 + x) * 4;
|
|
571
|
+
baseRaw[idx] = 255;
|
|
572
|
+
baseRaw[idx + 1] = 255;
|
|
573
|
+
baseRaw[idx + 2] = 255;
|
|
574
|
+
baseRaw[idx + 3] = 255;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const [cropLeft, cropTop, cropW, cropH] = parseIntList(args['patch-crop'], 4, '--patch-crop');
|
|
580
|
+
const [dstLeft, dstTop, dstW, dstH] = parseIntList(args['target-box'], 4, '--target-box');
|
|
581
|
+
|
|
582
|
+
let patchPipeline;
|
|
583
|
+
if (args['raw-patch-coords']) {
|
|
584
|
+
patchPipeline = sharp(path.resolve(args.patch))
|
|
585
|
+
.flatten({ background: { r: 255, g: 255, b: 255 } })
|
|
586
|
+
.extract({ left: cropLeft, top: cropTop, width: cropW, height: cropH });
|
|
587
|
+
} else {
|
|
588
|
+
const patchNorm = await normalizeTo1024White(sharp, args.patch, null);
|
|
589
|
+
patchPipeline = sharp(patchNorm.raw, { raw: { width: 1024, height: 1024, channels: 4 } }).extract({
|
|
590
|
+
left: cropLeft,
|
|
591
|
+
top: cropTop,
|
|
592
|
+
width: cropW,
|
|
593
|
+
height: cropH,
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const resizedPatchPng = await patchPipeline
|
|
598
|
+
.resize(dstW, dstH, { fit: 'fill', kernel: sharp.kernel.lanczos3 })
|
|
599
|
+
.png()
|
|
600
|
+
.toBuffer();
|
|
601
|
+
|
|
602
|
+
const outPngPath = path.resolve(args.out);
|
|
603
|
+
ensureParentDir(outPngPath);
|
|
604
|
+
await sharp(baseRaw, { raw: { width: 1024, height: 1024, channels: 4 } })
|
|
605
|
+
.composite([{ input: resizedPatchPng, left: dstLeft, top: dstTop }])
|
|
606
|
+
.png()
|
|
607
|
+
.toFile(outPngPath);
|
|
608
|
+
|
|
609
|
+
const reportAbs = writeJsonReport(outReport, {
|
|
610
|
+
ok: true,
|
|
611
|
+
command: 'splice',
|
|
612
|
+
base: path.resolve(args.base),
|
|
613
|
+
patch: path.resolve(args.patch),
|
|
614
|
+
patchCrop: { left: cropLeft, top: cropTop, width: cropW, height: cropH },
|
|
615
|
+
targetBox: { left: dstLeft, top: dstTop, width: dstW, height: dstH },
|
|
616
|
+
clearedBoxes: clearBoxes,
|
|
617
|
+
outFile: outPngPath,
|
|
618
|
+
});
|
|
619
|
+
console.log(`splice OK -> ${outPngPath} | report: ${reportAbs}`);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
async function cmdProcess(sharp, args) {
|
|
623
|
+
const outReport = args.output;
|
|
624
|
+
if (!outReport) fail('Missing required --output <json-path>.');
|
|
625
|
+
for (const req of ['input', 'name', 'out-dir']) {
|
|
626
|
+
if (!args[req]) fail(`Missing required --${req}.`, outReport);
|
|
627
|
+
}
|
|
628
|
+
const inputAbs = path.resolve(args.input);
|
|
629
|
+
if (!fs.existsSync(inputAbs)) fail(`Input image not found: ${args.input}`, outReport);
|
|
630
|
+
|
|
631
|
+
const stem = String(args.name).replace(/\.(png|jpg|jpeg|webp)$/i, '');
|
|
632
|
+
if (!stem || /[\\/:*?"<>|\x00-\x1f]/.test(stem) || stem === '.' || stem === '..') {
|
|
633
|
+
fail('Invalid --name: expected a filename stem without path separators or invalid characters.', outReport);
|
|
634
|
+
}
|
|
635
|
+
const outDir = path.resolve(args['out-dir']);
|
|
636
|
+
const previewDir = args['preview-dir'] ? path.resolve(args['preview-dir']) : outDir;
|
|
637
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
638
|
+
fs.mkdirSync(previewDir, { recursive: true });
|
|
639
|
+
|
|
640
|
+
const targetSize = args.size !== undefined ? Number(args.size) : 256;
|
|
641
|
+
if (!Number.isInteger(targetSize) || targetSize < 64 || targetSize > 2048) {
|
|
642
|
+
fail(`Invalid --size "${args.size}" (expected integer 64..2048).`, outReport);
|
|
643
|
+
}
|
|
644
|
+
const bgHard = args['bg-hard'] !== undefined ? Number(args['bg-hard']) : 248;
|
|
645
|
+
const bgSoft = args['bg-soft'] !== undefined ? Number(args['bg-soft']) : 226;
|
|
646
|
+
const gapCloseRadius = args['gap-close-radius'] !== undefined ? Number(args['gap-close-radius']) : 0;
|
|
647
|
+
const whiteBorder = args['white-border'] !== undefined ? Number(args['white-border']) : 0;
|
|
648
|
+
const protectBoxes = parseBoxes(args['protect-boxes'], '--protect-boxes');
|
|
649
|
+
const extraSeeds = parseSeeds(args['extra-seeds']);
|
|
650
|
+
|
|
651
|
+
const W = 1024;
|
|
652
|
+
const H = 1024;
|
|
653
|
+
const norm = await normalizeTo1024White(sharp, inputAbs, null);
|
|
654
|
+
const rgba = Buffer.from(norm.raw);
|
|
655
|
+
|
|
656
|
+
// Build protected pixel mask
|
|
657
|
+
const protectedMask = new Uint8Array(W * H);
|
|
658
|
+
for (const box of protectBoxes) {
|
|
659
|
+
const x0 = Math.max(0, box.x0);
|
|
660
|
+
const y0 = Math.max(0, box.y0);
|
|
661
|
+
const x1 = Math.min(W - 1, box.x1);
|
|
662
|
+
const y1 = Math.min(H - 1, box.y1);
|
|
663
|
+
for (let y = y0; y <= y1; y++) {
|
|
664
|
+
for (let x = x0; x <= x1; x++) {
|
|
665
|
+
protectedMask[y * W + x] = 1;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// Optional morphological gap closing on dark outline barrier (flood barrier only; does not alter visible RGB)
|
|
671
|
+
const darkBarrier = new Uint8Array(W * H);
|
|
672
|
+
if (gapCloseRadius > 0) {
|
|
673
|
+
const rad = Math.min(6, Math.max(0, Math.round(gapCloseRadius)));
|
|
674
|
+
const rawDark = new Uint8Array(W * H);
|
|
675
|
+
for (let p = 0; p < W * H; p++) {
|
|
676
|
+
const idx = p * 4;
|
|
677
|
+
const minCh = Math.min(rgba[idx], rgba[idx + 1], rgba[idx + 2]);
|
|
678
|
+
if (minCh < 155) rawDark[p] = 1;
|
|
679
|
+
}
|
|
680
|
+
for (let y = 0; y < H; y++) {
|
|
681
|
+
for (let x = 0; x < W; x++) {
|
|
682
|
+
if (!rawDark[y * W + x]) continue;
|
|
683
|
+
for (let dy = -rad; dy <= rad; dy++) {
|
|
684
|
+
const ny = y + dy;
|
|
685
|
+
if (ny < 0 || ny >= H) continue;
|
|
686
|
+
for (let dx = -rad; dx <= rad; dx++) {
|
|
687
|
+
const nx = x + dx;
|
|
688
|
+
if (nx < 0 || nx >= W) continue;
|
|
689
|
+
if (dx * dx + dy * dy <= rad * rad) {
|
|
690
|
+
darkBarrier[ny * W + nx] = 1;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const canFlood = (p) => {
|
|
699
|
+
if (protectedMask[p] || darkBarrier[p]) return false;
|
|
700
|
+
const idx = p * 4;
|
|
701
|
+
return rgba[idx] >= bgHard && rgba[idx + 1] >= bgHard && rgba[idx + 2] >= bgHard;
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
const bgVisited = new Uint8Array(W * H);
|
|
705
|
+
const queue = new Int32Array(W * H);
|
|
706
|
+
let qHead = 0;
|
|
707
|
+
let qTail = 0;
|
|
708
|
+
|
|
709
|
+
const tryPush = (x, y) => {
|
|
710
|
+
if (x < 0 || x >= W || y < 0 || y >= H) return;
|
|
711
|
+
const p = y * W + x;
|
|
712
|
+
if (bgVisited[p] || !canFlood(p)) return;
|
|
713
|
+
bgVisited[p] = 1;
|
|
714
|
+
queue[qTail++] = p;
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
for (let x = 0; x < W; x++) {
|
|
718
|
+
tryPush(x, 0);
|
|
719
|
+
tryPush(x, H - 1);
|
|
720
|
+
}
|
|
721
|
+
for (let y = 0; y < H; y++) {
|
|
722
|
+
tryPush(0, y);
|
|
723
|
+
tryPush(W - 1, y);
|
|
724
|
+
}
|
|
725
|
+
for (const s of extraSeeds) {
|
|
726
|
+
tryPush(s.x, s.y);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
while (qHead < qTail) {
|
|
730
|
+
const p = queue[qHead++];
|
|
731
|
+
const x = p % W;
|
|
732
|
+
const y = (p - x) / W;
|
|
733
|
+
if (x > 0) tryPush(x - 1, y);
|
|
734
|
+
if (x + 1 < W) tryPush(x + 1, y);
|
|
735
|
+
if (y > 0) tryPush(x, y - 1);
|
|
736
|
+
if (y + 1 < H) tryPush(x, y + 1);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// Zero out flooded background
|
|
740
|
+
for (let p = 0; p < W * H; p++) {
|
|
741
|
+
if (bgVisited[p]) {
|
|
742
|
+
rgba[p * 4 + 3] = 0;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// 2-pass 1px edge unpremultiply ramp to eliminate white fringe on dark chat backgrounds
|
|
747
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
748
|
+
const prevAlpha = new Uint8Array(W * H);
|
|
749
|
+
for (let p = 0; p < W * H; p++) prevAlpha[p] = rgba[p * 4 + 3];
|
|
750
|
+
|
|
751
|
+
for (let y = 0; y < H; y++) {
|
|
752
|
+
for (let x = 0; x < W; x++) {
|
|
753
|
+
const p = y * W + x;
|
|
754
|
+
if (prevAlpha[p] === 0 || protectedMask[p]) continue;
|
|
755
|
+
let touchesTrans = false;
|
|
756
|
+
for (let dy = -1; dy <= 1 && !touchesTrans; dy++) {
|
|
757
|
+
const ny = y + dy;
|
|
758
|
+
if (ny < 0 || ny >= H) continue;
|
|
759
|
+
for (let dx = -1; dx <= 1; dx++) {
|
|
760
|
+
const nx = x + dx;
|
|
761
|
+
if (nx < 0 || nx >= W) continue;
|
|
762
|
+
if (prevAlpha[ny * W + nx] < 32) {
|
|
763
|
+
touchesTrans = true;
|
|
764
|
+
break;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (!touchesTrans) continue;
|
|
769
|
+
const idx = p * 4;
|
|
770
|
+
const r = rgba[idx];
|
|
771
|
+
const g = rgba[idx + 1];
|
|
772
|
+
const b = rgba[idx + 2];
|
|
773
|
+
const minCh = Math.min(r, g, b);
|
|
774
|
+
if (minCh >= bgSoft) {
|
|
775
|
+
const t = Math.max(0, Math.min(1, (bgHard - minCh) / Math.max(1, bgHard - bgSoft)));
|
|
776
|
+
const newA = Math.round(prevAlpha[p] * t);
|
|
777
|
+
rgba[idx + 3] = newA;
|
|
778
|
+
if (newA > 8) {
|
|
779
|
+
const aFrac = newA / 255;
|
|
780
|
+
rgba[idx] = Math.max(0, Math.min(255, Math.round((r - 255 * (1 - aFrac)) / aFrac)));
|
|
781
|
+
rgba[idx + 1] = Math.max(0, Math.min(255, Math.round((g - 255 * (1 - aFrac)) / aFrac)));
|
|
782
|
+
rgba[idx + 2] = Math.max(0, Math.min(255, Math.round((b - 255 * (1 - aFrac)) / aFrac)));
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// Optional outer white sticker border if explicitly requested (--white-border > 0)
|
|
790
|
+
if (whiteBorder > 0) {
|
|
791
|
+
const rad = Math.min(24, Math.round(whiteBorder));
|
|
792
|
+
const fgMask = new Uint8Array(W * H);
|
|
793
|
+
for (let p = 0; p < W * H; p++) {
|
|
794
|
+
if (rgba[p * 4 + 3] >= 100) fgMask[p] = 1;
|
|
795
|
+
}
|
|
796
|
+
const borderMask = new Uint8Array(W * H);
|
|
797
|
+
for (let y = 0; y < H; y++) {
|
|
798
|
+
for (let x = 0; x < W; x++) {
|
|
799
|
+
if (!fgMask[y * W + x]) continue;
|
|
800
|
+
for (let dy = -rad; dy <= rad; dy++) {
|
|
801
|
+
const ny = y + dy;
|
|
802
|
+
if (ny < 0 || ny >= H) continue;
|
|
803
|
+
for (let dx = -rad; dx <= rad; dx++) {
|
|
804
|
+
const nx = x + dx;
|
|
805
|
+
if (nx < 0 || nx >= W) continue;
|
|
806
|
+
if (dx * dx + dy * dy <= rad * rad) borderMask[ny * W + nx] = 1;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
for (let p = 0; p < W * H; p++) {
|
|
812
|
+
if (!borderMask[p]) continue;
|
|
813
|
+
const idx = p * 4;
|
|
814
|
+
const a = rgba[idx + 3] / 255;
|
|
815
|
+
rgba[idx] = Math.round(rgba[idx] * a + 255 * (1 - a));
|
|
816
|
+
rgba[idx + 1] = Math.round(rgba[idx + 1] * a + 255 * (1 - a));
|
|
817
|
+
rgba[idx + 2] = Math.round(rgba[idx + 2] * a + 255 * (1 - a));
|
|
818
|
+
rgba[idx + 3] = 255;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// Detect remaining enclosed pure-white pockets (outside --protect-boxes)
|
|
823
|
+
const pocketVisited = new Uint8Array(W * H);
|
|
824
|
+
const enclosedWhitePockets = [];
|
|
825
|
+
for (let p = 0; p < W * H; p++) {
|
|
826
|
+
if (pocketVisited[p] || protectedMask[p]) continue;
|
|
827
|
+
const idx = p * 4;
|
|
828
|
+
if (rgba[idx + 3] < 220 || rgba[idx] < bgHard || rgba[idx + 1] < bgHard || rgba[idx + 2] < bgHard) {
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
// BFS component
|
|
832
|
+
let head = 0;
|
|
833
|
+
let tail = 0;
|
|
834
|
+
queue[tail++] = p;
|
|
835
|
+
pocketVisited[p] = 1;
|
|
836
|
+
let sumX = 0,
|
|
837
|
+
sumY = 0,
|
|
838
|
+
minX = W,
|
|
839
|
+
minY = H,
|
|
840
|
+
maxX = 0,
|
|
841
|
+
maxY = 0;
|
|
842
|
+
while (head < tail) {
|
|
843
|
+
const cur = queue[head++];
|
|
844
|
+
const cx = cur % W;
|
|
845
|
+
const cy = (cur - cx) / W;
|
|
846
|
+
sumX += cx;
|
|
847
|
+
sumY += cy;
|
|
848
|
+
if (cx < minX) minX = cx;
|
|
849
|
+
if (cx > maxX) maxX = cx;
|
|
850
|
+
if (cy < minY) minY = cy;
|
|
851
|
+
if (cy > maxY) maxY = cy;
|
|
852
|
+
|
|
853
|
+
const neighbors = [
|
|
854
|
+
cx > 0 ? cur - 1 : -1,
|
|
855
|
+
cx + 1 < W ? cur + 1 : -1,
|
|
856
|
+
cy > 0 ? cur - W : -1,
|
|
857
|
+
cy + 1 < H ? cur + W : -1,
|
|
858
|
+
];
|
|
859
|
+
for (const nb of neighbors) {
|
|
860
|
+
if (nb < 0 || pocketVisited[nb] || protectedMask[nb]) continue;
|
|
861
|
+
const nIdx = nb * 4;
|
|
862
|
+
if (rgba[nIdx + 3] >= 220 && rgba[nIdx] >= bgHard && rgba[nIdx + 1] >= bgHard && rgba[nIdx + 2] >= bgHard) {
|
|
863
|
+
pocketVisited[nb] = 1;
|
|
864
|
+
queue[tail++] = nb;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
if (tail >= 25) {
|
|
869
|
+
// Pick an actual pixel from the component closest to centroid so --extra-seeds hits inside
|
|
870
|
+
const avgX = sumX / tail;
|
|
871
|
+
const avgY = sumY / tail;
|
|
872
|
+
let bestP = queue[0];
|
|
873
|
+
let bestDist = Infinity;
|
|
874
|
+
for (let k = 0; k < tail; k++) {
|
|
875
|
+
const qp = queue[k];
|
|
876
|
+
const qx = qp % W;
|
|
877
|
+
const qy = (qp - qx) / W;
|
|
878
|
+
const d = (qx - avgX) * (qx - avgX) + (qy - avgY) * (qy - avgY);
|
|
879
|
+
if (d < bestDist) {
|
|
880
|
+
bestDist = d;
|
|
881
|
+
bestP = qp;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
const seedX = bestP % W;
|
|
885
|
+
const seedY = (bestP - seedX) / W;
|
|
886
|
+
enclosedWhitePockets.push({
|
|
887
|
+
areaPx: tail,
|
|
888
|
+
seed: `${seedX},${seedY}`,
|
|
889
|
+
bbox: `${minX},${minY},${maxX},${maxY}`,
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
enclosedWhitePockets.sort((a, b) => b.areaPx - a.areaPx);
|
|
894
|
+
|
|
895
|
+
// Foreground bounding box after matting
|
|
896
|
+
let fgMinX = W,
|
|
897
|
+
fgMinY = H,
|
|
898
|
+
fgMaxX = -1,
|
|
899
|
+
fgMaxY = -1,
|
|
900
|
+
opaqueCount = 0;
|
|
901
|
+
for (let p = 0; p < W * H; p++) {
|
|
902
|
+
if (rgba[p * 4 + 3] >= 20) {
|
|
903
|
+
opaqueCount++;
|
|
904
|
+
const x = p % W;
|
|
905
|
+
const y = (p - x) / W;
|
|
906
|
+
if (x < fgMinX) fgMinX = x;
|
|
907
|
+
if (x > fgMaxX) fgMaxX = x;
|
|
908
|
+
if (y < fgMinY) fgMinY = y;
|
|
909
|
+
if (y > fgMaxY) fgMaxY = y;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
const master1024Path = path.join(outDir, `${stem}_1024.png`);
|
|
914
|
+
const finalPngPath = path.join(outDir, `${stem}.png`);
|
|
915
|
+
|
|
916
|
+
const masterPngBuf = await sharp(rgba, { raw: { width: W, height: H, channels: 4 } })
|
|
917
|
+
.png({ compressionLevel: 9 })
|
|
918
|
+
.toBuffer();
|
|
919
|
+
fs.writeFileSync(master1024Path, masterPngBuf);
|
|
920
|
+
|
|
921
|
+
const finalPngBuf = await sharp(rgba, { raw: { width: W, height: H, channels: 4 } })
|
|
922
|
+
.resize(targetSize, targetSize, { fit: 'contain', kernel: sharp.kernel.lanczos3 })
|
|
923
|
+
.png({ compressionLevel: 9 })
|
|
924
|
+
.toBuffer();
|
|
925
|
+
fs.writeFileSync(finalPngPath, finalPngBuf);
|
|
926
|
+
|
|
927
|
+
// Build side-by-side Dark (#252830) & Light (#F2F4F8) preview card
|
|
928
|
+
const cardSize = 480;
|
|
929
|
+
const pad = 24;
|
|
930
|
+
const previewCardImg = await sharp(rgba, { raw: { width: W, height: H, channels: 4 } })
|
|
931
|
+
.resize(cardSize, cardSize, { fit: 'contain', kernel: sharp.kernel.lanczos3 })
|
|
932
|
+
.png()
|
|
933
|
+
.toBuffer();
|
|
934
|
+
|
|
935
|
+
const previewSvg = Buffer.from(
|
|
936
|
+
`<svg width="${cardSize * 2 + pad * 3}" height="${cardSize + pad * 2 + 34}" xmlns="http://www.w3.org/2000/svg">
|
|
937
|
+
<rect x="0" y="0" width="${cardSize * 2 + pad * 3}" height="${cardSize + pad * 2 + 34}" fill="#181A20" />
|
|
938
|
+
<rect x="${pad}" y="${pad}" width="${cardSize}" height="${cardSize}" rx="14" fill="#252830" />
|
|
939
|
+
<rect x="${cardSize + pad * 2}" y="${pad}" width="${cardSize}" height="${cardSize}" rx="14" fill="#F2F4F8" />
|
|
940
|
+
<text x="${pad + cardSize / 2}" y="${cardSize + pad + 24}" text-anchor="middle" font-family="Consolas, sans-serif" font-size="14" fill="#CBD5E1">DARK (#252830) - ${targetSize}x${targetSize}</text>
|
|
941
|
+
<text x="${cardSize + pad * 2 + cardSize / 2}" y="${cardSize + pad + 24}" text-anchor="middle" font-family="Consolas, sans-serif" font-size="14" fill="#CBD5E1">LIGHT (#F2F4F8) - ${stem}.png</text>
|
|
942
|
+
</svg>`
|
|
943
|
+
);
|
|
944
|
+
|
|
945
|
+
const previewBuf = await sharp(previewSvg)
|
|
946
|
+
.composite([
|
|
947
|
+
{ input: previewCardImg, left: pad, top: pad },
|
|
948
|
+
{ input: previewCardImg, left: cardSize + pad * 2, top: pad },
|
|
949
|
+
])
|
|
950
|
+
.png()
|
|
951
|
+
.toBuffer();
|
|
952
|
+
|
|
953
|
+
const defaultPreviewPath = path.join(previewDir, `${stem}_preview.png`);
|
|
954
|
+
fs.writeFileSync(defaultPreviewPath, previewBuf);
|
|
955
|
+
|
|
956
|
+
let taggedPreviewPath = null;
|
|
957
|
+
if (args.tag) {
|
|
958
|
+
taggedPreviewPath = path.join(previewDir, `${stem}_${args.tag}_preview.png`);
|
|
959
|
+
fs.writeFileSync(taggedPreviewPath, previewBuf);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const report = {
|
|
963
|
+
ok: true,
|
|
964
|
+
command: 'process',
|
|
965
|
+
name: stem,
|
|
966
|
+
targetSize,
|
|
967
|
+
whiteBorder,
|
|
968
|
+
files: {
|
|
969
|
+
master1024: master1024Path,
|
|
970
|
+
stickerPng: finalPngPath,
|
|
971
|
+
stickerBytes: finalPngBuf.length,
|
|
972
|
+
preview: taggedPreviewPath || defaultPreviewPath,
|
|
973
|
+
defaultPreview: defaultPreviewPath,
|
|
974
|
+
},
|
|
975
|
+
foregroundStats: {
|
|
976
|
+
opaquePixels1024: opaqueCount,
|
|
977
|
+
opaqueCoveragePct: Number(((opaqueCount / (W * H)) * 100).toFixed(1)),
|
|
978
|
+
bbox1024: fgMaxX >= fgMinX ? { x0: fgMinX, y0: fgMinY, x1: fgMaxX, y1: fgMaxY } : null,
|
|
979
|
+
},
|
|
980
|
+
enclosedWhitePocketCount: enclosedWhitePockets.length,
|
|
981
|
+
enclosedWhitePockets: enclosedWhitePockets.slice(0, 20),
|
|
982
|
+
hint:
|
|
983
|
+
enclosedWhitePockets.length > 0
|
|
984
|
+
? 'Inspect enclosedWhitePockets: pass background holes to --extra-seeds "x,y;..." or intentional white fills (sclera/book/pleats) to --protect-boxes "x0,y0,x1,y1;...".'
|
|
985
|
+
: 'No unshielded pure-white pockets (>=25px) detected.',
|
|
986
|
+
};
|
|
987
|
+
|
|
988
|
+
const reportAbs = writeJsonReport(outReport, report);
|
|
989
|
+
console.log(
|
|
990
|
+
`process OK -> ${finalPngPath} (${finalPngBuf.length} B, pockets=${enclosedWhitePockets.length}) | preview: ${
|
|
991
|
+
taggedPreviewPath || defaultPreviewPath
|
|
992
|
+
} | report: ${reportAbs}`
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
async function cmdRegister(sharp, args) {
|
|
997
|
+
const outReport = args.output;
|
|
998
|
+
if (!outReport) fail('Missing required --output <json-path>.');
|
|
999
|
+
for (const req of ['input', 'emotion', 'look', 'note']) {
|
|
1000
|
+
if (!args[req]) fail(`Missing required --${req}.`, outReport);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const inputAbs = path.resolve(args.input);
|
|
1004
|
+
if (!fs.existsSync(inputAbs)) fail(`Sticker PNG not found: ${args.input}`, outReport);
|
|
1005
|
+
|
|
1006
|
+
const fileName = args.file ? String(args.file) : path.basename(inputAbs);
|
|
1007
|
+
if (path.basename(fileName) !== fileName || /[\\/:*?"<>|\x00-\x1f]/.test(fileName) || !/\.png$/i.test(fileName)) {
|
|
1008
|
+
fail('Invalid target filename: expected a PNG basename without path separators or invalid characters.', outReport);
|
|
1009
|
+
}
|
|
1010
|
+
if (!args['allow-custom-prefix'] && !/^(cat|fish|gemini|claude|gpt)_.+\.png$/i.test(fileName)) {
|
|
1011
|
+
fail(
|
|
1012
|
+
`Invalid target filename "${fileName}". Expected cat_, fish_, gemini_, claude_, or gpt_ prefix (pass --allow-custom-prefix to override).`,
|
|
1013
|
+
outReport
|
|
1014
|
+
);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
const meta = await sharp(inputAbs).metadata();
|
|
1018
|
+
if (meta.format !== 'png') {
|
|
1019
|
+
fail(`Expected PNG format, got "${meta.format}".`, outReport);
|
|
1020
|
+
}
|
|
1021
|
+
if (!meta.hasAlpha) {
|
|
1022
|
+
fail(`Sticker PNG "${fileName}" does not have an alpha channel (RGBA required).`, outReport);
|
|
1023
|
+
}
|
|
1024
|
+
if (meta.width !== meta.height) {
|
|
1025
|
+
fail(`Sticker PNG "${fileName}" must be square, got ${meta.width}x${meta.height}.`, outReport);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const { data: pixels } = await sharp(inputAbs).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
1029
|
+
let hasTransparentPixel = false;
|
|
1030
|
+
let hasVisiblePixel = false;
|
|
1031
|
+
for (let i = 3; i < pixels.length; i += 4) {
|
|
1032
|
+
if (pixels[i] < 255) hasTransparentPixel = true;
|
|
1033
|
+
if (pixels[i] > 0) hasVisiblePixel = true;
|
|
1034
|
+
if (hasTransparentPixel && hasVisiblePixel) break;
|
|
1035
|
+
}
|
|
1036
|
+
if (!hasTransparentPixel || !hasVisiblePixel) {
|
|
1037
|
+
fail('Sticker must contain both visible content and actual transparency; empty or fully opaque PNGs are not stickers.', outReport);
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const rawBytes = fs.readFileSync(inputAbs);
|
|
1041
|
+
const maxKb = args['max-kb'] !== undefined ? Number(args['max-kb']) : 300;
|
|
1042
|
+
if (!args['allow-large'] && rawBytes.length > maxKb * 1024) {
|
|
1043
|
+
fail(
|
|
1044
|
+
`Sticker "${fileName}" is ${(rawBytes.length / 1024).toFixed(1)} KB (> ${maxKb} KB limit). Pass --allow-large if intentional.`,
|
|
1045
|
+
outReport
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const sha256 = crypto.createHash('sha256').update(rawBytes).digest('hex');
|
|
1050
|
+
const stickersDir = args['stickers-dir'] ? path.resolve(args['stickers-dir']) : resolveDefaultStickersDir();
|
|
1051
|
+
const indexPath = path.join(stickersDir, 'index.json');
|
|
1052
|
+
const dryRun = Boolean(args['dry-run']);
|
|
1053
|
+
let indexList;
|
|
1054
|
+
if (!fs.existsSync(indexPath)) {
|
|
1055
|
+
if (args.init) {
|
|
1056
|
+
if (!dryRun) {
|
|
1057
|
+
fs.mkdirSync(stickersDir, { recursive: true });
|
|
1058
|
+
}
|
|
1059
|
+
indexList = [];
|
|
1060
|
+
} else {
|
|
1061
|
+
fail(`stickers/index.json not found at ${indexPath}. Pass --stickers-dir <dir> or --init to initialize.`, outReport);
|
|
1062
|
+
}
|
|
1063
|
+
} else {
|
|
1064
|
+
try {
|
|
1065
|
+
indexList = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
|
|
1066
|
+
if (!Array.isArray(indexList)) throw new Error('Root JSON value is not an array.');
|
|
1067
|
+
} catch (err) {
|
|
1068
|
+
fail(`Failed to parse ${indexPath}: ${err.message}`, outReport);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
const autoVal = String(args.auto || 'false').toLowerCase() === 'true';
|
|
1073
|
+
const existingIdx = indexList.findIndex((item) => item && item.file === fileName);
|
|
1074
|
+
const nowMs = Date.now();
|
|
1075
|
+
const entry = {
|
|
1076
|
+
emotion: String(args.emotion).trim(),
|
|
1077
|
+
file: fileName,
|
|
1078
|
+
bytes: rawBytes.length,
|
|
1079
|
+
sha256,
|
|
1080
|
+
auto: autoVal,
|
|
1081
|
+
createdAt: existingIdx >= 0 && indexList[existingIdx].createdAt ? indexList[existingIdx].createdAt : nowMs,
|
|
1082
|
+
look: String(args.look).trim(),
|
|
1083
|
+
note: String(args.note).trim(),
|
|
1084
|
+
};
|
|
1085
|
+
|
|
1086
|
+
const destPngPath = path.join(stickersDir, fileName);
|
|
1087
|
+
|
|
1088
|
+
if (!dryRun) {
|
|
1089
|
+
if (path.resolve(inputAbs) !== path.resolve(destPngPath)) {
|
|
1090
|
+
fs.copyFileSync(inputAbs, destPngPath);
|
|
1091
|
+
}
|
|
1092
|
+
if (existingIdx >= 0) {
|
|
1093
|
+
indexList[existingIdx] = entry;
|
|
1094
|
+
} else {
|
|
1095
|
+
indexList.push(entry);
|
|
1096
|
+
}
|
|
1097
|
+
const tmpIndexPath = `${indexPath}.tmp.${process.pid}`;
|
|
1098
|
+
fs.writeFileSync(tmpIndexPath, JSON.stringify(indexList, null, 2) + '\n', 'utf8');
|
|
1099
|
+
fs.renameSync(tmpIndexPath, indexPath);
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
const reportAbs = writeJsonReport(outReport, {
|
|
1103
|
+
ok: true,
|
|
1104
|
+
command: 'register',
|
|
1105
|
+
dryRun,
|
|
1106
|
+
action: existingIdx >= 0 ? 'updated' : 'inserted',
|
|
1107
|
+
totalEntries: dryRun && existingIdx < 0 ? indexList.length + 1 : indexList.length,
|
|
1108
|
+
dimensions: `${meta.width}x${meta.height}`,
|
|
1109
|
+
destFile: destPngPath,
|
|
1110
|
+
indexPath,
|
|
1111
|
+
entry,
|
|
1112
|
+
});
|
|
1113
|
+
|
|
1114
|
+
console.log(
|
|
1115
|
+
`register ${dryRun ? '(DRY-RUN) ' : ''}OK -> ${fileName} (${entry.bytes} B, ${entry.sha256.slice(
|
|
1116
|
+
0,
|
|
1117
|
+
12
|
|
1118
|
+
)}..., ${existingIdx >= 0 ? 'updated' : 'inserted'}) | report: ${reportAbs}`
|
|
1119
|
+
);
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
async function main() {
|
|
1123
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1124
|
+
const subcmd = args._[0];
|
|
1125
|
+
|
|
1126
|
+
if (!subcmd || args.help) {
|
|
1127
|
+
printHelp(subcmd);
|
|
1128
|
+
process.exit(0);
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
let sharp;
|
|
1132
|
+
try {
|
|
1133
|
+
sharp = loadSharp();
|
|
1134
|
+
} catch (err) {
|
|
1135
|
+
fail(err.message, subcmd === 'export' ? undefined : args.output);
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
try {
|
|
1139
|
+
if (subcmd === 'align-guide') {
|
|
1140
|
+
await cmdAlignGuide(sharp, args);
|
|
1141
|
+
} else if (subcmd === 'splice') {
|
|
1142
|
+
await cmdSplice(sharp, args);
|
|
1143
|
+
} else if (subcmd === 'process') {
|
|
1144
|
+
await cmdProcess(sharp, args);
|
|
1145
|
+
} else if (subcmd === 'export') {
|
|
1146
|
+
const report = await exportSticker(sharp, args);
|
|
1147
|
+
console.log(`export OK -> ${report.files.stickerPng} (${report.final.bytes} B) | preview: ${report.files.preview} | report: ${report.reportPath}`);
|
|
1148
|
+
} else if (subcmd === 'register') {
|
|
1149
|
+
await cmdRegister(sharp, args);
|
|
1150
|
+
} else {
|
|
1151
|
+
fail(`Unknown subcommand "${subcmd}". Run with --help to see available subcommands.`, args.output);
|
|
1152
|
+
}
|
|
1153
|
+
} catch (err) {
|
|
1154
|
+
fail(err.stack || err.message || String(err), subcmd === 'export' ? err.exportReportPath : args.output);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
main();
|