@makemidas/cli 0.3.1 → 0.5.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/dist/cli.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { Api, KINDS } from "./api.js";
3
- import { audioInput, compareModels, compareOptions, editInput, filmSeconds, filmSettings, feedbackKind, generationInput, intOption, parse, sourceArg, transcriptionInput, usageError, } from "./args.js";
3
+ import { audioInput, compareModels, compareOptions, editInput, filmSeconds, filmSettings, feedbackKind, generationInput, intOption, parse, renderBrand, renderOptions, sourceArg, templateValues, transcriptionInput, usageError, } from "./args.js";
4
4
  import * as commands from "./commands.js";
5
+ import { filmEdit } from "./film-edit.js";
5
6
  import * as films from "./films.js";
7
+ import * as templates from "./templates.js";
6
8
  import { resolveBaseUrl, VERSION } from "./config.js";
7
9
  import { CliError, EXIT, formatError } from "./errors.js";
8
10
  import { setQuiet } from "./output.js";
9
- const HELP = `makemidas ${VERSION}: AI images, videos, audio, transcripts and edits from the terminal, with your MakeMidas credits
11
+ const HELP = `makemidas ${VERSION}: AI images, videos, audio, transcripts, edits, templates and short films from the terminal, with your MakeMidas credits
10
12
 
11
13
  Usage:
12
14
  makemidas auth login [--no-browser] Sign in (opens the browser)
@@ -21,6 +23,8 @@ Usage:
21
23
  makemidas remove-bg <image> Remove the background (transparent WebP)
22
24
  makemidas upscale <image> Upscale an image (--scale 1|2|4|8)
23
25
  makemidas upscale-video <video> Upscale a clip (--resolution 1080P|2K|4K)
26
+ makemidas avatar <photo> <voice> Lip-sync a portrait to a voice track (a talking
27
+ avatar); --character <id> in place of the photo
24
28
  makemidas compare "<prompt>" --models a,b[,c,d]
25
29
  One prompt on 2-4 image models
26
30
  makemidas get <id> Fetch a generation (and save its files)
@@ -29,19 +33,37 @@ Usage:
29
33
  makemidas brands [<id>|default] Saved brands, or one brand's guidelines
30
34
  makemidas characters Saved characters
31
35
  makemidas assets [--q words] [--kind image|video|audio]
32
- Files in the asset library
36
+ Search the asset library
37
+ makemidas assets upload <file|url>… Keep files in the asset library (--name, --tag)
38
+ makemidas assets delete <id> [--yes] Remove a file from the library
33
39
  makemidas credits Credit balance and plan
34
40
  makemidas credits buy Links and prices for plans and credit packs
35
41
  makemidas estimate <command> "<prompt>|<file>"
36
42
  Price a request without charging: image,
37
43
  video, music, sfx, speech, transcribe,
38
- remove-bg, upscale or upscale-video
44
+ remove-bg, upscale, upscale-video or avatar
39
45
  makemidas models [<kind>] Models, options and credit prices; kind is
40
46
  image, video, audio, transcription or edit
41
47
  makemidas models <id> One model: options, defaults, prices
42
48
  makemidas feedback "<message>" Send feedback (--kind bug|feature|praise|other,
43
49
  --generation <id>)
44
50
 
51
+ HTML templates (exact text: OG images, quote cards, lower thirds, title cards;
52
+ the first renders each day are free, then 1 credit an image; videos cost
53
+ 1 credit per started 5 seconds):
54
+ makemidas templates [<category>] Built-in and saved templates (social, web,
55
+ promo, video, custom) and free renders left
56
+ makemidas template <id> One template: sizes, video, its --set fields
57
+ makemidas render <id> --set f=v… Fill a template and save the image (--video
58
+ for an animated one)
59
+ makemidas html <page.html|-> Render your own HTML and CSS to an image, or
60
+ with --video its CSS animations to a video
61
+ makemidas template save <page.html> --name <name> [--fields fields.json]
62
+ Keep a page as a template with fill-in fields
63
+ makemidas template update <id> [<page.html>]
64
+ Change a saved template
65
+ makemidas template delete <id> [--yes]
66
+
45
67
  Film projects (a brief → script and storyboard → frames → clips, voiceover
46
68
  and music → one film; each paid stage is approved at the credits shown):
47
69
  makemidas film new "<brief>" Create a project and write its storyboard
@@ -61,6 +83,9 @@ and music → one film; each paid stage is approved at the credits shown):
61
83
  makemidas film download <id> [--pieces]
62
84
  The film, or every clip, voiceover and the
63
85
  music with timeline.json to cut it yourself
86
+ makemidas film edit <id> A HyperFrames project of the finished film
87
+ (word-by-word captions, slow push-ins) to
88
+ render and edit on this computer, free
64
89
  makemidas film delete <id> [--yes] Delete the project (its generations stay)
65
90
 
66
91
  Generation options (image, video, estimate):
@@ -103,6 +128,35 @@ Transcribe and edit options:
103
128
  --scale <n> upscale: 1 (sharpen), 2 (default), 4 or 8
104
129
  -r, --resolution <r> upscale-video: 1080P, 2K (default) or 4K
105
130
 
131
+ Avatar options:
132
+ -m, --model <id> kie/infinitetalk or kwaivgi/kling-ai-avatar (default:
133
+ the first on sale; see \`makemidas models edit\`)
134
+ -r, --resolution <r> 480p or 720p (default: the model's smallest)
135
+ --direction <words> Expression and movement, e.g. "smiles, nods once"
136
+ --character <id> A saved character's portrait instead of a photo
137
+ The voice track (MP3, WAV, M4A, AAC or OGG, up to 5 minutes) is spoken as
138
+ given; make one first with \`makemidas speech\`. Billed per second of it.
139
+
140
+ Template and HTML options (render, html):
141
+ --set <field>=<value> Repeat per field. Text as written; images as
142
+ asset:<id>, generation:<id>[/<n>], background:<id>,
143
+ brand-image:<id>, or a local JPG/PNG/WebP (kept in
144
+ the asset library); empty clears the field
145
+ --size <id> square, portrait, story, landscape or og
146
+ --width, --height <px> A custom size, 200-2048 (videos: even, up to 1920)
147
+ --scale 1|2 Image pixel density
148
+ --format <f> png or webp; with --video, mp4 or mov (mov keeps
149
+ a transparent template's alpha)
150
+ --brand <id|none> render: the brand's colors, fonts and logo
151
+ (default: your default brand)
152
+ --css <file> html: a stylesheet; --transparent keeps unpainted
153
+ areas transparent
154
+ --video Render a video; --seconds 2-15, --matte #rrggbb
155
+ behind a transparent page in an MP4
156
+ Saved templates: --name, --description, --fields fields.json (text, color,
157
+ image or choice fields that fill data-var-text, data-var-src, --<id> CSS
158
+ variables and data-<id> attributes), --width and --height (the canvas)
159
+
106
160
  Compare options:
107
161
  --models <a,b,…> 2-4 different image model ids
108
162
  -a, --aspect, --ref, --max-credits, --quoted-credits as for image
@@ -131,6 +185,17 @@ Film options:
131
185
  --speech-model <id>, --voice <id|default>
132
186
  --music-model <id|none>, --music-prompt <words>
133
187
  --transition cut|fade|crossfade, --clip-audio, --brand <id|none>
188
+ --style film|social social: a short vertical video written to stop the
189
+ scroll (9:16, about 15 s, subtitles on by default)
190
+ --subtitles on|off Burn the voiceover in as subtitles
191
+ --title-card, --end-card on|off|"<title>"
192
+ Open or close with an animated template card
193
+ --lower-thirds on|off Each speaker's name the first time they speak
194
+ --characters <id,…|none>
195
+ Cast (up to 4 saved characters); a shot with
196
+ "type": "talking" in --file has its character say
197
+ the line to camera, lip-synced
198
+ --avatar-model <id> The talking avatar model for talking shots
134
199
  --no-write film new: create it without writing the storyboard
135
200
  --file <shots.json> film update: the whole storyboard, in order
136
201
  --max-credits <n> Charge the step's price only if it is at most n
@@ -153,6 +218,11 @@ Examples:
153
218
  makemidas compare "a red fox in snow" --models a/one,b/two --max-credits 40
154
219
  makemidas models google/gemini-omni-flash
155
220
  makemidas film new "A 20-second ad for our cold brew" --max-credits 40
221
+ makemidas film new "Why our mugs never chip" --style social --max-credits 30
222
+ makemidas avatar host.png line.mp3 -r 720p --max-credits 40
223
+ makemidas render quote-card --set quote="Make it simple." --set author=Ada
224
+ makemidas html card.html --css card.css --size og
225
+ makemidas html intro.html --video --seconds 6
156
226
  makemidas film approve <id> frames --quoted-credits 10 --wait
157
227
 
158
228
  Credentials: \`auth login\`, or MAKEMIDAS_API_KEY (Settings → API keys).
@@ -178,6 +248,33 @@ function editTask(command) {
178
248
  return 'upscale-image';
179
249
  return 'upscale-video';
180
250
  }
251
+ /** `avatar <photo> <voice>`, or `avatar <voice> --character <id>`. */
252
+ function avatarSources(rest, character, command) {
253
+ if (character) {
254
+ if (rest.length !== 1) {
255
+ throw usageError(`With --character, give only the voice track: \`makemidas ${command} line.mp3 --character <id>\`.`);
256
+ }
257
+ return [undefined, rest[0]];
258
+ }
259
+ if (rest.length !== 2) {
260
+ throw usageError(`Give a portrait and a voice track: \`makemidas ${command} face.png line.mp3\` (make the track with \`makemidas speech\`).`);
261
+ }
262
+ return [rest[0], rest[1]];
263
+ }
264
+ /** Name, description and canvas of a saved template, from the options. */
265
+ function savedTemplateRest(v) {
266
+ const width = intOption(v.width, 'width', 200, 2048);
267
+ const height = intOption(v.height, 'height', 200, 2048);
268
+ if ((width === undefined) !== (height === undefined)) {
269
+ throw usageError('Give --width and --height together.');
270
+ }
271
+ return {
272
+ ...(v.name ? { name: v.name } : {}),
273
+ ...(v.description !== undefined ? { description: v.description } : {}),
274
+ ...(width !== undefined ? { width, height } : {}),
275
+ ...(v.transparent ? { transparent: true } : {}),
276
+ };
277
+ }
181
278
  async function main(argv) {
182
279
  const { values: v, positionals } = parse(argv);
183
280
  setQuiet(v.quiet);
@@ -220,6 +317,57 @@ async function main(argv) {
220
317
  const { input, format } = transcriptionInput(v);
221
318
  return commands.transcribe(api, g, input, source, format, save, wait, maxCredits(v));
222
319
  }
320
+ case 'avatar':
321
+ case 'talking-avatar': {
322
+ const input = editInput('talking-avatar', v);
323
+ const [photo, voice] = avatarSources(rest, Boolean(v.character), command);
324
+ return commands.generate(api, g, input, photo ? [photo] : [], save, wait, maxCredits(v), { kind: 'voice', source: voice });
325
+ }
326
+ case 'templates':
327
+ if (rest.length > 1)
328
+ throw usageError('Use `templates [<category>]`.');
329
+ return templates.templatesList(api, g, rest[0] ?? v.kind);
330
+ case 'template': {
331
+ const [sub, ...args] = rest;
332
+ const deleteOpts = { yes: v.yes, interactive: Boolean(process.stdin.isTTY) };
333
+ switch (sub) {
334
+ case 'save':
335
+ case 'new':
336
+ return templates.templateSave(api, g, await templates.savedTemplateInput({ html: args[0], css: v.css, fields: v.fields }, savedTemplateRest(v)));
337
+ case 'update':
338
+ return templates.templateUpdate(api, g, args[0], await templates.savedTemplateInput({ html: args[1], css: v.css, fields: v.fields }, savedTemplateRest(v)));
339
+ case 'delete':
340
+ return templates.templateDelete(api, g, args[0], deleteOpts);
341
+ case 'list':
342
+ case undefined:
343
+ return templates.templatesList(api, g, args[0]);
344
+ default:
345
+ return templates.templateShow(api, g, sub);
346
+ }
347
+ }
348
+ case 'render': {
349
+ if (rest.length !== 1) {
350
+ throw usageError('Give one template id: `makemidas render quote-card --set quote="…"`.');
351
+ }
352
+ const { values, files } = templateValues(v.set);
353
+ return templates.render(api, g, {
354
+ input: templates.templateRender(rest[0], values, renderOptions(v), renderBrand(v.brand)),
355
+ files,
356
+ video: v.video,
357
+ }, save, wait);
358
+ }
359
+ case 'html': {
360
+ if (rest.length !== 1) {
361
+ throw usageError('Give one HTML file (or - for stdin): `makemidas html page.html`.');
362
+ }
363
+ if (v.set.length || v.brand) {
364
+ throw usageError('--set and --brand are for templates; your own page renders as written.');
365
+ }
366
+ return templates.render(api, g, {
367
+ input: await templates.htmlRender(rest[0], v.css, v.transparent, renderOptions(v)),
368
+ video: v.video,
369
+ }, save, wait);
370
+ }
223
371
  case 'remove-bg':
224
372
  case 'upscale':
225
373
  case 'upscale-video': {
@@ -273,6 +421,20 @@ async function main(argv) {
273
421
  case 'characters':
274
422
  return commands.characters(api, g);
275
423
  case 'assets':
424
+ if (rest[0] === 'upload' || rest[0] === 'add') {
425
+ return templates.assetUpload(api, g, rest.slice(1), {
426
+ ...(v.name ? { name: v.name } : {}),
427
+ tags: v.tag,
428
+ });
429
+ }
430
+ if (rest[0] === 'delete' || rest[0] === 'rm') {
431
+ if (rest.length > 2)
432
+ throw usageError('Delete one asset at a time.');
433
+ return templates.assetDelete(api, g, rest[1], {
434
+ yes: v.yes,
435
+ interactive: Boolean(process.stdin.isTTY),
436
+ });
437
+ }
276
438
  return commands.assets(api, g, {
277
439
  q: v.q ?? (rest.join(' ') || undefined),
278
440
  kind: v.kind,
@@ -305,6 +467,11 @@ async function main(argv) {
305
467
  source,
306
468
  });
307
469
  }
470
+ case 'avatar':
471
+ case 'talking-avatar': {
472
+ const [photo, voice] = avatarSources(args, Boolean(v.character), `estimate ${kind}`);
473
+ return commands.estimate(api, g, editInput('talking-avatar', v), photo ? [photo] : [], 'avatar', { kind: 'voice', source: voice });
474
+ }
308
475
  case 'remove-bg':
309
476
  case 'upscale':
310
477
  case 'upscale-video': {
@@ -316,7 +483,7 @@ async function main(argv) {
316
483
  : commands.estimate(api, g, input, [source], kind);
317
484
  }
318
485
  default:
319
- throw usageError('Use `estimate <command> …` with image, video, music, sfx, speech, transcribe, remove-bg, upscale or upscale-video.');
486
+ throw usageError('Use `estimate <command> …` with image, video, music, sfx, speech, transcribe, remove-bg, upscale, upscale-video or avatar.');
320
487
  }
321
488
  }
322
489
  case 'models': {
@@ -378,13 +545,15 @@ async function main(argv) {
378
545
  return films.filmAssemble(api, g, id, save, filmWait);
379
546
  case 'download':
380
547
  return films.filmDownload(api, g, id, save, { pieces: v.pieces });
548
+ case 'edit':
549
+ return filmEdit(api, g, films.need(id, 'a film id: `makemidas film edit <id>`'), { ...save, out: save.out ?? '.' });
381
550
  case 'delete':
382
551
  return films.filmDelete(api, g, id, {
383
552
  yes: v.yes,
384
553
  interactive: Boolean(process.stdin.isTTY),
385
554
  });
386
555
  default:
387
- throw usageError('Use `film new`, `list`, `get`, `write`, `update`, `approve`, `redo`, `resume`, `assemble`, `download` or `delete`.');
556
+ throw usageError('Use `film new`, `list`, `get`, `write`, `update`, `approve`, `redo`, `resume`, `assemble`, `download`, `edit` or `delete`.');
388
557
  }
389
558
  }
390
559
  default:
package/dist/commands.js CHANGED
@@ -84,7 +84,7 @@ export async function authLogout(api, g) {
84
84
  print(removed ? 'Signed out.' : 'Not signed in.');
85
85
  }
86
86
  /** Save every finished output into `dir`; returns the file paths. */
87
- async function saveOutputs(api, generation, save) {
87
+ export async function saveOutputs(api, generation, save) {
88
88
  if (!save.out)
89
89
  return [];
90
90
  const dir = resolve(save.out);
@@ -102,7 +102,7 @@ async function saveOutputs(api, generation, save) {
102
102
  return files;
103
103
  }
104
104
  /** Keep asking for a running generation until it finishes or time runs out. */
105
- async function waitFor(api, generation, timeoutMin) {
105
+ export async function waitFor(api, generation, timeoutMin) {
106
106
  const deadline = Date.now() + timeoutMin * 60_000;
107
107
  let current = generation;
108
108
  while (current.status === 'running' && Date.now() < deadline) {
@@ -111,7 +111,7 @@ async function waitFor(api, generation, timeoutMin) {
111
111
  }
112
112
  return current;
113
113
  }
114
- function report(g, generation, files, links = generation.outputs.flatMap((o) => (o.url ? [o.url] : []))) {
114
+ export function report(g, generation, files, links = generation.outputs.flatMap((o) => (o.url ? [o.url] : []))) {
115
115
  if (g.json) {
116
116
  printJson({ ...generation, files });
117
117
  }
package/dist/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- export const VERSION = '0.3.1';
4
+ export const VERSION = '0.5.0';
5
5
  export const USER_AGENT = `makemidas-cli/${VERSION}`;
6
6
  export const DEFAULT_BASE_URL = 'https://makemidas.com';
7
7
  export function resolveBaseUrl(flag) {
@@ -0,0 +1,280 @@
1
+ import { copyFile, mkdir } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { writeOutput } from "./commands.js";
5
+ import { log, print, printJson } from "./output.js";
6
+ /*
7
+ * `makemidas film edit <id>`: a finished film as a HyperFrames project
8
+ * (https://hyperframes.heygen.com) an agent or a person renders and keeps
9
+ * editing on their own computer. The service sends the edit kit: every
10
+ * clip, voiceover line and the music on one timeline, each line's words
11
+ * with the time each is heard, and caption groups. This writes the pieces
12
+ * under assets/ and an index.html that plays them with a slow push-in on
13
+ * every shot (held shots play slower rather than freeze), captions that pop
14
+ * in a few words at a time with the spoken word lit, and the music under
15
+ * the voice. Nothing here is charged.
16
+ */
17
+ /** The HyperFrames release the project's scripts pin, for repeatable renders. */
18
+ export const HYPERFRAMES_VERSION = '0.10.11';
19
+ const GSAP_URL = 'https://cdn.jsdelivr.net/npm/gsap@3.15.0/dist/gsap.min.js';
20
+ /** The caption look: white words, the spoken one in gold. */
21
+ export const CAPTION_COLORS = { ink: '#ffffff', lit: '#FFC83D' };
22
+ const WIDE = /[⺀-鿿가-힯豈-﫿︰-﹏＀-￯]/;
23
+ const EXT = {
24
+ 'video/mp4': 'mp4',
25
+ 'video/quicktime': 'mov',
26
+ 'audio/mpeg': 'mp3',
27
+ 'audio/wav': 'wav',
28
+ 'audio/x-wav': 'wav',
29
+ 'audio/mp4': 'm4a',
30
+ };
31
+ function r(value) {
32
+ return Math.round(value * 1000) / 1000;
33
+ }
34
+ function escapeHtml(text) {
35
+ return text
36
+ .replace(/&/g, '&amp;')
37
+ .replace(/</g, '&lt;')
38
+ .replace(/>/g, '&gt;')
39
+ .replace(/"/g, '&quot;')
40
+ .replace(/'/g, '&#39;');
41
+ }
42
+ /** Where captions sit: clear of the buttons short-video apps draw. */
43
+ function captionBox(width, height) {
44
+ if (width < height) {
45
+ // 9:16: the area TikTok, Reels and Shorts all leave clear.
46
+ return {
47
+ left: Math.round(width * 0.111),
48
+ width: Math.round(width * 0.611),
49
+ bottom: Math.round(height * 0.365),
50
+ size: Math.round(width * 0.08),
51
+ };
52
+ }
53
+ const square = width === height;
54
+ return {
55
+ left: Math.round(width * 0.12),
56
+ width: Math.round(width * 0.76),
57
+ bottom: Math.round(height * (square ? 0.16 : 0.1)),
58
+ size: Math.round(Math.min(width, height) * (square ? 0.075 : 0.065)),
59
+ };
60
+ }
61
+ /** The composition: the film as HyperFrames HTML. Pure. */
62
+ export function compositionHtml(kit, files) {
63
+ const { width: W, height: H } = kit;
64
+ const total = r(kit.seconds);
65
+ const shots = [];
66
+ const tweens = [];
67
+ const crossfade = kit.transition === 'crossfade';
68
+ kit.clips.forEach((clip, i) => {
69
+ const n = i + 1;
70
+ const held = clip.playbackRate < 1;
71
+ const push = held ? 1.1 : 1.06;
72
+ const drift = held ? 0 : [0, -2, 2][i % 3];
73
+ shots.push(`<div class="shot" id="s${n}"><div class="inner" data-layout-allow-overflow>` +
74
+ `<video id="v${n}" class="clip" src="${escapeHtml(files.clips[i])}" ` +
75
+ `data-start="${r(clip.start)}" data-duration="${r(clip.seconds)}" ` +
76
+ `data-playback-rate="${clip.playbackRate}" data-track-index="${n}" ` +
77
+ 'muted playsinline></video></div></div>');
78
+ tweens.push(`tl.fromTo('#s${n} .inner', { scale: 1, xPercent: 0 }, { scale: ${push}, xPercent: ${drift}, duration: ${r(clip.seconds)}, ease: 'none' }, ${r(clip.start)});`);
79
+ if (crossfade && i > 0) {
80
+ const overlap = r(kit.clips[i - 1].start + kit.clips[i - 1].seconds - clip.start);
81
+ if (overlap > 0) {
82
+ tweens.push(`tl.fromTo('#s${n}', { opacity: 0 }, { opacity: 1, duration: ${overlap}, ease: 'none' }, ${r(clip.start)});`);
83
+ }
84
+ }
85
+ });
86
+ const audio = kit.voiceover.map((line, i) => `<audio id="voice${i + 1}" src="${escapeHtml(files.voiceover[i])}" ` +
87
+ `data-start="${r(line.start)}" data-duration="${r(line.seconds)}" ` +
88
+ `data-track-index="${100 + i}" data-volume="1"></audio>`);
89
+ if (kit.music && files.music) {
90
+ const v = kit.music.volume;
91
+ const lane = {
92
+ version: 1,
93
+ lanes: [
94
+ {
95
+ target: 'volume',
96
+ points: [
97
+ { t: 0, v: 0 },
98
+ { t: 0.6, v },
99
+ { t: r(Math.max(0.6, total - 1.2)), v },
100
+ { t: total, v: 0 },
101
+ ],
102
+ },
103
+ ],
104
+ };
105
+ audio.push(`<audio id="music" src="${escapeHtml(files.music)}" data-start="0" ` +
106
+ `data-duration="${total}" data-track-index="99" ` +
107
+ `data-automation='${JSON.stringify(lane)}'></audio>`);
108
+ }
109
+ const box = captionBox(W, H);
110
+ const captions = [];
111
+ kit.captions.forEach((group, g) => {
112
+ const id = `c${g + 1}`;
113
+ const show = r(Math.max(0, group.start - 0.04));
114
+ const hide = r(Math.min(group.end - 0.04, total));
115
+ if (hide <= show)
116
+ return;
117
+ const words = group.words.map((word, w) => {
118
+ const gap = w > 0 &&
119
+ !(WIDE.test(group.words[w - 1].text.slice(-1)) && WIDE.test(word.text[0]))
120
+ ? ' '
121
+ : '';
122
+ const wid = `${id}w${w}`;
123
+ const off = group.words[w + 1]?.start ?? word.end;
124
+ tweens.push(`tl.fromTo('#${wid}', { color: '${CAPTION_COLORS.ink}', scale: 1 }, { color: '${CAPTION_COLORS.lit}', scale: 1.1, duration: 0.07, ease: 'power2.out', immediateRender: false }, ${r(word.start)});`, `tl.fromTo('#${wid}', { color: '${CAPTION_COLORS.lit}', scale: 1.1 }, { color: '${CAPTION_COLORS.ink}', scale: 1, duration: 0.1, ease: 'power2.in', immediateRender: false }, ${r(off)});`);
125
+ return `${gap}<span class="w" id="${wid}">${escapeHtml(word.text)}</span>`;
126
+ });
127
+ captions.push(`<div class="cap clip" id="${id}" data-start="${show}" data-duration="${r(hide - show)}" data-track-index="200">` +
128
+ `<div class="cap-in" data-layout-allow-overlap>${words.join('')}</div></div>`);
129
+ tweens.push(`tl.fromTo('#${id} .cap-in', { scale: 0.72, y: ${Math.round(box.size * 0.28)}, opacity: 0 }, { scale: 1, y: 0, opacity: 1, duration: 0.16, ease: 'back.out(2.2)' }, ${show});`);
130
+ });
131
+ tweens.push(`tl.fromTo('#fade', { opacity: 0 }, { opacity: 1, duration: 0.35, ease: 'none' }, ${r(Math.max(0, total - 0.35))});`);
132
+ const indent = (lines, pad) => lines.map((line) => pad + line).join('\n');
133
+ return `<!doctype html>
134
+ <html lang="en">
135
+ <head>
136
+ <meta charset="UTF-8" />
137
+ <meta name="viewport" content="width=${W}, height=${H}" />
138
+ <title>${escapeHtml(kit.title)}</title>
139
+ <script src="${GSAP_URL}"></script>
140
+ <style>
141
+ @font-face { font-family: 'Inter'; font-weight: 900; src: url('assets/fonts/inter-latin-900-normal.woff2') format('woff2'); }
142
+ * { margin: 0; padding: 0; box-sizing: border-box; }
143
+ html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: #000; }
144
+ #root { position: relative; width: ${W}px; height: ${H}px; }
145
+ .shot, .inner { position: absolute; inset: 0; overflow: hidden; }
146
+ .inner { transform-origin: 50% 40%; }
147
+ .inner video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
148
+ /* Captions: edit the size, colours and place here. */
149
+ .cap { position: absolute; left: ${box.left}px; width: ${box.width}px; bottom: ${box.bottom}px; display: flex; justify-content: center; align-items: flex-end; }
150
+ .cap-in { text-align: center; font-family: 'Inter', sans-serif; font-weight: 900; font-size: ${box.size}px; line-height: 1.1; letter-spacing: -0.01em; color: ${CAPTION_COLORS.ink}; -webkit-text-stroke: ${Math.round(box.size * 0.15)}px #000; paint-order: stroke fill; text-shadow: 0 ${Math.round(box.size * 0.07)}px ${Math.round(box.size * 0.2)}px rgba(0, 0, 0, 0.55); }
151
+ .w { display: inline-block; transform-origin: 50% 70%; margin: 0 0.05em; }
152
+ #fade { position: absolute; inset: 0; background: #000; opacity: 0; }
153
+ </style>
154
+ </head>
155
+ <body>
156
+ <div id="root" data-composition-id="main" data-start="0" data-duration="${total}" data-width="${W}" data-height="${H}">
157
+ ${indent(shots, ' ')}
158
+ ${indent(captions, ' ')}
159
+ <div id="fade"></div>
160
+ ${indent(audio, ' ')}
161
+ </div>
162
+ <script>
163
+ const tl = gsap.timeline({ paused: true });
164
+ ${indent(tweens, ' ')}
165
+ window.__timelines['main'] = tl;
166
+ tl.seek(0);
167
+ </script>
168
+ </body>
169
+ </html>
170
+ `;
171
+ }
172
+ function projectPackage(name) {
173
+ const hf = `npx --yes hyperframes@${HYPERFRAMES_VERSION}`;
174
+ return `${JSON.stringify({
175
+ name,
176
+ private: true,
177
+ type: 'module',
178
+ scripts: {
179
+ check: `${hf} check`,
180
+ preview: `${hf} preview`,
181
+ render: `${hf} render --quality delivery -o renders/film.mp4`,
182
+ },
183
+ }, null, 2)}\n`;
184
+ }
185
+ const HYPERFRAMES_JSON = `${JSON.stringify({
186
+ $schema: 'https://hyperframes.heygen.com/schema/hyperframes.json',
187
+ paths: { assets: 'assets' },
188
+ media: { autoProxy: true },
189
+ }, null, 2)}\n`;
190
+ function readme(kit, dir) {
191
+ return `# ${kit.title}
192
+
193
+ A HyperFrames project of MakeMidas film ${kit.filmId}, made by \`makemidas film edit\`.
194
+
195
+ - \`npm run render\` makes \`renders/film.mp4\` (${kit.width}x${kit.height}, ${kit.seconds}s).
196
+ - \`npm run preview\` opens it in HyperFrames Studio; \`npm run check\` lints it.
197
+ - \`index.html\` is the film: each shot is a \`<video>\` with its start, length
198
+ and playback rate; captions are the \`.cap\` blocks, styled at the top of the
199
+ file; \`kit.json\` holds the timeline and each word's time.
200
+ - Ask your agent for changes in plain words ("bigger captions", "music
201
+ quieter", "cut shot 3 shorter"); the makemidas-film-edit skill knows this
202
+ layout.
203
+
204
+ Made in ${dir}.
205
+ `;
206
+ }
207
+ /** The fonts shipped with the CLI (OFL), for the captions. */
208
+ function fontsDir() {
209
+ return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fonts');
210
+ }
211
+ /**
212
+ * Writes the HyperFrames project for film `id` into `<out>/film-<id>-edit/`
213
+ * and returns its directory and the files written.
214
+ */
215
+ export async function writeEditProject(api, id, save) {
216
+ const kit = await api.filmEditKit(id);
217
+ const dir = resolve(save.out ?? '.', `film-${id.slice(0, 8)}-edit`);
218
+ await mkdir(join(dir, 'assets', 'fonts'), { recursive: true });
219
+ const written = [];
220
+ const fetchTo = async (url, name) => {
221
+ const { bytes, type } = await api.download(url);
222
+ const rel = `assets/${name}.${EXT[type.split(';')[0].trim()] ?? 'bin'}`;
223
+ if (await writeOutput(join(dir, rel), bytes, save.force)) {
224
+ written.push(join(dir, rel));
225
+ }
226
+ return rel;
227
+ };
228
+ log(`Downloading ${kit.clips.length} clips, ${kit.voiceover.length} voiceover lines${kit.music ? ' and the music' : ''}…`);
229
+ const files = { clips: [], voiceover: [], music: null };
230
+ let shot = 0;
231
+ for (const clip of kit.clips) {
232
+ const name = clip.kind === 'title_card'
233
+ ? 'title-card'
234
+ : clip.kind === 'end_card'
235
+ ? 'end-card'
236
+ : `clip-${++shot}`;
237
+ files.clips.push(await fetchTo(clip.url, name));
238
+ }
239
+ for (const [i, line] of kit.voiceover.entries()) {
240
+ files.voiceover.push(await fetchTo(line.url, `voice-${i + 1}`));
241
+ }
242
+ if (kit.music)
243
+ files.music = await fetchTo(kit.music.url, 'music');
244
+ for (const font of ['inter-latin-900-normal.woff2', 'OFL.txt']) {
245
+ await copyFile(join(fontsDir(), font), join(dir, 'assets', 'fonts', font));
246
+ }
247
+ const text = (name, body) => ({ name, body });
248
+ const local = {
249
+ ...kit,
250
+ clips: kit.clips.map(({ url: _url, ...clip }, i) => ({ ...clip, file: files.clips[i] })),
251
+ voiceover: kit.voiceover.map(({ url: _url, ...line }, i) => ({
252
+ ...line,
253
+ file: files.voiceover[i],
254
+ })),
255
+ music: kit.music && files.music ? { volume: kit.music.volume, file: files.music } : null,
256
+ };
257
+ for (const file of [
258
+ text('index.html', compositionHtml(kit, files)),
259
+ text('kit.json', `${JSON.stringify(local, null, 2)}\n`),
260
+ text('package.json', projectPackage(`film-${id.slice(0, 8)}`)),
261
+ text('hyperframes.json', HYPERFRAMES_JSON),
262
+ text('README.md', readme(kit, dir)),
263
+ ]) {
264
+ const path = join(dir, file.name);
265
+ if (await writeOutput(path, new TextEncoder().encode(file.body), save.force)) {
266
+ written.push(path);
267
+ }
268
+ }
269
+ return { dir, files: written, kit };
270
+ }
271
+ export async function filmEdit(api, g, id, save) {
272
+ const { dir, files, kit } = await writeEditProject(api, id, save);
273
+ const next = [`cd ${JSON.stringify(dir)}`, 'npm run render'];
274
+ if (g.json) {
275
+ printJson({ id: kit.filmId, dir, files, seconds: kit.seconds, next });
276
+ return;
277
+ }
278
+ print(dir);
279
+ log(`HyperFrames project ready (${kit.seconds}s, ${kit.captions.length} caption groups). Render it on this computer, free:\n ${next.join('\n ')}\nNeeds Node.js 22+ and FFmpeg; the first render downloads a headless Chrome.`);
280
+ }