forked from ilkerzg/fal-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-model-schemas.js
More file actions
346 lines (307 loc) · 11.2 KB
/
Copy pathfetch-model-schemas.js
File metadata and controls
346 lines (307 loc) · 11.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
#!/usr/bin/env node
/**
* Fetch FAL model schemas from OpenAPI and generate config files
* Uses FAL's OpenAPI endpoint to get accurate parameter definitions
*/
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Models to fetch schemas for
const MODELS_TO_FETCH = [
// Original models that need schema updates
{
id: 'fal-ai/flux-pro/kontext/max/text-to-image',
name: 'FLUX Pro Kontext Max',
category: 'Professional',
costPerImage: 0.08,
description: 'Advanced FLUX model with maximum context understanding',
modelKey: 'flux-kontext-max'
},
{
id: 'fal-ai/flux-pro/kontext/text-to-image',
name: 'FLUX Pro Kontext',
category: 'Professional',
costPerImage: 0.04,
description: 'Professional FLUX model with enhanced context understanding',
modelKey: 'flux-kontext-pro'
},
{
id: 'fal-ai/flux-pro/v1.1-ultra',
name: 'FLUX Pro Ultra v1.1',
category: 'Ultra Quality',
costPerImage: 0.06,
description: 'Latest FLUX Pro model with ultra-high quality output',
modelKey: 'flux-pro-ultra'
},
{
id: 'fal-ai/imagen4/preview/ultra',
name: 'Imagen 4 Ultra (Preview)',
category: 'Ultra Quality',
costPerImage: 0.06,
description: "Google's latest high-quality image generation model",
modelKey: 'imagen4-ultra'
},
{
id: 'fal-ai/qwen-image',
name: 'Qwen Image',
category: 'General Purpose',
costPerImage: 0.05,
description: 'High-quality text-to-image model with excellent text rendering',
modelKey: 'qwen-image'
},
// New models added
{
id: 'fal-ai/gemini-25-flash-image',
name: 'Gemini 2.5 Flash Image',
category: 'Advanced',
costPerImage: 0.03,
description: 'Google Gemini 2.5 Flash for fast image generation',
modelKey: 'gemini-25-flash-image'
},
{
id: 'fal-ai/gemini-25-flash-image/edit',
name: 'Gemini 2.5 Flash Edit',
category: 'Image Editing',
costPerImage: 0.03,
description: 'Google Gemini 2.5 Flash for image editing',
isEditModel: true,
modelKey: 'gemini-25-flash-edit'
},
{
id: 'fal-ai/gemini-flash-edit',
name: 'Gemini Flash Edit',
category: 'Image Editing',
costPerImage: 0.04,
description: 'Edit images using Google Gemini with natural language',
isEditModel: true,
modelKey: 'gemini-flash-edit'
},
{
id: 'fal-ai/flux-pro/kontext',
name: 'FLUX Pro Kontext Edit',
category: 'Image Editing',
costPerImage: 0.05,
description: 'FLUX Pro model for image-to-image transformation',
isEditModel: true,
modelKey: 'flux-pro-kontext-edit'
},
{
id: 'fal-ai/nano-banana',
name: 'Nano Banana',
category: 'Advanced',
costPerImage: 0.04,
description: "Google's state-of-the-art image generation model",
modelKey: 'nano-banana'
},
{
id: 'fal-ai/nano-banana/edit',
name: 'Nano Banana Edit',
category: 'Image Editing',
costPerImage: 0.04,
description: "Google's state-of-the-art image editing model",
isEditModel: true,
modelKey: 'nano-banana-edit'
},
{
id: 'fal-ai/ideogram/character/edit',
name: 'Ideogram Character Edit',
category: 'Image Editing',
costPerImage: 0.05,
description: 'Modify consistent characters while preserving core identity',
isEditModel: true,
modelKey: 'ideogram-character-edit'
},
{
id: 'fal-ai/qwen-image-edit-plus',
name: 'Qwen Image Edit Plus',
category: 'Image Editing',
costPerImage: 0.04,
description: 'Advanced image editing with Qwen model',
isEditModel: true,
modelKey: 'qwen-image-edit-plus'
}
];
async function fetchModelSchema(modelId) {
const url = `https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=${modelId}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Failed to fetch schema for ${modelId}:`, error.message);
return null;
}
}
function extractParametersFromSchema(openApiSchema, modelInfo) {
// Default structure
const config = {
id: modelInfo.id,
name: modelInfo.name,
description: modelInfo.description,
category: modelInfo.category,
costPerImage: modelInfo.costPerImage,
type: modelInfo.isEditModel ? 'image-edit' : 'text-to-image',
defaultParams: {},
supportedAspectRatios: [],
supportedFormats: ['jpeg', 'png'],
maxImages: 4,
parameters: {}
};
try {
// Look for main endpoint path
const paths = openApiSchema.paths || {};
const mainPath = `/fal-ai/${modelInfo.id.replace('fal-ai/', '')}`;
let inputSchema = null;
// Try to find the input schema
if (paths[mainPath]?.post?.requestBody?.content?.['application/json']?.schema) {
const schema = paths[mainPath].post.requestBody.content['application/json'].schema;
// Handle $ref to components
if (schema.$ref) {
const refName = schema.$ref.split('/').pop();
if (openApiSchema.components?.schemas?.[refName]) {
inputSchema = openApiSchema.components.schemas[refName];
}
} else {
inputSchema = schema;
}
}
// Fallback: look for input schema in components
if (!inputSchema && openApiSchema.components?.schemas) {
const inputSchemaName = Object.keys(openApiSchema.components.schemas).find(name =>
name.toLowerCase().includes('input') || name.toLowerCase().includes('request')
);
if (inputSchemaName) {
inputSchema = openApiSchema.components.schemas[inputSchemaName];
}
}
// Parse the schema if found
if (inputSchema) {
const properties = inputSchema.properties || {};
const required = inputSchema.required || [];
// Extract parameters
for (const [key, value] of Object.entries(properties)) {
config.parameters[key] = {
type: value.type,
required: required.includes(key),
description: value.description || '',
default: value.default,
enum: value.enum,
minimum: value.minimum,
maximum: value.maximum
};
// Set defaults
if (value.default !== undefined) {
config.defaultParams[key] = value.default;
}
// Extract enums for aspect ratios
if (key === 'aspect_ratio' && value.enum) {
config.supportedAspectRatios = value.enum;
}
// Extract supported formats
if (key === 'output_format' && value.enum) {
config.supportedFormats = value.enum;
}
// Extract max images
if (key === 'num_images' && value.maximum) {
config.maxImages = value.maximum;
}
}
}
// For edit models, ensure we have image_url parameter
if (modelInfo.isEditModel) {
config.parameters.image_url = {
type: 'string',
required: true,
description: 'URL of the image to edit'
};
config.parameters.prompt = {
type: 'string',
required: true,
description: 'Description of the edit to make'
};
}
// Set reasonable defaults if not found
if (!config.defaultParams.num_images) {
config.defaultParams.num_images = 1;
}
if (config.supportedAspectRatios.length === 0) {
config.supportedAspectRatios = ['1:1', '16:9', '9:16', '4:3', '3:4'];
}
} catch (error) {
console.warn(`Warning: Could not fully parse schema for ${modelInfo.id}:`, error.message);
}
return config;
}
async function generateModelConfigs() {
console.log('🔍 Fetching model schemas from FAL OpenAPI...\n');
const modelsDir = path.join(__dirname, 'models');
await fs.ensureDir(modelsDir);
let successCount = 0;
let failCount = 0;
for (const modelInfo of MODELS_TO_FETCH) {
console.log(`📥 Fetching schema for ${modelInfo.name}...`);
const schema = await fetchModelSchema(modelInfo.id);
if (schema) {
const config = extractParametersFromSchema(schema, modelInfo);
// Generate filename from model ID (or use custom key)
const filename = (modelInfo.modelKey || modelInfo.id
.replace('fal-ai/', '')
.replace(/\//g, '-')
.replace(/[^a-z0-9-]/gi, '-')
.toLowerCase()) + '.json';
const filepath = path.join(modelsDir, filename);
// Add optimization prompt based on model type
if (modelInfo.isEditModel) {
config.optimization_system_prompt = `You are optimizing edit instructions for ${modelInfo.name}. This model excels at precise image modifications while preserving the original image's structure and quality. Focus on: 1) Clear, specific edit instructions that describe exactly what to change. 2) Preserve elements that should remain unchanged by explicitly mentioning what to keep. 3) Use directional and positional language for spatial edits. 4) For style changes, describe the target style in detail. Example: 'change color to red' → 'Change the car's color from blue to bright cherry red while preserving all reflections, shadows, and environmental lighting'`;
} else {
config.optimization_system_prompt = `You are optimizing prompts for ${modelInfo.name}. Focus on detailed visual descriptions, artistic style, composition, and technical aspects that enhance image quality. Be specific about lighting, colors, textures, and spatial relationships.`;
}
await fs.writeJson(filepath, config, { spaces: 2 });
console.log(`✅ Created ${filename}`);
successCount++;
} else {
console.log(`❌ Failed to fetch schema for ${modelInfo.id}`);
// Create basic config anyway
const filename = (modelInfo.modelKey || modelInfo.id
.replace('fal-ai/', '')
.replace(/\//g, '-')
.replace(/[^a-z0-9-]/gi, '-')
.toLowerCase()) + '.json';
const basicConfig = {
id: modelInfo.id,
name: modelInfo.name,
description: modelInfo.description,
category: modelInfo.category,
costPerImage: modelInfo.costPerImage,
type: modelInfo.isEditModel ? 'image-edit' : 'text-to-image',
defaultParams: {
num_images: 1
},
supportedAspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4'],
supportedFormats: ['jpeg', 'png'],
maxImages: modelInfo.isEditModel ? 1 : 4,
parameters: modelInfo.isEditModel ? {
prompt: { type: 'string', required: true },
image_url: { type: 'string', required: true }
} : {
prompt: { type: 'string', required: true },
num_images: { type: 'integer', required: false }
}
};
const filepath = path.join(modelsDir, filename);
await fs.writeJson(filepath, basicConfig, { spaces: 2 });
console.log(`⚠️ Created basic config for ${filename} (schema fetch failed)`);
failCount++;
}
}
console.log(`\n✨ Done! Created ${successCount} configs from schemas, ${failCount} basic configs`);
console.log(`📁 Model configs saved to: ${modelsDir}`);
}
// Run if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
generateModelConfigs().catch(console.error);
}
export { fetchModelSchema, extractParametersFromSchema, generateModelConfigs };