-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguff.ts
More file actions
executable file
·782 lines (683 loc) · 22.4 KB
/
guff.ts
File metadata and controls
executable file
·782 lines (683 loc) · 22.4 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
#!/usr/bin/env bun
import { parseArgs } from "util";
import { resolve, basename, extname, join } from "path";
import { existsSync, mkdirSync, rmSync } from "fs";
import { tmpdir } from "os";
import { execFileSync } from "child_process";
import sharp from "sharp";
// Check if a key was loaded from .env in cwd
function keyFromDotenv(key: string): boolean {
try {
const envPath = resolve(".env");
if (!existsSync(envPath)) return false;
const content = require("fs").readFileSync(envPath, "utf-8");
return content.split("\n").some((line: string) => {
const trimmed = line.trim();
return !trimmed.startsWith("#") && trimmed.startsWith(`${key}=`);
});
} catch {
return false;
}
}
const RESOLUTIONS: Record<string, string> = {
"1k": "1K",
"2k": "2K",
"4k": "4K",
};
const PROVIDERS: Record<string, (opts: GenerateOpts) => Promise<Buffer[]>> = {
gemini: generateGemini,
claude: generateClaude,
};
const ASPECT_RATIOS = [
{ label: "1:1", value: 1 },
{ label: "16:9", value: 16 / 9 },
{ label: "9:16", value: 9 / 16 },
{ label: "4:3", value: 4 / 3 },
{ label: "3:4", value: 3 / 4 },
];
interface InputImage {
mimeType: string;
data: string; // base64
}
interface GenerateOpts {
model: string;
prompt: string;
aspectRatio: string;
imageSize: string;
temperature: number;
debug: boolean;
inputImages: InputImage[];
numFrames: number;
outputW: number;
outputH: number;
cols: number;
rows: number;
frameAR: number;
}
function usage(): never {
console.log(`Usage: guff [options] <prompt>
Generate animated GIFs using AI.
Options:
-f, --frames <n> Number of animation frames (default: 32)
-D, --delay <ms> Delay between frames in ms (default: 100)
-s, --size <WxH> Output size (default: 128x128)
-a, --aspect <W:H> Frame aspect ratio (default: 1:1)
-o, --output <file> Output filename (default: auto-generated)
-i, --input <file> Input image(s) for reference (repeatable)
-r, --resolution <res> Resolution: 1k, 2k, 4k (default: 1k, Gemini only)
-t, --temperature <temp> Temperature 0.0-2.0 (default: 1.0)
-m, --model <provider/model> Model (default: claude/claude-sonnet-4-6)
-c, --colors <n> Max colors in GIF palette (default: 256)
-d, --debug Log full prompt and API details
-h, --help Show this help
Requires: gifsicle (brew install gifsicle)
Examples:
guff 'a bouncing ball'
guff -f 8 -s 256x256 'a spinning star'
guff -d 'a dancing penguin'
guff -m gemini/gemini-2-flash-preview-image-generation 'a waving hand'`);
process.exit(0);
}
const { values, positionals } = parseArgs({
args: Bun.argv.slice(2),
options: {
frames: { type: "string", short: "f", default: "32" },
delay: { type: "string", short: "D", default: "100" },
size: { type: "string", short: "s", default: "128x128" },
output: { type: "string", short: "o" },
input: { type: "string", short: "i", multiple: true },
resolution: { type: "string", short: "r", default: "1k" },
temperature: { type: "string", short: "t", default: "1.0" },
model: {
type: "string",
short: "m",
default: "claude/claude-sonnet-4-6",
},
colors: { type: "string", short: "c", default: "256" },
aspect: { type: "string", short: "a", default: "1:1" },
debug: { type: "boolean", short: "d", default: false },
help: { type: "boolean", short: "h", default: false },
},
allowPositionals: true,
strict: true,
});
if (values.help) usage();
const prompt = positionals[0];
if (!prompt) {
console.error("Error: prompt is required. Use --help for usage.");
process.exit(1);
}
// Validate frames
const numFrames = parseInt(values.frames!, 10);
if (isNaN(numFrames) || numFrames < 2 || numFrames > 64) {
console.error("Error: frames must be between 2 and 64");
process.exit(1);
}
// Validate delay
const delay = parseInt(values.delay!, 10);
if (isNaN(delay) || delay < 10 || delay > 10000) {
console.error("Error: delay must be between 10 and 10000 ms");
process.exit(1);
}
// Parse size
const sizeMatch = values.size!.match(/^(\d+)x(\d+)$/);
if (!sizeMatch) {
console.error("Error: size must be in WxH format (e.g., 128x128)");
process.exit(1);
}
const outputW = parseInt(sizeMatch[1]!, 10);
const outputH = parseInt(sizeMatch[2]!, 10);
// Parse provider/model
const modelStr = values.model!;
const slashIdx = modelStr.indexOf("/");
const provider = slashIdx !== -1 ? modelStr.slice(0, slashIdx) : "gemini";
const modelName = slashIdx !== -1 ? modelStr.slice(slashIdx + 1) : modelStr;
const generateFn = PROVIDERS[provider];
if (!generateFn) {
console.error(
`Error: unsupported provider "${provider}". Supported: ${Object.keys(PROVIDERS).join(", ")}`
);
process.exit(1);
}
// Parse resolution
const resKey = values.resolution!.toLowerCase();
const imageSize = RESOLUTIONS[resKey];
if (!imageSize) {
console.error(
`Error: unknown resolution "${values.resolution}". Use: ${Object.keys(RESOLUTIONS).join(", ")}`
);
process.exit(1);
}
// Parse temperature
const temperature = parseFloat(values.temperature!);
if (isNaN(temperature) || temperature < 0 || temperature > 2) {
console.error("Error: temperature must be between 0.0 and 2.0");
process.exit(1);
}
// Parse colors
const colors = parseInt(values.colors!, 10);
if (isNaN(colors) || colors < 2 || colors > 256) {
console.error("Error: colors must be between 2 and 256");
process.exit(1);
}
// Parse frame aspect ratio
const frameARMatch = values.aspect!.match(/^(\d+):(\d+)$/);
if (!frameARMatch) {
console.error(
"Error: aspect must be in W:H format (e.g., 1:1, 16:9, 4:3)"
);
process.exit(1);
}
const frameAR =
parseInt(frameARMatch[1]!, 10) / parseInt(frameARMatch[2]!, 10);
// Check gifsicle is available
try {
execFileSync("gifsicle", ["--version"], { stdio: "pipe" });
} catch {
console.error(
"Error: gifsicle is required but not found. Install with: brew install gifsicle"
);
process.exit(1);
}
// Compute grid layout for N frames — find the most square-like factor pair
function gridLayout(n: number): { cols: number; rows: number } {
let bestCols = n,
bestRows = 1;
for (let r = 2; r * r <= n; r++) {
if (n % r === 0) {
bestCols = n / r;
bestRows = r;
}
}
return { cols: bestCols, rows: bestRows };
}
function bestAspectRatio(
cols: number,
rows: number,
frameAR: number
): string {
const target = (cols * frameAR) / rows;
let best = ASPECT_RATIOS[0]!;
let bestDist = Infinity;
for (const r of ASPECT_RATIOS) {
const dist = Math.abs(Math.log(r.value / target));
if (dist < bestDist) {
bestDist = dist;
best = r;
}
}
return best.label;
}
const { cols, rows } = gridLayout(numFrames);
// Grid validation only applies to Gemini (which generates sprite sheets)
if (provider === "gemini" && rows === 1 && cols > 3) {
const suggest: number[] = [];
for (let n = numFrames - 1; n >= 2; n--) {
const { rows: r } = gridLayout(n);
if (r > 1 || n <= 3) {
suggest.push(n);
break;
}
}
for (let n = numFrames + 1; n <= 16; n++) {
const { rows: r } = gridLayout(n);
if (r > 1 || n <= 3) {
suggest.push(n);
break;
}
}
console.error(
`Error: ${numFrames} frames can't form a clean grid (only ${cols}x1). Try: ${suggest.join(" or ")}`
);
process.exit(1);
}
const aspectRatio = bestAspectRatio(cols, rows, frameAR);
// Load input images
const MIME_TYPES: Record<string, string> = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
};
const inputImages: InputImage[] = [];
for (const file of values.input ?? []) {
const path = resolve(file);
if (!existsSync(path)) {
console.error(`Error: input file not found: ${file}`);
process.exit(1);
}
const ext = extname(path).toLowerCase();
const mimeType = MIME_TYPES[ext];
if (!mimeType) {
console.error(
`Error: unsupported image format "${ext}". Use: ${Object.keys(MIME_TYPES).join(", ")}`
);
process.exit(1);
}
const data = Buffer.from(await Bun.file(path).arrayBuffer()).toString(
"base64"
);
inputImages.push({ mimeType, data });
}
// Generate frames
console.log(`Generating ${numFrames}-frame animation...`);
const frames = await generateFn({
model: modelName,
prompt,
aspectRatio,
imageSize,
temperature,
debug: values.debug!,
inputImages,
numFrames,
outputW,
outputH,
cols,
rows,
frameAR,
});
// Assemble GIF with gifsicle
const tmpDir = join(tmpdir(), `guff-${Date.now()}`);
mkdirSync(tmpDir, { recursive: true });
try {
// Write individual frames as GIF files
const frameFiles: string[] = [];
for (let i = 0; i < frames.length; i++) {
const framePath = join(tmpDir, `frame-${i}.gif`);
await sharp(frames[i]!).gif().toFile(framePath);
frameFiles.push(framePath);
}
// Output filename
const outputPath = uniquePath(
values.output ? resolve(values.output) : resolve(`${slugify(prompt)}.gif`)
);
// Merge and optimize with gifsicle
const delayCs = Math.round(delay / 10); // ms → centiseconds
execFileSync("gifsicle", [
"--delay",
String(delayCs),
"--loop",
"--colors",
String(colors),
"-O3",
...frameFiles,
"-o",
outputPath,
]);
console.log(`Saved ${basename(outputPath)}`);
await displayInTerminal(outputPath);
} finally {
rmSync(tmpDir, { recursive: true, force: true });
}
// --- Helpers ---
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 60);
}
function uniquePath(p: string): string {
if (!existsSync(p)) return p;
const ext = extname(p);
const base = p.slice(0, -ext.length);
let n = 2;
while (existsSync(`${base}-${n}${ext}`)) n++;
return `${base}-${n}${ext}`;
}
// --- Terminal inline image display ---
async function displayInTerminal(path: string) {
const term = process.env.TERM_PROGRAM;
const fileData = Buffer.from(await Bun.file(path).arrayBuffer());
if (term === "iTerm.app") {
// iTerm2 inline image protocol (supports GIF natively)
const b64 = fileData.toString("base64");
const name = Buffer.from(basename(path)).toString("base64");
process.stdout.write(
`\x1b]1337;File=inline=1;name=${name};size=${fileData.length}:${b64}\x07`
);
process.stdout.write("\n");
} else if (term === "ghostty") {
// Kitty graphics protocol — convert first frame to PNG for display
const pngData = await sharp(fileData, { animated: false }).png().toBuffer();
const b64 = pngData.toString("base64");
const CHUNK_SIZE = 4096;
for (let i = 0; i < b64.length; i += CHUNK_SIZE) {
const chunk = b64.slice(i, i + CHUNK_SIZE);
const isLast = i + CHUNK_SIZE >= b64.length;
if (i === 0) {
process.stdout.write(
`\x1b_Ga=T,f=100,m=${isLast ? 0 : 1};${chunk}\x1b\\`
);
} else {
process.stdout.write(`\x1b_Gm=${isLast ? 0 : 1};${chunk}\x1b\\`);
}
}
process.stdout.write("\n");
}
}
// --- Helpers for Claude provider ---
function extractCode(text: string): string | null {
const fenced = text.match(/```(?:typescript|ts|)\n([\s\S]*?)```/);
if (fenced) return fenced[1]!;
if (text.includes("console.log") && text.includes("JSON.stringify"))
return text;
return null;
}
async function executeFrameScript(
code: string,
opts: GenerateOpts
): Promise<string[]> {
const tmpFile = join(tmpdir(), `guff-gen-${Date.now()}.ts`);
try {
await Bun.write(tmpFile, code);
if (opts.debug) {
console.log(`--- Generated code written to ${tmpFile} ---`);
console.log(code);
console.log("--- Executing... ---");
}
const proc = Bun.spawnSync(["bun", "run", tmpFile], {
timeout: 30_000,
stdout: "pipe",
stderr: "pipe",
});
if (proc.exitCode !== 0) {
const stderr = proc.stderr.toString();
console.error(`Error: generated code failed (exit ${proc.exitCode}):`);
console.error(stderr);
process.exit(1);
}
const stdout = proc.stdout.toString().trim();
let svgs: string[];
try {
svgs = JSON.parse(stdout);
} catch {
console.error("Error: generated code did not output valid JSON");
if (opts.debug) console.error("stdout:", stdout.slice(0, 500));
process.exit(1);
}
if (!Array.isArray(svgs) || svgs.length === 0) {
console.error(`Error: expected array of SVG strings, got ${typeof svgs}`);
process.exit(1);
}
if (svgs.length !== opts.numFrames) {
console.log(
`Warning: got ${svgs.length} frames (expected ${opts.numFrames})`
);
}
for (let i = 0; i < svgs.length; i++) {
if (typeof svgs[i] !== "string" || !svgs[i]!.trim().startsWith("<svg")) {
console.error(`Error: frame ${i} is not a valid SVG string`);
process.exit(1);
}
}
return svgs;
} finally {
if (!opts.debug) {
try {
rmSync(tmpFile);
} catch {}
}
}
}
// --- Provider implementations ---
async function generateClaude(opts: GenerateOpts): Promise<Buffer[]> {
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
console.error("Error: ANTHROPIC_API_KEY environment variable is required");
process.exit(1);
}
if (keyFromDotenv("ANTHROPIC_API_KEY")) {
console.log("Using ANTHROPIC_API_KEY from .env");
}
const systemPrompt = `You are an animation frame generator. You write TypeScript code that produces SVG strings for animation frames.
OUTPUT FORMAT:
Write a self-contained TypeScript script that:
1. Creates exactly ${opts.numFrames} SVG strings, each ${opts.outputW}x${opts.outputH} pixels
2. Outputs a JSON array of SVG strings to stdout via console.log(JSON.stringify(svgs))
3. Uses ONLY built-in JavaScript/TypeScript — no imports, no require, no dependencies
4. Each SVG must be a complete, valid SVG document starting with <svg> and ending with </svg>
SVG GUIDELINES:
- Use viewBox="0 0 ${opts.outputW} ${opts.outputH}" on each SVG
- Use basic SVG elements: <rect>, <circle>, <ellipse>, <polygon>, <path>, <line>, <text>, <g>
- Use transform attributes for rotation, scaling, translation
- Use math (Math.sin, Math.cos, Math.PI) for smooth animation curves
- Use vibrant, complementary colors — avoid plain black-on-white
- Make subjects large, filling most of the frame
- Keep the subject centered and consistently sized across frames
ANIMATION PRINCIPLES:
- The animation should loop seamlessly (last frame flows back to first)
- Use easing: ease-in-out via sine curves, not linear interpolation
- For N frames, compute progress as t = i / N (not N-1, since it loops)
- Common patterns:
- Oscillation: Math.sin(t * 2 * Math.PI)
- Rotation: angle = t * 360
- Bounce: Math.abs(Math.sin(t * Math.PI))
- Pulse: 1 + 0.2 * Math.sin(t * 2 * Math.PI)
QUALITY:
- Add visual depth: gradients, shadows, layered shapes
- Use stroke-width >= 2 for outlines
- Add details: highlights, secondary motion, particle effects
- Make it visually polished, not basic placeholder graphics
CODE STRUCTURE TEMPLATE:
const frames: string[] = [];
const W = ${opts.outputW};
const H = ${opts.outputH};
const N = ${opts.numFrames};
for (let i = 0; i < N; i++) {
const t = i / N; // 0 to 1, looping
// ... build SVG string with template literals ...
frames.push(svg);
}
console.log(JSON.stringify(frames));`;
const userContent: any[] = [];
for (const img of opts.inputImages) {
userContent.push({
type: "image",
source: { type: "base64", media_type: img.mimeType, data: img.data },
});
}
userContent.push({
type: "text",
text: `Create a ${opts.numFrames}-frame looping animation of: ${opts.prompt}`,
});
const body = {
model: opts.model,
max_tokens: 16384,
temperature: opts.temperature,
system: systemPrompt,
messages: [{ role: "user", content: userContent }],
};
if (opts.debug) {
console.log("--- Claude API Request ---");
console.log(JSON.stringify({ ...body, system: "(see above)" }, null, 2));
console.log("--- System Prompt ---");
console.log(systemPrompt);
console.log("-------------------");
}
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.text();
console.error(`Error: Claude API returned ${res.status}: ${err}`);
process.exit(1);
}
const data: any = await res.json();
// Log token usage
const usage = data.usage;
if (usage) {
console.log(
`Tokens: ${usage.input_tokens} in / ${usage.output_tokens} out`
);
}
const textBlock = data.content?.find((b: any) => b.type === "text");
if (!textBlock?.text) {
console.error("Error: no text in Claude API response");
if (opts.debug) console.error(JSON.stringify(data, null, 2));
process.exit(1);
}
const code = extractCode(textBlock.text);
if (!code) {
console.error("Error: could not extract code from Claude's response");
if (opts.debug) console.error(textBlock.text.slice(0, 1000));
process.exit(1);
}
const svgs = await executeFrameScript(code, opts);
// Convert SVGs to PNGs
const frames: Buffer[] = [];
for (const svg of svgs) {
const png = await sharp(Buffer.from(svg))
.resize(opts.outputW, opts.outputH, { fit: "contain", background: { r: 255, g: 255, b: 255, alpha: 1 } })
.png()
.toBuffer();
frames.push(png);
}
return frames;
}
async function generateGemini(opts: GenerateOpts): Promise<Buffer[]> {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.error("Error: GEMINI_API_KEY environment variable is required");
process.exit(1);
}
if (keyFromDotenv("GEMINI_API_KEY")) {
console.log("Using GEMINI_API_KEY from .env");
}
// Build grid prompt
const fullPrompt = [
`Generate a ${opts.cols}x${opts.rows} grid of ${opts.numFrames} animation frames showing: ${opts.prompt}`,
``,
`CRITICAL INSTRUCTIONS:`,
`- Create exactly ${opts.numFrames} frames arranged in a ${opts.cols}-column, ${opts.rows}-row grid`,
`- Frame order: left-to-right, top-to-bottom (frame 1 is top-left)`,
`- Each frame shows the next step in a smooth, looping animation`,
`- Use a plain white background in all frames`,
`- All frames must be exactly the same size with clear, straight boundaries between them`,
`- Do NOT draw borders, lines, or dividers between frames`,
`- The animation should loop seamlessly from the last frame back to the first`,
`- The subject should fill most of each frame with minimal padding — avoid large empty margins`,
`- Keep the subject centered and consistently sized across all frames`,
`- ABSOLUTELY NO text of any kind in the image: no frame numbers, no labels, no captions, no watermarks, no annotations`,
].join("\n");
if (opts.debug) {
console.log("--- Prompt ---");
console.log(fullPrompt);
console.log(
`--- Grid: ${opts.cols}x${opts.rows}, Aspect ratio: ${opts.aspectRatio} ---`
);
}
const url = `https://generativelanguage.googleapis.com/v1beta/models/${opts.model}:generateContent?key=${apiKey}`;
const parts: any[] = opts.inputImages.map((img) => ({
inlineData: { mimeType: img.mimeType, data: img.data },
}));
parts.push({ text: fullPrompt });
const body = {
contents: [{ parts }],
generation_config: {
response_modalities: ["TEXT", "IMAGE"],
temperature: opts.temperature,
image_config: {
aspect_ratio: opts.aspectRatio,
image_size: opts.imageSize,
},
},
};
if (opts.debug) {
console.log("--- API Request ---");
console.log(`POST ${url.replace(apiKey, "***")}`);
console.log(JSON.stringify(body, null, 2));
console.log("-------------------");
}
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.text();
console.error(`Error: Gemini API returned ${res.status}: ${err}`);
process.exit(1);
}
const data: any = await res.json();
// Log token usage
const usage = data.usageMetadata;
if (usage) {
console.log(
`Tokens: ${usage.promptTokenCount} in / ${usage.candidatesTokenCount} out`
);
}
const candidate = data.candidates?.[0];
const imagePart = candidate?.content?.parts?.find(
(p: any) => p.inlineData
);
if (!imagePart?.inlineData?.data) {
console.error("Error: no image data in API response");
if (opts.debug) console.error(JSON.stringify(data, null, 2));
process.exit(1);
}
const imageBuffer = Buffer.from(imagePart.inlineData.data, "base64");
// In debug mode, save the raw unsliced image
if (opts.debug) {
const debugPath = resolve("debug-unsliced.png");
await sharp(imageBuffer).png().toFile(debugPath);
console.log(`--- Saved unsliced image: ${debugPath} ---`);
}
// Split generated image into frames
const metadata = await sharp(imageBuffer).metadata();
const imgW = metadata.width!;
const imgH = metadata.height!;
const expectedFrameW = imgW / opts.cols;
const expectedFrameH = expectedFrameW / opts.frameAR;
const detectedRows = Math.round(imgH / expectedFrameH);
let actualRows = opts.rows;
if (detectedRows !== opts.rows) {
console.log(
`Warning: detected ${detectedRows} rows (expected ${opts.rows}), adjusting`
);
actualRows = detectedRows;
}
const frameW = Math.floor(imgW / opts.cols);
const frameH = Math.floor(imgH / actualRows);
if (opts.debug) {
console.log(
`--- Image: ${imgW}x${imgH}, Frame: ${frameW}x${frameH}, Grid: ${opts.cols}x${actualRows} ---`
);
}
// Extract raw frames with 3% inset to crop grid borders
const insetX = Math.max(1, Math.round(frameW * 0.03));
const insetY = Math.max(1, Math.round(frameH * 0.03));
const frames: Buffer[] = [];
for (
let row = 0;
row < actualRows && frames.length < opts.numFrames;
row++
) {
for (
let col = 0;
col < opts.cols && frames.length < opts.numFrames;
col++
) {
const frame = await sharp(imageBuffer)
.extract({
left: col * frameW + insetX,
top: row * frameH + insetY,
width: frameW - insetX * 2,
height: frameH - insetY * 2,
})
.resize(opts.outputW, opts.outputH, { fit: "cover" })
.toBuffer();
frames.push(frame);
}
}
return frames;
}