-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
174 lines (148 loc) · 5.35 KB
/
Copy pathcli.ts
File metadata and controls
174 lines (148 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env node
import { parseArgs } from "util";
import { existsSync, mkdirSync, statSync, readdirSync, readFileSync, writeFileSync, globSync } from "fs";
import { join, basename, dirname, resolve, extname } from "path";
// @ts-ignore - generated by wasm-pack
import { process_image } from "./wasm/crispx.js";
function printUsage() {
console.log(`
crispx - Optimize AI-generated pixel art images
Usage:
crispx <input> [options]
crispx <input...> -o <output-dir> [options]
Arguments:
input Image file, directory, or glob pattern (e.g. "images/*.png")
Options:
-o, --output <path> Output file or directory (default: <input>_crispx.png)
--merge-threshold <n> Color merge threshold, higher = fewer colors (default: 50)
--colors <n> Max colors via median-cut (optional)
--edge-threshold <n> Edge threshold 0.0-1.0 (default: auto)
--max-size <n> Max pixel size to check (default: auto)
--debug Save debug visualizations alongside output
-h, --help Show this help
`);
}
function processImage(
inputPath: string,
outputPath: string,
opts: {
mergeThreshold: number;
colors: number;
edgeThreshold: number;
maxSize: number;
debug: boolean;
}
): boolean {
try {
const pngData = new Uint8Array(readFileSync(inputPath));
const result = process_image(
pngData,
opts.mergeThreshold,
opts.colors,
opts.edgeThreshold,
opts.maxSize,
opts.debug,
);
// Write output PNG
const outDir = dirname(resolve(outputPath));
mkdirSync(outDir, { recursive: true });
writeFileSync(outputPath, new Uint8Array(result.png_data));
const inputSize = (statSync(inputPath).size / 1024).toFixed(1);
const outputSize = (result.png_data.length / 1024).toFixed(1);
console.log(` ${basename(inputPath)} → ${basename(outputPath)}`);
console.log(` ${inputSize}KB → ${outputSize}KB | grid: ${result.optimal_size}px | squares: ${result.num_squares} | output: ${result.grid_width}x${result.grid_height}`);
// Write debug images
if (result.debug) {
const name = basename(outputPath, extname(outputPath));
const debugDir = join(outDir, `${name}_debug`);
mkdirSync(debugDir, { recursive: true });
writeFileSync(join(debugDir, "edges.png"), new Uint8Array(result.debug.edges));
writeFileSync(join(debugDir, "seeds.png"), new Uint8Array(result.debug.seeds));
writeFileSync(join(debugDir, "coverage.png"), new Uint8Array(result.debug.coverage));
writeFileSync(join(debugDir, "tiers.png"), new Uint8Array(result.debug.tiers));
console.log(` debug → ${basename(debugDir)}/`);
}
return true;
} catch (err: any) {
console.error(` Error processing ${basename(inputPath)}: ${err.message}`);
return false;
}
}
function resolveInputFiles(patterns: string[]): string[] {
const files: string[] = [];
for (const pattern of patterns) {
if (pattern.includes("*")) {
for (const match of globSync(pattern)) {
files.push(resolve(match));
}
} else if (existsSync(pattern)) {
const stat = statSync(pattern);
if (stat.isDirectory()) {
for (const f of readdirSync(pattern)) {
if (/\.(png|jpg|jpeg|webp|gif)$/i.test(f)) {
files.push(resolve(join(pattern, f)));
}
}
} else {
files.push(resolve(pattern));
}
} else {
console.error(`File not found: ${pattern}`);
}
}
return files;
}
// --- Main ---
const { values, positionals } = parseArgs({
args: process.argv.slice(2),
options: {
output: { type: "string", short: "o" },
"merge-threshold": { type: "string" },
colors: { type: "string" },
"edge-threshold": { type: "string" },
"max-size": { type: "string" },
debug: { type: "boolean", default: false },
help: { type: "boolean", short: "h", default: false },
},
allowPositionals: true,
});
if (values.help || positionals.length === 0) {
printUsage();
process.exit(values.help ? 0 : 1);
}
const inputFiles = resolveInputFiles(positionals);
if (inputFiles.length === 0) {
console.error("No input files found.");
process.exit(1);
}
const opts = {
mergeThreshold: parseInt(values["merge-threshold"] ?? "50"),
colors: values.colors ? parseInt(values.colors) : -1, // -1 = no limit
edgeThreshold: values["edge-threshold"] ? parseFloat(values["edge-threshold"]) : -1.0, // -1 = auto
maxSize: values["max-size"] ? parseInt(values["max-size"]) : -1, // -1 = auto
debug: values.debug ?? false,
};
let successCount = 0;
for (const inputPath of inputFiles) {
let outputPath: string;
if (values.output) {
if (inputFiles.length > 1 || (existsSync(values.output) && statSync(values.output).isDirectory())) {
mkdirSync(values.output, { recursive: true });
const name = basename(inputPath, extname(inputPath));
outputPath = join(values.output, `${name}.png`);
} else {
mkdirSync(dirname(values.output), { recursive: true });
outputPath = values.output;
}
} else {
const dir = dirname(inputPath);
const name = basename(inputPath, extname(inputPath));
outputPath = join(dir, `${name}_crispx.png`);
}
if (processImage(inputPath, outputPath, opts)) {
successCount++;
}
}
if (inputFiles.length > 1) {
console.log(`\nProcessed ${successCount}/${inputFiles.length} images.`);
}