egaki 0.11.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 +66 -0
  2. package/dist/cli/cli.d.ts.map +1 -1
  3. package/dist/cli/cli.js +171 -2
  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 +4 -2
  8. package/dist/cli/generate.d.ts.map +1 -1
  9. package/dist/cli/generate.js +14 -6
  10. package/dist/cli/model-catalog.d.ts.map +1 -1
  11. package/dist/cli/model-catalog.js +158 -5
  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 +11 -6
  30. package/src/cli/cli.ts +231 -2
  31. package/src/cli/clone-generate.ts +1 -1
  32. package/src/cli/generate.ts +24 -11
  33. package/src/cli/model-catalog.ts +167 -5
  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
@@ -56,6 +56,16 @@ const openaiImage = {
56
56
  strategy: 'image',
57
57
  providerOptions: openaiImageProviderOptions,
58
58
  };
59
+ // GPT Image 2.5 models add `xhigh` and `max` quality levels.
60
+ // Docs: https://developers.openai.com/api/docs/models/gpt-image-2.5-sunburst
61
+ const openaiImage25ProviderOptions = [
62
+ { flag: 'quality', providerKey: 'quality', description: 'Image quality', values: ['auto', 'low', 'medium', 'high', 'xhigh', 'max'], defaultValue: 'auto', type: 'string' },
63
+ { flag: 'output-format', providerKey: 'outputFormat', description: 'Output format', values: ['png', 'jpeg', 'webp'], defaultValue: 'png', type: 'string' },
64
+ ];
65
+ const openaiImage25 = {
66
+ ...openaiImage,
67
+ providerOptions: openaiImage25ProviderOptions,
68
+ };
59
69
  const replicateImage = {
60
70
  provider: 'replicate',
61
71
  strategy: 'image',
@@ -91,6 +101,14 @@ const xaiImage = {
91
101
  strategy: 'image',
92
102
  providerOptions: xaiImageProviderOptions,
93
103
  };
104
+ // Docs: https://docs.x.ai/developers/model-capabilities/images/generation
105
+ // quality is only honored by grok-imagine-image-2.0. 'auto' is the server default
106
+ // (low for generation, medium for editing), so egaki omits the field for 'auto'.
107
+ const xaiImage2ProviderOptions = [
108
+ { flag: 'quality', providerKey: 'quality', description: 'Image quality', values: ['auto', 'low', 'medium'], defaultValue: 'auto', type: 'string' },
109
+ { flag: 'resolution', providerKey: 'resolution', description: 'Output resolution', values: ['1k', '2k'], defaultValue: '1k', type: 'string' },
110
+ { flag: 'output-format', providerKey: 'output_format', description: 'Output format', values: ['png', 'jpeg'], defaultValue: 'png', type: 'string' },
111
+ ];
94
112
  // Source: node_modules/@ai-sdk/xai/dist/index.d.ts → XaiVideoModelOptions
95
113
  // Docs: https://docs.x.ai/docs/api-reference#create-video
96
114
  const xaiVideoProviderOptions = [
@@ -101,6 +119,19 @@ const xaiVideoProviderOptions = [
101
119
  { flag: 'video-url', providerKey: 'videoUrl', description: 'Source video URL for editing or extension (internal)', type: 'string' },
102
120
  { flag: 'reference-images', providerKey: 'referenceImageUrls', description: 'Reference images for R2V (1-7 files or URLs)', type: 'string', array: true },
103
121
  ];
122
+ // Docs: https://docs.x.ai/developers/model-capabilities/video/overview
123
+ // grok-imagine-video-1.5: T2V/I2V at native 1080p, R2V up to 720p with up to 14 references.
124
+ // No editing or extension. Preset voices (reference_audios), last_frame and keyframes exist
125
+ // on the REST API but are not exposed by @ai-sdk/xai yet.
126
+ const xaiVideo15ProviderOptions = [
127
+ { flag: 'resolution', providerKey: 'resolution', description: 'Output resolution (R2V is capped at 720p)', values: ['480p', '720p', '1080p'], defaultValue: '720p', type: 'string' },
128
+ { flag: 'mode', providerKey: 'mode', description: 'Video operation mode', values: ['reference-to-video'], type: 'string' },
129
+ { flag: 'reference-images', providerKey: 'referenceImageUrls', description: 'Reference images for R2V (1-14 files or URLs)', type: 'string', array: true },
130
+ ];
131
+ // grok-imagine-video-1.5-lite: T2V/I2V only. 1080p is upscaled from 720p.
132
+ const xaiVideo15LiteProviderOptions = [
133
+ { flag: 'resolution', providerKey: 'resolution', description: 'Output resolution (1080p is upscaled from 720p)', values: ['480p', '720p', '1080p'], defaultValue: '720p', type: 'string' },
134
+ ];
104
135
  // Source: node_modules/@ai-sdk/bytedance/dist/index.d.ts → ByteDanceVideoProviderOptions
105
136
  // Docs: https://sdk.vercel.ai/docs/providers/bytedance
106
137
  const bytedanceVideoProviderOptions = [
@@ -580,6 +611,24 @@ export const CATALOG = [
580
611
  multipleImages: true,
581
612
  },
582
613
  },
614
+ {
615
+ id: 'grok-imagine-image-2.0',
616
+ name: 'Grok Imagine Image 2.0',
617
+ released: '2026-08',
618
+ ...xaiImage,
619
+ providerOptions: xaiImage2ProviderOptions,
620
+ // $0.04 at low quality (what 'auto' serves for generation); medium is $0.06, 2k costs more.
621
+ cost: { type: 'per-image', perImage: 0.04 },
622
+ features: {
623
+ editing: true,
624
+ inpainting: false,
625
+ aspectRatios: ['1:1', '3:4', '4:3', '9:16', '16:9', '2:3', '3:2', '21:9', '5:2'],
626
+ seed: false,
627
+ multipleImages: true,
628
+ },
629
+ },
630
+ // xAI retires grok-imagine-image-quality on 2026-11-02. After that date, requests to
631
+ // this slug are served by grok-imagine-image-2.0 with quality 'low'.
583
632
  {
584
633
  id: 'grok-imagine-image-quality',
585
634
  name: 'Grok Imagine Image Quality',
@@ -688,6 +737,80 @@ export const CATALOG = [
688
737
  multipleImages: true,
689
738
  },
690
739
  },
740
+ {
741
+ id: 'gpt-image-2.5-flare',
742
+ name: 'GPT Image 2.5 Flare',
743
+ description: 'Fastest GPT Image 2.5 model for high-quality everyday generation and editing. ' +
744
+ 'Token rates match gpt-image-2; $0.053 is the medium-quality 1024×1024 estimate.',
745
+ released: '2026-09-08',
746
+ ...openaiImage25,
747
+ // Token-based pricing: $30/1M output image tokens, same rates as gpt-image-2.
748
+ cost: { type: 'per-image', perImage: 0.053 },
749
+ features: {
750
+ editing: true,
751
+ inpainting: true,
752
+ aspectRatios: [],
753
+ sizes: ['1024x1024', '1536x1024', '1024x1536'],
754
+ seed: false,
755
+ multipleImages: true,
756
+ },
757
+ },
758
+ {
759
+ id: 'gpt-image-2.5-sunburst',
760
+ name: 'GPT Image 2.5 Sunburst',
761
+ description: 'Most capable GPT Image 2.5 model, for work where editing precision and reference ' +
762
+ 'fidelity matter most. Slower than Flare. Token rates match gpt-image-2; actual cost ' +
763
+ 'is usually higher because it spends more tokens per image.',
764
+ released: '2026-09-08',
765
+ ...openaiImage25,
766
+ // Token-based pricing: $30/1M output image tokens, same rates as gpt-image-2.
767
+ cost: { type: 'per-image', perImage: 0.053 },
768
+ features: {
769
+ editing: true,
770
+ inpainting: true,
771
+ aspectRatios: [],
772
+ sizes: ['1024x1024', '1536x1024', '1024x1536'],
773
+ seed: false,
774
+ multipleImages: true,
775
+ },
776
+ },
777
+ // GPT Image 2.6 (changelog: https://developers.openai.com/api/docs/changelog, 2026-11-04).
778
+ // Quality levels and pricing are assumed equal to 2.5 until OpenAI's model pages confirm them.
779
+ {
780
+ id: 'gpt-image-2.6-flare',
781
+ name: 'GPT Image 2.6 Flare',
782
+ description: 'Fastest GPT Image 2.6 model for image generation and editing, with adjustable complexity. ' +
783
+ 'Pricing assumed equal to gpt-image-2.5-flare.',
784
+ released: '2026-11-04',
785
+ ...openaiImage25,
786
+ cost: { type: 'per-image', perImage: 0.053 },
787
+ features: {
788
+ editing: true,
789
+ inpainting: true,
790
+ aspectRatios: [],
791
+ sizes: ['1024x1024', '1536x1024', '1024x1536'],
792
+ seed: false,
793
+ multipleImages: true,
794
+ },
795
+ },
796
+ {
797
+ id: 'gpt-image-2.6-sunburst',
798
+ name: 'GPT Image 2.6 Sunburst',
799
+ description: 'Most capable GPT Image 2.6 model, for work where editing precision and reference ' +
800
+ 'fidelity matter most. Slower than Flare. Pricing assumed equal to gpt-image-2.5-sunburst; ' +
801
+ 'actual cost is usually higher because it spends more tokens per image.',
802
+ released: '2026-11-04',
803
+ ...openaiImage25,
804
+ cost: { type: 'per-image', perImage: 0.053 },
805
+ features: {
806
+ editing: true,
807
+ inpainting: true,
808
+ aspectRatios: [],
809
+ sizes: ['1024x1024', '1536x1024', '1024x1536'],
810
+ seed: false,
811
+ multipleImages: true,
812
+ },
813
+ },
691
814
  {
692
815
  id: 'chatgpt-image-latest',
693
816
  name: 'ChatGPT Image',
@@ -1433,25 +1556,55 @@ export const VIDEO_CATALOG = [
1433
1556
  provider: 'xai',
1434
1557
  strategy: 'video',
1435
1558
  released: '2026-05',
1559
+ // Source: https://ai-gateway.vercel.sh/v1/models (spacexai/grok-imagine-video-1.5)
1436
1560
  cost: {
1437
1561
  type: 'per-video-second',
1438
1562
  defaultDurationSec: 5,
1439
1563
  tiers: [
1440
1564
  { resolution: '480p', costPerSecond: 0.08 },
1441
1565
  { resolution: '720p', costPerSecond: 0.14 },
1566
+ { resolution: '1080p', costPerSecond: 0.25 },
1442
1567
  ],
1443
1568
  },
1444
1569
  features: {
1445
- textToVideo: false,
1570
+ textToVideo: true,
1446
1571
  imageToVideo: true,
1447
- capabilities: ['i2v'],
1448
- aspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'],
1449
- resolutions: ['480p', '720p'],
1572
+ capabilities: ['t2v', 'i2v', 'r2v'],
1573
+ aspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3', '21:9', '5:2'],
1574
+ resolutions: ['480p', '720p', '1080p'],
1450
1575
  durationRangeSec: { min: 1, max: 15 },
1451
1576
  seed: false,
1452
1577
  multipleVideos: false,
1453
1578
  },
1454
- providerOptions: xaiVideoProviderOptions,
1579
+ providerOptions: xaiVideo15ProviderOptions,
1580
+ },
1581
+ {
1582
+ id: 'grok-imagine-video-1.5-lite',
1583
+ name: 'Grok Imagine Video 1.5 Lite',
1584
+ provider: 'xai',
1585
+ strategy: 'video',
1586
+ released: '2026-10-08',
1587
+ // Source: https://ai-gateway.vercel.sh/v1/models (spacexai/grok-imagine-video-1.5-lite)
1588
+ cost: {
1589
+ type: 'per-video-second',
1590
+ defaultDurationSec: 5,
1591
+ tiers: [
1592
+ { resolution: '480p', costPerSecond: 0.02 },
1593
+ { resolution: '720p', costPerSecond: 0.03 },
1594
+ { resolution: '1080p', costPerSecond: 0.14 },
1595
+ ],
1596
+ },
1597
+ features: {
1598
+ textToVideo: true,
1599
+ imageToVideo: true,
1600
+ capabilities: ['t2v', 'i2v'],
1601
+ aspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3', '21:9', '5:2'],
1602
+ resolutions: ['480p', '720p', '1080p'],
1603
+ durationRangeSec: { min: 1, max: 15 },
1604
+ seed: false,
1605
+ multipleVideos: false,
1606
+ },
1607
+ providerOptions: xaiVideo15LiteProviderOptions,
1455
1608
  },
1456
1609
  // ── Kling (AI Gateway) ──────────────────────────────────────────────
1457
1610
  // Source: https://ai-gateway.vercel.sh/v1/models (klingai/* entries)
@@ -0,0 +1,97 @@
1
+ import { ValidationError, type GeneratedFile } from './generate.js';
2
+ export declare const MIDJOURNEY_UPSCALE_MODELS: readonly ["midjourney", "midjourney-creative"];
3
+ export declare const DEFAULT_UPSCALE_MODEL = "gpt-image-2.6-sunburst";
4
+ /** GPT Image models that accept custom WIDTHxHEIGHT sizes. */
5
+ export declare const GPT_UPSCALE_MODELS: string[];
6
+ export declare const UPSCALE_MODELS: string[];
7
+ export interface UpscaleImageOptions {
8
+ image: Uint8Array;
9
+ model?: string;
10
+ /** Target scale factor. GPT Image: default is the largest size it supports. Midjourney: always 2. */
11
+ scale?: number;
12
+ /** Extra instructions appended to the upscale prompt (GPT), or the job prompt (Midjourney). */
13
+ prompt?: string;
14
+ }
15
+ export interface UpscaleImageResult {
16
+ image: GeneratedFile;
17
+ model: string;
18
+ input: {
19
+ width: number;
20
+ height: number;
21
+ };
22
+ output: {
23
+ width: number;
24
+ height: number;
25
+ };
26
+ /** Exact prompt sent to the model. */
27
+ prompt?: string;
28
+ /** Number of GPT Image calls (tiles) blended into the output. */
29
+ tiles?: number;
30
+ /** Midjourney upscale job ID. */
31
+ jobId?: string;
32
+ /** Set when the provider returned a smaller image than requested. */
33
+ warning?: string;
34
+ cost: number | null;
35
+ }
36
+ /**
37
+ * Pick the GPT Image output size for an upscale: the input scaled by `scale`
38
+ * (or as large as allowed), snapped to multiples of 16, inside the model limits,
39
+ * keeping the aspect ratio as close as the 16px grid allows.
40
+ */
41
+ export declare function gptUpscaleSize({ width, height, scale, }: {
42
+ width: number;
43
+ height: number;
44
+ scale?: number;
45
+ }): ValidationError | {
46
+ width: number;
47
+ height: number;
48
+ };
49
+ /**
50
+ * Prompt for GPT Image upscales. Structure from the common ChatGPT upscale
51
+ * templates: action, keep list, allowed improvements, forbidden changes.
52
+ * See docs/upscale-apis.md for sources.
53
+ */
54
+ export declare function gptUpscalePrompt({ width, height, extra, }: {
55
+ width: number;
56
+ height: number;
57
+ extra?: string;
58
+ }): string;
59
+ export type Tile = {
60
+ x: number;
61
+ y: number;
62
+ width: number;
63
+ height: number;
64
+ };
65
+ /** Split an image into grid x grid tiles that overlap by TILE_OVERLAP of a tile. */
66
+ export declare function planTiles({ width, height, grid }: {
67
+ width: number;
68
+ height: number;
69
+ grid: number;
70
+ }): Tile[];
71
+ /**
72
+ * Smallest grid whose tiles, each returned at `pixelsPerCall`, reach the target
73
+ * width. Stops before tiles get under MIN_TILE_SIDE, where the model sees too
74
+ * little context and invents detail.
75
+ */
76
+ export declare function chooseGrid({ width, height, targetWidth, pixelsPerCall, }: {
77
+ width: number;
78
+ height: number;
79
+ targetWidth: number;
80
+ pixelsPerCall: number;
81
+ }): number;
82
+ /**
83
+ * Blend upscaled RGB tiles (output coordinates) into one image. Each tile is
84
+ * matched to the reference (the input resized to the output size) by
85
+ * per-channel mean and standard deviation, which removes the color drift
86
+ * generative models add, then feathered across the overlaps.
87
+ */
88
+ export declare function blendTiles({ width, height, reference, tiles, }: {
89
+ width: number;
90
+ height: number;
91
+ reference: Uint8Array;
92
+ tiles: Array<Tile & {
93
+ pixels: Uint8Array;
94
+ }>;
95
+ }): Uint8Array;
96
+ export declare function upscaleImageUncached(opts: UpscaleImageOptions): Promise<Error | UpscaleImageResult>;
97
+ //# sourceMappingURL=upscale-generate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upscale-generate.d.ts","sourceRoot":"","sources":["../../src/cli/upscale-generate.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,300 @@
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
+ import sharp from 'sharp';
13
+ import dedent from 'string-dedent';
14
+ import { generateImageUncached, ValidationError } from './generate.js';
15
+ import { CATALOG } from './model-catalog.js';
16
+ import { shouldUseChatGptBackend } from './credentials.js';
17
+ export const MIDJOURNEY_UPSCALE_MODELS = ['midjourney', 'midjourney-creative'];
18
+ export const DEFAULT_UPSCALE_MODEL = 'gpt-image-2.6-sunburst';
19
+ /** GPT Image models that accept custom WIDTHxHEIGHT sizes. */
20
+ export const GPT_UPSCALE_MODELS = CATALOG
21
+ .map((m) => m.id)
22
+ .filter((id) => id.startsWith('gpt-image-2'));
23
+ export const UPSCALE_MODELS = [...GPT_UPSCALE_MODELS, ...MIDJOURNEY_UPSCALE_MODELS];
24
+ // https://developers.openai.com/api/docs/guides/image-generation#size-and-quality-options
25
+ const GPT_SIZE_MULTIPLE = 16;
26
+ const GPT_MAX_EDGE = 3840;
27
+ const GPT_MIN_PIXELS = 655_360;
28
+ const GPT_MAX_PIXELS = 8_294_400;
29
+ const GPT_MAX_RATIO = 3;
30
+ /**
31
+ * Pick the GPT Image output size for an upscale: the input scaled by `scale`
32
+ * (or as large as allowed), snapped to multiples of 16, inside the model limits,
33
+ * keeping the aspect ratio as close as the 16px grid allows.
34
+ */
35
+ export function gptUpscaleSize({ width, height, scale, }) {
36
+ const ratio = width / height;
37
+ if (Math.max(ratio, 1 / ratio) > GPT_MAX_RATIO) {
38
+ return new ValidationError(`GPT Image supports aspect ratios up to ${GPT_MAX_RATIO}:1. The input is ${width}x${height}.`);
39
+ }
40
+ if (scale !== undefined && !(scale > 1)) {
41
+ return new ValidationError(`Scale must be greater than 1, got ${scale}.`);
42
+ }
43
+ const area = width * height;
44
+ const targetArea = scale === undefined ? GPT_MAX_PIXELS : area * scale * scale;
45
+ // Try every long edge on the 16px grid, keep the valid size closest in area to the target.
46
+ const landscape = width >= height;
47
+ const longRatio = landscape ? ratio : 1 / ratio;
48
+ let best;
49
+ for (let long = GPT_SIZE_MULTIPLE; long <= GPT_MAX_EDGE; long += GPT_SIZE_MULTIPLE) {
50
+ const short = Math.max(GPT_SIZE_MULTIPLE, Math.round(long / longRatio / GPT_SIZE_MULTIPLE) * GPT_SIZE_MULTIPLE);
51
+ const pixels = long * short;
52
+ if (pixels < GPT_MIN_PIXELS || pixels > GPT_MAX_PIXELS || long / short > GPT_MAX_RATIO)
53
+ continue;
54
+ if (!best || Math.abs(pixels - targetArea) < Math.abs(best.width * best.height - targetArea)) {
55
+ best = landscape ? { width: long, height: short } : { width: short, height: long };
56
+ }
57
+ }
58
+ if (!best || best.width * best.height <= area) {
59
+ return new ValidationError(`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.`);
60
+ }
61
+ return best;
62
+ }
63
+ /**
64
+ * Prompt for GPT Image upscales. Structure from the common ChatGPT upscale
65
+ * templates: action, keep list, allowed improvements, forbidden changes.
66
+ * See docs/upscale-apis.md for sources.
67
+ */
68
+ export function gptUpscalePrompt({ width, height, extra, }) {
69
+ const prompt = dedent `
70
+ 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.
71
+
72
+ 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.
73
+
74
+ 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.
75
+
76
+ 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.
77
+ `;
78
+ return extra?.trim() ? `${prompt}\n\nAdditional instructions: ${extra.trim()}` : prompt;
79
+ }
80
+ // The ChatGPT subscription backend ignores `size` and `quality` and returns about
81
+ // 1536x1024 worth of pixels in the input aspect ratio (verified Nov 2026, see
82
+ // docs/chatgpt-codex-image-backend.md). To reach the target size there, the
83
+ // input is split into overlapping tiles, each tile is upscaled, then blended.
84
+ const CHATGPT_MAX_PIXELS = 1536 * 1024;
85
+ const MAX_GRID = 4;
86
+ const TILE_OVERLAP = 0.2;
87
+ const MIN_TILE_SIDE = 192;
88
+ /** Split an image into grid x grid tiles that overlap by TILE_OVERLAP of a tile. */
89
+ export function planTiles({ width, height, grid }) {
90
+ const tileWidth = Math.round(width / (grid - (grid - 1) * TILE_OVERLAP));
91
+ const tileHeight = Math.round(height / (grid - (grid - 1) * TILE_OVERLAP));
92
+ const offsets = (size, tile) => Array.from({ length: grid }, (_, i) => (grid === 1 ? 0 : Math.round((i * (size - tile)) / (grid - 1))));
93
+ return offsets(height, tileHeight).flatMap((y) => offsets(width, tileWidth).map((x) => ({ x, y, width: tileWidth, height: tileHeight })));
94
+ }
95
+ /**
96
+ * Smallest grid whose tiles, each returned at `pixelsPerCall`, reach the target
97
+ * width. Stops before tiles get under MIN_TILE_SIDE, where the model sees too
98
+ * little context and invents detail.
99
+ */
100
+ export function chooseGrid({ width, height, targetWidth, pixelsPerCall, }) {
101
+ let grid = 1;
102
+ while (grid < MAX_GRID) {
103
+ const tile = planTiles({ width, height, grid })[0];
104
+ if (width * Math.sqrt(pixelsPerCall / (tile.width * tile.height)) >= targetWidth)
105
+ return grid;
106
+ const next = planTiles({ width, height, grid: grid + 1 })[0];
107
+ if (Math.min(next.width, next.height) < MIN_TILE_SIDE)
108
+ return grid;
109
+ grid++;
110
+ }
111
+ return grid;
112
+ }
113
+ /**
114
+ * Blend upscaled RGB tiles (output coordinates) into one image. Each tile is
115
+ * matched to the reference (the input resized to the output size) by
116
+ * per-channel mean and standard deviation, which removes the color drift
117
+ * generative models add, then feathered across the overlaps.
118
+ */
119
+ export function blendTiles({ width, height, reference, tiles, }) {
120
+ const sum = new Float32Array(width * height * 3);
121
+ const weight = new Float32Array(width * height);
122
+ for (const tile of tiles) {
123
+ const count = tile.width * tile.height;
124
+ const channelStats = (read) => [0, 1, 2].map((c) => {
125
+ let total = 0;
126
+ let squares = 0;
127
+ for (let p = 0; p < count; p++) {
128
+ const v = read(p, c);
129
+ total += v;
130
+ squares += v * v;
131
+ }
132
+ const mean = total / count;
133
+ return { mean, std: Math.sqrt(Math.max(1, squares / count - mean * mean)) };
134
+ });
135
+ const target = channelStats((p, c) => reference[((tile.y + Math.floor(p / tile.width)) * width + tile.x + (p % tile.width)) * 3 + c]);
136
+ const actual = channelStats((p, c) => tile.pixels[p * 3 + c]);
137
+ // weights ramp to 0 only on sides that overlap a neighbor tile
138
+ const rampX = tile.width * TILE_OVERLAP;
139
+ const rampY = tile.height * TILE_OVERLAP;
140
+ for (let py = 0; py < tile.height; py++) {
141
+ const top = tile.y > 0 ? py / rampY : 1;
142
+ const bottom = tile.y + tile.height < height ? (tile.height - 1 - py) / rampY : 1;
143
+ for (let px = 0; px < tile.width; px++) {
144
+ const left = tile.x > 0 ? px / rampX : 1;
145
+ const right = tile.x + tile.width < width ? (tile.width - 1 - px) / rampX : 1;
146
+ const w = Math.max(1e-4, Math.min(1, top, bottom, left, right));
147
+ const o = (tile.y + py) * width + tile.x + px;
148
+ for (let c = 0; c < 3; c++) {
149
+ const v = tile.pixels[(py * tile.width + px) * 3 + c];
150
+ sum[o * 3 + c] += (((v - actual[c].mean) / actual[c].std) * target[c].std + target[c].mean) * w;
151
+ }
152
+ weight[o] += w;
153
+ }
154
+ }
155
+ }
156
+ const out = new Uint8Array(width * height * 3);
157
+ for (let o = 0; o < width * height; o++) {
158
+ for (let c = 0; c < 3; c++)
159
+ out[o * 3 + c] = Math.max(0, Math.min(255, Math.round(sum[o * 3 + c] / weight[o])));
160
+ }
161
+ return out;
162
+ }
163
+ // sharp and @egaki/midjourney reject with Error instances
164
+ const toError = (err) => err;
165
+ async function readImageSize(bytes) {
166
+ const meta = await sharp(bytes).metadata().catch(toError);
167
+ if (meta instanceof Error)
168
+ return new ValidationError(`Could not read the image: ${meta.message}`);
169
+ return meta.autoOrient;
170
+ }
171
+ export async function upscaleImageUncached(opts) {
172
+ const model = opts.model ?? DEFAULT_UPSCALE_MODEL;
173
+ if (model === 'midjourney' || model === 'midjourney-creative') {
174
+ if (opts.scale !== undefined && opts.scale !== 2) {
175
+ return new ValidationError('Midjourney only upscales 2x. Remove --scale or pass --scale 2.');
176
+ }
177
+ const input = await readImageSize(opts.image);
178
+ if (input instanceof Error)
179
+ return input;
180
+ return upscaleWithMidjourney({ image: opts.image, model, input, prompt: opts.prompt });
181
+ }
182
+ if (!GPT_UPSCALE_MODELS.includes(model)) {
183
+ return new ValidationError(`Model ${model} cannot upscale. Use one of: ${UPSCALE_MODELS.join(', ')}`);
184
+ }
185
+ return upscaleWithGpt({ image: opts.image, model, scale: opts.scale, extra: opts.prompt });
186
+ }
187
+ async function upscaleWithGpt(opts) {
188
+ const decoded = await sharp(opts.image)
189
+ .autoOrient()
190
+ .removeAlpha()
191
+ .toColourspace('srgb')
192
+ .raw()
193
+ .toBuffer({ resolveWithObject: true })
194
+ .catch(toError);
195
+ if (decoded instanceof Error)
196
+ return new ValidationError(`Could not read the image: ${decoded.message}`);
197
+ const input = { width: decoded.info.width, height: decoded.info.height };
198
+ const raw = { raw: { width: input.width, height: input.height, channels: 3 } };
199
+ const size = gptUpscaleSize({ ...input, scale: opts.scale });
200
+ if (size instanceof Error)
201
+ return size;
202
+ // with an API key one call returns the full size; ChatGPT login needs tiles
203
+ const grid = shouldUseChatGptBackend()
204
+ ? chooseGrid({ ...input, targetWidth: size.width, pixelsPerCall: CHATGPT_MAX_PIXELS })
205
+ : 1;
206
+ const tiles = planTiles({ ...input, grid });
207
+ const sx = size.width / input.width;
208
+ const sy = size.height / input.height;
209
+ const extra = grid > 1
210
+ ? ['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(' ')
211
+ : opts.extra;
212
+ const reference = await sharp(decoded.data, raw)
213
+ .resize(size.width, size.height, { fit: 'fill', kernel: 'lanczos3' })
214
+ .raw()
215
+ .toBuffer();
216
+ const prompts = [];
217
+ const upscaled = await Promise.all(tiles.map(async (tile) => {
218
+ const x = Math.round(tile.x * sx);
219
+ const y = Math.round(tile.y * sy);
220
+ const box = { x, y, width: Math.round((tile.x + tile.width) * sx) - x, height: Math.round((tile.y + tile.height) * sy) - y };
221
+ const crop = await sharp(decoded.data, raw)
222
+ .extract({ left: tile.x, top: tile.y, width: tile.width, height: tile.height })
223
+ .png()
224
+ .toBuffer();
225
+ const prompt = gptUpscalePrompt({ width: box.width, height: box.height, extra });
226
+ prompts.push(prompt);
227
+ const request = () => generateImageUncached({
228
+ prompt,
229
+ model: opts.model,
230
+ inputImages: [new Uint8Array(crop)],
231
+ // the ChatGPT backend ignores size; only send it when it is a valid API size
232
+ size: grid === 1 ? `${box.width}x${box.height}` : undefined,
233
+ quality: 'high',
234
+ });
235
+ // one retry: with many parallel tiles a single transient failure is likely
236
+ let result = await request();
237
+ if (result instanceof Error && !(result instanceof ValidationError))
238
+ result = await request();
239
+ if (result instanceof Error)
240
+ return result;
241
+ const file = result.images[0];
242
+ if (!file)
243
+ return new Error('GPT Image returned no image.');
244
+ const returned = await sharp(file.uint8Array).metadata().catch(toError);
245
+ if (returned instanceof Error)
246
+ return returned;
247
+ const pixels = await sharp(file.uint8Array)
248
+ .removeAlpha()
249
+ .resize(box.width, box.height, { fit: 'fill', kernel: 'lanczos3' })
250
+ .raw()
251
+ .toBuffer()
252
+ .catch(toError);
253
+ if (pixels instanceof Error)
254
+ return pixels;
255
+ return { ...box, pixels, returned: { width: returned.width, height: returned.height }, cost: result.cost };
256
+ }));
257
+ const done = [];
258
+ for (const tile of upscaled) {
259
+ if (tile instanceof Error)
260
+ return tile;
261
+ done.push(tile);
262
+ }
263
+ const pixels = blendTiles({ ...size, reference, tiles: done });
264
+ const png = await sharp(pixels, { raw: { ...size, channels: 3 } }).png().toBuffer();
265
+ const small = done.find((tile) => tile.returned.width * tile.returned.height < tile.width * tile.height * 0.9);
266
+ const costs = done.map((tile) => tile.cost);
267
+ return {
268
+ image: { uint8Array: new Uint8Array(png), mediaType: 'image/png' },
269
+ model: opts.model,
270
+ input,
271
+ output: size,
272
+ tiles: tiles.length,
273
+ prompt: prompts[0],
274
+ warning: small
275
+ ? `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.`
276
+ : undefined,
277
+ cost: costs.every((cost) => cost !== null) ? costs.reduce((a, b) => a + b, 0) : null,
278
+ };
279
+ }
280
+ async function upscaleWithMidjourney(opts) {
281
+ const { Midjourney } = await import('@egaki/midjourney');
282
+ const mj = new Midjourney();
283
+ const result = await mj
284
+ .upscaleImage(Buffer.from(opts.image), {
285
+ type: opts.model === 'midjourney-creative' ? 'v7_2x_creative' : 'v7_2x_subtle',
286
+ prompt: opts.prompt,
287
+ })
288
+ .catch(toError);
289
+ await mj.close().catch(() => { });
290
+ if (result instanceof Error)
291
+ return result;
292
+ return {
293
+ image: { uint8Array: new Uint8Array(result.image), mediaType: 'image/jpeg' },
294
+ model: opts.model,
295
+ input: opts.input,
296
+ output: { width: result.width, height: result.height },
297
+ jobId: result.upscaleJobId,
298
+ cost: null,
299
+ };
300
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=upscale-generate.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upscale-generate.test.d.ts","sourceRoot":"","sources":["../../src/cli/upscale-generate.test.ts"],"names":[],"mappings":""}