cheapgen 0.1.2 → 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.
@@ -0,0 +1,250 @@
1
+ // Higgsfield adapter. API: https://docs.higgsfield.ai (the pay-as-you-go API, not the
2
+ // higgsfield.ai website plans). Higgsfield doesn't charge for failed or moderated (nsfw) jobs, and
3
+ // refunds a cancelled queued job. There's no balance API: an empty balance shows up as a 403 when
4
+ // submitting, which is a clear rejection.
5
+ //
6
+ // Submits carry an Idempotency-Key. After a timeout, network error or 5xx the same request is sent
7
+ // again with the same key, and Higgsfield returns the original request instead of creating a
8
+ // second one (https://docs.higgsfield.ai/docs/concepts/idempotency.md).
9
+ import { randomUUID } from 'node:crypto';
10
+ import { http, NetworkError, describeBody } from '../http.js';
11
+ import { SubmitRejected, SubmitUnknown } from './errors.js';
12
+ import { SUBMIT_TIMEOUT_MS, readError, fileBlob, uploadLabel, asRejection, videoFields, videoMedia, imageFields, editImages, endpointPath } from './common.js';
13
+ import { pricedRequest, promptFor } from '../request.js';
14
+
15
+ const BASE = 'https://api.higgsfield.ai';
16
+ /** Hosts that may receive the key. A status URL from a response is used only on one of these. */
17
+ const API_HOSTS = new Set(['api.higgsfield.ai', 'platform.higgsfield.ai']);
18
+ const auth = (ctx) => ({ Authorization: `Key ${ctx.key}` });
19
+
20
+ /** The estimate endpoint needs a prompt; `quote` may not have one, and the price doesn't depend on it. */
21
+ const ESTIMATE_PROMPT = 'price estimate';
22
+ const RETRY_DELAYS_MS = [1_000, 2_000];
23
+ const MAX_RETRY_AFTER_MS = 30_000;
24
+ /** Each attempt can take up to SUBMIT_TIMEOUT_MS; don't start another one after this long. */
25
+ const RETRY_DEADLINE_MS = 240_000;
26
+
27
+ const STATES = { queued: 'queued', in_progress: 'running', completed: 'succeeded', failed: 'failed', nsfw: 'failed',
28
+ canceled: 'cancelled' };
29
+
30
+ const VIDEO_INPUTS = { first: 'image_url', last: 'end_image_url', refImages: 'image_urls', refAudio: 'audio_urls' };
31
+
32
+ /** Higgsfield documents no way to name an input in the prompt; it gets the plain "@Image1" form. */
33
+ function body(r, entry, inputs = {}) {
34
+ const text = r.kind === 'image' ? r.prompt : promptFor(r, 'plain');
35
+ const prompt = typeof text === 'string' && text.trim() ? { prompt: text } : {};
36
+ if (r.kind === 'image') return { ...prompt, ...imageFields(r, entry, 'resolution'), ...editImages(r, entry, inputs.imageUrls) };
37
+ return { ...prompt, ...videoFields(r, { entry }), ...videoMedia(r, entry, VIDEO_INPUTS, inputs) };
38
+ }
39
+
40
+ /**
41
+ * Stand-in addresses for the reference inputs of an estimate: the price doesn't depend on which
42
+ * files they are, local files aren't uploaded yet, and the user's own addresses needn't be sent
43
+ * for a price.
44
+ */
45
+ function estimateInputs(r) {
46
+ if (r.mode !== 'reference-to-video') return {};
47
+ return {
48
+ refImageUrls: r.refImages.map((_, i) => `https://example.com/reference-image-${i + 1}.png`),
49
+ refAudioUrls: r.refAudio.map((_, i) => `https://example.com/reference-audio-${i + 1}.wav`),
50
+ };
51
+ }
52
+
53
+ function isApiUrl(url) {
54
+ try {
55
+ const u = new URL(url);
56
+ return u.protocol === 'https:' && API_HOSTS.has(u.hostname) && u.port === '' && !u.username && !u.password;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ const statusUrlFor = (url, id) => (typeof url === 'string' && isApiUrl(url) ? url
63
+ : `${BASE}/requests/${encodeURIComponent(id)}/status`);
64
+
65
+ const correlationOf = (res) => res?.headers?.get?.('x-correlation-id') || null;
66
+
67
+ /**
68
+ * The per-second rate for `resolution` from the description answer that Seedance models get
69
+ * instead of an amount. It comes in two forms:
70
+ * - one list: "Standard self-serve rates in USD per video second: 480p: $0.0804; ... Total price
71
+ * = selected rate × output duration in seconds."
72
+ * - two lists, from the reference endpoint: "... rates in USD per second of generated video.
73
+ * - Without video input: 480p: $0.0804; ... - With video input: 480p: $0.0991; ... Total price
74
+ * = selected rate × output duration in seconds." cheapgen sends no input video, so only the
75
+ * "Without video input" list is read.
76
+ * Null unless the text still says the things this relies on, so changed wording falls back to
77
+ * the bundled price.
78
+ */
79
+ function rateFromDescription(text, resolution) {
80
+ if (typeof text !== 'string' || typeof resolution !== 'string') return null;
81
+ if (!/rate\s*[×x*]\s*output duration in seconds/i.test(text)) return null;
82
+ let rates;
83
+ if (/\bUSD per video second\b/i.test(text)) rates = text;
84
+ else if (/\bUSD per second of generated video\b/i.test(text)) rates = text.match(/^.*\bWithout video input\s*:(.*)$/im)?.[1];
85
+ if (!rates) return null;
86
+ for (const [, label, value] of rates.matchAll(/([0-9][0-9.]*[a-z]+)\s*:\s*\$\s*([0-9][0-9.eE+-]*)/gi)) {
87
+ if (label.toLowerCase() !== resolution.toLowerCase()) continue;
88
+ const rate = Number(value.replace(/\.$/, ''));
89
+ return Number.isFinite(rate) && rate >= 0 ? rate : null;
90
+ }
91
+ return null;
92
+ }
93
+
94
+ /** Seconds from a Retry-After header as milliseconds (capped), or the default delay for this retry. */
95
+ function retryDelay(res, retry) {
96
+ const header = res?.headers?.get?.('retry-after');
97
+ const seconds = typeof header === 'string' && header.trim() ? Number(header) : NaN;
98
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);
99
+ return RETRY_DELAYS_MS[retry];
100
+ }
101
+
102
+ export default {
103
+ id: 'higgsfield',
104
+ displayName: 'Higgsfield',
105
+ envVar: 'HIGGSFIELD_API_KEY',
106
+ billing: { failedJobCharged: false, validationErrorMayCharge: false },
107
+ /** Higgsfield keys are two values joined: the key id and the secret. */
108
+ /** The audio types the upload endpoint accepts: WAV, not MP3. */
109
+ audioUploadTypes: ['wav'],
110
+ keyFormat: {
111
+ prompt: 'Higgsfield key (KEY_ID:KEY_SECRET, hidden): ',
112
+ pattern: /^[^:\s]+:[^:\s]+$/,
113
+ hint: 'a Higgsfield key is the key id and the secret joined by a colon, KEY_ID:KEY_SECRET '
114
+ + '(both from console.higgsfield.ai). Nothing was stored.',
115
+ },
116
+
117
+ buildRequest(r, inputs) {
118
+ return { method: 'POST', url: `${BASE}/${endpointPath(r, inputs.entry)}`, body: body(r, inputs.entry, inputs) };
119
+ },
120
+
121
+ /**
122
+ * The price from Higgsfield's estimate endpoint. Most models get the account's own amount
123
+ * ({type: "estimate", usd}, discounts included); Seedance models get only the standard
124
+ * per-second rates as text ({type: "description"}), priced here as rate × duration.
125
+ * Image-to-video is estimated as text-to-video with the same settings: Higgsfield prices both
126
+ * the same, and an image-to-video estimate would need an uploaded image. An image edit is
127
+ * estimated as text-to-image for the same reason: the price is the same and input images add
128
+ * nothing. The price doesn't depend on the aspect ratio, so "follow the input" is asked as 1:1.
129
+ * A reference-to-video request is estimated on its own endpoint, with stand-in addresses for
130
+ * the inputs; its answer lists rates with and without an input video.
131
+ */
132
+ async livePrice(r, ctx, { entry }) {
133
+ let req = pricedRequest(r);
134
+ if (req.mode === 'image-to-video') {
135
+ req = { ...req, mode: 'text-to-video', image: undefined, imageIsLocal: false, lastImage: undefined };
136
+ }
137
+ if (req.mode === 'image-edit') {
138
+ req = { ...req, mode: 'text-to-image', images: undefined, aspectRatio: req.aspectRatio === 'auto' ? '1:1' : req.aspectRatio };
139
+ }
140
+ if (!(typeof req.prompt === 'string' && req.prompt.trim())) req = { ...req, prompt: ESTIMATE_PROMPT };
141
+ if (entry.modes && typeof entry.modes[req.mode] !== 'string') return null;
142
+ try {
143
+ const res = await http(ctx, { method: 'POST', url: `${BASE}/estimate/${endpointPath(req, entry)}`, headers: auth(ctx),
144
+ json: body(req, entry, estimateInputs(req)), timeoutMs: 10_000, retries: 0 });
145
+ const j = res.ok ? res.json : undefined;
146
+ if (j?.type === 'description') {
147
+ const rate = req.kind === 'video' ? rateFromDescription(j.pricing_description, req.resolution) : null;
148
+ return rate === null || !(req.duration > 0) ? null : { usd: rate * req.duration, unit: 'request' };
149
+ }
150
+ const raw = j?.usd;
151
+ if (!(typeof raw === 'number' || (typeof raw === 'string' && raw.trim()))) return null;
152
+ const usd = Number(raw);
153
+ return Number.isFinite(usd) && usd >= 0 ? { usd, unit: 'request' } : null;
154
+ } catch {
155
+ return null;
156
+ }
157
+ },
158
+
159
+ async balance() {
160
+ return null;
161
+ },
162
+
163
+ async upload(filePath, ctx, contentType) {
164
+ return asRejection(`${uploadLabel(contentType)} to Higgsfield`, async () => {
165
+ const { blob, type } = fileBlob(filePath, contentType);
166
+ const init = await http(ctx, { method: 'POST', url: `${BASE}/files/generate-upload-url`, headers: auth(ctx),
167
+ json: { content_type: type }, timeoutMs: 30_000 });
168
+ const j = init.json;
169
+ if (!init.ok) throw new Error(`HTTP ${init.status}: ${describeBody(init)}`);
170
+ if (typeof j?.upload_url !== 'string' || !/^https:\/\//.test(j.upload_url) || typeof j?.public_url !== 'string') {
171
+ throw new Error('no upload URL in the response');
172
+ }
173
+ // Exactly the headers Higgsfield asked for. The API key must never go to the storage host.
174
+ const headers = Object.fromEntries(Object.entries(j.upload_headers ?? {})
175
+ .filter(([k, v]) => typeof v === 'string' && k.toLowerCase() !== 'authorization'));
176
+ const put = await http(ctx, { method: 'PUT', url: j.upload_url, body: blob, headers, timeoutMs: 300_000 });
177
+ if (!put.ok) throw new Error(`HTTP ${put.status}: ${describeBody(put)}`);
178
+ return j.public_url;
179
+ });
180
+ },
181
+
182
+ async submit(r, ctx, inputs) {
183
+ const { url, body: json } = this.buildRequest(r, inputs);
184
+ const idempotencyKey = randomUUID();
185
+ const headers = { ...auth(ctx), 'Idempotency-Key': idempotencyKey };
186
+ const now = () => (ctx.now ? ctx.now().getTime() : Date.now());
187
+ const started = now();
188
+ let correlationId = null;
189
+ const unknown = (problem, status = null) => new SubmitUnknown(
190
+ `${problem}. Higgsfield idempotency key: ${idempotencyKey}${correlationId ? `, correlation id: ${correlationId}` : ''}`,
191
+ { status, details: { idempotencyKey, correlationId } });
192
+
193
+ for (let attempt = 0; ; attempt += 1) {
194
+ let res = null;
195
+ let problem;
196
+ let status = null;
197
+ try {
198
+ res = await http(ctx, { method: 'POST', url, headers, json, timeoutMs: SUBMIT_TIMEOUT_MS });
199
+ } catch (err) {
200
+ if (!(err instanceof NetworkError)) throw err;
201
+ problem = err.timeout ? 'the submit request timed out' : err.message;
202
+ }
203
+ if (res) {
204
+ correlationId = correlationOf(res) ?? correlationId;
205
+ if (res.status >= 200 && res.status < 300) {
206
+ const id = res.json?.request_id;
207
+ if (!id) throw unknown(`no request id in the response: ${describeBody(res)}`);
208
+ return { nativeId: String(id), meta: { statusUrl: statusUrlFor(res.json.status_url, id), correlationId } };
209
+ }
210
+ const message = `HTTP ${res.status}: ${describeBody(res)}`;
211
+ if (res.status < 500) {
212
+ if (attempt === 0) {
213
+ throw new SubmitRejected(`${message}${correlationId ? ` (correlation id ${correlationId})` : ''}`, { status: res.status });
214
+ }
215
+ // An earlier attempt may have been accepted, so this answer doesn't prove nothing was created.
216
+ throw unknown(`${message}, after an earlier attempt whose outcome is unknown`, res.status);
217
+ }
218
+ problem = message;
219
+ status = res.status;
220
+ }
221
+ if (attempt >= RETRY_DELAYS_MS.length || now() - started >= RETRY_DEADLINE_MS) throw unknown(problem, status);
222
+ await ctx.sleep?.(retryDelay(res, attempt));
223
+ }
224
+ },
225
+
226
+ async status(nativeId, ctx, meta) {
227
+ const res = await http(ctx, { url: statusUrlFor(meta?.statusUrl, nativeId), headers: auth(ctx), timeoutMs: 30_000 });
228
+ if (res.status === 404) {
229
+ return { state: 'failed', outputs: [], error: { code: '404', providerFault: false,
230
+ message: `Higgsfield has no request ${nativeId} for this key. It deletes request data 7 days after a job `
231
+ + 'finishes, so an older job\'s files are gone.' } };
232
+ }
233
+ if (!res.ok) throw readError(`HTTP ${res.status}: ${describeBody(res)}`, res.status);
234
+ const j = res.json ?? {};
235
+ const state = STATES[j.status] ?? 'running';
236
+ if (state === 'succeeded') {
237
+ const outputs = [j.video?.url, ...(Array.isArray(j.images) ? j.images : []).map((i) => i?.url)]
238
+ .filter((u) => typeof u === 'string');
239
+ return { state, outputs };
240
+ }
241
+ if (j.status === 'nsfw') {
242
+ return { state, outputs: [], error: { code: 'nsfw', providerFault: false,
243
+ message: 'Higgsfield\'s content moderation rejected the input or the output. The job wasn\'t charged.' } };
244
+ }
245
+ if (state === 'failed') {
246
+ return { state, outputs: [], error: { code: null, message: j.error ? String(j.error) : 'the job failed', providerFault: false } };
247
+ }
248
+ return { state, outputs: [] };
249
+ },
250
+ };
@@ -3,28 +3,78 @@ import kie from './kie.js';
3
3
  import replicate from './replicate.js';
4
4
  import wavespeed from './wavespeed.js';
5
5
  import fal from './fal.js';
6
+ import higgsfield from './higgsfield.js';
7
+ import { entryFor, variantFor } from '../catalog.js';
6
8
 
7
- export const ADAPTERS = Object.freeze({ kie, replicate, wavespeed, fal });
9
+ export const ADAPTERS = Object.freeze({ kie, replicate, wavespeed, fal, higgsfield });
8
10
 
9
11
  /**
10
12
  * Does `providerId` offer this request, according to data/models.json? A provider-level
11
- * `modes`, `resolutions`, `durations`, `sizes` or `aspectRatios` entry narrows the model's options.
13
+ * `modes`, `resolutions`, `durations`, `sizes` or `aspectRatios` entry narrows the model's options, and
14
+ * `autoDuration: false` means the provider can't let the model pick the length. An image edit
15
+ * also has to fit the provider's edit block: its input count, file size and total-pixel limits,
16
+ * and a way to follow the input image when no aspect ratio was given.
12
17
  * @returns {{ ok: true, entry: object } | { ok: false, reason: string }}
13
18
  */
14
19
  export function supports(catalog, providerId, r) {
15
- const entry = catalog.models[r.model]?.providers?.[providerId];
20
+ const entry = entryFor(catalog, providerId, r);
16
21
  const no = (reason) => ({ ok: false, reason: `${providerId} ${reason}` });
17
22
  if (!entry) return no(`doesn't offer ${r.model}`);
18
- if (entry.modes && typeof entry.modes[r.mode] !== 'string') return no(`doesn't offer ${r.model} as ${r.mode}`);
23
+ if (r.mode === 'image-edit') {
24
+ const why = editProblem(r, entry.edit);
25
+ if (why) return no(why);
26
+ } else if (entry.modes && typeof entry.modes[r.mode] !== 'string') return no(`doesn't offer ${r.model} as ${r.mode}`);
27
+ if (r.mode === 'reference-to-video') {
28
+ const why = referenceProblem(r, entry, ADAPTERS[providerId]);
29
+ if (why) return no(why);
30
+ }
19
31
  if (r.resolution && entry.resolutions && !entry.resolutions.includes(r.resolution)) {
20
32
  return no(`doesn't offer ${r.model} at ${r.resolution}`);
21
33
  }
34
+ // A resolution the model doesn't list itself is sold only by the provider whose variant has it.
35
+ const model = catalog.models[r.model];
36
+ if (r.resolution && model.resolutions && !model.resolutions.includes(r.resolution)
37
+ && variantFor(model, r.resolution)?.provider !== providerId) {
38
+ return no(`doesn't offer ${r.model} at ${r.resolution}`);
39
+ }
22
40
  if (r.size && entry.sizes && !entry.sizes.includes(r.size)) return no(`doesn't offer ${r.model} at size ${r.size}`);
23
- if (entry.aspectRatios && !entry.aspectRatios.includes(r.aspectRatio)) {
41
+ if (entry.aspectRatios && r.aspectRatio !== 'auto' && !entry.aspectRatios.includes(r.aspectRatio)) {
24
42
  return no(`doesn't offer ${r.model} at ${r.aspectRatio}`);
25
43
  }
44
+ if (entry.autoDuration === false && r.autoDuration) return no(`doesn't offer ${r.model} with --duration auto`);
26
45
  if (entry.durations && !r.autoDuration && (r.duration < entry.durations.min || r.duration > entry.durations.max)) {
27
46
  return no(`offers ${r.model} only from ${entry.durations.min} to ${entry.durations.max} seconds`);
28
47
  }
29
48
  return { ok: true, entry };
30
49
  }
50
+
51
+ /** Why a provider can't take these reference inputs, or null when it can. */
52
+ function referenceProblem(r, entry, adapter) {
53
+ if (!r.refImages?.length && !entry.references?.audioAlone) {
54
+ return `doesn't say it takes reference audio alone for ${r.model} (add a reference image)`;
55
+ }
56
+ const types = adapter?.audioUploadTypes;
57
+ const refused = types && r.refAudio?.find((a) => a.isLocal && !types.includes(a.type));
58
+ if (refused) {
59
+ return `can't take a local ${refused.type.toUpperCase()} file: its upload accepts ${types.map((t) => t.toUpperCase()).join(', ')} `
60
+ + 'audio only (give the file as a URL instead)';
61
+ }
62
+ return null;
63
+ }
64
+
65
+ /** Why a provider can't take this image edit, or null when it can. */
66
+ function editProblem(r, edit) {
67
+ if (!edit) return `doesn't offer ${r.model} with input images`;
68
+ const images = r.images ?? [];
69
+ if (images.length > edit.maxImages) return `takes at most ${edit.maxImages} input images for ${r.model}`;
70
+ if (edit.maxFileMB && images.some((i) => i.bytes > edit.maxFileMB * 1e6)) {
71
+ return `takes input images up to ${edit.maxFileMB} MB each for ${r.model}`;
72
+ }
73
+ if (edit.maxTotalMP && typeof r.inputPixels === 'number' && r.inputPixels > edit.maxTotalMP * 1e6) {
74
+ return `takes at most ${edit.maxTotalMP} megapixels of input images in total for ${r.model}`;
75
+ }
76
+ if (r.aspectRatio === 'auto' && !edit.follow && !r.effectiveAspect) {
77
+ return `needs --aspect for ${r.model}: it can't follow an input image given as a URL`;
78
+ }
79
+ return null;
80
+ }
@@ -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, { entry, imageUrl }) {
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.prompt, ...videoFields(r, { entry }), ...(imageUrl ? { first_frame_url: imageUrl } : {}) };
45
- return { method: 'POST', url: `${BASE}/api/v1/jobs/createTask`, body: { model: entry.id, input } };
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
- /** Price from Kie's public list, matched on the entry's `live.kieDescription`. */
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 description = entry?.live?.kieDescription;
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
- return { usd: cost({ ...entry.pricing, usd: unitUsd }, pricedRequest(r), frameSizes), unit: entry.pricing.type };
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
- async upload(filePath, ctx) {
66
- return asRejection('the image to Kie', async () => {
67
- const { blob, name } = fileBlob(filePath);
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, { entry, imageUrl }) {
79
- const { url, body } = this.buildRequest(r, { entry, imageUrl });
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, { entry, imageUrl }) {
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.prompt, ...videoFields(r, { entry }), ...(imageUrl ? { image: imageUrl } : {}) };
24
- return { method: 'POST', url: `${BASE}/models/${entry.id}/predictions`, body: { input } };
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('the image to Replicate', async () => {
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, { entry, imageUrl }) {
45
- const { url, body } = this.buildRequest(r, { entry, imageUrl });
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
- function body(r, entry, imageUrl) {
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.prompt, ...videoFields(r, { entry }), ...(imageUrl ? { image: imageUrl } : {}) };
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, { entry, imageUrl }) {
29
- return { method: 'POST', url: `${BASE}/${modelPath(r, entry)}`, body: body(r, entry, imageUrl) };
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
- const priced = pricedRequest(r);
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(priced, entry), input: body(priced, entry) } });
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('the image to WaveSpeed', async () => {
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, { entry, imageUrl }) {
60
- const { url, body: json } = this.buildRequest(r, { entry, imageUrl });
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;