@makemidas/cli 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -0
- package/dist/args.js +14 -0
- package/dist/captions.js +212 -0
- package/dist/cli.js +30 -1
- package/dist/config.js +1 -1
- package/dist/cut.js +128 -0
- package/dist/media.js +101 -0
- package/dist/words.js +327 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -61,6 +61,8 @@ makemidas film new "a 15-second social video for our mugs" --style social --max-
|
|
|
61
61
|
| `models [image\|video\|audio\|transcription\|edit] [--for <use>]` | Model ids, options and credit prices; `--for draft\|final\|edit\|text\|references\|first-last\|sound` lists the image and video models good for that job |
|
|
62
62
|
| `models <id>` | One model: options, defaults, voices, prices and an example request |
|
|
63
63
|
| `estimate <command> "<prompt>"\|<file>` | Price a request without charging; `<command>` is `image`, `video`, `music`, `sfx`, `speech`, `transcribe`, `remove-bg`, `upscale`, `upscale-video` or `avatar`, with that command's options |
|
|
64
|
+
| `captions <video> --transcript <t.json> [--max-words n] [--no-render]` | Word-by-word captions burned into a video on your computer (HyperFrames and FFmpeg), the spoken word lit; free ([below](#captions-and-cuts-on-your-computer)) |
|
|
65
|
+
| `cut <video\|audio> --transcript <t.json> --list \| --remove 3,12-18 \| --fillers \| --gaps <s>` | Cut a recording on its words with FFmpeg and write the cut's transcript; free |
|
|
64
66
|
| `frames <video\|url> [--count 1-16] [--width 120-1920]` | Stills evenly spread over a clip and one contact sheet (`<name>-frames/sheet.jpg`), made on your computer with FFmpeg; free, nothing is sent |
|
|
65
67
|
| `feedback "<message>" [--kind bug\|quality\|feature\|praise\|other] [--generation <id>]` | Send feedback to the MakeMidas team (`quality`: a result clearly short of the request) |
|
|
66
68
|
|
|
@@ -121,6 +123,33 @@ or charged twice. Exit 6 after that means it still had no answer: look for
|
|
|
121
123
|
it with `makemidas list` (or `makemidas film get <id>`) before running the
|
|
122
124
|
command again.
|
|
123
125
|
|
|
126
|
+
## Captions and cuts on your computer
|
|
127
|
+
|
|
128
|
+
`captions` and `cut` work on a local file with its transcript, and send
|
|
129
|
+
nothing to MakeMidas. The transcript is the JSON `transcribe` saves; with
|
|
130
|
+
Nemotron (`-m nvidia/nemotron-3.5-transcribe --format json`) every word has
|
|
131
|
+
its own time. A Whisper transcript (the default model) has sentence times
|
|
132
|
+
only, so word times are estimated.
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
makemidas transcribe talk.mp4 -m nvidia/nemotron-3.5-transcribe --format json # talk.json (paid)
|
|
136
|
+
makemidas cut talk.mp4 --transcript talk.json --list # numbered words
|
|
137
|
+
makemidas cut talk.mp4 --transcript talk.json --remove 41-58 --fillers --gaps 0.4
|
|
138
|
+
makemidas captions talk-cut.mp4 --transcript talk-cut.json
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- `cut` drops words by number (`--remove`), filler words (`--fillers`: um,
|
|
142
|
+
uh, 嗯, 呃 …) and shortens pauses to at most `--gaps` seconds. It writes
|
|
143
|
+
`<name>-cut.mp4` (or `.m4a` for audio) and `<name>-cut.json`, the
|
|
144
|
+
transcript with the kept words at their new times.
|
|
145
|
+
- `captions` makes `<name>-captions/`, a HyperFrames project of the captions
|
|
146
|
+
layer, renders it and lays it over the video into `<name>-captions.mp4`; the
|
|
147
|
+
picture and sound are otherwise untouched. A few words show at a time and
|
|
148
|
+
the spoken one lights up gold; `--max-words` sets how many. Edit the look in
|
|
149
|
+
the project's `index.html` and run `npm run render` there to make it again.
|
|
150
|
+
Needs Node.js 22+ and FFmpeg; the first render downloads a headless Chrome,
|
|
151
|
+
and rendering takes a few seconds per second of video.
|
|
152
|
+
|
|
124
153
|
## Talking avatars
|
|
125
154
|
|
|
126
155
|
`avatar` turns one portrait photo and a voice track into a lip-synced video
|
package/dist/args.js
CHANGED
|
@@ -81,6 +81,13 @@ export function parse(argv) {
|
|
|
81
81
|
fields: { type: 'string' },
|
|
82
82
|
tag: { type: 'string', multiple: true, default: [] },
|
|
83
83
|
keep: { type: 'boolean', default: false },
|
|
84
|
+
transcript: { type: 'string' },
|
|
85
|
+
list: { type: 'boolean', default: false },
|
|
86
|
+
remove: { type: 'string' },
|
|
87
|
+
fillers: { type: 'boolean', default: false },
|
|
88
|
+
gaps: { type: 'string' },
|
|
89
|
+
'max-words': { type: 'string' },
|
|
90
|
+
'no-render': { type: 'boolean', default: false },
|
|
84
91
|
subtitles: { type: 'string' },
|
|
85
92
|
'title-card': { type: 'string' },
|
|
86
93
|
'end-card': { type: 'string' },
|
|
@@ -281,6 +288,13 @@ export function sourceArg(rest, command, what) {
|
|
|
281
288
|
}
|
|
282
289
|
return rest[0];
|
|
283
290
|
}
|
|
291
|
+
/** `--transcript` for captions and cut: the JSON transcribe saves. */
|
|
292
|
+
export function transcriptArg(value, command) {
|
|
293
|
+
if (!value) {
|
|
294
|
+
throw usageError(`\`${command}\` needs the recording's transcript: \`makemidas transcribe <file> -m nvidia/nemotron-3.5-transcribe --format json\` (every word timed), then --transcript <file>.json.`);
|
|
295
|
+
}
|
|
296
|
+
return value;
|
|
297
|
+
}
|
|
284
298
|
/** A `makemidas transcribe` request, without the fileId the upload returns. */
|
|
285
299
|
export function transcriptionInput(v) {
|
|
286
300
|
refuse(v, [
|
package/dist/captions.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { copyFile, mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { CliError, EXIT } from "./errors.js";
|
|
6
|
+
import { CAPTION_COLORS, HYPERFRAMES_VERSION } from "./film-edit.js";
|
|
7
|
+
import { baseName, ffmpeg, localFile, probeMedia, runVisible, safeInput } from "./media.js";
|
|
8
|
+
import { log, print, printJson } from "./output.js";
|
|
9
|
+
import { captionGroups, readTranscript, timedWords } from "./words.js";
|
|
10
|
+
const WIDE = /[⺀-鿿가-豈-︰-﹏-]/;
|
|
11
|
+
/** Captions render at most this many pixels on the long side, then scale. */
|
|
12
|
+
const MAX_SIDE = 1920;
|
|
13
|
+
function r(value) {
|
|
14
|
+
return Math.round(value * 1000) / 1000;
|
|
15
|
+
}
|
|
16
|
+
function escapeHtml(text) {
|
|
17
|
+
return text
|
|
18
|
+
.replace(/&/g, '&')
|
|
19
|
+
.replace(/</g, '<')
|
|
20
|
+
.replace(/>/g, '>')
|
|
21
|
+
.replace(/"/g, '"')
|
|
22
|
+
.replace(/'/g, ''');
|
|
23
|
+
}
|
|
24
|
+
/** The page size: the video's, scaled so the long side is at most 1920. */
|
|
25
|
+
export function pageSize(width, height) {
|
|
26
|
+
const scale = Math.min(1, MAX_SIDE / Math.max(width, height));
|
|
27
|
+
const even = (n) => Math.max(2, Math.round((n * scale) / 2) * 2);
|
|
28
|
+
return { width: even(width), height: even(height) };
|
|
29
|
+
}
|
|
30
|
+
/** Words and width per caption: fewer, bigger words on a tall video. */
|
|
31
|
+
export function captionFit(width, height, maxWords) {
|
|
32
|
+
const tall = width < height;
|
|
33
|
+
return { maxWords: maxWords ?? (tall ? 3 : 5), maxEms: tall ? 8 : 14 };
|
|
34
|
+
}
|
|
35
|
+
/** Where captions sit: clear of the buttons short-video apps draw. */
|
|
36
|
+
function captionBox(width, height) {
|
|
37
|
+
if (width < height) {
|
|
38
|
+
return {
|
|
39
|
+
left: Math.round(width * 0.111),
|
|
40
|
+
width: Math.round(width * 0.778),
|
|
41
|
+
bottom: Math.round(height * 0.3),
|
|
42
|
+
size: Math.round(width * 0.08),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const square = width === height;
|
|
46
|
+
return {
|
|
47
|
+
left: Math.round(width * 0.08),
|
|
48
|
+
width: Math.round(width * 0.84),
|
|
49
|
+
bottom: Math.round(height * (square ? 0.14 : 0.09)),
|
|
50
|
+
size: Math.round(Math.min(width, height) * (square ? 0.07 : 0.06)),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** The captions page: transparent, one block per caption group. Pure. */
|
|
54
|
+
export function captionsHtml(groups, size, seconds) {
|
|
55
|
+
const { width: W, height: H } = size;
|
|
56
|
+
const total = r(seconds);
|
|
57
|
+
const box = captionBox(W, H);
|
|
58
|
+
const blocks = [];
|
|
59
|
+
const tweens = [];
|
|
60
|
+
groups.forEach((group, g) => {
|
|
61
|
+
const id = `c${g + 1}`;
|
|
62
|
+
const show = r(Math.max(0, group.start - 0.04));
|
|
63
|
+
const hide = r(Math.min(group.end, total));
|
|
64
|
+
if (hide <= show)
|
|
65
|
+
return;
|
|
66
|
+
const words = group.words.map((word, w) => {
|
|
67
|
+
const gap = w > 0 && !(WIDE.test(group.words[w - 1].text.slice(-1)) && WIDE.test(word.text[0]))
|
|
68
|
+
? ' '
|
|
69
|
+
: '';
|
|
70
|
+
const wid = `${id}w${w}`;
|
|
71
|
+
const off = Math.min(group.words[w + 1]?.start ?? word.end, hide);
|
|
72
|
+
tweens.push(`tl.fromTo('#${wid}', { color: '${CAPTION_COLORS.ink}', scale: 1 }, { color: '${CAPTION_COLORS.lit}', scale: 1.06, duration: 0.07, ease: 'power2.out', immediateRender: false }, ${r(Math.max(word.start, show))});`, `tl.fromTo('#${wid}', { color: '${CAPTION_COLORS.lit}', scale: 1.06 }, { color: '${CAPTION_COLORS.ink}', scale: 1, duration: 0.1, ease: 'power2.in', immediateRender: false }, ${r(off)});`);
|
|
73
|
+
const cls = WIDE.test(word.text[0]) ? 'w cjk' : 'w';
|
|
74
|
+
return `${gap}<span class="${cls}" id="${wid}">${escapeHtml(word.text)}</span>`;
|
|
75
|
+
});
|
|
76
|
+
blocks.push(`<div class="cap clip" id="${id}" data-start="${show}" data-duration="${r(hide - show)}" data-track-index="1">` +
|
|
77
|
+
`<div class="cap-in" data-layout-allow-overlap>${words.join('')}</div></div>`);
|
|
78
|
+
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});`);
|
|
79
|
+
});
|
|
80
|
+
const indent = (lines, pad) => lines.map((line) => pad + line).join('\n');
|
|
81
|
+
return `<!doctype html>
|
|
82
|
+
<html lang="en">
|
|
83
|
+
<head>
|
|
84
|
+
<meta charset="UTF-8" />
|
|
85
|
+
<meta name="viewport" content="width=${W}, height=${H}" />
|
|
86
|
+
<title>Captions</title>
|
|
87
|
+
<script src="https://cdn.jsdelivr.net/npm/gsap@3.15.0/dist/gsap.min.js"></script>
|
|
88
|
+
<style>
|
|
89
|
+
@font-face { font-family: 'Inter'; font-weight: 900; src: url('assets/fonts/inter-latin-900-normal.woff2') format('woff2'); }
|
|
90
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
91
|
+
html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: transparent; }
|
|
92
|
+
#root { position: relative; width: ${W}px; height: ${H}px; }
|
|
93
|
+
/* Captions: edit the size, colours and place here, then npm run render. */
|
|
94
|
+
.cap { position: absolute; left: ${box.left}px; width: ${box.width}px; bottom: ${box.bottom}px; display: flex; justify-content: center; align-items: flex-end; }
|
|
95
|
+
.cap-in { text-align: center; font-family: 'Inter', sans-serif; font-weight: 900; font-size: ${box.size}px; line-height: 1.12; 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); }
|
|
96
|
+
.w { display: inline-block; transform-origin: 50% 70%; margin: 0 0.1em; }
|
|
97
|
+
.w.cjk { margin: 0 0.02em; }
|
|
98
|
+
</style>
|
|
99
|
+
</head>
|
|
100
|
+
<body>
|
|
101
|
+
<div id="root" data-composition-id="main" data-start="0" data-duration="${total}" data-width="${W}" data-height="${H}">
|
|
102
|
+
${indent(blocks, ' ')}
|
|
103
|
+
</div>
|
|
104
|
+
<script>
|
|
105
|
+
const tl = gsap.timeline({ paused: true });
|
|
106
|
+
${indent(tweens, ' ')}
|
|
107
|
+
window.__timelines['main'] = tl;
|
|
108
|
+
tl.seek(0);
|
|
109
|
+
</script>
|
|
110
|
+
</body>
|
|
111
|
+
</html>
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
/** FFmpeg's arguments to lay the captions over the video. */
|
|
115
|
+
export function overlayArgs(video, layer, size, output, audio) {
|
|
116
|
+
return [
|
|
117
|
+
'-i',
|
|
118
|
+
video,
|
|
119
|
+
'-i',
|
|
120
|
+
layer,
|
|
121
|
+
'-filter_complex',
|
|
122
|
+
`[1:v]scale=${size.width}:${size.height}[c];[0:v][c]overlay=0:0:eof_action=pass:format=auto,format=yuv420p[v]`,
|
|
123
|
+
'-map',
|
|
124
|
+
'[v]',
|
|
125
|
+
...(audio ? ['-map', '0:a:0', '-c:a', 'aac', '-b:a', '192k'] : []),
|
|
126
|
+
'-c:v',
|
|
127
|
+
'libx264',
|
|
128
|
+
'-crf',
|
|
129
|
+
'18',
|
|
130
|
+
'-preset',
|
|
131
|
+
'medium',
|
|
132
|
+
'-movflags',
|
|
133
|
+
'+faststart',
|
|
134
|
+
output,
|
|
135
|
+
];
|
|
136
|
+
}
|
|
137
|
+
const sh = (arg) => `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
138
|
+
function fontsDir() {
|
|
139
|
+
return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fonts');
|
|
140
|
+
}
|
|
141
|
+
export async function captions(g, source, opts) {
|
|
142
|
+
const t = timedWords(await readTranscript(opts.transcript));
|
|
143
|
+
if (!t.words.length) {
|
|
144
|
+
throw new CliError(`${opts.transcript} has no words to caption.`, EXIT.USAGE, 'bad_transcript');
|
|
145
|
+
}
|
|
146
|
+
const input = resolve(safeInput(localFile(source, 'captions')));
|
|
147
|
+
const media = await probeMedia(input, 'captions');
|
|
148
|
+
if (!media.video) {
|
|
149
|
+
throw new CliError(`${source} has no picture to put captions on.`, EXIT.USAGE, 'bad_file');
|
|
150
|
+
}
|
|
151
|
+
if (t.estimated) {
|
|
152
|
+
log('This transcript has no word timings, so each word is timed by guessing within its sentence. For captions that follow the voice exactly, transcribe with Nemotron, which times every word: `makemidas transcribe <file> -m nvidia/nemotron-3.5-transcribe --format json`.');
|
|
153
|
+
}
|
|
154
|
+
const size = pageSize(media.video.width, media.video.height);
|
|
155
|
+
const groups = captionGroups(t.words, captionFit(media.video.width, media.video.height, opts.maxWords));
|
|
156
|
+
const out = resolve(opts.out);
|
|
157
|
+
const name = baseName(source);
|
|
158
|
+
const dir = join(out, `${name}-captions`);
|
|
159
|
+
const output = join(out, `${name}-captions.mp4`);
|
|
160
|
+
if ((existsSync(join(dir, 'index.html')) || existsSync(output)) && !opts.force) {
|
|
161
|
+
throw new CliError(`${existsSync(output) ? output : dir} exists; use --force to overwrite or -o for another folder.`, EXIT.USAGE, 'exists');
|
|
162
|
+
}
|
|
163
|
+
await mkdir(join(dir, 'assets', 'fonts'), { recursive: true });
|
|
164
|
+
for (const font of ['inter-latin-900-normal.woff2', 'OFL.txt']) {
|
|
165
|
+
await copyFile(join(fontsDir(), font), join(dir, 'assets', 'fonts', font));
|
|
166
|
+
}
|
|
167
|
+
const layer = join(dir, 'renders', 'captions.mov');
|
|
168
|
+
const hf = `npx --yes hyperframes@${HYPERFRAMES_VERSION}`;
|
|
169
|
+
const renderLayer = `${hf} render --format mov --fps ${media.video.fps} -o renders/captions.mov`;
|
|
170
|
+
const burn = `ffmpeg -v error -y ${overlayArgs(input, 'renders/captions.mov', media.video, output, media.audio).map(sh).join(' ')}`;
|
|
171
|
+
const files = {
|
|
172
|
+
'index.html': captionsHtml(groups, size, media.seconds),
|
|
173
|
+
'words.json': `${JSON.stringify({ estimated: t.estimated, groups }, null, 2)}\n`,
|
|
174
|
+
'package.json': `${JSON.stringify({
|
|
175
|
+
name: `${name}-captions`,
|
|
176
|
+
private: true,
|
|
177
|
+
type: 'module',
|
|
178
|
+
scripts: {
|
|
179
|
+
check: `${hf} check`,
|
|
180
|
+
preview: `${hf} preview`,
|
|
181
|
+
render: `${renderLayer} && ${burn}`,
|
|
182
|
+
},
|
|
183
|
+
}, null, 2)}\n`,
|
|
184
|
+
'hyperframes.json': `${JSON.stringify({ $schema: 'https://hyperframes.heygen.com/schema/hyperframes.json', paths: { assets: 'assets' } }, null, 2)}\n`,
|
|
185
|
+
'README.md': `# Captions for ${name}\n\nMade by \`makemidas captions\`. \`index.html\` is the captions layer (styles at the top);\n\`words.json\` holds each caption's words and times. \`npm run render\` renders the\nlayer and lays it over the video into ${output}.\n`,
|
|
186
|
+
};
|
|
187
|
+
for (const [file, body] of Object.entries(files)) {
|
|
188
|
+
await writeFile(join(dir, file), body);
|
|
189
|
+
}
|
|
190
|
+
if (!opts.render) {
|
|
191
|
+
if (g.json)
|
|
192
|
+
printJson({ dir, groups: groups.length, estimated: t.estimated, next: [`cd ${JSON.stringify(dir)}`, 'npm run render'] });
|
|
193
|
+
else {
|
|
194
|
+
print(dir);
|
|
195
|
+
log(`Captions project ready (${groups.length} captions). Render it: cd ${JSON.stringify(dir)} && npm run render`);
|
|
196
|
+
}
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
log(`Rendering ${groups.length} captions over ${media.seconds.toFixed(1)}s with HyperFrames (the first run downloads a headless Chrome)…`);
|
|
200
|
+
await runVisible('npx', ['--yes', `hyperframes@${HYPERFRAMES_VERSION}`, 'render', '--format', 'mov', '--fps', String(media.video.fps), '-o', 'renders/captions.mov'], dir, 'captions');
|
|
201
|
+
if (!existsSync(layer)) {
|
|
202
|
+
throw new CliError('HyperFrames made no captions layer; its output is above.', EXIT.FAILED, 'render_failed');
|
|
203
|
+
}
|
|
204
|
+
log('Laying the captions over the video…');
|
|
205
|
+
await ffmpeg(overlayArgs(input, layer, media.video, output, media.audio), 'captions', `Can't put the captions on ${source}`);
|
|
206
|
+
if (g.json) {
|
|
207
|
+
printJson({ file: output, dir, groups: groups.length, estimated: t.estimated });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
print(output);
|
|
211
|
+
log(`Edit the look in ${join(dir, 'index.html')} and run \`npm run render\` there to make it again.`);
|
|
212
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Api, KINDS, MODEL_USES, } from "./api.js";
|
|
3
|
-
import { audioInput, compareModels, compareOptions, editInput, filmSeconds, filmSettings, feedbackKind, generationInput, intOption, parse, renderBrand, renderOptions, sourceArg, templateValues, transcriptionInput, usageError, } from "./args.js";
|
|
3
|
+
import { audioInput, compareModels, compareOptions, editInput, filmSeconds, filmSettings, feedbackKind, generationInput, intOption, numberOption, parse, renderBrand, renderOptions, sourceArg, templateValues, transcriptArg, transcriptionInput, usageError, } from "./args.js";
|
|
4
4
|
import * as commands from "./commands.js";
|
|
5
|
+
import { captions } from "./captions.js";
|
|
6
|
+
import { cut } from "./cut.js";
|
|
5
7
|
import { filmEdit } from "./film-edit.js";
|
|
6
8
|
import { FRAME_DEFAULTS, frames } from "./frames.js";
|
|
7
9
|
import * as films from "./films.js";
|
|
@@ -61,6 +63,15 @@ Usage:
|
|
|
61
63
|
first-last|sound picks image and video models
|
|
62
64
|
by the job
|
|
63
65
|
makemidas models <id> One model: options, defaults, prices
|
|
66
|
+
makemidas captions <video> --transcript <t.json>
|
|
67
|
+
Burn word-by-word captions in, made here with
|
|
68
|
+
HyperFrames and FFmpeg; free (--max-words,
|
|
69
|
+
--no-render keeps the project only)
|
|
70
|
+
makemidas cut <video|audio> --transcript <t.json>
|
|
71
|
+
Cut on words, here with FFmpeg; free:
|
|
72
|
+
--list numbers the words, --remove 3,12-18,
|
|
73
|
+
--fillers (um, uh), --gaps <s> shortens pauses;
|
|
74
|
+
writes the cut and its re-timed transcript
|
|
64
75
|
makemidas frames <video|url> Stills and a contact sheet of a clip, made
|
|
65
76
|
here with FFmpeg; free (--count 1-16,
|
|
66
77
|
default 6; --width 120-1920, default 480)
|
|
@@ -365,6 +376,24 @@ async function main(argv) {
|
|
|
365
376
|
const { input, format } = transcriptionInput(v);
|
|
366
377
|
return commands.transcribe(api, g, input, source, format, save, wait, maxCredits(v));
|
|
367
378
|
}
|
|
379
|
+
case 'captions':
|
|
380
|
+
return captions(g, sourceArg(rest, 'captions', 'video file'), {
|
|
381
|
+
transcript: transcriptArg(v.transcript, 'captions'),
|
|
382
|
+
maxWords: intOption(v['max-words'], 'max-words', 1, 8),
|
|
383
|
+
render: !v['no-render'],
|
|
384
|
+
out: v.out,
|
|
385
|
+
force: v.force,
|
|
386
|
+
});
|
|
387
|
+
case 'cut':
|
|
388
|
+
return cut(g, sourceArg(rest, 'cut', 'video or audio file'), {
|
|
389
|
+
transcript: transcriptArg(v.transcript, 'cut'),
|
|
390
|
+
list: v.list,
|
|
391
|
+
remove: v.remove,
|
|
392
|
+
fillers: v.fillers,
|
|
393
|
+
gaps: numberOption(v.gaps, 'gaps', 0, 10),
|
|
394
|
+
out: v.out,
|
|
395
|
+
force: v.force,
|
|
396
|
+
});
|
|
368
397
|
case 'frames':
|
|
369
398
|
return frames(g, sourceArg(rest, 'frames', 'video file or link'), {
|
|
370
399
|
count: intOption(v.count, 'count', 1, 16) ?? FRAME_DEFAULTS.count,
|
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.
|
|
4
|
+
export const VERSION = '0.11.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) {
|
package/dist/cut.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { CliError, EXIT } from "./errors.js";
|
|
5
|
+
import { baseName, ffmpeg, localFile, probeMedia, safeInput } from "./media.js";
|
|
6
|
+
import { log, print, printJson } from "./output.js";
|
|
7
|
+
import { cutTranscript, isFiller, keepIntervals, parseWordRanges, readTranscript, timedWords, } from "./words.js";
|
|
8
|
+
function fmt(t) {
|
|
9
|
+
const m = Math.floor(t / 60);
|
|
10
|
+
return `${m}:${(t - m * 60).toFixed(2).padStart(5, '0')}`;
|
|
11
|
+
}
|
|
12
|
+
/** The numbered words, as `--list` prints them. */
|
|
13
|
+
export function wordList(words) {
|
|
14
|
+
return words
|
|
15
|
+
.map((w, i) => `${String(i + 1).padStart(5)} ${fmt(w.start)} ${w.text}`)
|
|
16
|
+
.join('\n');
|
|
17
|
+
}
|
|
18
|
+
/** Which words go and which parts stay. Pure. */
|
|
19
|
+
export function planCut(words, duration, opts) {
|
|
20
|
+
const removed = new Set(opts.remove ? parseWordRanges(opts.remove, words.length) : []);
|
|
21
|
+
if (opts.fillers) {
|
|
22
|
+
words.forEach((w, i) => {
|
|
23
|
+
if (isFiller(w.text))
|
|
24
|
+
removed.add(i);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
const keep = keepIntervals(words, removed, duration, opts.gaps);
|
|
28
|
+
return {
|
|
29
|
+
removed: [...removed].sort((a, b) => a - b),
|
|
30
|
+
keep,
|
|
31
|
+
seconds: duration,
|
|
32
|
+
cutSeconds: Math.round(keep.reduce((sum, p) => sum + p.end - p.start, 0) * 1000) / 1000,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** FFmpeg's filter graph: each kept part trimmed, faded a hair, joined. */
|
|
36
|
+
export function cutFilter(keep, media) {
|
|
37
|
+
const parts = [];
|
|
38
|
+
const labels = [];
|
|
39
|
+
keep.forEach((p, i) => {
|
|
40
|
+
const len = Math.round((p.end - p.start) * 1000) / 1000;
|
|
41
|
+
const fade = Math.min(0.01, len / 4);
|
|
42
|
+
if (media.video) {
|
|
43
|
+
parts.push(`[0:v]trim=start=${p.start}:end=${p.end},setpts=PTS-STARTPTS[v${i}]`);
|
|
44
|
+
labels.push(`[v${i}]`);
|
|
45
|
+
}
|
|
46
|
+
if (media.audio) {
|
|
47
|
+
parts.push(`[0:a]atrim=start=${p.start}:end=${p.end},asetpts=PTS-STARTPTS,afade=t=in:d=${fade},afade=t=out:st=${Math.max(0, len - fade)}:d=${fade}[a${i}]`);
|
|
48
|
+
labels.push(`[a${i}]`);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
const v = media.video ? 1 : 0;
|
|
52
|
+
const a = media.audio ? 1 : 0;
|
|
53
|
+
const outs = `${v ? '[v]' : ''}${a ? '[a]' : ''}`;
|
|
54
|
+
parts.push(`${labels.join('')}concat=n=${keep.length}:v=${v}:a=${a}${outs}`);
|
|
55
|
+
return parts.join(';');
|
|
56
|
+
}
|
|
57
|
+
export async function cut(g, source, opts) {
|
|
58
|
+
const t = timedWords(await readTranscript(opts.transcript));
|
|
59
|
+
if (!t.words.length) {
|
|
60
|
+
throw new CliError(`${opts.transcript} has no words to cut on.`, EXIT.USAGE, 'bad_transcript');
|
|
61
|
+
}
|
|
62
|
+
if (opts.list) {
|
|
63
|
+
if (g.json) {
|
|
64
|
+
printJson({
|
|
65
|
+
estimated: t.estimated,
|
|
66
|
+
words: t.words.map((w, i) => ({ n: i + 1, ...w })),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
print(wordList(t.words));
|
|
71
|
+
if (t.estimated)
|
|
72
|
+
log(ESTIMATED);
|
|
73
|
+
}
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (!opts.remove && !opts.fillers && opts.gaps === undefined) {
|
|
77
|
+
throw new CliError('Say what to cut: --remove <word numbers> (see --list), --fillers, or --gaps <seconds>.', EXIT.USAGE, 'usage');
|
|
78
|
+
}
|
|
79
|
+
if (t.estimated)
|
|
80
|
+
log(ESTIMATED);
|
|
81
|
+
const input = safeInput(localFile(source, 'cut'));
|
|
82
|
+
const media = await probeMedia(input, 'cut');
|
|
83
|
+
const plan = planCut(t.words, media.seconds, opts);
|
|
84
|
+
if (!plan.keep.length) {
|
|
85
|
+
throw new CliError('That removes every word; nothing would be left.', EXIT.USAGE, 'usage');
|
|
86
|
+
}
|
|
87
|
+
const dir = resolve(opts.out);
|
|
88
|
+
const ext = media.video ? 'mp4' : 'm4a';
|
|
89
|
+
const file = join(dir, `${baseName(source)}-cut.${ext}`);
|
|
90
|
+
const json = join(dir, `${baseName(source)}-cut.json`);
|
|
91
|
+
for (const path of [file, json]) {
|
|
92
|
+
if (existsSync(path) && !opts.force) {
|
|
93
|
+
throw new CliError(`${path} exists; use --force to overwrite or -o for another folder.`, EXIT.USAGE, 'exists');
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
await mkdir(dir, { recursive: true });
|
|
97
|
+
log(`Cutting ${plan.removed.length} words: ${plan.seconds.toFixed(1)}s → ${plan.cutSeconds.toFixed(1)}s in ${plan.keep.length} parts…`);
|
|
98
|
+
await ffmpeg([
|
|
99
|
+
'-i',
|
|
100
|
+
input,
|
|
101
|
+
'-filter_complex',
|
|
102
|
+
cutFilter(plan.keep, media),
|
|
103
|
+
...(media.video ? ['-map', '[v]'] : []),
|
|
104
|
+
...(media.audio ? ['-map', '[a]'] : []),
|
|
105
|
+
...(media.video ? ['-c:v', 'libx264', '-crf', '18', '-preset', 'medium', '-pix_fmt', 'yuv420p'] : []),
|
|
106
|
+
...(media.audio ? ['-c:a', 'aac', '-b:a', '192k'] : []),
|
|
107
|
+
'-movflags',
|
|
108
|
+
'+faststart',
|
|
109
|
+
file,
|
|
110
|
+
], 'cut', `Can't cut ${source}`);
|
|
111
|
+
const removed = new Set(plan.removed);
|
|
112
|
+
const transcript = cutTranscript(t.words, removed, plan.keep, t.language);
|
|
113
|
+
await writeFile(json, `${JSON.stringify(transcript, null, 2)}\n`);
|
|
114
|
+
if (g.json) {
|
|
115
|
+
printJson({
|
|
116
|
+
file,
|
|
117
|
+
transcript: json,
|
|
118
|
+
seconds: plan.seconds,
|
|
119
|
+
cutSeconds: plan.cutSeconds,
|
|
120
|
+
removedWords: plan.removed.map((i) => ({ n: i + 1, ...t.words[i] })),
|
|
121
|
+
keep: plan.keep,
|
|
122
|
+
});
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
print(file);
|
|
126
|
+
log(`Transcript of the cut: ${json} (use it with \`makemidas captions\`).`);
|
|
127
|
+
}
|
|
128
|
+
const ESTIMATED = 'This transcript has no word timings, so they are estimated from its segments and a cut may land mid-word. For exact cuts, transcribe with Nemotron, which times every word: `makemidas transcribe <file> -m nvidia/nemotron-3.5-transcribe --format json`.';
|
package/dist/media.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { basename, extname } from 'node:path';
|
|
3
|
+
import { CliError, EXIT } from "./errors.js";
|
|
4
|
+
import { runTool } from "./frames.js";
|
|
5
|
+
export function toolMissing(tool, command) {
|
|
6
|
+
return new CliError(`\`makemidas ${command}\` needs ${tool} on this computer: ${tool === 'FFmpeg' ? 'https://ffmpeg.org/download.html' : 'Node.js 22+ (https://nodejs.org)'}`, EXIT.USAGE, tool === 'FFmpeg' ? 'ffmpeg_missing' : 'node_missing');
|
|
7
|
+
}
|
|
8
|
+
/** Frame rate from ffprobe's `30000/1001`, rounded; 30 when unreadable. */
|
|
9
|
+
export function parseRate(rate) {
|
|
10
|
+
const [num, den] = (rate ?? '').split('/').map(Number);
|
|
11
|
+
const fps = den ? num / den : num;
|
|
12
|
+
return Number.isFinite(fps) && fps > 1 && fps <= 240 ? Math.round(fps) : 30;
|
|
13
|
+
}
|
|
14
|
+
export async function probeMedia(source, command, run = runTool) {
|
|
15
|
+
let out;
|
|
16
|
+
try {
|
|
17
|
+
out = await run('ffprobe', [
|
|
18
|
+
'-v',
|
|
19
|
+
'error',
|
|
20
|
+
'-show_entries',
|
|
21
|
+
'format=duration:stream=codec_type,width,height,avg_frame_rate,r_frame_rate:stream_disposition=attached_pic',
|
|
22
|
+
'-of',
|
|
23
|
+
'json',
|
|
24
|
+
source,
|
|
25
|
+
]);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (error?.code === 'ENOENT') {
|
|
29
|
+
throw toolMissing('FFmpeg', command);
|
|
30
|
+
}
|
|
31
|
+
throw new CliError(`Can't read ${source} as audio or video.`, EXIT.USAGE, 'bad_file');
|
|
32
|
+
}
|
|
33
|
+
const info = JSON.parse(out);
|
|
34
|
+
const seconds = Number.parseFloat(info.format?.duration ?? '');
|
|
35
|
+
const streams = info.streams ?? [];
|
|
36
|
+
// Cover art in an MP3 is a "video" stream of one picture: not a video.
|
|
37
|
+
const v = streams.find((s) => s.codec_type === 'video' && !s.disposition?.attached_pic && s.width && s.height);
|
|
38
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
39
|
+
throw new CliError(`${source} has no length.`, EXIT.USAGE, 'bad_file');
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
seconds,
|
|
43
|
+
video: v
|
|
44
|
+
? {
|
|
45
|
+
width: v.width,
|
|
46
|
+
height: v.height,
|
|
47
|
+
fps: parseRate(v.avg_frame_rate && v.avg_frame_rate !== '0/0' ? v.avg_frame_rate : v.r_frame_rate),
|
|
48
|
+
}
|
|
49
|
+
: null,
|
|
50
|
+
audio: streams.some((s) => s.codec_type === 'audio'),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** `talk.mp4` → `talk`, safe as a file name. */
|
|
54
|
+
export function baseName(source) {
|
|
55
|
+
return basename(source, extname(source)).replace(/[^\w.-]+/g, '-') || 'video';
|
|
56
|
+
}
|
|
57
|
+
/** captions and cut work on a file on this computer, not a link. */
|
|
58
|
+
export function localFile(source, command) {
|
|
59
|
+
if (/^https?:\/\//i.test(source)) {
|
|
60
|
+
throw new CliError(`\`makemidas ${command}\` works on a file on this computer; download ${source} first.`, EXIT.USAGE, 'usage');
|
|
61
|
+
}
|
|
62
|
+
return source;
|
|
63
|
+
}
|
|
64
|
+
/** A file name starting with "-" would read as an FFmpeg option. */
|
|
65
|
+
export function safeInput(source) {
|
|
66
|
+
return source.startsWith('-') ? `./${source}` : source;
|
|
67
|
+
}
|
|
68
|
+
/** Runs FFmpeg; on failure, its last line of output says why. */
|
|
69
|
+
export async function ffmpeg(args, command, what) {
|
|
70
|
+
await new Promise((done, fail) => {
|
|
71
|
+
execFile('ffmpeg', ['-v', 'error', '-y', ...args], { maxBuffer: 16 * 1024 * 1024 }, (error, _stdout, stderr) => {
|
|
72
|
+
if (!error)
|
|
73
|
+
return done();
|
|
74
|
+
if (error.code === 'ENOENT') {
|
|
75
|
+
return fail(toolMissing('FFmpeg', command));
|
|
76
|
+
}
|
|
77
|
+
const detail = String(stderr).trim().split('\n').at(-1);
|
|
78
|
+
fail(new CliError(`${what}${detail ? `: ${detail}` : ''}`, EXIT.FAILED, 'ffmpeg_failed'));
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Runs a long command (HyperFrames) with its progress shown on stderr,
|
|
84
|
+
* so stdout stays for the result.
|
|
85
|
+
*/
|
|
86
|
+
export async function runVisible(program, args, cwd, command) {
|
|
87
|
+
await new Promise((done, fail) => {
|
|
88
|
+
const child = spawn(program, args, { cwd, stdio: ['ignore', 2, 2] });
|
|
89
|
+
child.on('error', (error) => {
|
|
90
|
+
fail(error.code === 'ENOENT'
|
|
91
|
+
? toolMissing('Node.js', command)
|
|
92
|
+
: error);
|
|
93
|
+
});
|
|
94
|
+
child.on('exit', (code) => {
|
|
95
|
+
if (code === 0)
|
|
96
|
+
done();
|
|
97
|
+
else
|
|
98
|
+
fail(new CliError(`${program} ${args.slice(0, 3).join(' ')} stopped (exit ${code}); its output is above.`, EXIT.FAILED, 'render_failed'));
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
package/dist/words.js
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { CliError, EXIT } from "./errors.js";
|
|
3
|
+
const WIDE = /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꀀ-가-힣豈-︰-﹏-⦆¢-₩]/;
|
|
4
|
+
const STOP = /[.!?…。!?]["'”’」』)]*$/;
|
|
5
|
+
const CLAUSE = /[,;:—–,;:、]["'”’」』)]*$/;
|
|
6
|
+
/** Punctuation that belongs to the word before it. */
|
|
7
|
+
const TRAILING = /^[.,!?…;:)\]}"'”’」』。!?,;:、—–]+$/;
|
|
8
|
+
function round(value) {
|
|
9
|
+
return Math.round(value * 1000) / 1000;
|
|
10
|
+
}
|
|
11
|
+
/** Reads a transcript JSON file, refusing anything without timings. */
|
|
12
|
+
export async function readTranscript(path) {
|
|
13
|
+
let parsed;
|
|
14
|
+
try {
|
|
15
|
+
parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new CliError(`Can't read ${path} as a transcript: make one with \`makemidas transcribe <file> -m nvidia/nemotron-3.5-transcribe --format json\`.`, EXIT.USAGE, 'bad_transcript');
|
|
19
|
+
}
|
|
20
|
+
const t = parsed;
|
|
21
|
+
if (!t || !Array.isArray(t.segments)) {
|
|
22
|
+
throw new CliError(`${path} is not a MakeMidas transcript (no segments): make one with \`makemidas transcribe <file> -m nvidia/nemotron-3.5-transcribe --format json\`.`, EXIT.USAGE, 'bad_transcript');
|
|
23
|
+
}
|
|
24
|
+
return t;
|
|
25
|
+
}
|
|
26
|
+
/** The words of a line: spaced words, and each CJK character on its own. */
|
|
27
|
+
export function wordsOf(text) {
|
|
28
|
+
const out = [];
|
|
29
|
+
for (const chunk of text.replace(/\s+/g, ' ').trim().split(' ')) {
|
|
30
|
+
if (!chunk)
|
|
31
|
+
continue;
|
|
32
|
+
if (!WIDE.test(chunk)) {
|
|
33
|
+
if (TRAILING.test(chunk) && out.length)
|
|
34
|
+
out[out.length - 1] += chunk;
|
|
35
|
+
else
|
|
36
|
+
out.push(chunk);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
let latin = '';
|
|
40
|
+
for (const char of chunk) {
|
|
41
|
+
if (WIDE.test(char) && !TRAILING.test(char)) {
|
|
42
|
+
if (latin)
|
|
43
|
+
out.push(latin);
|
|
44
|
+
latin = '';
|
|
45
|
+
out.push(char);
|
|
46
|
+
}
|
|
47
|
+
else if (TRAILING.test(char) && !latin && out.length) {
|
|
48
|
+
out[out.length - 1] += char;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
latin += char;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (latin)
|
|
55
|
+
out.push(latin);
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
/** About how many syllables a word takes to say. */
|
|
60
|
+
function syllables(word) {
|
|
61
|
+
const wide = [...word].filter((char) => WIDE.test(char)).length;
|
|
62
|
+
if (wide)
|
|
63
|
+
return wide;
|
|
64
|
+
const letters = word.replace(/[^A-Za-z0-9]/g, '');
|
|
65
|
+
if (!letters)
|
|
66
|
+
return 0.3;
|
|
67
|
+
if (/^[A-Z]{2,5}$/.test(letters))
|
|
68
|
+
return letters.length;
|
|
69
|
+
const groups = letters.toLowerCase().replace(/([^aeiouy])e$/, '$1').match(/[aeiouy]+/g);
|
|
70
|
+
return Math.max(1, groups?.length ?? 0);
|
|
71
|
+
}
|
|
72
|
+
/** Words of one segment, its time shared out by syllables. */
|
|
73
|
+
export function estimateWords(text, start, end) {
|
|
74
|
+
const words = wordsOf(text);
|
|
75
|
+
const span = end - start;
|
|
76
|
+
if (!words.length || !(span > 0))
|
|
77
|
+
return [];
|
|
78
|
+
const weights = words.map(syllables);
|
|
79
|
+
const total = weights.reduce((sum, w) => sum + w, 0);
|
|
80
|
+
let at = start;
|
|
81
|
+
return words.map((word, i) => {
|
|
82
|
+
const from = at;
|
|
83
|
+
at += (weights[i] / total) * span;
|
|
84
|
+
return { text: word, start: round(from), end: round(at) };
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** Every word with its time: the transcript's own, or estimated. */
|
|
88
|
+
export function timedWords(t) {
|
|
89
|
+
const last = t.segments.at(-1)?.end ?? 0;
|
|
90
|
+
const duration = Math.max(t.durationSeconds || 0, last);
|
|
91
|
+
if (t.words?.length) {
|
|
92
|
+
return {
|
|
93
|
+
words: t.words
|
|
94
|
+
.map((w) => ({ text: w.word.trim(), start: w.start, end: w.end }))
|
|
95
|
+
.filter((w) => w.text && w.end >= w.start),
|
|
96
|
+
estimated: false,
|
|
97
|
+
duration,
|
|
98
|
+
language: t.language,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
words: t.segments.flatMap((s) => estimateWords(s.text, s.start, s.end)),
|
|
103
|
+
estimated: true,
|
|
104
|
+
duration,
|
|
105
|
+
language: t.language,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Shown width of a word, in ems: a CJK character is one, others half. */
|
|
109
|
+
function ems(text) {
|
|
110
|
+
let total = 0;
|
|
111
|
+
for (const char of text)
|
|
112
|
+
total += WIDE.test(char) ? 1 : 0.5;
|
|
113
|
+
return total;
|
|
114
|
+
}
|
|
115
|
+
/** A group's words as one line: spaced, except between CJK characters. */
|
|
116
|
+
export function joinText(words) {
|
|
117
|
+
let out = '';
|
|
118
|
+
for (const word of words) {
|
|
119
|
+
const spaced = out && !(WIDE.test(out.at(-1) ?? '') && WIDE.test(word.text[0]));
|
|
120
|
+
out += (spaced ? ' ' : '') + word.text;
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
/** How long a caption stays after its last word when nobody speaks next. */
|
|
125
|
+
const LINGER = 0.6;
|
|
126
|
+
/** Silence that always starts a new caption. */
|
|
127
|
+
const BREAK = 0.5;
|
|
128
|
+
/**
|
|
129
|
+
* The words in groups shown one after another: at most `maxWords` words
|
|
130
|
+
* (a CJK character counts 0.4) and `maxEms` wide, a group ends at a sentence or clause mark or a pause,
|
|
131
|
+
* and each stays until the next starts or a moment after its last word.
|
|
132
|
+
*/
|
|
133
|
+
export function captionGroups(words, options) {
|
|
134
|
+
const groups = [];
|
|
135
|
+
let current = [];
|
|
136
|
+
const width = (list) => ems(joinText(list));
|
|
137
|
+
// A CJK character is a word here, but reads as less than an English one.
|
|
138
|
+
const count = (list) => list.reduce((sum, w) => sum + (WIDE.test(w.text[0]) ? 0.4 : 1), 0);
|
|
139
|
+
for (const word of words) {
|
|
140
|
+
const prev = current.at(-1);
|
|
141
|
+
const paused = prev !== undefined && word.start - prev.end > BREAK;
|
|
142
|
+
const full = count(current) + count([word]) > options.maxWords ||
|
|
143
|
+
width([...current, word]) > options.maxEms;
|
|
144
|
+
if (current.length && (full || paused)) {
|
|
145
|
+
groups.push(current);
|
|
146
|
+
current = [];
|
|
147
|
+
}
|
|
148
|
+
current.push(word);
|
|
149
|
+
if (STOP.test(word.text) || CLAUSE.test(word.text)) {
|
|
150
|
+
groups.push(current);
|
|
151
|
+
current = [];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (current.length)
|
|
155
|
+
groups.push(current);
|
|
156
|
+
return groups.map((group, i) => {
|
|
157
|
+
const last = group[group.length - 1].end;
|
|
158
|
+
const next = groups[i + 1]?.[0].start ?? Number.POSITIVE_INFINITY;
|
|
159
|
+
return {
|
|
160
|
+
start: group[0].start,
|
|
161
|
+
end: round(Math.min(next, last + LINGER)),
|
|
162
|
+
words: group,
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
// Cutting
|
|
168
|
+
/** Words people say while thinking, removed by `cut --fillers`. */
|
|
169
|
+
const FILLERS = new Set([
|
|
170
|
+
'um',
|
|
171
|
+
'umm',
|
|
172
|
+
'uh',
|
|
173
|
+
'uhh',
|
|
174
|
+
'uhm',
|
|
175
|
+
'erm',
|
|
176
|
+
'er',
|
|
177
|
+
'ah',
|
|
178
|
+
'hmm',
|
|
179
|
+
'hm',
|
|
180
|
+
'mm',
|
|
181
|
+
'mhm',
|
|
182
|
+
'嗯',
|
|
183
|
+
'呃',
|
|
184
|
+
'额',
|
|
185
|
+
'恩',
|
|
186
|
+
]);
|
|
187
|
+
export function isFiller(text) {
|
|
188
|
+
return FILLERS.has(text.toLowerCase().replace(/[^\p{L}]/gu, ''));
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Word numbers (from 1, as `cut --list` prints them) from `5`, `12-18`
|
|
192
|
+
* and lists of them: `3,12-18,40`.
|
|
193
|
+
*/
|
|
194
|
+
export function parseWordRanges(spec, count) {
|
|
195
|
+
const picked = new Set();
|
|
196
|
+
for (const part of spec.split(',').map((p) => p.trim()).filter(Boolean)) {
|
|
197
|
+
const match = /^(\d+)(?:\s*-\s*(\d+))?$/.exec(part);
|
|
198
|
+
const from = Number(match?.[1]);
|
|
199
|
+
const to = Number(match?.[2] ?? match?.[1]);
|
|
200
|
+
if (!match || from < 1 || to < from || to > count) {
|
|
201
|
+
throw new CliError(`--remove takes word numbers from 1 to ${count} (\`makemidas cut <video> --transcript <t.json> --list\`), like 3,12-18; not "${part}".`, EXIT.USAGE, 'usage');
|
|
202
|
+
}
|
|
203
|
+
for (let n = from; n <= to; n++)
|
|
204
|
+
picked.add(n - 1);
|
|
205
|
+
}
|
|
206
|
+
return [...picked].sort((a, b) => a - b);
|
|
207
|
+
}
|
|
208
|
+
/** Kept around each word so its first and last sounds aren't clipped. */
|
|
209
|
+
export const CUT_PAD = 0.08;
|
|
210
|
+
/**
|
|
211
|
+
* The parts of the recording to keep when the words at `removed` (0-based)
|
|
212
|
+
* go. Silence between kept words stays, shortened to at most `maxGap`
|
|
213
|
+
* seconds when given; where words were removed, the pauses either side of
|
|
214
|
+
* them stay (each up to `maxGap / 2`). Sound before the first word and
|
|
215
|
+
* after the last stays when that word stays.
|
|
216
|
+
*/
|
|
217
|
+
export function keepIntervals(words, removed, duration, maxGap) {
|
|
218
|
+
const out = [];
|
|
219
|
+
// Silence kept next to a pause that is shortened: half the gap each side.
|
|
220
|
+
const edge = maxGap === undefined
|
|
221
|
+
? Number.POSITIVE_INFINITY
|
|
222
|
+
: Math.max(CUT_PAD, maxGap / 2);
|
|
223
|
+
let open = null;
|
|
224
|
+
words.forEach((word, i) => {
|
|
225
|
+
const prev = words[i - 1];
|
|
226
|
+
if (removed.has(i)) {
|
|
227
|
+
if (open && prev) {
|
|
228
|
+
// Keep the pause before the removed word (up to maxGap / 2).
|
|
229
|
+
open.end = Math.min(word.start, Math.max(open.end, prev.end + edge));
|
|
230
|
+
out.push(open);
|
|
231
|
+
open = null;
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (open && prev) {
|
|
236
|
+
// The word before stays too: keep the silence between, up to maxGap.
|
|
237
|
+
if (word.start - prev.end <= 2 * edge) {
|
|
238
|
+
open.end = word.end + CUT_PAD;
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
open.end = prev.end + edge;
|
|
242
|
+
out.push(open);
|
|
243
|
+
open = { start: word.start - edge, end: word.end + CUT_PAD };
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
// The first word, or the first after removed words: keep the pause
|
|
247
|
+
// before it (up to maxGap / 2).
|
|
248
|
+
open = {
|
|
249
|
+
start: prev ? Math.max(prev.end, word.start - edge) : word.start - edge,
|
|
250
|
+
end: word.end + CUT_PAD,
|
|
251
|
+
};
|
|
252
|
+
});
|
|
253
|
+
if (open && !removed.has(words.length - 1)) {
|
|
254
|
+
const last = words[words.length - 1];
|
|
255
|
+
open.end = Math.max(open.end, last.end + edge);
|
|
256
|
+
}
|
|
257
|
+
if (open)
|
|
258
|
+
out.push(open);
|
|
259
|
+
// Clamp, round, and join parts that touch.
|
|
260
|
+
const merged = [];
|
|
261
|
+
for (const part of out) {
|
|
262
|
+
const start = round(Math.max(0, part.start));
|
|
263
|
+
const end = round(Math.min(duration, part.end));
|
|
264
|
+
if (end - start < 0.02)
|
|
265
|
+
continue;
|
|
266
|
+
const prev = merged.at(-1);
|
|
267
|
+
if (prev && start <= prev.end + 0.001)
|
|
268
|
+
prev.end = Math.max(prev.end, end);
|
|
269
|
+
else
|
|
270
|
+
merged.push({ start, end });
|
|
271
|
+
}
|
|
272
|
+
return merged;
|
|
273
|
+
}
|
|
274
|
+
/** Where a time of the original lands in the cut, or null when cut out. */
|
|
275
|
+
export function mapTime(t, keep) {
|
|
276
|
+
let offset = 0;
|
|
277
|
+
for (const part of keep) {
|
|
278
|
+
if (t < part.start)
|
|
279
|
+
return null;
|
|
280
|
+
if (t <= part.end)
|
|
281
|
+
return round(offset + t - part.start);
|
|
282
|
+
offset += part.end - part.start;
|
|
283
|
+
}
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
/** The transcript of the cut: kept words at their new times. */
|
|
287
|
+
export function cutTranscript(words, removed, keep, language) {
|
|
288
|
+
const kept = [];
|
|
289
|
+
words.forEach((word, i) => {
|
|
290
|
+
if (removed.has(i))
|
|
291
|
+
return;
|
|
292
|
+
const start = mapTime(Math.max(word.start, 0), keep);
|
|
293
|
+
const end = mapTime(word.end, keep);
|
|
294
|
+
if (start === null || end === null)
|
|
295
|
+
return;
|
|
296
|
+
kept.push({ text: word.text, start, end: Math.max(start, end) });
|
|
297
|
+
});
|
|
298
|
+
const segments = [];
|
|
299
|
+
let line = [];
|
|
300
|
+
const flush = () => {
|
|
301
|
+
if (!line.length)
|
|
302
|
+
return;
|
|
303
|
+
segments.push({
|
|
304
|
+
start: line[0].start,
|
|
305
|
+
end: line[line.length - 1].end,
|
|
306
|
+
text: joinText(line),
|
|
307
|
+
});
|
|
308
|
+
line = [];
|
|
309
|
+
};
|
|
310
|
+
for (const word of kept) {
|
|
311
|
+
const prev = line.at(-1);
|
|
312
|
+
if (prev && word.start - prev.end > 1)
|
|
313
|
+
flush();
|
|
314
|
+
line.push(word);
|
|
315
|
+
if (STOP.test(word.text))
|
|
316
|
+
flush();
|
|
317
|
+
}
|
|
318
|
+
flush();
|
|
319
|
+
const duration = round(keep.reduce((sum, p) => sum + p.end - p.start, 0));
|
|
320
|
+
return {
|
|
321
|
+
text: joinText(kept),
|
|
322
|
+
durationSeconds: duration,
|
|
323
|
+
...(language ? { language } : {}),
|
|
324
|
+
segments,
|
|
325
|
+
words: kept.map((w) => ({ word: w.text, start: w.start, end: w.end })),
|
|
326
|
+
};
|
|
327
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@makemidas/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "AI image, video and audio generation CLI for AI agents (Claude Code, Cursor, Codex) and people: Nano Banana, GPT Image, Seedream, Seedance, Kling, Veo, Suno and more, plus talking avatars, HTML templates and short films, through MakeMidas.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai-image-generator",
|