forked from ilkerzg/fal-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1673 lines (1457 loc) · 52.3 KB
/
cli.js
File metadata and controls
executable file
·1673 lines (1457 loc) · 52.3 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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* ===== FAL CLI - AI IMAGE GENERATION COMMAND LINE INTERFACE =====
*
* A comprehensive command-line interface for FAL AI image generation models.
* This CLI provides an interactive, user-friendly way to generate images using
* various AI models with advanced features and customization options.
*
* CORE FEATURES:
* - Interactive model selection with detailed information
* - Single and batch generation modes
* - Intelligent prompt optimization using LLM
* - Secure API key management with encryption
* - Cost estimation and spending protection
* - Real-time progress tracking with playful animations
* - Organized output with metadata preservation
* - Browser integration for viewing results
*
* WORKFLOW:
* 1. Authentication - Secure API key setup and validation
* 2. Model Selection - Multi-select from available FAL models
* 3. Mode Selection - Choose between single or batch generation
* 4. Input Configuration - Prompts, images, or batch data files
* 5. Prompt Optimization - Optional LLM-based prompt enhancement
* 6. Parameter Tuning - Model-specific parameter configuration
* 7. Output Setup - Image count, batch size, and directory selection
* 8. Cost Estimation - Transparent pricing with user confirmation
* 9. Generation - Multi-threaded image generation with progress tracking
* 10. Post-Processing - Results display, browser opening, and further actions
*
* SECURITY:
* - AES-256-GCM encryption for stored API keys
* - Machine-specific encryption keys
* - OS-appropriate secure storage locations
* - API key format validation
*
* ARCHITECTURE:
* - Modular design with shared core libraries
* - Commander.js for command parsing
* - Inquirer.js for interactive prompts
* - Chalk and Ora for beautiful terminal UI
* - Async/await throughout for modern JavaScript
*
* @author ilkerzg
* @version 0.0.1
* @license MIT
*/
import { Command } from 'commander';
import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import boxen from 'boxen';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import { fal } from '@fal-ai/client';
import open from 'open';
import { storeApiKey, retrieveApiKey, hasStoredApiKey, removeApiKey, getConfigPath, validateApiKey } from './secure-storage.js';
import { getAllModels, getModelById, getSharedParameters, loadModels } from './models-new.js';
const program = new Command();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Load environment variables
dotenv.config();
// ===== CLI CONFIGURATION =====
/**
* Configure the main CLI program with metadata, options, and global settings.
* This sets up the foundation for all CLI commands and interactions.
*/
program
.name('fal-cli')
.description('🎨 FAL AI Models CLI - Generate images and videos with FAL AI models')
.version('3.0.0')
.option('-v, --verbose', 'enable verbose logging')
.option('--no-color', 'disable colored output');
// ===== GLOBAL STATE MANAGEMENT =====
/**
* Global state variables that persist throughout the CLI session.
* These maintain user selections and configuration across different steps.
*/
let FAL_KEY = null; // Authenticated FAL API key
let selectedModels = []; // Array of selected model configurations
let isBatchMode = false; // Whether to use batch or single generation mode
let batchData = { prompts: [], images: [] }; // Batch processing data
let userPrompt = ''; // User's input prompt for single mode
let userImagePath = ''; // Path to input image for image-to-image
let imagesPerModel = 1; // Number of images to generate per model
let batchSize = 1; // Concurrent generation batch size
let parameters = {}; // Model-specific generation parameters
let isOptimized = false; // Whether prompts have been optimized
let generationId = ''; // Unique identifier for this generation session
let outputDirectory = null; // Directory for saving generated images
// Playful loading messages inspired by the original CLI
const thinkingMessages = [
'🤔 Pondering the perfect pixels...',
'🎨 Mixing digital paint on the canvas...',
'🧠 Consulting the AI muses...',
'✨ Weaving dreams into reality...',
'🔮 Channeling creative energy...',
'🎭 Staging the visual narrative...',
'🌈 Blending colors in hyperspace...',
'🚀 Launching imagination rockets...',
'💫 Stardust and algorithms colliding...',
'🎪 The AI circus is in full swing...'
];
const generatingMessages = [
'⚡ Electrons are dancing...',
'🔥 Neural networks are sparking...',
'💎 Crystallizing your vision...',
'🌊 Riding the wave of creativity...',
'🎵 Composing visual symphonies...',
'🏗️ Architecting pixel masterpieces...',
'🌸 Blooming digital artwork...',
'🎯 Aiming for aesthetic perfection...',
'🦋 Metamorphosis in progress...',
'🎨 The brush strokes are coming alive...'
];
const optimizingMessages = [
'🎨 Converting words into visual concepts...',
'🖌️ Sketching the perfect composition...',
'📐 Calculating optimal visual elements...',
'🎭 Staging your creative vision...',
'🔄 Translating text to image blueprint...',
'⚡ Inference engines are processing...',
'🖼️ Compositing the perfect scene...',
'🎪 Orchestrating visual storytelling...',
'🌈 Blending colors and concepts...',
'🔍 Analyzing prompt for visual clarity...',
'🧩 Assembling artistic elements...',
'🎯 Fine-tuning visual parameters...',
'🌟 Illuminating creative possibilities...',
'🎬 Directing the visual narrative...',
'✨ Transforming ideas into imagery...',
'🎨 Painting with digital brushstrokes...',
'🧠 Neural networks are dreaming...',
'🔮 Materializing your imagination...',
'🎭 Choreographing visual poetry...',
'🌊 Flowing through creative dimensions...',
'🎪 Juggling artistic possibilities...',
'🔥 Igniting creative sparks...',
'🌙 Crafting moonlit masterpieces...',
'🎵 Harmonizing visual symphony...',
'🦋 Metamorphosing concepts to art...',
'🌺 Blooming creative visions...',
'🗿 Sculpting digital narratives...',
'🎨 Mixing palette of possibilities...',
'🔬 Experimenting with visual chemistry...',
'🎪 Spinning artistic alchemy...',
'🌌 Weaving cosmic inspirations...',
'🎭 Masking reality with dreams...',
'🔥 Forging artistic brilliance...',
'🌟 Constellation of creative ideas...',
'🎨 Brushing strokes of genius...',
'🌊 Surfing waves of inspiration...',
'🎪 Balancing artistic elements...',
'🔮 Crystallizing visual thoughts...',
'🎭 Revealing hidden aesthetics...',
'🌸 Cultivating digital gardens...',
'🎨 Architecting visual stories...',
'🔥 Kindling creative flames...',
'🌙 Moonbeam pixel arrangements...',
'🎪 Circus of creative algorithms...',
'🌈 Refracting light into art...',
'🎭 Theatre of digital dreams...',
'🔮 Gazing into artistic futures...',
'🌺 Petals of visual poetry...',
'🎨 Canvas of infinite possibilities...',
'⚗️ Brewing artistic potions...',
'🌟 Stardust composition magic...',
'🎪 Ringmaster of visual circus...',
'🔥 Phoenix of creative rebirth...',
'🌊 Tidal waves of inspiration...',
'🎭 Masks of artistic expression...',
'🌙 Lunar eclipse of creativity...',
'🎨 Palette knife precision...',
'🔮 Crystal ball revelations...',
'🌺 Garden of visual delights...',
'🎪 Acrobatic artistic maneuvers...',
'🌟 Galactic art laboratories...',
'🔥 Forge of digital artisans...',
'🌊 Ocean depths of creativity...',
'🎭 Theatrical visual arrangements...',
'🌙 Crescent moon compositions...',
'🎨 Artistic DNA sequencing...',
'🔮 Mystical creative synthesis...',
'🌺 Blooming pixel gardens...',
'🎪 Carnival of visual wonders...',
'🌟 Shooting star inspirations...',
'🔥 Volcanic creative eruptions...',
'🌊 Whirlpool of artistic energy...',
'🎭 Masquerade of visual beauty...',
'🌙 Midnight artistic sessions...',
'🎨 Fresco of digital dreams...',
'🔮 Oracle of creative wisdom...',
'🌺 Orchid arrangements in pixels...',
'🎪 Trapeze artists of creativity...',
'🌟 Nebula of artistic birth...',
'🔥 Ember glow of inspiration...',
'🌊 Tsunami of visual impact...',
'🎭 Ballet of artistic grace...',
'🌙 Eclipse shadows and highlights...',
'🎨 Mosaic of creative fragments...',
'🔮 Prism refracting pure art...',
'🌺 Lotus blooms in digital ponds...',
'🎪 Juggling spheres of beauty...',
'🌟 Cosmic dust artistic formation...',
'🔥 Blazing trails of creativity...',
'🌊 Ripples across artistic waters...',
'🎭 Opera of visual storytelling...',
'🌙 Twilight artistic revelations...',
'🎨 Watercolor wisdom flowing...',
'🔮 Enchanted artistic realms...',
'🌺 Sakura petals of inspiration...',
'🎪 Tightrope walking creativity...',
'🌟 Aurora borealis of art...',
'🔥 Campfire stories in pixels...',
'🌊 Lighthouse beams of vision...',
'🎭 Symphony of visual harmony...',
'🌙 Lunar tides of creativity...',
'🎨 Sculpture garden of ideas...',
'🔮 Kaleidoscope of possibilities...',
'🌺 Zen garden of visual peace...',
'🎪 Magic show of artistic tricks...',
'🌟 Constellation map drawing...',
'🔥 Hearth warming creative souls...',
'🌊 Pearl diving for art gems...'
];
const getRandomMessage = (messages) => {
return messages[Math.floor(Math.random() * messages.length)];
};
// Enhanced spinner with playful animations
const createPlayfulSpinner = (message, messageArray = thinkingMessages) => {
const spinner = ora({
text: message,
spinner: {
interval: 120,
frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
}
});
let messageIndex = 0;
const messageInterval = setInterval(() => {
spinner.text = getRandomMessage(messageArray);
messageIndex++;
}, 2500);
const originalStop = spinner.stop.bind(spinner);
spinner.stop = () => {
clearInterval(messageInterval);
originalStop();
};
const originalSucceed = spinner.succeed.bind(spinner);
spinner.succeed = (text) => {
clearInterval(messageInterval);
return originalSucceed(text);
};
const originalFail = spinner.fail.bind(spinner);
spinner.fail = (text) => {
clearInterval(messageInterval);
return originalFail(text);
};
return spinner;
};
// Utility functions
const displayWelcome = () => {
console.log(boxen(
chalk.bold.cyan('🎨 FAL AI Models CLI\n') +
chalk.white('Generate images and videos with FAL AI models\n') +
chalk.gray('OpenAPI compatible, batch processing supported'),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'cyan'
}
));
};
const displayError = (message) => {
console.log(chalk.red.bold('✗ ERROR:'), chalk.red(message));
};
const displaySuccess = (message) => {
console.log(chalk.green.bold('✓ SUCCESS:'), chalk.green(message));
};
const displayInfo = (message) => {
console.log(chalk.blue.bold('ℹ INFO:'), chalk.cyan(message));
};
const createSpinner = (message) => {
return ora({
text: message,
spinner: 'dots',
color: 'cyan'
});
};
// Step 1: Authentication
const authenticateUser = async () => {
// Simple priority: environment variable, .env file, secure storage (optional)
// 1. Check environment variable first
if (process.env.FAL_KEY) {
FAL_KEY = process.env.FAL_KEY;
return;
}
// 2. Check secure storage (silently, no errors)
try {
const storedKey = await retrieveApiKey();
if (storedKey) {
FAL_KEY = storedKey;
return;
}
} catch (error) {
// Silently continue
}
// No API key found - simple error message
displayError('FAL API key not found!');
displayInfo('Set your FAL API key:');
console.log(chalk.yellow(' export FAL_KEY="your_key_here"'));
console.log(chalk.yellow(' or: echo "FAL_KEY=your_key_here" > .env'));
console.log(chalk.yellow(' or: fal-cli config --set-key your_key'));
process.exit(1);
};
// Helper function to prompt and store API key securely
const promptAndStoreApiKey = async () => {
const { inputApiKey } = await inquirer.prompt([
{
type: 'password',
name: 'inputApiKey',
message: 'Enter your FAL API key:',
validate: (input) => {
if (!input || input.trim() === '') {
return 'API key is required';
}
if (!validateApiKey(input.trim())) {
return 'Invalid API key format. Expected format: uuid:hex_string';
}
return true;
}
}
]);
const key = inputApiKey.trim();
try {
await storeApiKey(key);
apiKey = key;
fal.config({ credentials: apiKey });
displaySuccess('✅ API key stored securely!');
displayInfo(`📁 Stored in: ${getConfigPath()}`);
} catch (error) {
displayError(`Failed to store API key: ${error.message}`);
process.exit(1);
}
};
// Step 2: Model Selection
const selectModels = async () => {
const models = await getAllModels();
console.log('\n' + chalk.cyan.bold('📋 Available Models:'));
// Group models by category for better display
const categories = {};
models.forEach(model => {
if (!categories[model.category]) {
categories[model.category] = [];
}
categories[model.category].push(model);
});
// Display models grouped by category
Object.entries(categories).forEach(([category, categoryModels]) => {
console.log(chalk.blue.bold(`\n🏷️ ${category}:`));
categoryModels.forEach((model, index) => {
const globalIndex = models.findIndex(m => m.key === model.key);
console.log(chalk.green(` ${globalIndex + 1}. ${model.name}`));
console.log(chalk.gray(` ${model.description}`));
console.log(chalk.yellow(` Cost: $${model.costPerImage}/image | Max: ${model.maxImages} images`));
});
});
const { modelIndices } = await inquirer.prompt([
{
type: 'checkbox',
name: 'modelIndices',
message: 'Select models (use SPACE to select, ENTER to confirm):',
choices: models.map((model, index) => ({
name: `${model.name} - ${model.category} ($${model.costPerImage}/img)`,
value: index,
checked: false
})),
validate: (input) => {
if (input.length === 0) {
return 'Please select at least one model';
}
return true;
}
}
]);
selectedModels = modelIndices.map(index => models[index]);
displaySuccess(`Selected ${selectedModels.length} model(s):`);
selectedModels.forEach(model => {
console.log(chalk.green(` • ${model.name} (${model.category})`));
});
};
// Step 3: Batch vs Single Mode
const selectMode = async () => {
const { mode } = await inquirer.prompt([
{
type: 'list',
name: 'mode',
message: 'Choose generation mode:',
choices: [
{ name: '📝 Single - Enter prompt manually', value: 'single' },
{ name: '📁 Batch - Process multiple prompts from file', value: 'batch' }
]
}
]);
isBatchMode = mode === 'batch';
if (isBatchMode) {
displayInfo('Batch mode selected. Please ensure /batch/prompts.txt exists');
displayInfo('All selected models are text-to-image, so only prompts are needed.');
}
};
// Step 4: Load Batch Data
const loadBatchData = async () => {
if (!isBatchMode) return;
const batchDir = path.join(process.cwd(), 'batch');
const promptsFile = path.join(batchDir, 'prompts.txt');
try {
// Check if batch directory exists
if (!await fs.pathExists(batchDir)) {
throw new Error('/batch directory not found');
}
// Load prompts
if (!await fs.pathExists(promptsFile)) {
throw new Error('/batch/prompts.txt not found');
}
const promptsContent = await fs.readFile(promptsFile, 'utf-8');
batchData.prompts = promptsContent
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
if (batchData.prompts.length === 0) {
throw new Error('No prompts found in prompts.txt');
}
displaySuccess(`Loaded ${batchData.prompts.length} prompts from batch file`);
displayInfo('Ready for text-to-image generation with batch prompts');
} catch (error) {
displayError(error.message);
process.exit(1);
}
};
// Step 5: Single Mode Input
const getSingleInput = async () => {
if (isBatchMode) return;
// Get prompt
const { prompt } = await inquirer.prompt([
{
type: 'input',
name: 'prompt',
message: 'Enter your prompt:',
validate: (input) => {
if (!input || input.trim() === '') {
return 'Prompt is required';
}
return true;
}
}
]);
userPrompt = prompt.trim();
displaySuccess(`Prompt set: "${userPrompt}"`);
};
// Step 6: Prompt Optimization
const optimizePrompt = async () => {
if (isBatchMode) {
// For batch mode, ask once if all prompts should be optimized
const { wantsOptimize } = await inquirer.prompt([
{
type: 'confirm',
name: 'wantsOptimize',
message: 'Do you want to optimize all batch prompts using AI?',
default: false
}
]);
if (!wantsOptimize) {
displayInfo('Using original batch prompts without optimization');
return;
}
displayInfo('\n📝 Optimizing batch prompts...');
// Optimize each prompt in the batch
const optimizedPrompts = [];
for (let i = 0; i < batchData.prompts.length; i++) {
const originalPrompt = batchData.prompts[i];
displayInfo(`\nOptimizing prompt ${i + 1}/${batchData.prompts.length}: "${originalPrompt.slice(0, 50)}..."`);
try {
const optimizedPrompt = await optimizeSinglePrompt(originalPrompt, selectedModels[0]);
optimizedPrompts.push(optimizedPrompt);
displaySuccess(`✓ Optimized: "${optimizedPrompt.slice(0, 50)}..."`);
} catch (error) {
displayError(`Failed to optimize prompt ${i + 1}: ${error.message}`);
displayInfo(`Using original: "${originalPrompt.slice(0, 50)}..."`);
optimizedPrompts.push(originalPrompt);
}
}
// Update batch data with optimized prompts
batchData.prompts = optimizedPrompts;
displaySuccess(`\n✅ Batch optimization complete! ${optimizedPrompts.length} prompts processed.`);
} else {
// Single mode optimization
const { wantsOptimize } = await inquirer.prompt([
{
type: 'confirm',
name: 'wantsOptimize',
message: 'Do you want to optimize your prompt using AI?',
default: false
}
]);
if (!wantsOptimize) {
displayInfo('Using original prompt without optimization');
return;
}
displayInfo('\n📝 Optimizing your prompt...');
try {
const optimizedPrompt = await optimizeSinglePrompt(userPrompt, selectedModels[0]);
// Show comparison
console.log('\n' + boxen(
`${chalk.yellow('Original:')}\n${userPrompt}\n\n${chalk.green('Optimized:')}\n${optimizedPrompt}`,
{ padding: 1, borderColor: 'blue', title: 'Prompt Comparison' }
));
const { useOptimized } = await inquirer.prompt([
{
type: 'confirm',
name: 'useOptimized',
message: 'Use the optimized prompt?',
default: true
}
]);
if (useOptimized) {
userPrompt = optimizedPrompt;
displaySuccess('✅ Using optimized prompt for generation');
} else {
displayInfo('Using original prompt');
}
} catch (error) {
displayError(`Failed to optimize prompt: ${error.message}`);
displayInfo('Using original prompt');
}
}
};
// Helper function to optimize a single prompt
const optimizeSinglePrompt = async (prompt, model) => {
const spinner = createPlayfulSpinner(
`✨ Optimizing "${prompt.substring(0, 30)}${prompt.length > 30 ? '...' : ''}"`,
optimizingMessages
);
spinner.start();
try {
// Use the selected model's actual optimization system prompt
const systemPrompt = model.optimization_system_prompt ||
`You are an expert prompt engineer. Optimize the following prompt for AI image generation to be more detailed, specific, and likely to produce high-quality results. Focus on visual details, artistic style, composition, and technical aspects that work well with ${model.name || 'this AI model'}.`;
const result = await fal.subscribe('fal-ai/any-llm', {
input: {
prompt: prompt,
system_prompt: systemPrompt,
max_tokens: 500
},
credentials: FAL_KEY,
logs: false
});
spinner.succeed('🎉 Prompt optimization complete!');
// Extract the optimized prompt from the response
let optimizedPrompt = '';
if (result.data && result.data.output) {
optimizedPrompt = result.data.output.trim();
} else if (result.output) {
optimizedPrompt = result.output.trim();
} else {
throw new Error('Unexpected LLM response format');
}
// Ensure we got a valid response
if (!optimizedPrompt || optimizedPrompt.length < 10) {
throw new Error('LLM returned an invalid or too short optimized prompt');
}
return optimizedPrompt;
} catch (error) {
spinner.fail('❌ Optimization failed');
throw error;
}
};
// Step 7: Parameter Configuration
const configureParameters = async () => {
const { wantsConfigure } = await inquirer.prompt([
{
type: 'confirm',
name: 'wantsConfigure',
message: 'Do you want to configure model parameters?',
default: false
}
]);
if (!wantsConfigure) {
displayInfo('Using default parameters');
return;
}
// Get shared parameters for multi-model selection
const sharedParams = getSharedParameters(selectedModels);
if (Object.keys(sharedParams).length === 0) {
displayInfo('No shared parameters found between selected models. Using defaults.');
return;
}
console.log(chalk.cyan.bold('\n⚙️ Configuring Parameters:'));
console.log(chalk.gray('Only parameters common to all selected models are shown.\n'));
for (const [paramName, paramConfig] of Object.entries(sharedParams)) {
if (paramName === 'prompt' || paramName === 'image_url') continue; // Skip these, handled separately
let paramValue;
if (paramConfig.options) {
// Choice parameter
const { choice } = await inquirer.prompt([
{
type: 'list',
name: 'choice',
message: `${paramName}:`,
choices: paramConfig.options.map(option => ({ name: option, value: option })),
default: paramConfig.default
}
]);
paramValue = choice;
} else if (paramConfig.type === 'integer') {
// Integer parameter
const { value } = await inquirer.prompt([
{
type: 'number',
name: 'value',
message: `${paramName} (${paramConfig.min || 'min'} - ${paramConfig.max || 'max'}):`,
default: paramConfig.default,
validate: (input) => {
const num = parseInt(input);
if (isNaN(num)) return 'Please enter a valid number';
if (paramConfig.min && num < paramConfig.min) return `Minimum value is ${paramConfig.min}`;
if (paramConfig.max && num > paramConfig.max) return `Maximum value is ${paramConfig.max}`;
return true;
}
}
]);
paramValue = parseInt(value);
} else if (paramConfig.type === 'float') {
// Float parameter
const { value } = await inquirer.prompt([
{
type: 'number',
name: 'value',
message: `${paramName} (${paramConfig.min || 'min'} - ${paramConfig.max || 'max'}):`,
default: paramConfig.default,
validate: (input) => {
const num = parseFloat(input);
if (isNaN(num)) return 'Please enter a valid number';
if (paramConfig.min && num < paramConfig.min) return `Minimum value is ${paramConfig.min}`;
if (paramConfig.max && num > paramConfig.max) return `Maximum value is ${paramConfig.max}`;
return true;
}
}
]);
paramValue = parseFloat(value);
}
if (paramValue !== undefined) {
parameters[paramName] = paramValue;
}
}
if (Object.keys(parameters).length > 0) {
displaySuccess('Parameters configured:');
Object.entries(parameters).forEach(([key, value]) => {
console.log(chalk.green(` • ${key}: ${value}`));
});
}
};
// Step 8: Image Count Selection (Iterations)
const selectImageCount = async () => {
console.log('\n' + chalk.cyan.bold('🖼️ Image Generation Settings:'));
console.log(chalk.gray('There are two different image count settings:'));
console.log(chalk.yellow(' 1. Model Parameter (num_images): Images per API call (set in parameters, max 4)'));
console.log(chalk.yellow(' 2. Iterations: How many times to run the model with these settings'));
console.log(chalk.gray('\nTotal images = num_images × iterations'));
if (parameters.num_images) {
console.log(chalk.green(`\nYour model parameter setting: ${parameters.num_images} images per API call`));
} else {
console.log(chalk.yellow('\nModel parameter num_images not set, will default to 1 image per API call'));
}
const { iterationCount } = await inquirer.prompt([
{
type: 'number',
name: 'iterationCount',
message: 'How many iterations (API calls) to run?',
default: 1,
validate: (input) => {
const num = parseInt(input);
if (isNaN(num) || num < 1) return 'Please enter a number >= 1';
if (num > 50) return 'Maximum 50 iterations for safety';
return true;
}
}
]);
imagesPerModel = parseInt(iterationCount);
const imagesPerCall = parameters.num_images || 1;
const totalImagesPerModel = imagesPerCall * imagesPerModel;
console.log(chalk.green.bold(`\n📊 Generation Summary:`));
console.log(chalk.cyan(` • Images per API call: ${imagesPerCall}`));
console.log(chalk.cyan(` • Number of iterations: ${imagesPerModel}`));
console.log(chalk.cyan(` • Total images per model: ${totalImagesPerModel}`));
console.log(chalk.cyan(` • Total images (all models): ${totalImagesPerModel * selectedModels.length}`));
};
// Step 9: Batch Size Selection
const selectBatchSize = async () => {
const totalGenerations = isBatchMode ?
batchData.prompts.length * selectedModels.length :
selectedModels.length;
const maxBatchSize = Math.min(10, totalGenerations);
if (totalGenerations > 1) {
const { batchSizeInput } = await inquirer.prompt([
{
type: 'number',
name: 'batchSizeInput',
message: `Batch size for concurrent requests? (max ${maxBatchSize}):`,
default: Math.min(3, maxBatchSize),
validate: (input) => {
const num = parseInt(input);
if (isNaN(num) || num < 1) return 'Please enter a number >= 1';
if (num > maxBatchSize) return `Maximum ${maxBatchSize} concurrent requests`;
return true;
}
}
]);
batchSize = parseInt(batchSizeInput);
}
};
// Step 10: Output Directory Selection
const selectOutputDirectory = async () => {
if (!outputDirectory) {
const { useCustomDir } = await inquirer.prompt([
{
type: 'confirm',
name: 'useCustomDir',
message: 'Use custom output directory?',
default: false
}
]);
if (useCustomDir) {
const { customDir } = await inquirer.prompt([
{
type: 'input',
name: 'customDir',
message: 'Enter output directory path:',
default: './generated-images',
validate: (input) => {
if (!input.trim()) return 'Please enter a directory path';
return true;
}
}
]);
outputDirectory = path.resolve(customDir);
} else {
// Use current working directory
outputDirectory = path.join(process.cwd(), 'generated-images');
}
}
console.log(chalk.green(`\n📁 Output directory: ${outputDirectory}`));
};
// Step 11: Cost and Confirmation
const showCostEstimate = async () => {
const modelImages = isBatchMode ?
batchData.prompts.length * imagesPerModel * (parameters.num_images || 1) :
imagesPerModel * (parameters.num_images || 1);
const totalCost = selectedModels.reduce((sum, model) => {
return sum + (model.costPerImage * modelImages);
}, 0);
console.log('\n' + chalk.cyan.bold('💰 Cost Estimate:'));
selectedModels.forEach(model => {
const modelCost = model.costPerImage * modelImages;
console.log(chalk.yellow(` • ${model.name}: $${modelCost.toFixed(4)} (${modelImages} images × $${model.costPerImage})`));
});
console.log(chalk.green.bold(`\n Total Cost: $${totalCost.toFixed(4)}`));
const { confirmed } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirmed',
message: 'Proceed with generation?',
default: true
}
]);
if (!confirmed) {
displayInfo('Generation cancelled');
process.exit(0);
}
};
// Step 12: Generation
const generateImages = async () => {
const startTime = Date.now();
const generationId = `gen_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
console.log(chalk.cyan.bold(`\n🎨 Starting generation (ID: ${generationId})`));
const outputDir = path.join(outputDirectory, generationId);
await fs.ensureDir(outputDir);
const results = [];
const tasks = [];
// Prepare generation tasks
if (isBatchMode) {
batchData.prompts.forEach((prompt, promptIndex) => {
selectedModels.forEach(model => {
for (let imageIndex = 0; imageIndex < imagesPerModel; imageIndex++) {
tasks.push({
model,
prompt,
promptIndex: promptIndex + 1,
imageIndex: imageIndex + 1
});
}
});
});
} else {
selectedModels.forEach(model => {
for (let imageIndex = 0; imageIndex < imagesPerModel; imageIndex++) {
tasks.push({
model,
prompt: userPrompt,
promptIndex: 1,
imageIndex: imageIndex + 1
});
}
});
}
// Process tasks in batches
const totalTasks = tasks.length;
let completedTasks = 0;
for (let i = 0; i < tasks.length; i += batchSize) {
const batch = tasks.slice(i, i + batchSize);
console.log(chalk.blue(`\nProcessing batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(tasks.length / batchSize)}`));
const batchPromises = batch.map(async (task) => {
try {
const result = await generateSingleImage(task, outputDir, generationId);
completedTasks++;
console.log(chalk.green(`✓ Completed ${completedTasks}/${totalTasks} tasks`));
return result;
} catch (error) {
completedTasks++;
console.log(chalk.red(`✗ Failed ${completedTasks}/${totalTasks} tasks: ${error.message}`));
return null;
}
});
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults.filter(result => result !== null));
}
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(1);
// Count total images from all successful tasks
const totalImagesGenerated = results
.filter(result => result && result.images)
.reduce((sum, result) => sum + result.images.length, 0);
displaySuccess(`Generation completed in ${duration}s`);
displayInfo(`Generated ${totalImagesGenerated} images`);
displayInfo(`Completed ${results.length} tasks`);
displayInfo(`Output directory: ${outputDir}`);
// Display FAL URLs with browser opening option
await displayFalUrls(results);
return results;
};
const generateSingleImage = async (task, outputDir, generationId) => {
const { model, prompt, promptIndex, imageIndex } = task;
const timestamp = Date.now();
const randomSuffix = Math.random().toString(36).substring(2, 8);
// Validate model object
if (!model || !model.id || !model.name) {
throw new Error(`Invalid model object: ${JSON.stringify(model)}`);
}
// Create playful spinner for this generation
const spinner = createPlayfulSpinner(
`🎨 Creating with ${model.name}...`,
generatingMessages
);
spinner.start();
try {
// Prepare request parameters
const requestParams = {
prompt: prompt,
...parameters
};
const result = await fal.subscribe(model.id, {
input: requestParams,
logs: false,
credentials: FAL_KEY,
onQueueUpdate: (update) => {
try {
if (update.status === 'IN_QUEUE') {