cheapgen 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -111
- package/data/frame-sizes.json +52 -0
- package/data/models.json +397 -28
- package/data/prices.json +526 -42
- package/package.json +4 -3
- package/skills/cheapgen/SKILL.md +43 -6
- package/src/catalog.js +28 -0
- package/src/cli/commands/config.js +9 -6
- package/src/cli/commands/index.js +24 -5
- package/src/cli/commands/info.js +11 -3
- package/src/cli/commands/mcp.js +21 -0
- package/src/cli/commands/quote.js +18 -5
- package/src/cli/commands/run.js +46 -7
- package/src/cli/commands/shared.js +2 -1
- package/src/cli/commands/skill.js +141 -0
- package/src/cli/main.js +11 -4
- package/src/config.js +32 -6
- package/src/http.js +1 -1
- package/src/mcp/errors.js +8 -0
- package/src/mcp/server.js +144 -0
- package/src/mcp/stdio.js +41 -0
- package/src/mcp/tools.js +383 -0
- package/src/media.js +231 -0
- package/src/pricing/check.js +14 -8
- package/src/pricing/formulas.js +26 -0
- package/src/pricing/index.js +5 -2
- package/src/providers/common.js +47 -6
- package/src/providers/errors.js +6 -2
- package/src/providers/fal.js +31 -14
- package/src/providers/higgsfield.js +250 -0
- package/src/providers/index.js +55 -5
- package/src/providers/kie.js +48 -14
- package/src/providers/replicate.js +15 -10
- package/src/providers/wavespeed.js +21 -14
- package/src/request.js +276 -23
package/src/providers/kie.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
// Kie adapter. API: https://docs.kie.ai
|
|
2
2
|
//
|
|
3
3
|
// Endpoint paths and field names follow Kie's docs.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
4
6
|
import { http, describeBody } from '../http.js';
|
|
5
7
|
import { SubmitRejected, SubmitUnknown } from './errors.js';
|
|
6
|
-
import { postJob, getJson, readError, fileBlob, asRejection, videoFields, imageFields } from './common.js';
|
|
8
|
+
import { postJob, getJson, readError, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, modelId } from './common.js';
|
|
7
9
|
import { loadKiePriceList, kieUnitPrice, USD_PER_CREDIT } from './kie-price-list.js';
|
|
8
10
|
import { cost } from '../pricing/formulas.js';
|
|
9
|
-
import { pricedRequest } from '../request.js';
|
|
11
|
+
import { pricedRequest, promptFor } from '../request.js';
|
|
10
12
|
|
|
11
13
|
const BASE = 'https://api.kie.ai';
|
|
12
14
|
const UPLOAD_URL = 'https://kieai.redpandaai.co/api/file-stream-upload';
|
|
@@ -14,6 +16,9 @@ export { USD_PER_CREDIT };
|
|
|
14
16
|
|
|
15
17
|
const auth = (ctx) => ({ Authorization: `Bearer ${ctx.key}` });
|
|
16
18
|
|
|
19
|
+
const VIDEO_INPUTS = { first: 'first_frame_url', last: 'last_frame_url', refImages: 'reference_image_urls',
|
|
20
|
+
refAudio: 'reference_audio_urls' };
|
|
21
|
+
|
|
17
22
|
const STATES = { waiting: 'queued', queuing: 'queued', generating: 'running', success: 'succeeded', fail: 'failed' };
|
|
18
23
|
|
|
19
24
|
/**
|
|
@@ -26,6 +31,15 @@ function chargeOf(state, credits) {
|
|
|
26
31
|
return known ? credits * USD_PER_CREDIT : null;
|
|
27
32
|
}
|
|
28
33
|
|
|
34
|
+
const UPLOAD_EXTENSIONS = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif',
|
|
35
|
+
'audio/wav': 'wav', 'audio/mpeg': 'mp3' };
|
|
36
|
+
|
|
37
|
+
/** The extension for an upload's generated name: from its content type, else the file's own. */
|
|
38
|
+
function uploadExtension(type, filePath) {
|
|
39
|
+
const own = path.extname(filePath).slice(1).toLowerCase();
|
|
40
|
+
return UPLOAD_EXTENSIONS[type] ?? (/^[a-z0-9]{1,8}$/.test(own) ? own : 'bin');
|
|
41
|
+
}
|
|
42
|
+
|
|
29
43
|
/** The address of an uploaded file: Kie answers { code, msg, data: { downloadUrl, ... } }. */
|
|
30
44
|
function uploadedUrl(body) {
|
|
31
45
|
const url = body?.data?.downloadUrl;
|
|
@@ -38,22 +52,35 @@ export default {
|
|
|
38
52
|
envVar: 'KIE_API_KEY',
|
|
39
53
|
billing: { failedJobCharged: false, validationErrorMayCharge: false },
|
|
40
54
|
|
|
41
|
-
buildRequest(r,
|
|
55
|
+
buildRequest(r, inputs) {
|
|
56
|
+
const { entry, imageUrls } = inputs;
|
|
57
|
+
// Kie documents no way to name an input in the prompt; it gets the plain "@Image1" form.
|
|
42
58
|
const input = r.kind === 'image'
|
|
43
|
-
? { prompt: r.prompt, ...imageFields(r, entry, 'resolution') }
|
|
44
|
-
: { prompt: r
|
|
45
|
-
return { method: 'POST', url: `${BASE}/api/v1/jobs/createTask`, body: { model: entry
|
|
59
|
+
? { prompt: r.prompt, ...imageFields(r, entry, 'resolution'), ...editImages(r, entry, imageUrls) }
|
|
60
|
+
: { prompt: promptFor(r, 'plain'), ...videoFields(r, { entry }), ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
|
|
61
|
+
return { method: 'POST', url: `${BASE}/api/v1/jobs/createTask`, body: { model: modelId(r, entry), input } };
|
|
46
62
|
},
|
|
47
63
|
|
|
48
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* Price from Kie's public list, matched on the entry's `live.kieDescription`. An edit has its
|
|
66
|
+
* own rows: `live.kieEditDescription` for the output, and the input fee's `kieDescription`.
|
|
67
|
+
*/
|
|
49
68
|
async livePrice(r, ctx, { bundled, frameSizes }) {
|
|
50
69
|
const entry = bundled?.entry;
|
|
51
|
-
const
|
|
70
|
+
const editing = r.mode === 'image-edit';
|
|
71
|
+
const description = editing ? entry?.live?.kieEditDescription : entry?.live?.kieDescription;
|
|
52
72
|
if (!description) return null;
|
|
53
73
|
const rows = await loadKiePriceList(ctx);
|
|
54
74
|
const unitUsd = rows ? kieUnitPrice(rows, description, entry.pricing.type) : null;
|
|
55
75
|
if (unitUsd === null) return null;
|
|
56
|
-
|
|
76
|
+
const pricing = { ...entry.pricing, usd: unitUsd };
|
|
77
|
+
const fee = entry.pricing.inputFee;
|
|
78
|
+
if (editing && fee?.kieDescription) {
|
|
79
|
+
const feeUsd = kieUnitPrice(rows, fee.kieDescription, 'perImage');
|
|
80
|
+
if (feeUsd === null) return null;
|
|
81
|
+
pricing.inputFee = { ...fee, usdPerImage: feeUsd };
|
|
82
|
+
}
|
|
83
|
+
return { usd: cost(pricing, pricedRequest(r), frameSizes), unit: entry.pricing.type };
|
|
57
84
|
},
|
|
58
85
|
|
|
59
86
|
async balance(ctx) {
|
|
@@ -62,9 +89,16 @@ export default {
|
|
|
62
89
|
return typeof credits === 'number' ? credits * USD_PER_CREDIT : null;
|
|
63
90
|
},
|
|
64
91
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Kie stores an upload under the name it is given, and a second upload with the same name
|
|
94
|
+
* replaces the first (its docs add that the change can lag behind a cache). So every upload
|
|
95
|
+
* gets a name of its own: two files called photo.png never share an address, and the local
|
|
96
|
+
* file name isn't sent.
|
|
97
|
+
*/
|
|
98
|
+
async upload(filePath, ctx, contentType) {
|
|
99
|
+
return asRejection(`${uploadLabel(contentType)} to Kie`, async () => {
|
|
100
|
+
const { blob, type } = fileBlob(filePath, contentType);
|
|
101
|
+
const name = `${randomUUID()}.${uploadExtension(type, filePath)}`;
|
|
68
102
|
const form = new FormData();
|
|
69
103
|
form.append('file', blob, name);
|
|
70
104
|
form.append('uploadPath', 'images');
|
|
@@ -75,8 +109,8 @@ export default {
|
|
|
75
109
|
});
|
|
76
110
|
},
|
|
77
111
|
|
|
78
|
-
async submit(r, ctx,
|
|
79
|
-
const { url, body } = this.buildRequest(r,
|
|
112
|
+
async submit(r, ctx, inputs) {
|
|
113
|
+
const { url, body } = this.buildRequest(r, inputs);
|
|
80
114
|
const res = await postJob(ctx, { url, headers: auth(ctx), json: body });
|
|
81
115
|
const j = res.json;
|
|
82
116
|
if (!j || typeof j.code !== 'number') throw new SubmitUnknown(`unexpected response: ${describeBody(res)}`);
|
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
// Replicate has no balance or price API.
|
|
3
3
|
import { http, describeBody } from '../http.js';
|
|
4
4
|
import { SubmitUnknown } from './errors.js';
|
|
5
|
-
import { postJob, getJson, fileBlob, asRejection, videoFields, imageFields } from './common.js';
|
|
5
|
+
import { postJob, getJson, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, modelId } from './common.js';
|
|
6
|
+
import { promptFor } from '../request.js';
|
|
6
7
|
|
|
7
8
|
const BASE = 'https://api.replicate.com/v1';
|
|
8
9
|
const auth = (ctx) => ({ Authorization: `Bearer ${ctx.key}` });
|
|
9
10
|
|
|
11
|
+
const VIDEO_INPUTS = { first: 'image', last: 'last_frame_image', refImages: 'reference_images', refAudio: 'reference_audios' };
|
|
12
|
+
|
|
10
13
|
const STATES = { starting: 'queued', processing: 'running', succeeded: 'succeeded', failed: 'failed', canceled: 'cancelled' };
|
|
11
14
|
|
|
12
15
|
export default {
|
|
@@ -17,20 +20,22 @@ export default {
|
|
|
17
20
|
// (a cancelled one may be billed), so `spend` counts it as $0.
|
|
18
21
|
billing: { failedJobCharged: false, validationErrorMayCharge: false, failedJobFree: true },
|
|
19
22
|
|
|
20
|
-
buildRequest(r,
|
|
23
|
+
buildRequest(r, inputs) {
|
|
24
|
+
const { entry, imageUrls } = inputs;
|
|
25
|
+
// Replicate names inputs in the prompt as [Image1], [Audio1].
|
|
21
26
|
const input = r.kind === 'image'
|
|
22
|
-
? { prompt: r.prompt, ...imageFields(r, entry, 'size') }
|
|
23
|
-
: { prompt: r
|
|
24
|
-
return { method: 'POST', url: `${BASE}/models/${entry
|
|
27
|
+
? { prompt: r.prompt, ...imageFields(r, entry, 'size'), ...editImages(r, entry, imageUrls) }
|
|
28
|
+
: { prompt: promptFor(r, 'bracket'), ...videoFields(r, { entry }), ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
|
|
29
|
+
return { method: 'POST', url: `${BASE}/models/${modelId(r, entry)}/predictions`, body: { input } };
|
|
25
30
|
},
|
|
26
31
|
|
|
27
32
|
async balance() {
|
|
28
33
|
return null;
|
|
29
34
|
},
|
|
30
35
|
|
|
31
|
-
async upload(filePath, ctx) {
|
|
32
|
-
return asRejection(
|
|
33
|
-
const { blob, name, type } = fileBlob(filePath);
|
|
36
|
+
async upload(filePath, ctx, contentType) {
|
|
37
|
+
return asRejection(`${uploadLabel(contentType)} to Replicate`, async () => {
|
|
38
|
+
const { blob, name, type } = fileBlob(filePath, contentType);
|
|
34
39
|
const form = new FormData();
|
|
35
40
|
form.append('content', blob, name);
|
|
36
41
|
form.append('filename', name);
|
|
@@ -41,8 +46,8 @@ export default {
|
|
|
41
46
|
});
|
|
42
47
|
},
|
|
43
48
|
|
|
44
|
-
async submit(r, ctx,
|
|
45
|
-
const { url, body } = this.buildRequest(r,
|
|
49
|
+
async submit(r, ctx, inputs) {
|
|
50
|
+
const { url, body } = this.buildRequest(r, inputs);
|
|
46
51
|
const res = await postJob(ctx, { url, headers: auth(ctx), json: body });
|
|
47
52
|
if (!res.json?.id) throw new SubmitUnknown(`no prediction id in the response: ${describeBody(res)}`);
|
|
48
53
|
return { nativeId: String(res.json.id) };
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// WaveSpeed refunds jobs that fail on its side, and has balance and price APIs.
|
|
3
3
|
import { http, describeBody } from '../http.js';
|
|
4
4
|
import { SubmitRejected, SubmitUnknown } from './errors.js';
|
|
5
|
-
import { postJob, getJson, fileBlob, asRejection, videoFields, imageFields, endpointPath } from './common.js';
|
|
6
|
-
import { pricedRequest } from '../request.js';
|
|
5
|
+
import { postJob, getJson, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, endpointPath } from './common.js';
|
|
6
|
+
import { pricedRequest, promptFor } from '../request.js';
|
|
7
7
|
|
|
8
8
|
const BASE = 'https://api.wavespeed.ai/api/v3';
|
|
9
9
|
const auth = (ctx) => ({ Authorization: `Bearer ${ctx.key}` });
|
|
@@ -13,10 +13,13 @@ const STATES = { created: 'queued', pending: 'queued', processing: 'running', co
|
|
|
13
13
|
|
|
14
14
|
const modelPath = endpointPath;
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
const VIDEO_INPUTS = { first: 'image', last: 'last_image', refImages: 'reference_images', refAudio: 'reference_audios' };
|
|
17
|
+
|
|
18
|
+
/** WaveSpeed names inputs in the prompt as "@Image 1", "@Audio 1". */
|
|
19
|
+
function body(r, entry, inputs = {}) {
|
|
17
20
|
return r.kind === 'image'
|
|
18
|
-
? { prompt: r.prompt, ...imageFields(r, entry, 'size') }
|
|
19
|
-
: { prompt: r
|
|
21
|
+
? { prompt: r.prompt, ...imageFields(r, entry, 'size'), ...editImages(r, entry, inputs.imageUrls) }
|
|
22
|
+
: { prompt: promptFor(r, 'spaced'), ...videoFields(r, { entry }), ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
|
|
20
23
|
}
|
|
21
24
|
|
|
22
25
|
export default {
|
|
@@ -25,14 +28,18 @@ export default {
|
|
|
25
28
|
envVar: 'WAVESPEED_API_KEY',
|
|
26
29
|
billing: { failedJobCharged: false, validationErrorMayCharge: false },
|
|
27
30
|
|
|
28
|
-
buildRequest(r,
|
|
29
|
-
return { method: 'POST', url: `${BASE}/${modelPath(r, entry)}`, body: body(r, entry,
|
|
31
|
+
buildRequest(r, inputs) {
|
|
32
|
+
return { method: 'POST', url: `${BASE}/${modelPath(r, inputs.entry)}`, body: body(r, inputs.entry, inputs) };
|
|
30
33
|
},
|
|
31
34
|
|
|
32
35
|
async livePrice(r, ctx, { entry }) {
|
|
33
|
-
|
|
36
|
+
// The price API prices the request as it will be sent. Files that aren't uploaded yet stand
|
|
37
|
+
// in as placeholder addresses: the price depends on how many inputs there are, not on which.
|
|
38
|
+
// A video's frames, reference images and audio are left out: they don't change the price,
|
|
39
|
+
// and the price API fails on media it can't fetch.
|
|
40
|
+
const stand = r.images?.map((img, i) => (img.isLocal ? `https://example.com/input-${i + 1}.png` : img.source));
|
|
34
41
|
const res = await http(ctx, { method: 'POST', url: `${BASE}/model/price`, headers: auth(ctx), timeoutMs: 10_000,
|
|
35
|
-
json: { model_id: modelPath(
|
|
42
|
+
json: { model_id: modelPath(r, entry), input: body(r.autoDuration ? pricedRequest(r) : r, entry, { imageUrls: stand }) } });
|
|
36
43
|
const data = res.ok && res.json?.code === 200 ? res.json.data : null;
|
|
37
44
|
// discounted_price is what the account pays; price is the list price.
|
|
38
45
|
const price = typeof data?.discounted_price === 'number' ? data.discounted_price : data?.price;
|
|
@@ -45,9 +52,9 @@ export default {
|
|
|
45
52
|
return typeof balance === 'number' ? balance : null;
|
|
46
53
|
},
|
|
47
54
|
|
|
48
|
-
async upload(filePath, ctx) {
|
|
49
|
-
return asRejection(
|
|
50
|
-
const { blob, name } = fileBlob(filePath);
|
|
55
|
+
async upload(filePath, ctx, contentType) {
|
|
56
|
+
return asRejection(`${uploadLabel(contentType)} to WaveSpeed`, async () => {
|
|
57
|
+
const { blob, name } = fileBlob(filePath, contentType);
|
|
51
58
|
const form = new FormData();
|
|
52
59
|
form.append('file', blob, name);
|
|
53
60
|
const res = await http(ctx, { method: 'POST', url: `${BASE}/media/upload/binary`, headers: auth(ctx), body: form, timeoutMs: 300_000 });
|
|
@@ -56,8 +63,8 @@ export default {
|
|
|
56
63
|
});
|
|
57
64
|
},
|
|
58
65
|
|
|
59
|
-
async submit(r, ctx,
|
|
60
|
-
const { url, body: json } = this.buildRequest(r,
|
|
66
|
+
async submit(r, ctx, inputs) {
|
|
67
|
+
const { url, body: json } = this.buildRequest(r, inputs);
|
|
61
68
|
// Insufficient credits is code 1407, with HTTP 400 (rejected by postJob) or inside a 200 envelope.
|
|
62
69
|
const res = await postJob(ctx, { url, headers: auth(ctx), json });
|
|
63
70
|
const j = res.json;
|
package/src/request.js
CHANGED
|
@@ -5,16 +5,25 @@ import fs from 'node:fs';
|
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { usageError } from './errors.js';
|
|
7
7
|
import { frameSize } from './pricing/formulas.js';
|
|
8
|
+
import { probeImage, probeAudio, nearestRatio } from './media.js';
|
|
9
|
+
import { variantFor } from './catalog.js';
|
|
8
10
|
|
|
9
11
|
/**
|
|
10
12
|
* @typedef {object} CanonicalRequest
|
|
11
13
|
* @property {string} model
|
|
12
14
|
* @property {'video'|'image'} kind
|
|
13
15
|
* @property {string} [frameSeries]
|
|
14
|
-
* @property {'text-to-video'|'image-to-video'|'text-to-image'} mode
|
|
16
|
+
* @property {'text-to-video'|'image-to-video'|'reference-to-video'|'text-to-image'|'image-edit'} mode
|
|
15
17
|
* @property {string} [prompt]
|
|
16
18
|
* @property {string} [image] URL, or absolute local path when imageIsLocal
|
|
17
19
|
* @property {boolean} [imageIsLocal]
|
|
20
|
+
* @property {InputImage} [lastImage] image-to-video: the last frame
|
|
21
|
+
* @property {InputImage[]} [refImages] reference-to-video: the reference images, in the order given
|
|
22
|
+
* @property {InputAudio[]} [refAudio] reference-to-video: the reference audio files, in the order given
|
|
23
|
+
* @property {InputImage[]} [images] image-edit: the input images, in the order given
|
|
24
|
+
* @property {number|null} [inputPixels] image-edit: total pixels of the inputs; null when any is a URL
|
|
25
|
+
* @property {string|null} [effectiveAspect] image-edit with aspect "auto": the model's ratio closest to
|
|
26
|
+
* the first input; null when that input is a URL
|
|
18
27
|
* @property {string} [resolution] video
|
|
19
28
|
* @property {string} [size] image
|
|
20
29
|
* @property {string} aspectRatio
|
|
@@ -25,6 +34,37 @@ import { frameSize } from './pricing/formulas.js';
|
|
|
25
34
|
* @property {number} count
|
|
26
35
|
*/
|
|
27
36
|
|
|
37
|
+
/**
|
|
38
|
+
* @typedef {object} InputImage
|
|
39
|
+
* @property {string} source URL, or absolute local path when isLocal
|
|
40
|
+
* @property {boolean} isLocal
|
|
41
|
+
* @property {'png'|'jpeg'|'webp'} [type] local files only, read from the file's bytes
|
|
42
|
+
* @property {number} [bytes]
|
|
43
|
+
* @property {number} [width]
|
|
44
|
+
* @property {number} [height]
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @typedef {object} InputAudio
|
|
49
|
+
* @property {string} source URL, or absolute local path when isLocal
|
|
50
|
+
* @property {boolean} isLocal
|
|
51
|
+
* @property {'wav'|'mp3'} [type] local files only, read from the file's bytes
|
|
52
|
+
* @property {number} [bytes]
|
|
53
|
+
* @property {number|null} [seconds] null when the file doesn't state its length
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/** No provider takes a larger input image. */
|
|
57
|
+
export const MAX_INPUT_IMAGE_BYTES = 30_000_000;
|
|
58
|
+
/** What the video models accept as a first frame, last frame or reference image. */
|
|
59
|
+
const FRAME_SIDE = Object.freeze({ min: 300, max: 6000 });
|
|
60
|
+
const FRAME_RATIO = Object.freeze({ min: 0.4, max: 2.5 });
|
|
61
|
+
const MAX_AUDIO_BYTES = 15_000_000;
|
|
62
|
+
const MIN_AUDIO_SECONDS = 2;
|
|
63
|
+
/** Encoders pad a clip by a few hundredths of a second; providers allow about this much. */
|
|
64
|
+
const AUDIO_SLACK_SECONDS = 0.2;
|
|
65
|
+
const REFERENCE_MODE = 'reference-to-video';
|
|
66
|
+
export const AUTO_ASPECT = 'auto';
|
|
67
|
+
|
|
28
68
|
export const DEFAULTS = Object.freeze({ resolution: '720p', duration: 5, aspectRatio: '16:9', audio: true, size: '1K' });
|
|
29
69
|
|
|
30
70
|
const isUrl = (s) => /^https?:\/\//i.test(s);
|
|
@@ -33,10 +73,11 @@ const isUrl = (s) => /^https?:\/\//i.test(s);
|
|
|
33
73
|
* @param {string} modelId
|
|
34
74
|
* @param {object} flags parsed command-line values
|
|
35
75
|
* @param {object} catalog
|
|
36
|
-
* @param {{ cwd: string, requirePrompt: boolean }} opts
|
|
76
|
+
* @param {{ cwd: string, requirePrompt: boolean, allowVariants?: boolean }} opts `allowVariants`
|
|
77
|
+
* accepts a resolution that only a provider's variant of the model sells
|
|
37
78
|
* @returns {CanonicalRequest}
|
|
38
79
|
*/
|
|
39
|
-
export function buildCanonicalRequest(modelId, flags, catalog, { cwd, requirePrompt }) {
|
|
80
|
+
export function buildCanonicalRequest(modelId, flags, catalog, { cwd, requirePrompt, allowVariants = false }) {
|
|
40
81
|
if (!modelId) throw usageError('name a model, for example: cheapgen quote seedance-2.0-mini');
|
|
41
82
|
const model = catalog.models[modelId];
|
|
42
83
|
if (!model) {
|
|
@@ -48,24 +89,45 @@ export function buildCanonicalRequest(modelId, flags, catalog, { cwd, requirePro
|
|
|
48
89
|
throw usageError('--prompt is required');
|
|
49
90
|
}
|
|
50
91
|
|
|
92
|
+
// --image is repeatable on the command line; other callers may pass one value.
|
|
93
|
+
const given = flags.image === undefined ? [] : [flags.image].flat();
|
|
94
|
+
const editing = model.kind === 'image' && given.length > 0;
|
|
95
|
+
if (model.kind !== 'image' && given.length > 1) {
|
|
96
|
+
throw usageError(`${modelId} takes one --image (the first frame), got ${given.length}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const lastGiven = [flags['last-image'] ?? []].flat();
|
|
100
|
+
const refImagesGiven = [flags['ref-image'] ?? []].flat();
|
|
101
|
+
const refAudioGiven = [flags['ref-audio'] ?? []].flat();
|
|
102
|
+
if (model.kind === 'image') {
|
|
103
|
+
const flag = lastGiven.length ? '--last-image' : refImagesGiven.length ? '--ref-image' : refAudioGiven.length ? '--ref-audio' : null;
|
|
104
|
+
if (flag) throw usageError(`${flag} applies to video models; ${modelId} is an image model`);
|
|
105
|
+
}
|
|
106
|
+
|
|
51
107
|
let image;
|
|
52
108
|
let imageIsLocal = false;
|
|
53
|
-
if (
|
|
54
|
-
if (isUrl(
|
|
109
|
+
if (model.kind !== 'image' && given.length === 1) {
|
|
110
|
+
if (isUrl(given[0])) image = given[0];
|
|
55
111
|
else {
|
|
56
|
-
image = path.resolve(cwd,
|
|
57
|
-
if (!fs.existsSync(image)) throw usageError(`--image file not found: ${
|
|
112
|
+
image = path.resolve(cwd, given[0]);
|
|
113
|
+
if (!fs.existsSync(image)) throw usageError(`--image file not found: ${given[0]}`);
|
|
58
114
|
imageIsLocal = true;
|
|
115
|
+
// A first frame cheapgen can read is checked against the model's limits; other files pass as they are.
|
|
116
|
+
const info = readImage(image);
|
|
117
|
+
if (info) checkFrame(info, given[0], '--image');
|
|
59
118
|
}
|
|
60
119
|
}
|
|
61
120
|
|
|
62
|
-
const aspectRatio = flags.aspect ?? DEFAULTS.aspectRatio;
|
|
63
|
-
if (!
|
|
121
|
+
const aspectRatio = flags.aspect ?? (editing ? AUTO_ASPECT : DEFAULTS.aspectRatio);
|
|
122
|
+
if (aspectRatio === AUTO_ASPECT && !editing) {
|
|
123
|
+
throw usageError('--aspect auto follows an input image, so it needs --image on an image model. '
|
|
124
|
+
+ `Choose one of: ${model.aspectRatios.join(', ')}`);
|
|
125
|
+
}
|
|
126
|
+
if (aspectRatio !== AUTO_ASPECT && !model.aspectRatios.includes(aspectRatio)) {
|
|
64
127
|
throw usageError(`${modelId} doesn't support aspect ratio ${aspectRatio}. Choose one of: ${model.aspectRatios.join(', ')}`);
|
|
65
128
|
}
|
|
66
129
|
|
|
67
130
|
if (model.kind === 'image') {
|
|
68
|
-
if (image) throw usageError(`${modelId} is a text-to-image model; --image isn't supported yet`);
|
|
69
131
|
for (const f of ['res', 'duration', 'audio', 'no-audio']) {
|
|
70
132
|
if (flags[f] !== undefined) throw usageError(`--${f} doesn't apply to image models`);
|
|
71
133
|
}
|
|
@@ -74,16 +136,37 @@ export function buildCanonicalRequest(modelId, flags, catalog, { cwd, requirePro
|
|
|
74
136
|
throw usageError(`${modelId} doesn't support size ${size}. Choose one of: ${model.sizes.join(', ')}`);
|
|
75
137
|
}
|
|
76
138
|
const frameSeries = model.frameSeries ?? modelId;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
139
|
+
if (!editing) {
|
|
140
|
+
// Pixels for providers that take explicit sizes; null when the model has no table.
|
|
141
|
+
const pixels = frameSize({ frameSeries, size, aspectRatio }, catalog.frameSizes);
|
|
142
|
+
return withMode(model, { model: modelId, kind: 'image', frameSeries,
|
|
143
|
+
mode: 'text-to-image', prompt, size, aspectRatio, pixels, count: 1 });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (!model.modes.includes('image-edit')) {
|
|
147
|
+
throw usageError(`${modelId} is a text-to-image model; it doesn't take input images`);
|
|
148
|
+
}
|
|
149
|
+
const max = model.edit?.maxImages;
|
|
150
|
+
if (max && given.length > max) {
|
|
151
|
+
throw usageError(`${modelId} takes at most ${max} input images, got ${given.length}`);
|
|
152
|
+
}
|
|
153
|
+
const images = given.map((src) => inputImage(src, cwd));
|
|
154
|
+
const first = images[0];
|
|
155
|
+
const effectiveAspect = aspectRatio !== AUTO_ASPECT ? null
|
|
156
|
+
: first.isLocal ? nearestRatio(first.width, first.height, model.aspectRatios) : null;
|
|
157
|
+
const sizedBy = aspectRatio === AUTO_ASPECT ? effectiveAspect : aspectRatio;
|
|
158
|
+
const pixels = sizedBy ? frameSize({ frameSeries, size, aspectRatio: sizedBy }, catalog.frameSizes) : null;
|
|
159
|
+
const inputPixels = images.every((i) => i.isLocal) ? images.reduce((sum, i) => sum + i.width * i.height, 0) : null;
|
|
160
|
+
return withMode(model, { model: modelId, kind: 'image', frameSeries, mode: 'image-edit', prompt, size, aspectRatio,
|
|
161
|
+
effectiveAspect, pixels, images: Object.freeze(images), inputPixels, count: 1 });
|
|
81
162
|
}
|
|
82
163
|
|
|
83
164
|
if (flags.size !== undefined) throw usageError('--size applies to image models; use --res for video');
|
|
84
165
|
const resolution = flags.res ?? DEFAULTS.resolution;
|
|
85
|
-
|
|
86
|
-
|
|
166
|
+
const variant = variantFor(model, resolution);
|
|
167
|
+
if (!model.resolutions.includes(resolution) && !(variant && allowVariants)) {
|
|
168
|
+
throw usageError(`${modelId} doesn't support ${resolution}. Choose one of: ${model.resolutions.join(', ')}`
|
|
169
|
+
+ (variant ? `. ${variant.note} To allow that, run: cheapgen config set allowVariants true` : ''));
|
|
87
170
|
}
|
|
88
171
|
|
|
89
172
|
let duration = DEFAULTS.duration;
|
|
@@ -110,13 +193,159 @@ export function buildCanonicalRequest(modelId, flags, catalog, { cwd, requirePro
|
|
|
110
193
|
if (flags.audio && flags['no-audio']) throw usageError('pass either --audio or --no-audio, not both');
|
|
111
194
|
const audio = flags['no-audio'] ? false : DEFAULTS.audio;
|
|
112
195
|
|
|
196
|
+
// The model takes a first frame, a first and last frame, or references: never a mix.
|
|
197
|
+
const referencing = refImagesGiven.length + refAudioGiven.length > 0;
|
|
198
|
+
if (lastGiven.length > 1) throw usageError(`${modelId} takes one --last-image, got ${lastGiven.length}`);
|
|
199
|
+
if (referencing && (given.length || lastGiven.length)) {
|
|
200
|
+
throw usageError('--ref-image and --ref-audio can\'t be combined with --image or --last-image: the model takes a first '
|
|
201
|
+
+ 'frame, a first and last frame, or references, not a mix');
|
|
202
|
+
}
|
|
203
|
+
if (lastGiven.length && !given.length) throw usageError('--last-image needs --image (the first frame)');
|
|
204
|
+
const lastImage = lastGiven.length ? frameImage(lastGiven[0], cwd, '--last-image') : undefined;
|
|
205
|
+
const references = referencing ? referenceInputs(modelId, model, refImagesGiven, refAudioGiven, prompt, cwd) : {};
|
|
206
|
+
|
|
113
207
|
return withMode(model, {
|
|
114
208
|
model: modelId, kind: 'video', frameSeries: model.frameSeries ?? modelId,
|
|
115
|
-
mode: image ? 'image-to-video' : 'text-to-video',
|
|
209
|
+
mode: referencing ? REFERENCE_MODE : image ? 'image-to-video' : 'text-to-video',
|
|
116
210
|
prompt, image, imageIsLocal, resolution, aspectRatio, duration, autoDuration, maxDuration: max, audio, count: 1,
|
|
211
|
+
...(lastImage ? { lastImage } : {}),
|
|
212
|
+
...references,
|
|
213
|
+
...(variant ? { variant: Object.freeze({ id: variant.id, provider: variant.provider, label: variant.label, note: variant.note }) } : {}),
|
|
117
214
|
});
|
|
118
215
|
}
|
|
119
216
|
|
|
217
|
+
/** The reference images and audio of a reference-to-video request, checked against the model's limits. */
|
|
218
|
+
function referenceInputs(modelId, model, imagesGiven, audioGiven, prompt, cwd) {
|
|
219
|
+
const limits = model.references;
|
|
220
|
+
if (!limits || !model.modes.includes(REFERENCE_MODE)) throw usageError(`${modelId} doesn't take reference images or audio`);
|
|
221
|
+
if (imagesGiven.length > limits.maxImages) {
|
|
222
|
+
throw usageError(`${modelId} takes at most ${limits.maxImages} reference images, got ${imagesGiven.length}`);
|
|
223
|
+
}
|
|
224
|
+
if (audioGiven.length > limits.maxAudio) {
|
|
225
|
+
throw usageError(`${modelId} takes at most ${limits.maxAudio} reference audio files, got ${audioGiven.length}`);
|
|
226
|
+
}
|
|
227
|
+
if (!imagesGiven.length && !limits.audioAlone) {
|
|
228
|
+
throw usageError(`${modelId} can't use reference audio alone: add at least one reference image (--ref-image)`);
|
|
229
|
+
}
|
|
230
|
+
const refImages = imagesGiven.map((src) => frameImage(src, cwd, '--ref-image'));
|
|
231
|
+
const maxSeconds = limits.maxAudioSeconds;
|
|
232
|
+
const refAudio = audioGiven.map((src) => inputAudio(src, cwd, modelId, maxSeconds));
|
|
233
|
+
const total = refAudio.reduce((sum, a) => sum + (a.seconds ?? 0), 0);
|
|
234
|
+
if (maxSeconds && total > maxSeconds + AUDIO_SLACK_SECONDS) {
|
|
235
|
+
throw usageError(`the --ref-audio files add up to ${total.toFixed(1)} seconds. ${modelId} takes at most ${maxSeconds} `
|
|
236
|
+
+ 'seconds of reference audio in total.');
|
|
237
|
+
}
|
|
238
|
+
for (const name of promptNames(prompt)) {
|
|
239
|
+
const have = name.kind === 'image' ? refImages.length : refAudio.length;
|
|
240
|
+
if (name.number < 1 || name.number > have) {
|
|
241
|
+
const what = name.kind === 'image' ? 'reference image' : 'reference audio file';
|
|
242
|
+
throw usageError(`the prompt names @${name.kind}${name.number}, but ${have === 0 ? `no ${what} was` : `only ${have} ${what}${have === 1 ? ' was' : 's were'}`} given`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return { refImages: Object.freeze(refImages), refAudio: Object.freeze(refAudio) };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// An input named in the prompt: "@image1", "@Image 1" or "[Image1]" (the spellings fal,
|
|
249
|
+
// WaveSpeed and Replicate document), and the same for audio.
|
|
250
|
+
const PROMPT_NAME = /(?<![\w@])@(image|audio) ?(\d+)(?!\w)|\[(image|audio) ?(\d+)\]/gi;
|
|
251
|
+
const PROMPT_NAME_STYLES = Object.freeze({
|
|
252
|
+
plain: (kind, n) => `@${kind}${n}`,
|
|
253
|
+
spaced: (kind, n) => `@${kind} ${n}`,
|
|
254
|
+
bracket: (kind, n) => `[${kind}${n}]`,
|
|
255
|
+
});
|
|
256
|
+
const capitalized = (kind) => kind[0].toUpperCase() + kind.slice(1).toLowerCase();
|
|
257
|
+
|
|
258
|
+
/** The inputs a prompt names, as `{ kind: 'image'|'audio', number }`. */
|
|
259
|
+
export function promptNames(prompt) {
|
|
260
|
+
if (typeof prompt !== 'string') return [];
|
|
261
|
+
return [...prompt.matchAll(PROMPT_NAME)].map((m) => ({ kind: (m[1] ?? m[3]).toLowerCase(), number: Number(m[2] ?? m[4]) }));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The prompt with each named input written the way one provider documents it: `plain`
|
|
266
|
+
* ("@Image1"), `spaced` ("@Image 1") or `bracket` ("[Image1]"). Only a reference-to-video
|
|
267
|
+
* request has names; any other prompt is returned as it is.
|
|
268
|
+
*/
|
|
269
|
+
export function promptFor(request, style) {
|
|
270
|
+
if (request.mode !== REFERENCE_MODE || typeof request.prompt !== 'string') return request.prompt;
|
|
271
|
+
const write = PROMPT_NAME_STYLES[style];
|
|
272
|
+
return request.prompt.replace(PROMPT_NAME, (_, k1, n1, k2, n2) => write(capitalized(k1 ?? k2), Number(n1 ?? n2)));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** What a local image file is, or null when it isn't a PNG, JPEG or WebP that can be read. */
|
|
276
|
+
function readImage(file) {
|
|
277
|
+
try { return probeImage(file); } catch { return null; }
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Refuses an image the video models don't accept as a frame or a reference. */
|
|
281
|
+
function checkFrame(info, src, flag) {
|
|
282
|
+
if (info.bytes > MAX_INPUT_IMAGE_BYTES) {
|
|
283
|
+
throw usageError(`${flag} ${src} is ${(info.bytes / 1e6).toFixed(1)} MB. Input images can be at most `
|
|
284
|
+
+ `${MAX_INPUT_IMAGE_BYTES / 1e6} MB.`);
|
|
285
|
+
}
|
|
286
|
+
const size = `${info.width}×${info.height}`;
|
|
287
|
+
if (Math.min(info.width, info.height) < FRAME_SIDE.min || Math.max(info.width, info.height) > FRAME_SIDE.max) {
|
|
288
|
+
throw usageError(`${flag} ${src} is ${size} pixels. Each side must be between ${FRAME_SIDE.min} and ${FRAME_SIDE.max} pixels.`);
|
|
289
|
+
}
|
|
290
|
+
const ratio = info.width / info.height;
|
|
291
|
+
if (ratio < FRAME_RATIO.min || ratio > FRAME_RATIO.max) {
|
|
292
|
+
throw usageError(`${flag} ${src} is ${size} pixels. Its width divided by its height must be between `
|
|
293
|
+
+ `${FRAME_RATIO.min} and ${FRAME_RATIO.max}.`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** A last frame or reference image: a URL is passed through unread; a local file is measured and checked. */
|
|
298
|
+
function frameImage(src, cwd, flag) {
|
|
299
|
+
if (isUrl(src)) return Object.freeze({ source: src, isLocal: false });
|
|
300
|
+
const file = path.resolve(cwd, src);
|
|
301
|
+
if (!fs.existsSync(file)) throw usageError(`${flag} file not found: ${src}`);
|
|
302
|
+
const info = readImage(file);
|
|
303
|
+
if (!info) throw usageError(`${flag} ${src} isn't a PNG, JPEG or WebP image. It must be one of those three.`);
|
|
304
|
+
checkFrame(info, src, flag);
|
|
305
|
+
return Object.freeze({ source: file, isLocal: true, ...info });
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** A reference audio file: a URL is passed through unread; a local file is measured and checked. */
|
|
309
|
+
function inputAudio(src, cwd, modelId, maxSeconds) {
|
|
310
|
+
if (isUrl(src)) return Object.freeze({ source: src, isLocal: false });
|
|
311
|
+
const file = path.resolve(cwd, src);
|
|
312
|
+
if (!fs.existsSync(file)) throw usageError(`--ref-audio file not found: ${src}`);
|
|
313
|
+
let info = null;
|
|
314
|
+
try { info = probeAudio(file); } catch { info = null; }
|
|
315
|
+
if (!info) throw usageError(`--ref-audio ${src} isn't a WAV or MP3 file. Reference audio must be one of those two.`);
|
|
316
|
+
if (info.bytes > MAX_AUDIO_BYTES) {
|
|
317
|
+
throw usageError(`--ref-audio ${src} is ${(info.bytes / 1e6).toFixed(1)} MB. Reference audio can be at most `
|
|
318
|
+
+ `${MAX_AUDIO_BYTES / 1e6} MB.`);
|
|
319
|
+
}
|
|
320
|
+
// An MP3 that doesn't state its length is passed on unchecked.
|
|
321
|
+
if (info.seconds !== null && maxSeconds
|
|
322
|
+
&& (info.seconds < MIN_AUDIO_SECONDS - AUDIO_SLACK_SECONDS || info.seconds > maxSeconds + AUDIO_SLACK_SECONDS)) {
|
|
323
|
+
throw usageError(`--ref-audio ${src} is ${info.seconds.toFixed(1)} seconds long. ${modelId} takes reference audio of `
|
|
324
|
+
+ `${MIN_AUDIO_SECONDS} to ${maxSeconds} seconds.`);
|
|
325
|
+
}
|
|
326
|
+
return Object.freeze({ source: file, isLocal: true, ...info });
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The warning shown when a request is for a provider's variant of the model. */
|
|
330
|
+
export function variantWarning(request) {
|
|
331
|
+
return `${request.resolution} on ${request.model} is a variant: ${request.variant.note}`;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** One input image: a URL is passed through unread; a local file is measured and checked. */
|
|
335
|
+
function inputImage(src, cwd) {
|
|
336
|
+
if (isUrl(src)) return Object.freeze({ source: src, isLocal: false });
|
|
337
|
+
const file = path.resolve(cwd, src);
|
|
338
|
+
if (!fs.existsSync(file)) throw usageError(`--image file not found: ${src}`);
|
|
339
|
+
let info = null;
|
|
340
|
+
try { info = probeImage(file); } catch { info = null; }
|
|
341
|
+
if (!info) throw usageError(`--image ${src} isn't a PNG, JPEG or WebP image. Input images must be one of those three.`);
|
|
342
|
+
if (info.bytes > MAX_INPUT_IMAGE_BYTES) {
|
|
343
|
+
throw usageError(`--image ${src} is ${(info.bytes / 1e6).toFixed(1)} MB. Input images can be at most `
|
|
344
|
+
+ `${MAX_INPUT_IMAGE_BYTES / 1e6} MB.`);
|
|
345
|
+
}
|
|
346
|
+
return Object.freeze({ source: file, isLocal: true, ...info });
|
|
347
|
+
}
|
|
348
|
+
|
|
120
349
|
function withMode(model, request) {
|
|
121
350
|
if (!model.modes.includes(request.mode)) {
|
|
122
351
|
throw usageError(`${request.model} doesn't support ${request.mode}. It supports: ${model.modes.join(', ')}`);
|
|
@@ -124,25 +353,49 @@ function withMode(model, request) {
|
|
|
124
353
|
return Object.freeze(request);
|
|
125
354
|
}
|
|
126
355
|
|
|
127
|
-
/**
|
|
128
|
-
|
|
129
|
-
|
|
356
|
+
/**
|
|
357
|
+
* The request as priced: an auto duration is priced at the model's maximum, and an edit that
|
|
358
|
+
* follows its input image at the ratio worked out from that image.
|
|
359
|
+
*/
|
|
360
|
+
export function pricedRequest(request) {
|
|
361
|
+
if (request.autoDuration) return { ...request, duration: request.maxDuration };
|
|
362
|
+
if (request.aspectRatio === AUTO_ASPECT && request.effectiveAspect) return { ...request, aspectRatio: request.effectiveAspect };
|
|
363
|
+
return request;
|
|
364
|
+
}
|
|
130
365
|
|
|
131
366
|
/** Parameters written to the spend log. Never the prompt. */
|
|
132
367
|
export function logParams(request) {
|
|
133
|
-
if (request.kind === 'image')
|
|
368
|
+
if (request.kind === 'image') {
|
|
369
|
+
return { size: request.size, aspectRatio: request.aspectRatio, count: request.count,
|
|
370
|
+
...(request.images ? { inputImages: request.images.length } : {}) };
|
|
371
|
+
}
|
|
134
372
|
return {
|
|
135
373
|
resolution: request.resolution,
|
|
136
374
|
duration: request.autoDuration ? 'auto' : request.duration,
|
|
137
375
|
aspectRatio: request.aspectRatio,
|
|
138
376
|
audio: request.audio,
|
|
139
377
|
...(request.image ? { image: true } : {}),
|
|
378
|
+
...(request.lastImage ? { lastImage: true } : {}),
|
|
379
|
+
...(request.mode === REFERENCE_MODE ? { refImages: request.refImages.length, refAudio: request.refAudio.length } : {}),
|
|
140
380
|
};
|
|
141
381
|
}
|
|
142
382
|
|
|
383
|
+
/** What a video request was given besides the prompt, e.g. "first + last frame" or "2 images, 1 audio". */
|
|
384
|
+
function describeInputs(r) {
|
|
385
|
+
if (r.lastImage) return ['first + last frame'];
|
|
386
|
+
if (r.mode !== REFERENCE_MODE) return [];
|
|
387
|
+
const images = r.refImages.length;
|
|
388
|
+
const counts = [...(images ? [`${images} image${images === 1 ? '' : 's'}`] : []),
|
|
389
|
+
...(r.refAudio.length ? [`${r.refAudio.length} audio`] : [])];
|
|
390
|
+
return [counts.join(', ')];
|
|
391
|
+
}
|
|
392
|
+
|
|
143
393
|
/** A one-line description, e.g. "seedance-2.0-mini · text-to-video · 480p · 5s · 16:9 · audio on". */
|
|
144
394
|
export function describeRequest(r) {
|
|
145
|
-
if (r.kind === 'image')
|
|
146
|
-
|
|
395
|
+
if (r.kind === 'image') {
|
|
396
|
+
const inputs = r.images ? [`${r.images.length} image${r.images.length === 1 ? '' : 's'}`] : [];
|
|
397
|
+
return [r.model, r.mode, ...inputs, r.size, r.aspectRatio].join(' · ');
|
|
398
|
+
}
|
|
399
|
+
return [r.model, r.mode, ...describeInputs(r), r.resolution, r.autoDuration ? `auto (up to ${r.maxDuration}s)` : `${r.duration}s`,
|
|
147
400
|
r.aspectRatio, r.audio ? 'audio on' : 'audio off'].join(' · ');
|
|
148
401
|
}
|