egaki 0.12.0 → 0.13.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/cli/cli.d.ts.map +1 -1
  3. package/dist/cli/cli.js +167 -0
  4. package/dist/cli/clone-generate.d.ts +1 -0
  5. package/dist/cli/clone-generate.d.ts.map +1 -1
  6. package/dist/cli/clone-generate.js +1 -1
  7. package/dist/cli/generate.d.ts +3 -1
  8. package/dist/cli/generate.d.ts.map +1 -1
  9. package/dist/cli/generate.js +12 -5
  10. package/dist/cli/model-catalog.d.ts.map +1 -1
  11. package/dist/cli/model-catalog.js +37 -0
  12. package/dist/cli/upscale-generate.d.ts +97 -0
  13. package/dist/cli/upscale-generate.d.ts.map +1 -0
  14. package/dist/cli/upscale-generate.js +300 -0
  15. package/dist/cli/upscale-generate.test.d.ts +2 -0
  16. package/dist/cli/upscale-generate.test.d.ts.map +1 -0
  17. package/dist/cli/upscale-generate.test.js +92 -0
  18. package/dist/cli/voice-change-generate.d.ts +39 -0
  19. package/dist/cli/voice-change-generate.d.ts.map +1 -0
  20. package/dist/cli/voice-change-generate.js +123 -0
  21. package/dist/vite/angled-screen-shader.d.ts +4 -39
  22. package/dist/vite/angled-screen-shader.d.ts.map +1 -1
  23. package/dist/vite/angled-screen-shader.js +36 -440
  24. package/dist/vite/angled-screen.d.ts.map +1 -1
  25. package/dist/vite/angled-screen.js +9 -7
  26. package/dist/vite/shader-renderer.d.ts +0 -4
  27. package/dist/vite/shader-renderer.d.ts.map +1 -1
  28. package/dist/vite/shader-renderer.js +2 -66
  29. package/package.json +10 -5
  30. package/src/cli/cli.ts +227 -0
  31. package/src/cli/clone-generate.ts +1 -1
  32. package/src/cli/generate.ts +18 -6
  33. package/src/cli/model-catalog.ts +39 -0
  34. package/src/cli/upscale-generate.test.ts +96 -0
  35. package/src/cli/upscale-generate.ts +395 -0
  36. package/src/cli/voice-change-generate.ts +187 -0
  37. package/src/vite/angled-screen-shader.tsx +45 -498
  38. package/src/vite/angled-screen.tsx +9 -7
  39. package/src/vite/shader-renderer.tsx +7 -78
@@ -0,0 +1,395 @@
1
+ // Image upscaling for `egaki upscale`. Two kinds of upscalers:
2
+ //
3
+ // gpt-image-2* re-renders the input at a larger custom size with a strict
4
+ // "same image, more pixels" prompt, then color-matches it to
5
+ // the input. OpenAI key: one call. ChatGPT login: overlapping
6
+ // tiles, because that backend returns ~1.6 MP per call
7
+ // midjourney* registers the image as a midjourney.com editor upload, then
8
+ // runs Midjourney's 2x subtle or creative upscaler through the
9
+ // user's Chrome (@egaki/midjourney + Playwriter)
10
+ //
11
+ // Research on other upscale APIs (fal, Replicate, Topaz, ...): docs/upscale-apis.md
12
+
13
+ import sharp from 'sharp'
14
+ import dedent from 'string-dedent'
15
+ import { generateImageUncached, ValidationError, type GeneratedFile } from './generate.js'
16
+ import { CATALOG } from './model-catalog.js'
17
+ import { shouldUseChatGptBackend } from './credentials.js'
18
+
19
+ export const MIDJOURNEY_UPSCALE_MODELS = ['midjourney', 'midjourney-creative'] as const
20
+ export const DEFAULT_UPSCALE_MODEL = 'gpt-image-2.6-sunburst'
21
+
22
+ /** GPT Image models that accept custom WIDTHxHEIGHT sizes. */
23
+ export const GPT_UPSCALE_MODELS = CATALOG
24
+ .map((m) => m.id)
25
+ .filter((id) => id.startsWith('gpt-image-2'))
26
+
27
+ export const UPSCALE_MODELS = [...GPT_UPSCALE_MODELS, ...MIDJOURNEY_UPSCALE_MODELS]
28
+
29
+ export interface UpscaleImageOptions {
30
+ image: Uint8Array
31
+ model?: string
32
+ /** Target scale factor. GPT Image: default is the largest size it supports. Midjourney: always 2. */
33
+ scale?: number
34
+ /** Extra instructions appended to the upscale prompt (GPT), or the job prompt (Midjourney). */
35
+ prompt?: string
36
+ }
37
+
38
+ export interface UpscaleImageResult {
39
+ image: GeneratedFile
40
+ model: string
41
+ input: { width: number; height: number }
42
+ output: { width: number; height: number }
43
+ /** Exact prompt sent to the model. */
44
+ prompt?: string
45
+ /** Number of GPT Image calls (tiles) blended into the output. */
46
+ tiles?: number
47
+ /** Midjourney upscale job ID. */
48
+ jobId?: string
49
+ /** Set when the provider returned a smaller image than requested. */
50
+ warning?: string
51
+ cost: number | null
52
+ }
53
+
54
+ // https://developers.openai.com/api/docs/guides/image-generation#size-and-quality-options
55
+ const GPT_SIZE_MULTIPLE = 16
56
+ const GPT_MAX_EDGE = 3840
57
+ const GPT_MIN_PIXELS = 655_360
58
+ const GPT_MAX_PIXELS = 8_294_400
59
+ const GPT_MAX_RATIO = 3
60
+
61
+ /**
62
+ * Pick the GPT Image output size for an upscale: the input scaled by `scale`
63
+ * (or as large as allowed), snapped to multiples of 16, inside the model limits,
64
+ * keeping the aspect ratio as close as the 16px grid allows.
65
+ */
66
+ export function gptUpscaleSize({
67
+ width,
68
+ height,
69
+ scale,
70
+ }: {
71
+ width: number
72
+ height: number
73
+ scale?: number
74
+ }): ValidationError | { width: number; height: number } {
75
+ const ratio = width / height
76
+ if (Math.max(ratio, 1 / ratio) > GPT_MAX_RATIO) {
77
+ return new ValidationError(
78
+ `GPT Image supports aspect ratios up to ${GPT_MAX_RATIO}:1. The input is ${width}x${height}.`,
79
+ )
80
+ }
81
+ if (scale !== undefined && !(scale > 1)) {
82
+ return new ValidationError(`Scale must be greater than 1, got ${scale}.`)
83
+ }
84
+
85
+ const area = width * height
86
+ const targetArea = scale === undefined ? GPT_MAX_PIXELS : area * scale * scale
87
+
88
+ // Try every long edge on the 16px grid, keep the valid size closest in area to the target.
89
+ const landscape = width >= height
90
+ const longRatio = landscape ? ratio : 1 / ratio
91
+ let best: { width: number; height: number } | undefined
92
+ for (let long = GPT_SIZE_MULTIPLE; long <= GPT_MAX_EDGE; long += GPT_SIZE_MULTIPLE) {
93
+ const short = Math.max(GPT_SIZE_MULTIPLE, Math.round(long / longRatio / GPT_SIZE_MULTIPLE) * GPT_SIZE_MULTIPLE)
94
+ const pixels = long * short
95
+ if (pixels < GPT_MIN_PIXELS || pixels > GPT_MAX_PIXELS || long / short > GPT_MAX_RATIO) continue
96
+ if (!best || Math.abs(pixels - targetArea) < Math.abs(best.width * best.height - targetArea)) {
97
+ best = landscape ? { width: long, height: short } : { width: short, height: long }
98
+ }
99
+ }
100
+ if (!best || best.width * best.height <= area) {
101
+ return new ValidationError(
102
+ `GPT Image cannot upscale a ${width}x${height} image: its output is limited to ${GPT_MAX_EDGE}px per edge and ${(GPT_MAX_PIXELS / 1e6).toFixed(1)} MP.`,
103
+ )
104
+ }
105
+ return best
106
+ }
107
+
108
+ /**
109
+ * Prompt for GPT Image upscales. Structure from the common ChatGPT upscale
110
+ * templates: action, keep list, allowed improvements, forbidden changes.
111
+ * See docs/upscale-apis.md for sources.
112
+ */
113
+ export function gptUpscalePrompt({
114
+ width,
115
+ height,
116
+ extra,
117
+ }: {
118
+ width: number
119
+ height: number
120
+ extra?: string
121
+ }): string {
122
+ const prompt = dedent`
123
+ Upscale this image to ${width}x${height} pixels. This is a resolution upscale, not an edit: return the exact same image with more pixels and finer detail.
124
+
125
+ Keep everything identical to the input: composition, framing, crop and aspect ratio; the position, size, shape and proportions of every element; perspective and horizon line; colors, white balance, contrast and lighting; shadows and highlights; medium and style (brushwork, film grain, line art, paper or canvas texture); all text, letters and logos character for character; faces, identity and expressions.
126
+
127
+ Improve only resolution and definition: render crisp edges, fine textures and small details that are consistent with what is already visible, as if the same image had been captured or painted at a higher resolution. Remove blur, noise, JPEG compression artifacts and color banding.
128
+
129
+ Do not add, remove, move, restyle or reinterpret anything. No new objects, no recoloring, no relighting, no reframing, no cropping, no borders, no oversharpening halos, no plastic smoothing, no stylization.
130
+ `
131
+ return extra?.trim() ? `${prompt}\n\nAdditional instructions: ${extra.trim()}` : prompt
132
+ }
133
+
134
+ // The ChatGPT subscription backend ignores `size` and `quality` and returns about
135
+ // 1536x1024 worth of pixels in the input aspect ratio (verified Nov 2026, see
136
+ // docs/chatgpt-codex-image-backend.md). To reach the target size there, the
137
+ // input is split into overlapping tiles, each tile is upscaled, then blended.
138
+ const CHATGPT_MAX_PIXELS = 1536 * 1024
139
+ const MAX_GRID = 4
140
+ const TILE_OVERLAP = 0.2
141
+ const MIN_TILE_SIDE = 192
142
+
143
+ export type Tile = { x: number; y: number; width: number; height: number }
144
+
145
+ /** Split an image into grid x grid tiles that overlap by TILE_OVERLAP of a tile. */
146
+ export function planTiles({ width, height, grid }: { width: number; height: number; grid: number }): Tile[] {
147
+ const tileWidth = Math.round(width / (grid - (grid - 1) * TILE_OVERLAP))
148
+ const tileHeight = Math.round(height / (grid - (grid - 1) * TILE_OVERLAP))
149
+ const offsets = (size: number, tile: number) =>
150
+ Array.from({ length: grid }, (_, i) => (grid === 1 ? 0 : Math.round((i * (size - tile)) / (grid - 1))))
151
+ return offsets(height, tileHeight).flatMap((y) =>
152
+ offsets(width, tileWidth).map((x) => ({ x, y, width: tileWidth, height: tileHeight })),
153
+ )
154
+ }
155
+
156
+ /**
157
+ * Smallest grid whose tiles, each returned at `pixelsPerCall`, reach the target
158
+ * width. Stops before tiles get under MIN_TILE_SIDE, where the model sees too
159
+ * little context and invents detail.
160
+ */
161
+ export function chooseGrid({
162
+ width,
163
+ height,
164
+ targetWidth,
165
+ pixelsPerCall,
166
+ }: {
167
+ width: number
168
+ height: number
169
+ targetWidth: number
170
+ pixelsPerCall: number
171
+ }): number {
172
+ let grid = 1
173
+ while (grid < MAX_GRID) {
174
+ const tile = planTiles({ width, height, grid })[0]!
175
+ if (width * Math.sqrt(pixelsPerCall / (tile.width * tile.height)) >= targetWidth) return grid
176
+ const next = planTiles({ width, height, grid: grid + 1 })[0]!
177
+ if (Math.min(next.width, next.height) < MIN_TILE_SIDE) return grid
178
+ grid++
179
+ }
180
+ return grid
181
+ }
182
+
183
+ /**
184
+ * Blend upscaled RGB tiles (output coordinates) into one image. Each tile is
185
+ * matched to the reference (the input resized to the output size) by
186
+ * per-channel mean and standard deviation, which removes the color drift
187
+ * generative models add, then feathered across the overlaps.
188
+ */
189
+ export function blendTiles({
190
+ width,
191
+ height,
192
+ reference,
193
+ tiles,
194
+ }: {
195
+ width: number
196
+ height: number
197
+ reference: Uint8Array
198
+ tiles: Array<Tile & { pixels: Uint8Array }>
199
+ }): Uint8Array {
200
+ const sum = new Float32Array(width * height * 3)
201
+ const weight = new Float32Array(width * height)
202
+ for (const tile of tiles) {
203
+ const count = tile.width * tile.height
204
+ const channelStats = (read: (p: number, c: number) => number) =>
205
+ [0, 1, 2].map((c) => {
206
+ let total = 0
207
+ let squares = 0
208
+ for (let p = 0; p < count; p++) {
209
+ const v = read(p, c)
210
+ total += v
211
+ squares += v * v
212
+ }
213
+ const mean = total / count
214
+ return { mean, std: Math.sqrt(Math.max(1, squares / count - mean * mean)) }
215
+ })
216
+ const target = channelStats((p, c) =>
217
+ reference[((tile.y + Math.floor(p / tile.width)) * width + tile.x + (p % tile.width)) * 3 + c]!,
218
+ )
219
+ const actual = channelStats((p, c) => tile.pixels[p * 3 + c]!)
220
+
221
+ // weights ramp to 0 only on sides that overlap a neighbor tile
222
+ const rampX = tile.width * TILE_OVERLAP
223
+ const rampY = tile.height * TILE_OVERLAP
224
+ for (let py = 0; py < tile.height; py++) {
225
+ const top = tile.y > 0 ? py / rampY : 1
226
+ const bottom = tile.y + tile.height < height ? (tile.height - 1 - py) / rampY : 1
227
+ for (let px = 0; px < tile.width; px++) {
228
+ const left = tile.x > 0 ? px / rampX : 1
229
+ const right = tile.x + tile.width < width ? (tile.width - 1 - px) / rampX : 1
230
+ const w = Math.max(1e-4, Math.min(1, top, bottom, left, right))
231
+ const o = (tile.y + py) * width + tile.x + px
232
+ for (let c = 0; c < 3; c++) {
233
+ const v = tile.pixels[(py * tile.width + px) * 3 + c]!
234
+ sum[o * 3 + c]! += (((v - actual[c]!.mean) / actual[c]!.std) * target[c]!.std + target[c]!.mean) * w
235
+ }
236
+ weight[o]! += w
237
+ }
238
+ }
239
+ }
240
+ const out = new Uint8Array(width * height * 3)
241
+ for (let o = 0; o < width * height; o++) {
242
+ for (let c = 0; c < 3; c++) out[o * 3 + c] = Math.max(0, Math.min(255, Math.round(sum[o * 3 + c]! / weight[o]!)))
243
+ }
244
+ return out
245
+ }
246
+
247
+ // sharp and @egaki/midjourney reject with Error instances
248
+ const toError = (err: Error) => err
249
+
250
+ async function readImageSize(bytes: Uint8Array): Promise<ValidationError | { width: number; height: number }> {
251
+ const meta = await sharp(bytes).metadata().catch(toError)
252
+ if (meta instanceof Error) return new ValidationError(`Could not read the image: ${meta.message}`)
253
+ return meta.autoOrient
254
+ }
255
+
256
+ export async function upscaleImageUncached(opts: UpscaleImageOptions): Promise<Error | UpscaleImageResult> {
257
+ const model = opts.model ?? DEFAULT_UPSCALE_MODEL
258
+
259
+ if (model === 'midjourney' || model === 'midjourney-creative') {
260
+ if (opts.scale !== undefined && opts.scale !== 2) {
261
+ return new ValidationError('Midjourney only upscales 2x. Remove --scale or pass --scale 2.')
262
+ }
263
+ const input = await readImageSize(opts.image)
264
+ if (input instanceof Error) return input
265
+ return upscaleWithMidjourney({ image: opts.image, model, input, prompt: opts.prompt })
266
+ }
267
+
268
+ if (!GPT_UPSCALE_MODELS.includes(model)) {
269
+ return new ValidationError(`Model ${model} cannot upscale. Use one of: ${UPSCALE_MODELS.join(', ')}`)
270
+ }
271
+ return upscaleWithGpt({ image: opts.image, model, scale: opts.scale, extra: opts.prompt })
272
+ }
273
+
274
+ async function upscaleWithGpt(opts: {
275
+ image: Uint8Array
276
+ model: string
277
+ scale?: number
278
+ extra?: string
279
+ }): Promise<Error | UpscaleImageResult> {
280
+ const decoded = await sharp(opts.image)
281
+ .autoOrient()
282
+ .removeAlpha()
283
+ .toColourspace('srgb')
284
+ .raw()
285
+ .toBuffer({ resolveWithObject: true })
286
+ .catch(toError)
287
+ if (decoded instanceof Error) return new ValidationError(`Could not read the image: ${decoded.message}`)
288
+ const input = { width: decoded.info.width, height: decoded.info.height }
289
+ const raw = { raw: { width: input.width, height: input.height, channels: 3 as const } }
290
+
291
+ const size = gptUpscaleSize({ ...input, scale: opts.scale })
292
+ if (size instanceof Error) return size
293
+ // with an API key one call returns the full size; ChatGPT login needs tiles
294
+ const grid = shouldUseChatGptBackend()
295
+ ? chooseGrid({ ...input, targetWidth: size.width, pixelsPerCall: CHATGPT_MAX_PIXELS })
296
+ : 1
297
+ const tiles = planTiles({ ...input, grid })
298
+ const sx = size.width / input.width
299
+ const sy = size.height / input.height
300
+ const extra = grid > 1
301
+ ? ['This image is a crop of a larger image: content continues past every edge, so add no borders or vignettes.', opts.extra].filter(Boolean).join(' ')
302
+ : opts.extra
303
+
304
+ const reference = await sharp(decoded.data, raw)
305
+ .resize(size.width, size.height, { fit: 'fill', kernel: 'lanczos3' })
306
+ .raw()
307
+ .toBuffer()
308
+ const prompts: string[] = []
309
+
310
+ const upscaled = await Promise.all(tiles.map(async (tile) => {
311
+ const x = Math.round(tile.x * sx)
312
+ const y = Math.round(tile.y * sy)
313
+ const box = { x, y, width: Math.round((tile.x + tile.width) * sx) - x, height: Math.round((tile.y + tile.height) * sy) - y }
314
+ const crop = await sharp(decoded.data, raw)
315
+ .extract({ left: tile.x, top: tile.y, width: tile.width, height: tile.height })
316
+ .png()
317
+ .toBuffer()
318
+ const prompt = gptUpscalePrompt({ width: box.width, height: box.height, extra })
319
+ prompts.push(prompt)
320
+ const request = () => generateImageUncached({
321
+ prompt,
322
+ model: opts.model,
323
+ inputImages: [new Uint8Array(crop)],
324
+ // the ChatGPT backend ignores size; only send it when it is a valid API size
325
+ size: grid === 1 ? `${box.width}x${box.height}` : undefined,
326
+ quality: 'high',
327
+ })
328
+ // one retry: with many parallel tiles a single transient failure is likely
329
+ let result = await request()
330
+ if (result instanceof Error && !(result instanceof ValidationError)) result = await request()
331
+ if (result instanceof Error) return result
332
+ const file = result.images[0]
333
+ if (!file) return new Error('GPT Image returned no image.')
334
+ const returned = await sharp(file.uint8Array).metadata().catch(toError)
335
+ if (returned instanceof Error) return returned
336
+ const pixels = await sharp(file.uint8Array)
337
+ .removeAlpha()
338
+ .resize(box.width, box.height, { fit: 'fill', kernel: 'lanczos3' })
339
+ .raw()
340
+ .toBuffer()
341
+ .catch(toError)
342
+ if (pixels instanceof Error) return pixels
343
+ return { ...box, pixels, returned: { width: returned.width, height: returned.height }, cost: result.cost }
344
+ }))
345
+ const done: Array<Exclude<(typeof upscaled)[number], Error>> = []
346
+ for (const tile of upscaled) {
347
+ if (tile instanceof Error) return tile
348
+ done.push(tile)
349
+ }
350
+
351
+ const pixels = blendTiles({ ...size, reference, tiles: done })
352
+ const png = await sharp(pixels, { raw: { ...size, channels: 3 } }).png().toBuffer()
353
+
354
+ const small = done.find((tile) => tile.returned.width * tile.returned.height < tile.width * tile.height * 0.9)
355
+ const costs = done.map((tile) => tile.cost)
356
+ return {
357
+ image: { uint8Array: new Uint8Array(png), mediaType: 'image/png' },
358
+ model: opts.model,
359
+ input,
360
+ output: size,
361
+ tiles: tiles.length,
362
+ prompt: prompts[0],
363
+ warning: small
364
+ ? `GPT Image returned ${small.returned.width}x${small.returned.height} for a ${small.width}x${small.height} tile, so tiles were resized up and look softer.`
365
+ : undefined,
366
+ cost: costs.every((cost) => cost !== null) ? costs.reduce((a, b) => a + b, 0) : null,
367
+ }
368
+ }
369
+
370
+ async function upscaleWithMidjourney(opts: {
371
+ image: Uint8Array
372
+ model: string
373
+ input: { width: number; height: number }
374
+ prompt?: string
375
+ }): Promise<Error | UpscaleImageResult> {
376
+ const { Midjourney } = await import('@egaki/midjourney')
377
+ const mj = new Midjourney()
378
+ const result = await mj
379
+ .upscaleImage(Buffer.from(opts.image), {
380
+ type: opts.model === 'midjourney-creative' ? 'v7_2x_creative' : 'v7_2x_subtle',
381
+ prompt: opts.prompt,
382
+ })
383
+ .catch(toError)
384
+ await mj.close().catch(() => {})
385
+ if (result instanceof Error) return result
386
+
387
+ return {
388
+ image: { uint8Array: new Uint8Array(result.image), mediaType: 'image/jpeg' },
389
+ model: opts.model,
390
+ input: opts.input,
391
+ output: { width: result.width, height: result.height },
392
+ jobId: result.upscaleJobId,
393
+ cost: null,
394
+ }
395
+ }
@@ -0,0 +1,187 @@
1
+ // Voice change (speech-to-speech): re-speak a recording with another voice,
2
+ // keeping its timing, emotion and delivery. Plain multipart HTTP calls, no SDK.
3
+ // Returns Error | Result (errore style) instead of throwing.
4
+ //
5
+ // Each provider is one entry in VOICE_CHANGE_PROVIDERS. To add a provider,
6
+ // add an entry with its models and a change() function.
7
+ //
8
+ // ElevenLabs: POST https://api.elevenlabs.io/v1/voice-changer/{voice_id}
9
+ // Docs: https://elevenlabs.io/docs/api-reference/speech-to-speech/convert
10
+ //
11
+ // Cartesia: POST https://api.cartesia.ai/voice-changer/bytes
12
+ // Docs: https://docs.cartesia.ai/api-reference/voice-changer/bytes
13
+ import { injectCredentialsToEnv } from './credentials.js'
14
+ import { mimeTypeFromFilename } from './clone-generate.js'
15
+ import { ValidationError } from './models.js'
16
+
17
+ // ─── types ──────────────────────────────────────────────────────────────────
18
+
19
+ export interface VoiceChangeOptions {
20
+ /** Raw audio bytes of the recording to re-speak. */
21
+ audio: Uint8Array
22
+ /** Target voice ID from the provider's voice library (or a cloned voice). */
23
+ voice: string
24
+ provider: VoiceChangeProvider
25
+ /** Provider model ID. Defaults to the provider's default model. */
26
+ model?: string
27
+ /** Original filename for MIME type inference. */
28
+ filename?: string
29
+ /** ElevenLabs: remove background noise from the input before conversion. */
30
+ removeBackgroundNoise?: boolean
31
+ }
32
+
33
+ export interface VoiceChangeResult {
34
+ audio: Uint8Array
35
+ mediaType: string
36
+ provider: VoiceChangeProvider
37
+ model?: string
38
+ }
39
+
40
+ interface ProviderEntry {
41
+ /** Empty when the provider has no model choice. */
42
+ models: string[]
43
+ defaultModel?: string
44
+ supportsRemoveBackgroundNoise: boolean
45
+ change(opts: VoiceChangeOptions): Promise<Error | VoiceChangeResult>
46
+ }
47
+
48
+ // ─── shared helpers ─────────────────────────────────────────────────────────
49
+
50
+ function audioFile(opts: VoiceChangeOptions): File {
51
+ const mime = mimeTypeFromFilename(opts.filename)
52
+ const ext = opts.filename?.split('.').pop() ?? 'mp3'
53
+ return new File([Buffer.from(opts.audio)], `input.${ext}`, { type: mime })
54
+ }
55
+
56
+ async function readAudioResponse(
57
+ label: string,
58
+ response: Response | Error,
59
+ ): Promise<Error | { audio: Uint8Array; mediaType: string }> {
60
+ if (response instanceof Error) return response
61
+ if (!response.ok) {
62
+ const errorText = await response.text().catch(() => '')
63
+ return new Error(`${label} voice change API error ${response.status}: ${errorText || response.statusText}`)
64
+ }
65
+ const bytes = await response.arrayBuffer().catch(
66
+ (cause) => new Error(`${label} voice change response could not be read`, { cause }),
67
+ )
68
+ if (bytes instanceof Error) return bytes
69
+ if (bytes.byteLength === 0) return new Error(`${label} voice change API returned empty audio`)
70
+ return {
71
+ audio: new Uint8Array(bytes),
72
+ mediaType: response.headers.get('content-type')?.split(';')[0] ?? 'audio/mpeg',
73
+ }
74
+ }
75
+
76
+ // ─── ElevenLabs ─────────────────────────────────────────────────────────────
77
+
78
+ async function changeVoiceElevenLabs(
79
+ opts: VoiceChangeOptions,
80
+ ): Promise<Error | VoiceChangeResult> {
81
+ const apiKey = process.env['ELEVENLABS_API_KEY']
82
+ if (!apiKey) {
83
+ return new Error(
84
+ 'ELEVENLABS_API_KEY not found. Run: egaki login --provider elevenlabs\n' +
85
+ 'Get your key at https://elevenlabs.io/app/settings/api-keys',
86
+ )
87
+ }
88
+
89
+ const formData = new FormData()
90
+ formData.append('audio', audioFile(opts))
91
+ if (opts.model) formData.append('model_id', opts.model)
92
+ if (opts.removeBackgroundNoise) formData.append('remove_background_noise', 'true')
93
+
94
+ const url = `https://api.elevenlabs.io/v1/voice-changer/${encodeURIComponent(opts.voice)}?output_format=mp3_44100_128`
95
+ const response = await fetch(url, {
96
+ method: 'POST',
97
+ headers: { 'xi-api-key': apiKey },
98
+ body: formData,
99
+ }).catch((cause) => new Error('ElevenLabs voice change request failed', { cause }))
100
+
101
+ const result = await readAudioResponse('ElevenLabs', response)
102
+ if (result instanceof Error) return result
103
+ return { ...result, provider: 'elevenlabs', model: opts.model }
104
+ }
105
+
106
+ // ─── Cartesia ───────────────────────────────────────────────────────────────
107
+
108
+ async function changeVoiceCartesia(opts: VoiceChangeOptions): Promise<Error | VoiceChangeResult> {
109
+ const apiKey = process.env['CARTESIA_API_KEY']
110
+ if (!apiKey) {
111
+ return new Error(
112
+ 'CARTESIA_API_KEY not found. Run: egaki login --provider cartesia\n' +
113
+ 'Get your key at https://play.cartesia.ai/keys',
114
+ )
115
+ }
116
+
117
+ const formData = new FormData()
118
+ formData.append('clip', audioFile(opts))
119
+ formData.append('voice[id]', opts.voice)
120
+ formData.append('output_format[container]', 'mp3')
121
+ formData.append('output_format[sample_rate]', '44100')
122
+ formData.append('output_format[bit_rate]', '128000')
123
+
124
+ const response = await fetch('https://api.cartesia.ai/voice-changer/bytes', {
125
+ method: 'POST',
126
+ headers: {
127
+ 'Cartesia-Version': '2026-03-01',
128
+ 'Authorization': `Bearer ${apiKey}`,
129
+ },
130
+ body: formData,
131
+ }).catch((cause) => new Error('Cartesia voice change request failed', { cause }))
132
+
133
+ const result = await readAudioResponse('Cartesia', response)
134
+ if (result instanceof Error) return result
135
+ return { ...result, provider: 'cartesia' }
136
+ }
137
+
138
+ // ─── provider registry ──────────────────────────────────────────────────────
139
+
140
+ export const VOICE_CHANGE_PROVIDERS = {
141
+ elevenlabs: {
142
+ models: ['eleven_multilingual_sts_v2', 'eleven_english_sts_v2'],
143
+ defaultModel: 'eleven_multilingual_sts_v2',
144
+ supportsRemoveBackgroundNoise: true,
145
+ change: changeVoiceElevenLabs,
146
+ },
147
+ cartesia: {
148
+ models: [],
149
+ supportsRemoveBackgroundNoise: false,
150
+ change: changeVoiceCartesia,
151
+ },
152
+ } satisfies Record<string, ProviderEntry>
153
+
154
+ export type VoiceChangeProvider = keyof typeof VOICE_CHANGE_PROVIDERS
155
+
156
+ export const VOICE_CHANGE_PROVIDER_IDS = Object.keys(VOICE_CHANGE_PROVIDERS) as [
157
+ VoiceChangeProvider,
158
+ ...VoiceChangeProvider[],
159
+ ]
160
+
161
+ // ─── main entry point ───────────────────────────────────────────────────────
162
+
163
+ export async function changeVoiceUncached(
164
+ opts: VoiceChangeOptions,
165
+ ): Promise<Error | VoiceChangeResult> {
166
+ injectCredentialsToEnv()
167
+
168
+ const entry: ProviderEntry = VOICE_CHANGE_PROVIDERS[opts.provider]
169
+ if (opts.audio.length === 0) {
170
+ return new ValidationError('No audio data provided. Pass an audio file or use --stdin.')
171
+ }
172
+ if (!opts.voice || opts.voice.trim().length === 0) {
173
+ return new ValidationError('Target voice is required. Use --voice <voice-id>.')
174
+ }
175
+ if (opts.model && !entry.models.includes(opts.model)) {
176
+ return new ValidationError(
177
+ entry.models.length === 0
178
+ ? `${opts.provider} voice change has no model option. Remove -m.`
179
+ : `Unknown ${opts.provider} voice change model "${opts.model}". Supported: ${entry.models.join(', ')}`,
180
+ )
181
+ }
182
+ if (opts.removeBackgroundNoise && !entry.supportsRemoveBackgroundNoise) {
183
+ return new ValidationError(`--remove-background-noise is not supported by ${opts.provider}.`)
184
+ }
185
+
186
+ return entry.change({ ...opts, voice: opts.voice.trim(), model: opts.model ?? entry.defaultModel })
187
+ }