-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.ts
More file actions
executable file
·703 lines (619 loc) · 21.2 KB
/
Copy pathcli.ts
File metadata and controls
executable file
·703 lines (619 loc) · 21.2 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
#!/usr/bin/env -S npx tsx
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
import * as path from "node:path";
import { exec } from "node:child_process";
import dotenv from "dotenv";
import {
DEFAULT_VIDEO_MODEL,
FAST_VIDEO_MODEL,
type VideoConfig,
type VideoOperation,
} from "./lib/types.js";
import { showProgress, clearProgress } from "./lib/progress.js";
import { estimateVideoCost, formatCostWarning } from "./lib/cost.js";
dotenv.config({ quiet: true } as dotenv.DotenvConfigOptions);
const DEFAULT_MODEL = "gemini-3.1-flash-image-preview";
const FLASH_MODEL = "gemini-2.5-flash-image";
// Polling configuration
const POLL_INTERVAL_MS = 10_000; // 10 seconds
const MAX_WAIT_MS = 5 * 60 * 1000; // 5 minutes timeout
interface Model {
name: string;
}
interface ModelsResponse {
models?: Model[];
}
interface ContentPart {
text?: string;
inlineData?: {
mimeType: string;
data: string;
};
}
interface Candidate {
content: {
parts: ContentPart[];
};
}
interface GenerateContentResponse {
candidates: Candidate[];
}
async function listModels(apiKey: string): Promise<void> {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`
);
const data: ModelsResponse = await response.json();
if (data.models) {
console.log("Available models:");
console.log("\nImage Generation:");
data.models
.map((m) => m.name.replace("models/", ""))
.filter((name) => !name.includes("veo"))
.sort()
.forEach((name) => console.log(` ${name}`));
console.log("\nVideo Generation (Veo):");
data.models
.map((m) => m.name.replace("models/", ""))
.filter((name) => name.includes("veo"))
.sort()
.forEach((name) => console.log(` ${name}`));
} else {
console.error("Error fetching models:", data);
}
}
function getMimeType(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(`file --mime-type -b "${filePath}"`, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Error determining MIME type: ${stderr}`));
}
resolve(stdout.trim());
});
});
}
async function waitForVideoCompletion(
ai: GoogleGenAI,
operation: VideoOperation
): Promise<VideoOperation> {
const startTime = Date.now();
while (!operation.done) {
const elapsed = Math.floor((Date.now() - startTime) / 1000);
if (Date.now() - startTime > MAX_WAIT_MS) {
clearProgress();
throw new Error(`Video generation timeout after ${elapsed}s`);
}
showProgress(elapsed, "Generating video...");
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
// Poll for updated status
// eslint-disable-next-line @typescript-eslint/no-explicit-any
operation = await (ai as any).operations.getVideosOperation({
operation,
});
}
clearProgress();
return operation;
}
async function generateVideo(
ai: GoogleGenAI,
promptText: string,
config: VideoConfig,
inputImagePath?: string,
referenceImagePaths?: string[],
extendVideoUri?: string
): Promise<string> {
// Show cost estimate
const costEstimate = estimateVideoCost(config);
console.log(formatCostWarning(costEstimate));
// Prepare request
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const request: any = {
model: config.model,
prompt: promptText,
config: {
aspectRatio: config.aspectRatio,
durationSeconds: config.duration,
resolution: config.resolution,
// Note: generateAudio and personGeneration not supported in Gemini API yet
// generateAudio: config.generateAudio,
// personGeneration: config.personGeneration || "dont_allow",
},
};
// Add seed if specified
if (config.seed !== undefined) {
request.config.seed = config.seed;
}
// Add negative prompt if specified
if (config.negativePrompt) {
request.config.negativePrompt = config.negativePrompt;
}
// If extending a video, add the video reference
if (extendVideoUri) {
request.video = {
gcsUri: extendVideoUri
};
}
// If input image provided, add it for image-to-video (mutually exclusive with extend)
else if (inputImagePath) {
const imageBuffer = fs.readFileSync(inputImagePath);
const mimeType = await getMimeType(inputImagePath);
request.image = {
imageBytes: imageBuffer.toString("base64"),
mimeType: mimeType,
};
}
// Add reference images for character/style consistency
if (referenceImagePaths && referenceImagePaths.length > 0) {
request.referenceImages = await Promise.all(
referenceImagePaths.map(async (refPath) => {
const imageBuffer = fs.readFileSync(refPath);
const mimeType = await getMimeType(refPath);
return {
referenceImage: {
imageBytes: imageBuffer.toString("base64"),
mimeType: mimeType,
},
referenceType: "REFERENCE_TYPE_STYLE",
};
})
);
}
// Start generation
console.log("Starting video generation (this takes 2-4 minutes)...");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let operation = (await (ai as any).models.generateVideos(
request
)) as VideoOperation;
// Poll until complete
operation = await waitForVideoCompletion(ai, operation);
// Check for errors
if (operation.error) {
throw new Error(`Video generation failed: ${operation.error.message}`);
}
if (
!operation.response?.generatedVideos ||
operation.response.generatedVideos.length === 0
) {
throw new Error("No video generated in response");
}
return operation.response.generatedVideos[0].video;
}
interface Video {
uri?: string;
videoBytes?: string;
mimeType?: string;
}
async function downloadVideo(
ai: GoogleGenAI,
video: Video,
outputPath: string
): Promise<void> {
if (video.videoBytes) {
// Video bytes are provided directly (base64 encoded)
const buffer = Buffer.from(video.videoBytes, 'base64');
fs.writeFileSync(outputPath, buffer);
} else if (video.uri) {
// Download from URI
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (ai as any).files.download({
file: video.uri,
downloadPath: outputPath,
});
} else {
throw new Error("Video has neither videoBytes nor uri");
}
// Save the URI alongside the video file for potential scene extension
if (video.uri) {
const uriFilePath = outputPath.replace(/\.(mp4|mov)$/i, '.uri');
fs.writeFileSync(uriFilePath, video.uri, 'utf-8');
}
}
async function main(): Promise<void> {
const args = process.argv.slice(2);
// Common options
let filePath = "";
let promptText = "";
let promptFile = "";
let outputFileName = "";
// Image options
let useFlash = false;
let modelName = "";
// Video options
let videoMode = false;
let videoModel = "";
let videoFast = false;
let duration: 4 | 6 | 8 = 8;
let aspectRatio: "16:9" | "9:16" = "16:9";
let resolution: "720p" | "1080p" | "4K" = "1080p";
let generateAudio = true;
let seed: number | undefined;
let extendVideoPath = "";
let estimateCostOnly = false;
const referenceImages: string[] = [];
for (let i = 0; i < args.length; i++) {
if (args[i] === "--file") {
filePath = args[++i];
} else if (args[i] === "--prompt") {
promptText = args[++i];
} else if (args[i] === "--prompt-file") {
promptFile = args[++i];
} else if (args[i] === "--output") {
outputFileName = args[++i];
} else if (args[i] === "--flash") {
useFlash = true;
} else if (args[i] === "--model") {
modelName = args[++i];
} else if (args[i] === "--video") {
videoMode = true;
} else if (args[i] === "--video-model") {
videoModel = args[++i];
} else if (args[i] === "--video-fast") {
videoFast = true;
} else if (args[i] === "--duration") {
const d = parseInt(args[++i], 10);
if (d === 4 || d === 6 || d === 8) {
duration = d;
} else {
console.error("Error: --duration must be 4, 6, or 8");
process.exit(1);
}
} else if (args[i] === "--aspect") {
const a = args[++i];
if (a === "16:9" || a === "9:16") {
aspectRatio = a;
} else {
console.error("Error: --aspect must be 16:9 or 9:16");
process.exit(1);
}
} else if (args[i] === "--resolution") {
const r = args[++i];
if (r === "720p" || r === "1080p" || r === "4K") {
resolution = r;
} else {
console.error("Error: --resolution must be 720p, 1080p, or 4K");
process.exit(1);
}
} else if (args[i] === "--audio") {
generateAudio = true;
} else if (args[i] === "--no-audio") {
generateAudio = false;
} else if (args[i] === "--seed") {
seed = parseInt(args[++i], 10);
} else if (args[i] === "--reference") {
const refPath = args[++i];
if (!fs.existsSync(refPath)) {
console.error(`Error: Reference image not found at ${refPath}`);
process.exit(1);
}
referenceImages.push(refPath);
} else if (args[i] === "--extend") {
extendVideoPath = args[++i];
videoMode = true; // Extending a video implies video mode
} else if (args[i] === "--estimate-cost") {
estimateCostOnly = true;
videoMode = true; // Cost estimation implies video mode
} else if (args[i] === "--list-models") {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.error("Error: GEMINI_API_KEY environment variable is not set.");
process.exit(1);
}
await listModels(apiKey);
process.exit(0);
} else if (args[i] === "--help" || args[i] === "-h") {
printUsage();
process.exit(0);
} else if (!args[i].startsWith("--")) {
// Positional argument is the prompt
promptText = args[i];
}
}
if (promptFile) {
if (promptText) {
console.error(
"Error: Cannot use both --prompt and --prompt-file simultaneously."
);
process.exit(1);
}
try {
promptText = fs.readFileSync(promptFile, "utf-8");
} catch {
console.error(`Error: Could not read prompt file at ${promptFile}`);
process.exit(1);
}
}
if (!promptText) {
printUsage();
process.exit(1);
}
if (filePath && !fs.existsSync(filePath)) {
console.error(`Error: File not found at ${filePath}`);
process.exit(1);
}
const geminiApiKey = process.env.GEMINI_API_KEY;
if (!geminiApiKey) {
console.error("Error: GEMINI_API_KEY environment variable is not set.");
console.error(
"Please set it before running the script (e.g., export GEMINI_API_KEY='YOUR_API_KEY')."
);
process.exit(1);
}
const ai = new GoogleGenAI(geminiApiKey);
// Video generation mode
if (videoMode) {
// Validate extend video path
let extendVideoUri: string | undefined;
if (extendVideoPath) {
if (!fs.existsSync(extendVideoPath)) {
console.error(`Error: Video file not found at ${extendVideoPath}`);
process.exit(1);
}
// Load the URI file
const uriFilePath = extendVideoPath.replace(/\.(mp4|mov)$/i, '.uri');
if (!fs.existsSync(uriFilePath)) {
console.error(`Error: URI file not found at ${uriFilePath}`);
console.error('Can only extend videos generated by nano-banana (need .uri file)');
process.exit(1);
}
extendVideoUri = fs.readFileSync(uriFilePath, 'utf-8').trim();
// Enforce 720p resolution for extensions
if (resolution !== "720p") {
console.log("Note: Resolution forced to 720p for video extensions");
resolution = "720p";
}
// Can't use reference images with extension
if (referenceImages.length > 0) {
console.error("Error: Cannot use --reference with --extend");
process.exit(1);
}
// Can't use --file (image-to-video) with extension
if (filePath) {
console.error("Error: Cannot use --file with --extend");
process.exit(1);
}
}
// Validate reference images
if (referenceImages.length > 3) {
console.error("Error: Maximum 3 reference images allowed");
process.exit(1);
}
// Validate resolution/duration constraints
// 1080p only supports 8 seconds
if (resolution === "1080p" && duration !== 8) {
console.error(`Error: 1080p resolution only supports 8-second videos (got ${duration}s)`);
console.error(" Use --resolution 720p for shorter videos, or --duration 8 for 1080p");
process.exit(1);
}
// Reference images require 8 seconds
if (referenceImages.length > 0 && duration !== 8) {
console.error(`Error: Reference images require 8-second videos (got ${duration}s)`);
console.error(" Use --duration 8 when using --reference");
process.exit(1);
}
// Video extension requires 8 seconds
if (extendVideoPath && duration !== 8) {
console.error(`Error: Video extension requires 8-second videos (got ${duration}s)`);
console.error(" Use --duration 8 when using --extend");
process.exit(1);
}
const selectedVideoModel =
videoModel || (videoFast ? FAST_VIDEO_MODEL : DEFAULT_VIDEO_MODEL);
const videoConfig: VideoConfig = {
model: selectedVideoModel,
duration,
aspectRatio,
resolution,
generateAudio,
seed,
};
// If only estimating cost, show estimate and exit
if (estimateCostOnly) {
const costEstimate = estimateVideoCost(videoConfig);
console.log("\nCost Estimate:");
console.log(` Model: ${costEstimate.model}`);
console.log(` Duration: ${costEstimate.duration} seconds`);
console.log(` Audio: ${costEstimate.hasAudio ? "enabled" : "disabled"}`);
console.log(` Resolution: ${resolution}`);
console.log(` Aspect Ratio: ${aspectRatio}`);
console.log(
`\n Estimated cost: $${costEstimate.min.toFixed(2)} - $${costEstimate.max.toFixed(2)}`
);
if (extendVideoPath) {
console.log(
`\n Note: This is for a single extension. Each additional extension costs the same.`
);
}
console.log(
`\nTo generate this video, remove the --estimate-cost flag.`
);
process.exit(0);
}
let mode: string;
if (extendVideoUri) {
mode = `Extending '${extendVideoPath}'`;
} else if (filePath) {
mode = `Animating '${filePath}'`;
} else {
mode = "Generating video";
}
console.log(`${mode} using ${selectedVideoModel}`);
console.log(
`Prompt: "${promptText.substring(0, 60)}${promptText.length > 60 ? "..." : ""}"`
);
console.log(
`Settings: ${duration}s, ${aspectRatio}, ${resolution}, audio: ${generateAudio ? "yes" : "no"}`
);
if (referenceImages.length > 0) {
console.log(`Reference images: ${referenceImages.length}`);
}
try {
const video = await generateVideo(
ai,
promptText,
videoConfig,
filePath || undefined,
referenceImages.length > 0 ? referenceImages : undefined,
extendVideoUri
);
// Determine output path
let outputPath: string;
if (outputFileName) {
outputPath = outputFileName;
const outputDir = path.dirname(outputPath);
if (outputDir && !fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
} else {
const outputDir = "output";
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
if (filePath) {
const originalFileName = path.basename(
filePath,
path.extname(filePath)
);
outputPath = path.join(outputDir, `${originalFileName}-animated.mp4`);
} else {
const timestamp = Date.now();
outputPath = path.join(outputDir, `video-${timestamp}.mp4`);
}
}
console.log("Downloading video...");
await downloadVideo(ai, video as Video, outputPath);
console.log(`Video saved: ${outputPath}`);
} catch (error) {
console.error("Error generating video:", error);
process.exit(1);
}
return;
}
// Image generation mode (original behavior)
const contents: ContentPart[] = [{ text: promptText }];
// If file provided, add it to the request (image editing mode)
if (filePath) {
const base64Image = fs.readFileSync(filePath).toString("base64");
const mimeType = await getMimeType(filePath);
if (!mimeType.startsWith("image/")) {
console.error(
`Error: Input file '${filePath}' is not an image. Detected MIME type: ${mimeType}`
);
process.exit(1);
}
contents.push({
inlineData: {
mimeType: mimeType,
data: base64Image,
},
});
}
// Determine model: --model takes precedence, then --flash, then default
const selectedModel = modelName || (useFlash ? FLASH_MODEL : DEFAULT_MODEL);
try {
const mode = filePath ? `Editing '${filePath}'` : "Generating image";
console.log(`${mode} using ${selectedModel}`);
console.log(
`Prompt: "${promptText.substring(0, 60)}${promptText.length > 60 ? "..." : ""}"`
);
const response = (await ai.models.generateContent({
model: selectedModel,
contents: contents,
config: {
responseModalities: ["Text", "Image"],
},
})) as GenerateContentResponse;
let imageSaved = false;
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log("Response:", part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
let outputPath: string;
if (outputFileName) {
// Use exact path specified by --output
outputPath = outputFileName;
const outputDir = path.dirname(outputPath);
if (outputDir && !fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
} else {
// Default to output/ directory with auto-generated name
const outputDir = "output";
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
if (filePath) {
const originalFileName = path.basename(
filePath,
path.extname(filePath)
);
outputPath = path.join(outputDir, `${originalFileName}-edited.png`);
} else {
const timestamp = Date.now();
outputPath = path.join(outputDir, `generated-${timestamp}.png`);
}
}
fs.writeFileSync(outputPath, buffer);
console.log(`Image saved: ${outputPath}`);
imageSaved = true;
}
}
if (!imageSaved) {
console.log("No image in response.");
console.log("Full response:", JSON.stringify(response, null, 2));
}
} catch (error) {
console.error("Error calling Gemini API:", error);
process.exit(1);
}
}
function printUsage(): void {
console.log(`Usage: nano-banana <prompt> [options]
MODES:
(default) Generate or edit images using Gemini image models
--video Generate videos using Google Veo models
IMAGE OPTIONS:
--file <image> Input image for editing mode
--model <name> Gemini model (default: ${DEFAULT_MODEL})
--flash Use faster ${FLASH_MODEL} model
VIDEO OPTIONS:
--video Enable video generation mode
--video-model <name> Veo model (default: ${DEFAULT_VIDEO_MODEL})
--video-fast Use ${FAST_VIDEO_MODEL} (cheaper, faster)
--duration <sec> Duration: 4, 6, or 8 seconds (default: 8)
Note: 1080p requires 8s; 720p allows 4/6/8s
--aspect <ratio> 16:9 (landscape) or 9:16 (portrait) (default: 16:9)
--resolution <res> 720p, 1080p, or 4K (default: 1080p)
Note: 4K only available on preview models
--audio Generate synchronized audio (default)
--no-audio Disable audio generation (saves cost)
--reference <image> Reference image for character consistency (max 3)
Note: Requires 8s duration
--extend <video> Extend a previously generated video (max 20 extensions)
Note: Requires 8s duration
--seed <number> Seed for reproducibility
COMMON OPTIONS:
--output <file> Output path (default: output/)
--prompt-file <path> Read prompt from file
--estimate-cost Show cost estimate without generating (video only)
--list-models Show available models
--help, -h Show this help
IMAGE EXAMPLES:
nano-banana "a cat wearing a hat"
nano-banana "make it cartoon" --file photo.jpg
nano-banana "a sunset" --output sunset.png
VIDEO EXAMPLES:
nano-banana --video "A sunset over mountains, cinematic"
nano-banana --video "Character smiles" --file portrait.png
nano-banana --video "Quick test" --video-fast --no-audio
nano-banana --video "Hero walks through forest" --reference hero.jpg
nano-banana --video "Camera continues forward" --extend output/video-123.mp4
nano-banana --video "Complex scene" --duration 8 --estimate-cost
COST NOTES:
Video generation costs $0.10-$0.75 per second depending on model.
Use --video-fast and --no-audio for cheaper development iterations.
ENVIRONMENT:
GEMINI_API_KEY Required. Get from https://aistudio.google.com/apikey`);
}
main();