@senseihq/emaki-cli 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +69 -2
- package/package.json +44 -4
- package/plugin/.claude-plugin/plugin.json +19 -0
- package/plugin/PLAYBOOK.md +137 -0
- package/plugin/README.md +51 -0
- package/plugin/agents/fact-checker.md +28 -0
- package/plugin/agents/localizer.md +34 -0
- package/plugin/agents/scene-builder.md +43 -0
- package/plugin/agents/story-planner.md +42 -0
- package/plugin/agents/story-writer.md +34 -0
- package/plugin/agents/visual-reviewer.md +33 -0
- package/plugin/modules/campaign/README.md +30 -0
- package/plugin/modules/campaign/calendar.csv +2 -0
- package/plugin/modules/campaign/day-script.template.md +42 -0
- package/plugin/modules/posting-desk/README.md +37 -0
- package/plugin/skills/emaki/SKILL.md +107 -0
- package/plugin/skills/emaki/references/01-interview.md +68 -0
- package/plugin/skills/emaki/references/02-architecture.md +69 -0
- package/plugin/skills/emaki/references/03-content-model.md +68 -0
- package/plugin/skills/emaki/references/04-scene-authoring.md +99 -0
- package/plugin/skills/emaki/references/05-voice-and-video.md +97 -0
- package/plugin/skills/emaki/references/06-i18n.md +37 -0
- package/plugin/skills/emaki/references/07-quality-gates.md +44 -0
- package/plugin/skills/emaki/references/08-feedback-loop.md +32 -0
- package/plugin/skills/emaki/references/09-publishing.md +14 -0
- package/plugin/skills/story-build/SKILL.md +37 -0
- package/plugin/skills/story-localize/SKILL.md +24 -0
- package/plugin/skills/story-media/SKILL.md +38 -0
- package/plugin/skills/story-publish/SKILL.md +36 -0
- package/plugin/skills/story-review/SKILL.md +29 -0
- package/plugin/templates/brief.md +32 -0
- package/plugin/templates/change-request.md +7 -0
- package/plugin/templates/changelog.md +4 -0
- package/plugin/templates/decisions.md +5 -0
- package/plugin/templates/glossary.md +4 -0
- package/plugin/templates/item-card.md +34 -0
- package/plugin/templates/outline.md +19 -0
- package/plugin/templates/review-sheet.md +12 -0
- package/plugin/templates/style-guide.md +21 -0
- package/plugin/templates/tracker.md +11 -0
- package/src/api.js +20 -0
- package/src/campaign.js +157 -0
- package/src/capture.js +205 -0
- package/src/carousel.js +91 -0
- package/src/config.js +32 -0
- package/src/day-script.js +66 -0
- package/src/desk-client.js +37 -0
- package/src/desk-plan.js +57 -0
- package/src/films.js +152 -0
- package/src/http.js +30 -0
- package/src/index.js +353 -0
- package/src/init.js +110 -0
- package/src/media.js +236 -0
- package/src/migrate.js +67 -0
- package/src/plugin.js +106 -0
- package/src/publish.js +118 -0
- package/src/stage.js +107 -0
- package/src/stories.js +66 -0
- package/src/tts.js +290 -0
- package/src/upload/instagram.js +34 -0
- package/src/upload/youtube.js +90 -0
- package/src/util.js +66 -0
- package/src/voice.js +295 -0
- package/src/youtube-text.js +58 -0
- package/templates/content/films/index.json +1 -0
- package/templates/content/films/measure-the-right-work/film.json +68 -0
- package/templates/content/films/measure-the-right-work/look.css +17 -0
- package/templates/content/films/measure-the-right-work/scene-close.json +153 -0
- package/templates/content/films/measure-the-right-work/scene-groups.json +99 -0
- package/templates/content/films/measure-the-right-work/scene-hook.json +96 -0
- package/templates/content/films/measure-the-right-work/scene-pair.json +190 -0
- package/templates/content/films/measure-the-right-work/scene-problem.json +162 -0
- package/templates/content/films/measure-the-right-work/score.js +19 -0
- package/templates/content/films/measure-the-right-work/strings/en.json +50 -0
- package/templates/content/films/measure-the-right-work/strings/es.json +50 -0
- package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
- package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
- package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en.json +7 -0
- package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es.json +7 -0
- package/templates/content/logos/brand.svg +1 -0
- package/templates/content/site.json +10 -0
- package/templates/content/stories/en/measure-the-right-work.json +13 -0
- package/templates/content/stories/es/measure-the-right-work.json +13 -0
- package/templates/content/stories/index.json +12 -0
- package/templates/content/ui/en.json +1 -0
- package/templates/content/ui/es.json +1 -0
- package/templates/emaki.config.json +67 -0
- package/templates/film/look.css +17 -0
- package/templates/film/scene-close.json +153 -0
- package/templates/film/scene-template.json +71 -0
- package/templates/film/score.js +12 -0
package/src/media.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// What render and build decide, as pure functions: frame ranges, output paths, ffmpeg arguments, the freeze table,
|
|
2
|
+
// chapters, the description. capture.js and voice.js run what these return (Playwright, ffmpeg); the specs test these.
|
|
3
|
+
// The reference is the sensei-hq.com website's films/tools/render.py and build.py.
|
|
4
|
+
import { join, resolve } from 'node:path'
|
|
5
|
+
import { SUFFIX } from './config.js'
|
|
6
|
+
import { die, runningTime } from './util.js'
|
|
7
|
+
|
|
8
|
+
/** The frames to capture: from `from` (default 0) to `to` (default and at most the film's end), at least one. */
|
|
9
|
+
export function frameRange(duration, fps, from = 0, to = undefined) {
|
|
10
|
+
const t0 = Math.max(0, Number(from ?? 0))
|
|
11
|
+
const end = Math.min(to == null ? duration : Number(to), duration)
|
|
12
|
+
if (!Number.isFinite(t0) || !Number.isFinite(end) || !(end > t0))
|
|
13
|
+
die(`--from ${from ?? 0} --to ${to ?? 'the end'} is not a range inside the film (it runs ${duration.toFixed(1)} s)`)
|
|
14
|
+
const frames = Math.max(1, Math.round((end - t0) * fps))
|
|
15
|
+
return { t0, end, frames, seconds: frames / fps }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Where a layout's render goes: the render folder by default; --out FILE.mp4 for one layout, --out FOLDER for any. */
|
|
19
|
+
export function renderOut(dir, slug, locale, layout, { out = undefined, layouts = 1 } = {}) {
|
|
20
|
+
const name = `${slug}-${locale}-${SUFFIX[layout]}.mp4`
|
|
21
|
+
if (!out) return join(dir, name)
|
|
22
|
+
if (!/\.mp4$/i.test(out)) return resolve(out, name)
|
|
23
|
+
if (layouts > 1) die(`--out ${out} is one file, so it takes one layout: add --o landscape or --o portrait, or give a folder`)
|
|
24
|
+
return resolve(out)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Where the music comes from (--music): `synth` the page's score (window.__show.audio(), on the film's own timing),
|
|
28
|
+
* `export` the audio of an exported film (`exportFile`; silent if it is missing), `none` a silent picture. */
|
|
29
|
+
export function musicFor(mode = 'synth', { exportFile = '', exists = (_f) => false } = {}) {
|
|
30
|
+
if (mode === 'synth') return { kind: 'synth' }
|
|
31
|
+
if (mode === 'none') return { kind: 'none' }
|
|
32
|
+
if (mode !== 'export') die(`--music ${mode}: use synth | export | none`)
|
|
33
|
+
if (exists(exportFile)) return { kind: 'file', file: exportFile }
|
|
34
|
+
return { kind: 'none', note: `no ${exportFile}: silent picture` }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What a render run does: capture frames, lay the music, save the covers. --audio-only lays the music on the
|
|
38
|
+
* existing render; --cover-only saves just the covers. */
|
|
39
|
+
export function renderSteps({ audioOnly = false, coverOnly = false } = {}) {
|
|
40
|
+
if (audioOnly && coverOnly) die('--audio-only and --cover-only exclude each other')
|
|
41
|
+
return { frames: !audioOnly && !coverOnly, music: !coverOnly, cover: true }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** ffmpeg reading JPEG frames from stdin; `audio` (from film time t0) laid under them. */
|
|
45
|
+
export function encodeArgs({ fps, seconds, dst, audio = null, t0 = 0 }) {
|
|
46
|
+
return ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',
|
|
47
|
+
...(audio ? ['-ss', t0.toFixed(3), '-i', audio, '-map', '0:v', '-map', '1:a'] : []),
|
|
48
|
+
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p', '-r', String(fps),
|
|
49
|
+
...(audio ? ['-c:a', 'aac', '-b:a', '192k'] : []), '-t', seconds.toFixed(3), '-movflags', '+faststart', dst]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** --audio-only: copies the picture and lays `audio` (from film time t0, for dur) under it. */
|
|
53
|
+
export function muxArgs(video, audio, t0, dur, dst) {
|
|
54
|
+
return ['-y', '-loglevel', 'error', '-i', video, '-ss', t0.toFixed(3), '-i', audio, '-map', '0:v', '-map', '1:a',
|
|
55
|
+
'-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-t', dur.toFixed(3), '-movflags', '+faststart', dst]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Runs `fn`; when it fails (the dev server reloaded the page under it), awaits `recover` (the show coming back)
|
|
59
|
+
* and runs it again, up to `attempts` times in all, then lets the last error through. */
|
|
60
|
+
export async function retrying(fn, recover, attempts = 8) {
|
|
61
|
+
for (let i = 1; ; i++) {
|
|
62
|
+
try {
|
|
63
|
+
return await fn()
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (i >= attempts) throw e
|
|
66
|
+
await recover(e)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** build.py's plan: each scene's place on the rendered picture (start, dur: film.json plus timing.<locale>.json) and on
|
|
72
|
+
* the output (at, tot). A take is laid `lead` s into its scene; when lead + take + tail is longer than the scene, the
|
|
73
|
+
* scene's last frame is frozen for the difference (ext), so nothing is cut off or sped up. `takes`: scene id →
|
|
74
|
+
* { file, seconds }. After `emaki fit` and a fresh render no scene needs a freeze. */
|
|
75
|
+
export function buildPlan(film, timing, takes, { lead, tail }) {
|
|
76
|
+
const rows = []
|
|
77
|
+
let start = 0, at = 0
|
|
78
|
+
for (const [i, s] of film.scenes.entries()) {
|
|
79
|
+
const dur = runningTime(s, timing?.[s.id])
|
|
80
|
+
const take = takes.get(s.id) ?? null
|
|
81
|
+
const L = take ? take.seconds : 0
|
|
82
|
+
let ext = take ? Math.max(0, lead + L + tail - dur) : 0
|
|
83
|
+
if (ext < 1e-3) ext = 0
|
|
84
|
+
rows.push({ n: i + 1, id: s.id, name: s.name ?? s.id, start, dur, take: take?.file ?? null, L, ext, tot: dur + ext, at })
|
|
85
|
+
start += dur
|
|
86
|
+
at += dur + ext
|
|
87
|
+
}
|
|
88
|
+
return { rows, picture: start, total: at, extended: rows.some((r) => r.ext > 0), missing: rows.filter((r) => !r.take).map((r) => r.id) }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const mmss = (t) => `${String(Math.floor(t / 60)).padStart(2, '0')}:${String(Math.floor(t % 60)).padStart(2, '0')}`
|
|
92
|
+
|
|
93
|
+
/** The table build --check prints (build.py's): each scene's length, take, freeze and new length, and where it starts. */
|
|
94
|
+
export function planTable(plan) {
|
|
95
|
+
const f = (x, w) => x.toFixed(1).padStart(w)
|
|
96
|
+
const lines = [`${'#'.padStart(2)} ${'scene'.padEnd(12)} ${'dur'.padStart(5)} ${'take'.padStart(5)} ${'ext'.padStart(5)} ${'new'.padStart(6)} start`]
|
|
97
|
+
for (const r of plan.rows)
|
|
98
|
+
lines.push(`${String(r.n).padStart(2)} ${r.id.padEnd(12)} ${f(r.dur, 5)} ${f(r.L, 5)} ${f(r.ext, 5)} ${f(r.tot, 6)} ${mmss(r.at)}${r.take ? '' : ' (no take)'}`)
|
|
99
|
+
const k = plan.rows.filter((r) => r.ext > 0).length
|
|
100
|
+
lines.push(`total ${plan.total.toFixed(1)} s` + (k ? ` (${k} scene${k > 1 ? 's' : ''} frozen to fit ${k > 1 ? 'their takes' : 'its take'}; \`emaki fit\` and a new render make that unnecessary)` : ''))
|
|
101
|
+
return lines
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const escMeta = (s) => String(s).replace(/[\\=;#]/g, (c) => `\\${c}`).replace(/\n/g, ' ')
|
|
105
|
+
|
|
106
|
+
/** FFMETADATA with one chapter per scene, on the exact scene boundaries (VLC, QuickTime; YouTube ignores it). */
|
|
107
|
+
export function ffmeta(rows) {
|
|
108
|
+
const lines = [';FFMETADATA1']
|
|
109
|
+
for (const r of rows)
|
|
110
|
+
lines.push('[CHAPTER]', 'TIMEBASE=1/1000', `START=${Math.round(r.at * 1000)}`, `END=${Math.round((r.at + r.tot) * 1000)}`, `title=${escMeta(r.name)}`)
|
|
111
|
+
return lines.join('\n') + '\n'
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** YouTube's chapter list: [at, title] from 0:00, every chapter at least 10 s (YouTube shows none unless all its rules
|
|
115
|
+
* hold). Short scenes fold into the chapter they start; a short tail joins the last one. Boundaries stay on cuts. */
|
|
116
|
+
export function ytChapters(rows) {
|
|
117
|
+
const groups = []
|
|
118
|
+
let cur = [], start = 0
|
|
119
|
+
for (const r of rows) {
|
|
120
|
+
cur.push(r)
|
|
121
|
+
if (r.at + r.tot - start >= 10 - 1e-6) {
|
|
122
|
+
groups.push([start, cur])
|
|
123
|
+
cur = []
|
|
124
|
+
start = r.at + r.tot
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (cur.length) {
|
|
128
|
+
if (groups.length) groups.at(-1)[1].push(...cur)
|
|
129
|
+
else groups.push([start, cur])
|
|
130
|
+
}
|
|
131
|
+
return groups.map(([at, rs]) => [at, rs.map((r) => r.name).join(' + ')])
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** chapters.txt: "m:ss title" per line, ready for a video description. */
|
|
135
|
+
export const chaptersText = (chapters) =>
|
|
136
|
+
chapters.map(([at, name]) => `${Math.floor(at / 60)}:${String(Math.floor(at % 60)).padStart(2, '0')} ${name}\n`).join('')
|
|
137
|
+
|
|
138
|
+
/** description.txt: the title, the chapter list and the story link, ready to paste into a video description. */
|
|
139
|
+
export const description = ({ title, chapters, link = null }) => `${title}\n\n${chaptersText(chapters)}${link ? `\n${link}\n` : ''}`
|
|
140
|
+
|
|
141
|
+
/** The story page a video links to: emaki.config.json storyUrl ({site} {locale} {slug}), by default
|
|
142
|
+
* {site}/{locale}/stories/{slug}; null when the pattern needs the site url and site.json has none. */
|
|
143
|
+
export function storyLink(site, cfg, slug, locale) {
|
|
144
|
+
const pattern = cfg?.storyUrl ?? '{site}/{locale}/stories/{slug}'
|
|
145
|
+
const base = String(site?.url ?? '').replace(/\/+$/, '')
|
|
146
|
+
if (pattern.includes('{site}') && !base) return null
|
|
147
|
+
return pattern.replaceAll('{site}', base).replaceAll('{locale}', locale).replaceAll('{slug}', slug)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** poster.jpg, poster-vertical.jpg and <slug>-<locale>-thumb.jpg (1280x720, YouTube's custom thumbnail): from the
|
|
151
|
+
* covers render saved, else a still from the end card of the built video (2.5 s into the last scene, or 0.2 s
|
|
152
|
+
* before its end). Each step is { copy: [src, dst] } or { ffmpeg: args }; a step with no source is left out. */
|
|
153
|
+
export function posterSteps({ render, out, slug, locale, built, last, exists }) {
|
|
154
|
+
const cover = (sfx) => join(render, `${slug}-${locale}-cover-${sfx}.jpg`)
|
|
155
|
+
const still = (last.at + Math.min(last.tot - 0.2, 2.5)).toFixed(2)
|
|
156
|
+
const steps = []
|
|
157
|
+
for (const [sfx, layout, name] of [['16x9', 'landscape', 'poster.jpg'], ['9x16', 'portrait', 'poster-vertical.jpg']]) {
|
|
158
|
+
if (exists(cover(sfx))) steps.push({ copy: [cover(sfx), join(out, name)] })
|
|
159
|
+
else if (built[layout]) steps.push({ ffmpeg: ['-y', '-v', 'error', '-ss', still, '-i', built[layout], '-frames:v', '1', '-q:v', '2', join(out, name)] })
|
|
160
|
+
}
|
|
161
|
+
const thumb = join(out, `${slug}-${locale}-thumb.jpg`)
|
|
162
|
+
if (exists(cover('16x9'))) steps.push({ ffmpeg: ['-y', '-v', 'error', '-i', cover('16x9'), '-vf', 'scale=1280:720', '-q:v', '3', thumb] })
|
|
163
|
+
else if (built.landscape)
|
|
164
|
+
steps.push({ ffmpeg: ['-y', '-v', 'error', '-ss', still, '-i', built.landscape, '-vf', 'scale=1280:720', '-frames:v', '1', '-q:v', '3', thumb] })
|
|
165
|
+
return steps
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The -web.mp4: the 16:9 film at 30 fps, CRF 26, AAC 128k, chapters kept; small enough for static hosting. */
|
|
169
|
+
export const webArgs = (src, dst) => ['-y', '-v', 'error', '-i', src, '-r', '30', '-c:v', 'libx264', '-crf', '26', '-preset', 'slow',
|
|
170
|
+
'-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', '-map_chapters', '0', '-movflags', '+faststart', dst]
|
|
171
|
+
|
|
172
|
+
/** The web copy's size, flagged above the 25 MiB a static host such as Cloudflare Pages serves. */
|
|
173
|
+
export function webNote(bytes) {
|
|
174
|
+
const mb = bytes / 1048576
|
|
175
|
+
return `${mb.toFixed(1)} MiB${mb > 25 ? ' - OVER 25 MiB, raise -crf' : ''}`
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** One take for the browser (voice-web): mono AAC 64k at -16 LUFS (speech heard on its own, under a ducked score),
|
|
179
|
+
* the index up front so it starts streaming at once. */
|
|
180
|
+
export const webVoiceArgs = (src, dst) => ['-y', '-v', 'error', '-i', src, '-vn', '-ac', '1', '-ar', '48000',
|
|
181
|
+
'-af', 'loudnorm=I=-16:TP=-1.5:LRA=11', '-c:a', 'aac', '-b:a', '64k', '-movflags', '+faststart', dst]
|
|
182
|
+
|
|
183
|
+
const LOUDNORM = 'loudnorm=I=-14:TP=-1.5:LRA=11'
|
|
184
|
+
|
|
185
|
+
/** ffmpeg for one final video: the rendered picture (`pic`, its own audio track the music when `music`), the voice
|
|
186
|
+
* (`voice`, already on the output timeline), the score ducked under the voice, -14 LUFS, `subtitles` (a filter) burned
|
|
187
|
+
* in. When the plan freezes a scene, each scene is cut from the picture on its own input, the frozen one padded with
|
|
188
|
+
* its last frame and its music looped under the hold (5 ms fades hide the seam), and the scenes joined again.
|
|
189
|
+
* `chapters`: an FFMETADATA file (ffmeta) whose chapters are written in the same pass. */
|
|
190
|
+
export function buildArgs({ pic, voice, plan, music, subtitles = null, chapters = null, scoreLevel = 0.55, dst }) {
|
|
191
|
+
const inputs = [], fc = []
|
|
192
|
+
let vid, mu = null
|
|
193
|
+
if (plan.extended) {
|
|
194
|
+
const n = plan.rows.length
|
|
195
|
+
for (const r of plan.rows) inputs.push('-ss', r.start.toFixed(3), '-t', r.dur.toFixed(3), '-i', pic)
|
|
196
|
+
plan.rows.forEach((r, i) => {
|
|
197
|
+
fc.push(`[${i}:v]${r.ext ? `tpad=stop_mode=clone:stop_duration=${r.ext.toFixed(3)},` : ''}setpts=PTS-STARTPTS[v${i}]`)
|
|
198
|
+
if (music) {
|
|
199
|
+
const loop = r.ext ? `afade=t=in:st=0:d=0.005,afade=t=out:st=${(r.dur - 0.005).toFixed(3)}:d=0.005,aloop=loop=-1:size=2e9,` : ''
|
|
200
|
+
fc.push(`[${i}:a]aresample=48000,aformat=channel_layouts=stereo,${loop}apad,atrim=0:${r.tot.toFixed(3)},asetpts=PTS-STARTPTS[m${i}]`)
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
fc.push(`${plan.rows.map((_, i) => `[v${i}]`).join('')}concat=n=${n}:v=1:a=0[pv]`)
|
|
204
|
+
if (music) fc.push(`${plan.rows.map((_, i) => `[m${i}]`).join('')}concat=n=${n}:v=0:a=1[mu]`)
|
|
205
|
+
vid = '[pv]'
|
|
206
|
+
mu = music ? '[mu]' : null
|
|
207
|
+
} else {
|
|
208
|
+
inputs.push('-i', pic)
|
|
209
|
+
vid = '0:v'
|
|
210
|
+
if (music) {
|
|
211
|
+
fc.push('[0:a]aresample=48000,aformat=channel_layouts=stereo[mu]')
|
|
212
|
+
mu = '[mu]'
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const vo = inputs.filter((x) => x === '-i').length
|
|
216
|
+
inputs.push('-i', voice)
|
|
217
|
+
const meta = chapters ? ['-map_metadata', String(vo + 1), '-map_chapters', String(vo + 1)] : []
|
|
218
|
+
if (chapters) inputs.push('-i', chapters)
|
|
219
|
+
if (mu)
|
|
220
|
+
fc.push(`${mu}volume=${scoreLevel}[sc]`, `[${vo}:a]aresample=48000,asplit=2[vo][key]`,
|
|
221
|
+
'[sc][key]sidechaincompress=threshold=0.05:ratio=6:release=400[duck]', `[duck][vo]amix=inputs=2:normalize=0,${LOUDNORM}[a]`)
|
|
222
|
+
else fc.push(`[${vo}:a]${LOUDNORM}[a]`)
|
|
223
|
+
if (subtitles) {
|
|
224
|
+
fc.push(`${vid.startsWith('[') ? vid : `[${vid}]`}${subtitles}[v]`)
|
|
225
|
+
vid = '[v]'
|
|
226
|
+
}
|
|
227
|
+
return ['-y', '-v', 'error', ...inputs, '-filter_complex', fc.join(';'), '-map', vid, '-map', '[a]', ...meta,
|
|
228
|
+
'-c:v', 'libx264', '-crf', '18', '-preset', 'medium', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k',
|
|
229
|
+
'-t', plan.total.toFixed(3), '-movflags', '+faststart', dst]
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** A warning when an existing render no longer runs as long as the film (after a retiming): its frames are stale. */
|
|
233
|
+
export function staleRender(rendered, film, ranged = false) {
|
|
234
|
+
if (ranged || Math.abs(rendered - film) <= 0.2) return null
|
|
235
|
+
return `the render runs ${rendered.toFixed(1)} s but the film now runs ${film.toFixed(1)} s; render the frames again`
|
|
236
|
+
}
|
package/src/migrate.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// emaki migrate <website>: moves a sensei-hq.com-style site's motion content into emaki's layout, once, so `emaki`
|
|
2
|
+
// can take over its films (issue #1, gap 4). Nothing that already exists is overwritten; the report lists what was
|
|
3
|
+
// written and what was kept, and `emaki validate` checks the result.
|
|
4
|
+
//
|
|
5
|
+
// src/lib/motion/films/<slug>/ → content/films/<slug>/ (base.css becomes look.css)
|
|
6
|
+
// src/lib/motion/logos/ → content/logos/
|
|
7
|
+
// src/lib/content/articles/index.json → content/stories/index.json, minus the reader-facing text …
|
|
8
|
+
// src/lib/content/articles/<slug>.json → content/stories/<locale>/<slug>.json, plus that text (title, dek, …)
|
|
9
|
+
// films/<slug>/film.json scenes → content/films/<slug>/voice/<locale>.json (the narration)
|
|
10
|
+
// films/<slug>/takes/*.wav → production/<slug>/<locale>/takes/ (recorded takes: keep, don't regenerate)
|
|
11
|
+
import { copyFileSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { dirname, join } from 'node:path'
|
|
13
|
+
import { die, exists, load } from './util.js'
|
|
14
|
+
|
|
15
|
+
/** Index fields that are words for the reader: emaki keeps them per locale, in the story body. */
|
|
16
|
+
const TEXT = ['title', 'dek', 'kanjiGloss', 'series']
|
|
17
|
+
|
|
18
|
+
export function migrate(p, from, { locale = 'en' } = {}) {
|
|
19
|
+
const films = join(from, 'src/lib/motion/films'), articles = join(from, 'src/lib/content/articles')
|
|
20
|
+
if (!exists(films) && !exists(articles)) die(`${from} has neither src/lib/motion/films nor src/lib/content/articles`)
|
|
21
|
+
const wrote = [], kept = []
|
|
22
|
+
const put = (dst, write) => {
|
|
23
|
+
const rel = p.rel(dst)
|
|
24
|
+
if (exists(dst)) return kept.push(rel)
|
|
25
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
26
|
+
write(dst)
|
|
27
|
+
wrote.push(rel)
|
|
28
|
+
}
|
|
29
|
+
const copy = (src, dst) => put(dst, (d) => copyFileSync(src, d))
|
|
30
|
+
const json = (dst, data) => put(dst, (d) => writeFileSync(d, JSON.stringify(data, null, 1) + '\n'))
|
|
31
|
+
const tree = (src, dst, rename = (n) => n) => {
|
|
32
|
+
for (const e of readdirSync(src, { withFileTypes: true }))
|
|
33
|
+
if (e.isDirectory()) tree(join(src, e.name), join(dst, e.name))
|
|
34
|
+
else copy(join(src, e.name), join(dst, rename(e.name)))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (exists(films))
|
|
38
|
+
for (const slug of readdirSync(films).filter((d) => exists(join(films, d, 'film.json'))))
|
|
39
|
+
tree(join(films, slug), join(p.films, slug), (n) => (n === 'base.css' ? 'look.css' : n))
|
|
40
|
+
const logos = join(from, 'src/lib/motion/logos')
|
|
41
|
+
if (exists(logos)) tree(logos, join(p.content, 'logos'))
|
|
42
|
+
|
|
43
|
+
if (exists(join(articles, 'index.json'))) {
|
|
44
|
+
const index = load(join(articles, 'index.json'))
|
|
45
|
+
json(join(p.content, 'stories', 'index.json'), index.map((e) => Object.fromEntries(Object.entries(e).filter(([k]) => !TEXT.includes(k)))))
|
|
46
|
+
for (const e of index) {
|
|
47
|
+
const src = join(articles, `${e.slug}.json`)
|
|
48
|
+
if (!exists(src)) continue
|
|
49
|
+
const text = Object.fromEntries(TEXT.filter((k) => k in e).map((k) => [k, e[k]]))
|
|
50
|
+
json(join(p.content, 'stories', locale, `${e.slug}.json`), { ...text, ...load(src) })
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const masters = join(from, 'films')
|
|
55
|
+
if (exists(masters))
|
|
56
|
+
for (const slug of readdirSync(masters).filter((d) => exists(join(masters, d, 'film.json')))) {
|
|
57
|
+
const scenes = load(join(masters, slug, 'film.json')).scenes ?? []
|
|
58
|
+
if (scenes.length && exists(join(p.films, slug)))
|
|
59
|
+
json(join(p.films, slug, 'voice', `${locale}.json`), scenes.map((s) => ({ scene: s.id, text: s.text ?? '', say: s.say ?? null })))
|
|
60
|
+
const takes = join(masters, slug, 'takes')
|
|
61
|
+
if (exists(takes))
|
|
62
|
+
for (const f of readdirSync(takes).filter((n) => n.endsWith('.wav'))) copy(join(takes, f), p.prod(slug, locale, 'takes', f))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (!exists(join(p.content, 'site.json'))) json(join(p.content, 'site.json'), { name: '', url: '', locales: [locale], defaultLocale: locale })
|
|
66
|
+
return { wrote, kept }
|
|
67
|
+
}
|
package/src/plugin.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// The Claude plugin ships inside this package (plugin/): skills, agents, the playbook and planning templates. These
|
|
2
|
+
// commands copy it into a project's .claude/ so Claude Code / Cowork picks it up, the same way @rokkit/cli does.
|
|
3
|
+
/* eslint-disable no-console */
|
|
4
|
+
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
|
|
5
|
+
import { join, resolve } from 'node:path'
|
|
6
|
+
import { fileURLToPath } from 'node:url'
|
|
7
|
+
|
|
8
|
+
export const PLUGIN_DIR = (() => {
|
|
9
|
+
try {
|
|
10
|
+
return fileURLToPath(new URL('../plugin/', import.meta.url))
|
|
11
|
+
} catch {
|
|
12
|
+
return resolve(process.cwd(), 'packages/emaki-cli/plugin')
|
|
13
|
+
}
|
|
14
|
+
})()
|
|
15
|
+
|
|
16
|
+
/** name + description from a SKILL.md or agent .md frontmatter. */
|
|
17
|
+
export function parseFrontmatter(md) {
|
|
18
|
+
const block = md.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? ''
|
|
19
|
+
const field = (key) => {
|
|
20
|
+
const m = block.match(new RegExp(`^${key}:[ \t]*(.*)$`, 'm'))
|
|
21
|
+
if (!m) return ''
|
|
22
|
+
if (!/^[>|][-+]?$/.test(m[1].trim())) return m[1].trim()
|
|
23
|
+
// A folded (>) or literal (|) block: the indented lines that follow.
|
|
24
|
+
const rest = block.slice(m.index + m[0].length + 1).split('\n')
|
|
25
|
+
const lines = []
|
|
26
|
+
for (const l of rest) { if (l && !/^\s/.test(l)) break; lines.push(l.trim()) }
|
|
27
|
+
return lines.join(m[1].startsWith('|') ? '\n' : ' ').trim()
|
|
28
|
+
}
|
|
29
|
+
return { name: field('name'), description: field('description') }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function listSkills({ dir = PLUGIN_DIR } = {}) {
|
|
33
|
+
const root = join(dir, 'skills')
|
|
34
|
+
if (!existsSync(root)) return []
|
|
35
|
+
return readdirSync(root)
|
|
36
|
+
.filter((e) => existsSync(join(root, e, 'SKILL.md')))
|
|
37
|
+
.map((e) => ({ ...parseFrontmatter(readFileSync(join(root, e, 'SKILL.md'), 'utf-8')), folder: e }))
|
|
38
|
+
.filter((s) => s.name)
|
|
39
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function listAgents({ dir = PLUGIN_DIR } = {}) {
|
|
43
|
+
const root = join(dir, 'agents')
|
|
44
|
+
if (!existsSync(root)) return []
|
|
45
|
+
return readdirSync(root)
|
|
46
|
+
.filter((e) => e.endsWith('.md'))
|
|
47
|
+
.map((e) => ({ ...parseFrontmatter(readFileSync(join(root, e), 'utf-8')), file: e }))
|
|
48
|
+
.filter((a) => a.name)
|
|
49
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Copies skills into <cwd>/.claude/skills/<name>/ (idempotent unless force). */
|
|
53
|
+
export function installSkills(names, { cwd = process.cwd(), force = false, dir = PLUGIN_DIR } = {}) {
|
|
54
|
+
const catalog = new Map(listSkills({ dir }).map((s) => [s.name, s]))
|
|
55
|
+
const target = resolve(cwd, '.claude', 'skills')
|
|
56
|
+
return names.map((name) => {
|
|
57
|
+
const s = catalog.get(name)
|
|
58
|
+
if (!s) return { name, status: 'unknown' }
|
|
59
|
+
const dest = join(target, name)
|
|
60
|
+
if (existsSync(dest) && !force) return { name, status: 'skipped' }
|
|
61
|
+
mkdirSync(target, { recursive: true })
|
|
62
|
+
cpSync(join(dir, 'skills', s.folder), dest, { recursive: true })
|
|
63
|
+
return { name, status: 'added' }
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Copies agents into <cwd>/.claude/agents/<name>.md. */
|
|
68
|
+
export function installAgents(names, { cwd = process.cwd(), force = false, dir = PLUGIN_DIR } = {}) {
|
|
69
|
+
const catalog = new Map(listAgents({ dir }).map((a) => [a.name, a]))
|
|
70
|
+
const target = resolve(cwd, '.claude', 'agents')
|
|
71
|
+
return names.map((name) => {
|
|
72
|
+
const a = catalog.get(name)
|
|
73
|
+
if (!a) return { name, status: 'unknown' }
|
|
74
|
+
const dest = join(target, `${name}.md`)
|
|
75
|
+
if (existsSync(dest) && !force) return { name, status: 'skipped' }
|
|
76
|
+
mkdirSync(target, { recursive: true })
|
|
77
|
+
cpSync(join(dir, 'agents', a.file), dest)
|
|
78
|
+
return { name, status: 'added' }
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The whole plugin into the project: every skill and agent, plus the playbook and planning templates under
|
|
83
|
+
* .claude/emaki/ (the skills read them from there). */
|
|
84
|
+
export function installPlugin({ cwd = process.cwd(), force = false, dir = PLUGIN_DIR } = {}) {
|
|
85
|
+
const skills = installSkills(listSkills({ dir }).map((s) => s.name), { cwd, force, dir })
|
|
86
|
+
const agents = installAgents(listAgents({ dir }).map((a) => a.name), { cwd, force, dir })
|
|
87
|
+
const home = resolve(cwd, '.claude', 'emaki')
|
|
88
|
+
const extras = []
|
|
89
|
+
for (const f of ['PLAYBOOK.md', 'README.md', 'templates', 'modules']) {
|
|
90
|
+
const src = join(dir, f), dest = join(home, f)
|
|
91
|
+
if (!existsSync(src)) continue
|
|
92
|
+
if (existsSync(dest) && !force) { extras.push({ name: f, status: 'skipped' }); continue }
|
|
93
|
+
mkdirSync(home, { recursive: true })
|
|
94
|
+
cpSync(src, dest, { recursive: true })
|
|
95
|
+
extras.push({ name: f, status: 'added' })
|
|
96
|
+
}
|
|
97
|
+
return { skills, agents, extras }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function report(kind, results) {
|
|
101
|
+
for (const r of results) {
|
|
102
|
+
if (r.status === 'added') console.info(` added ${kind} ${r.name}`)
|
|
103
|
+
else if (r.status === 'skipped') console.info(` skipped ${kind} ${r.name} (exists; --force to overwrite)`)
|
|
104
|
+
else { console.error(` unknown ${kind}: ${r.name}`); process.exitCode = 1 }
|
|
105
|
+
}
|
|
106
|
+
}
|
package/src/publish.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// emaki publish youtube|instagram <slug>: post a finished, checked film straight to a platform (no desk approval),
|
|
2
|
+
// then write the link into the story's entry in content/stories/index.json (an existing id or link is never
|
|
3
|
+
// overwritten). --dry-run prints exactly what would post and touches nothing; --verify checks the credentials
|
|
4
|
+
// read-only and names the account.
|
|
5
|
+
//
|
|
6
|
+
// YouTube: the 16:9 film, the description (out/description.txt, else title + chapters + link), the story's tags,
|
|
7
|
+
// the captions and the 16:9 cover as thumbnail. Unlisted unless --privacy public. --update <id> refreshes an uploaded
|
|
8
|
+
// video in place. Needs YT_CLIENT_ID, YT_CLIENT_SECRET, YT_REFRESH_TOKEN.
|
|
9
|
+
// Instagram: the 9:16 film as a Reel with its cover. Meta fetches media from a public URL: pass --video-url and
|
|
10
|
+
// --cover-url, or the files go to the desk's media store and are linked for an hour with the desk's signature
|
|
11
|
+
// (STAGER_CLIENT_ID, STAGER_CLIENT_SECRET, MEDIA_URL_SECRET). Needs IG_USER_ID, IG_ACCESS_TOKEN.
|
|
12
|
+
import { readFileSync, statSync } from 'node:fs'
|
|
13
|
+
import { basename, join } from 'node:path'
|
|
14
|
+
import { signMedia } from '@senseihq/emaki-posting'
|
|
15
|
+
import { deskClient } from './desk-client.js'
|
|
16
|
+
import { need } from './http.js'
|
|
17
|
+
import { filmFiles, hashtags, recordLinks, storiesIndex, storyFor, storyUrl } from './stories.js'
|
|
18
|
+
import { instagram } from './upload/instagram.js'
|
|
19
|
+
import { youtube } from './upload/youtube.js'
|
|
20
|
+
import { die, exists, load, mediaLength } from './util.js'
|
|
21
|
+
import { mergeDescription, youtubeDescription } from './youtube-text.js'
|
|
22
|
+
|
|
23
|
+
const PRIVACY = ['public', 'unlisted', 'private']
|
|
24
|
+
const kb = (f) => `${Math.round(statSync(f).size / 1024)} KB`
|
|
25
|
+
|
|
26
|
+
export async function publish(p, channel, slug, opts = {}) {
|
|
27
|
+
if (channel === 'youtube') return publishYoutube(p, slug, opts)
|
|
28
|
+
if (channel === 'instagram') return publishInstagram(p, slug, opts)
|
|
29
|
+
die(`publish to youtube or instagram (got "${channel}")`)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ytClient(env, fetch, log) {
|
|
33
|
+
need(env, 'YT_CLIENT_ID', 'YT_CLIENT_SECRET', 'YT_REFRESH_TOKEN')
|
|
34
|
+
return youtube({ clientId: env.YT_CLIENT_ID, clientSecret: env.YT_CLIENT_SECRET, refreshToken: env.YT_REFRESH_TOKEN, fetch, log })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function publishYoutube(p, slug, { locale, verify, dryRun, privacy = 'unlisted', update, forceNew, descriptionMode = 'prepend', env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
|
|
38
|
+
if (verify) return log(`YouTube posts as: ${await ytClient(env, fetch, log).verify()}`)
|
|
39
|
+
if (!PRIVACY.includes(privacy)) die('--privacy: public, unlisted or private')
|
|
40
|
+
if (!['prepend', 'replace'].includes(descriptionMode)) die('--description-mode: prepend or replace')
|
|
41
|
+
locale ??= p.site.defaultLocale
|
|
42
|
+
const yt = dryRun ? null : ytClient(env, fetch, log)
|
|
43
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
44
|
+
if (!f.wide) die(`${slug}: no built 16:9 video (${p.rel(f.expect.wide)}); run \`emaki render ${slug}\` and \`emaki build ${slug}\` first`)
|
|
45
|
+
const desc = youtubeDescription(p, slug, locale, story.title), tags = story.tags
|
|
46
|
+
const srt = f.srt ? readFileSync(f.srt) : null, thumb = f.thumb ? readFileSync(f.thumb) : null
|
|
47
|
+
if (update) {
|
|
48
|
+
const remote = dryRun ? null : (await yt.getVideo(update)).snippet
|
|
49
|
+
const merged = remote ? mergeDescription(remote.description ?? '', desc, descriptionMode) : desc
|
|
50
|
+
log(`YouTube update · ${story.title} · https://www.youtube.com/watch?v=${update}`)
|
|
51
|
+
log(` title: ${remote ? JSON.stringify(remote.title) : '(remote)'} → ${JSON.stringify(story.title)}`)
|
|
52
|
+
log(` desc: ${descriptionMode}, ${merged.length} chars`)
|
|
53
|
+
log(` tags: ${tags.length ? tags.join(', ') : '(keep remote)'}`)
|
|
54
|
+
log(` captions: ${f.srt ? `replace uploaded tracks with ${basename(f.srt)}` : 'none (skipped)'}`)
|
|
55
|
+
log(` thumb: ${f.thumb ? `set ${basename(f.thumb)}` : 'skipped (none rendered)'}`)
|
|
56
|
+
if (dryRun) return log('dry run: nothing changed'), { dryRun: true }
|
|
57
|
+
await yt.updateMetadata(update, { title: story.title, description: merged, tags: tags.length ? tags : undefined })
|
|
58
|
+
if (srt) await yt.replaceCaptions(update, srt, locale)
|
|
59
|
+
if (thumb) await yt.setThumbnail(update, thumb)
|
|
60
|
+
recordLinks(p, slug, { youtube: update })
|
|
61
|
+
log(`updated; recorded in ${p.rel(storiesIndex(p))}`)
|
|
62
|
+
return { id: update, updated: true }
|
|
63
|
+
}
|
|
64
|
+
if (story.youtube && !forceNew)
|
|
65
|
+
die(`${slug} is already on YouTube as ${story.youtube}; pass --update ${story.youtube} to refresh it, or --force-new to upload again`)
|
|
66
|
+
log(`YouTube · ${story.title} · privacy ${privacy}`)
|
|
67
|
+
log(` video: ${basename(f.wide)} (${kb(f.wide)})`)
|
|
68
|
+
log(` desc: ${desc.length} chars, ${desc.split('\n').filter((l) => /^\d+:\d\d /.test(l)).length} chapters`)
|
|
69
|
+
log(` tags: ${tags.slice(0, 10).join(', ')}`)
|
|
70
|
+
log(` captions: ${f.srt ? basename(f.srt) : 'none (continues without)'}`)
|
|
71
|
+
log(` thumb: ${f.thumb ? basename(f.thumb) : 'none (continues without)'}`)
|
|
72
|
+
if (dryRun) return log('dry run: nothing posted'), { dryRun: true }
|
|
73
|
+
const r = await yt.publish(readFileSync(f.wide), { title: story.title, description: desc, tags, privacy, srt, thumb, language: locale })
|
|
74
|
+
recordLinks(p, slug, { youtube: r.id })
|
|
75
|
+
log(`posted: ${r.url}\nrecorded in ${p.rel(storiesIndex(p))}`)
|
|
76
|
+
return r
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Public URLs Meta can fetch: the flags, else the files staged on the desk and signed for an hour. */
|
|
80
|
+
async function reelUrls(p, slug, f, { videoUrl, coverUrl, env, fetch, now }) {
|
|
81
|
+
if (videoUrl && coverUrl) return [videoUrl, coverUrl]
|
|
82
|
+
need(env, 'STAGER_CLIENT_ID', 'STAGER_CLIENT_SECRET', 'MEDIA_URL_SECRET')
|
|
83
|
+
if (!f.coverTall) die(`${slug}: no 9:16 cover; run \`emaki render ${slug}\` first`)
|
|
84
|
+
const desk = deskClient(p, { env, fetch }), urls = []
|
|
85
|
+
for (const [key, file, type] of [[`${slug}/${basename(f.tall)}`, f.tall, 'video/mp4'], [`${slug}/instagram-${basename(f.coverTall)}`, f.coverTall, 'image/jpeg']]) {
|
|
86
|
+
await desk.putMedia(key.toLowerCase(), readFileSync(file), type)
|
|
87
|
+
urls.push(await signMedia(key.toLowerCase(), env.MEDIA_URL_SECRET, desk.origin, 3600, now(), env.MEDIA_PATH || '/m'))
|
|
88
|
+
}
|
|
89
|
+
return urls
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function publishInstagram(p, slug, { locale, verify, dryRun, videoUrl, coverUrl, env = process.env, fetch = globalThis.fetch, log = console.info, length = mediaLength, sleep, now = Date.now } = {}) {
|
|
93
|
+
const client = () => {
|
|
94
|
+
need(env, 'IG_USER_ID', 'IG_ACCESS_TOKEN')
|
|
95
|
+
return instagram({ userId: env.IG_USER_ID, token: env.IG_ACCESS_TOKEN, version: env.IG_GRAPH_VERSION || 'v21.0', fetch, ...(sleep ? { sleep } : {}) })
|
|
96
|
+
}
|
|
97
|
+
if (verify) return log(`Instagram posts as: @${await client().verify()}`)
|
|
98
|
+
if (Boolean(videoUrl) !== Boolean(coverUrl)) die('pass both --video-url and --cover-url, or neither (to stage them on the desk)')
|
|
99
|
+
locale ??= p.site.defaultLocale
|
|
100
|
+
const ig = dryRun ? null : client()
|
|
101
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
102
|
+
if (!f.tall) die(`${slug}: no built 9:16 video (${p.rel(f.expect.tall)}); render and build the portrait film first`)
|
|
103
|
+
const dur = length(f.tall)
|
|
104
|
+
if (dur > 15 * 60) die(`${slug}: ${Math.round(dur)} s is over the 15-minute Reels limit`)
|
|
105
|
+
const pj = join(p.films, slug, `post.${locale}.json`)
|
|
106
|
+
const staged = exists(pj) ? load(pj).instagram_reel?.caption : null
|
|
107
|
+
const caption = staged || `${story.title}. ${story.dek}\n\nRead the story: ${storyUrl(p, slug, locale)}\n\n${hashtags(story.tags)}`
|
|
108
|
+
log(`Instagram Reel · ${slug} · ${Math.round(dur)} s`)
|
|
109
|
+
log(` video: ${basename(f.tall)} (${kb(f.tall)})`)
|
|
110
|
+
log(` cover: ${f.coverTall ? basename(f.coverTall) : 'none!'}`)
|
|
111
|
+
log(` caption: ${caption.length} chars`)
|
|
112
|
+
if (dryRun) return log('dry run: nothing posted'), { dryRun: true }
|
|
113
|
+
const [video, cover] = await reelUrls(p, slug, f, { videoUrl, coverUrl, env, fetch, now })
|
|
114
|
+
const r = await ig.publishReel(video, caption, cover)
|
|
115
|
+
recordLinks(p, slug, { instagram: r.url })
|
|
116
|
+
log(`posted: ${r.url}\nrecorded in ${p.rel(storiesIndex(p))}`)
|
|
117
|
+
return r
|
|
118
|
+
}
|
package/src/stage.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// emaki stage <slug>: upload a finished piece's media and post text to the posting desk, so a person can review and
|
|
2
|
+
// approve exactly that. Restaging changes a post's fingerprint, so an earlier approval for that channel no longer
|
|
3
|
+
// applies (the desk's rule). --dry-run prints the posts and sends nothing.
|
|
4
|
+
//
|
|
5
|
+
// A campaign day (a day script in <campaign>/days/): every channel's text from the script; the film's 9:16 video for
|
|
6
|
+
// YouTube (a Short), the Reel and X; <campaign>/carousels/<slug>/*.png (as JPEG) for the carousel.
|
|
7
|
+
// A film: the 16:9 video (+ captions, + the 16:9 cover as thumbnail) for YouTube and X, the 9:16 video (+ cover) for
|
|
8
|
+
// the Reel, and the text in content/films/<slug>/post.<locale>.json, which the first run drafts for a read-through.
|
|
9
|
+
import { createHash } from 'node:crypto'
|
|
10
|
+
import { mkdtempSync, readdirSync, readFileSync } from 'node:fs'
|
|
11
|
+
import { tmpdir } from 'node:os'
|
|
12
|
+
import { basename, join } from 'node:path'
|
|
13
|
+
import { CHANNELS } from '@senseihq/emaki-posting'
|
|
14
|
+
import { campaignDir, channelCopy, dayScript } from './day-script.js'
|
|
15
|
+
import { deskClient } from './desk-client.js'
|
|
16
|
+
import { filmFiles, hashtags, storyFor, storyUrl } from './stories.js'
|
|
17
|
+
import { die, exists, load, run, save } from './util.js'
|
|
18
|
+
|
|
19
|
+
const TYPES = { mp4: 'video/mp4', srt: 'text/plain', vtt: 'text/vtt' }
|
|
20
|
+
const typeOf = (f) => TYPES[f.split('.').pop()] ?? 'image/jpeg'
|
|
21
|
+
|
|
22
|
+
/** PNG → JPEG with ffmpeg (Instagram takes JPEG only), into a temp folder. */
|
|
23
|
+
export function pngToJpeg(png) {
|
|
24
|
+
const out = join(mkdtempSync(join(tmpdir(), 'emaki-jpeg-')), basename(png).replace(/\.png$/i, '.jpg'))
|
|
25
|
+
run('ffmpeg', ['-y', '-loglevel', 'error', '-i', png, '-q:v', '2', out])
|
|
26
|
+
return out
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The draft text for a film's channels, from its story. */
|
|
30
|
+
function draftPosts(p, slug, locale, story, files) {
|
|
31
|
+
const link = storyUrl(p, slug, locale), tags = hashtags(story.tags)
|
|
32
|
+
const desc = files.description ? readFileSync(files.description, 'utf-8').trim() : `${story.dek}\n\nRead the story: ${link}\n${tags}`
|
|
33
|
+
return {
|
|
34
|
+
youtube: { title: story.title.slice(0, 100), description: desc, tags: story.tags, short: false },
|
|
35
|
+
instagram_reel: { caption: `${story.title}. ${story.dek}\n\nFull story: link in bio.\n\n${tags}` },
|
|
36
|
+
x: { text: `${story.title}: ${story.dek}`.slice(0, 270), thread: [`The full story, with the film: ${link}`] }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** { channel: [post text, [{ path, expect, name? }]] } for one piece. `path` null = missing; `expect` names it. */
|
|
41
|
+
export function postsFor(p, slug, locale) {
|
|
42
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
43
|
+
const tall = { path: f.tall, expect: f.expect.tall }, wide = { path: f.wide, expect: f.expect.wide }
|
|
44
|
+
const md = dayScript(p, slug, locale)
|
|
45
|
+
if (md) {
|
|
46
|
+
const c = channelCopy(md), dir = join(campaignDir(p), 'carousels', slug)
|
|
47
|
+
const slides = exists(dir) ? readdirSync(dir).filter((n) => n.endsWith('.png')).sort().map((n) => ({ path: join(dir, n) })) : []
|
|
48
|
+
return {
|
|
49
|
+
youtube: [{ ...c.youtube, short: true }, [tall]],
|
|
50
|
+
instagram_reel: [{ caption: c.caption }, [tall]],
|
|
51
|
+
instagram_carousel: [{ caption: c.caption }, slides.length ? slides : [{ path: null, expect: dir }]],
|
|
52
|
+
x: [c.x, [tall]]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const pj = join(p.films, slug, `post.${locale}.json`)
|
|
56
|
+
if (!exists(pj)) {
|
|
57
|
+
save(pj, draftPosts(p, slug, locale, story, f))
|
|
58
|
+
die(`wrote ${p.rel(pj)}: check the text, then run \`emaki stage ${slug}\` again`)
|
|
59
|
+
}
|
|
60
|
+
const text = load(pj), opt = (path, name) => (path ? [{ path, name }] : [])
|
|
61
|
+
const files = {
|
|
62
|
+
youtube: [wide, ...opt(f.srt), ...opt(f.thumb, `${slug}-${locale}-thumb.jpg`)], // -thumb.jpg: the poster sets it as the thumbnail
|
|
63
|
+
instagram_reel: [tall, ...opt(f.coverTall)],
|
|
64
|
+
x: [wide]
|
|
65
|
+
}
|
|
66
|
+
return Object.fromEntries(Object.keys(files).filter((c) => text[c]).map((c) => [c, [text[c], files[c]]]))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const sha = (bytes) => createHash('sha256').update(bytes).digest('hex')
|
|
70
|
+
|
|
71
|
+
export async function stage(p, slug, { locale, channels, dryRun = false, env = process.env, fetch = globalThis.fetch, log = console.info, toJpeg = pngToJpeg } = {}) {
|
|
72
|
+
locale ??= p.site.defaultLocale
|
|
73
|
+
const want = channels ? [channels].flat().flatMap((c) => String(c).split(',')).map((c) => c.trim()).filter(Boolean) : [...CHANNELS]
|
|
74
|
+
for (const c of want) if (!CHANNELS.includes(c)) die(`unknown channel "${c}" (${CHANNELS.join(', ')})`)
|
|
75
|
+
const posts = postsFor(p, slug, locale)
|
|
76
|
+
const desk = dryRun ? null : deskClient(p, { env, fetch })
|
|
77
|
+
const uploaded = new Map(), result = { staged: [], skipped: [], posts: {} }
|
|
78
|
+
for (const channel of CHANNELS.filter((c) => want.includes(c) && posts[c])) {
|
|
79
|
+
const [text, files] = posts[channel]
|
|
80
|
+
const missing = files.filter((x) => !x.path).map((x) => p.rel(x.expect))
|
|
81
|
+
if (missing.length) {
|
|
82
|
+
log(` ${channel}: skipped, missing ${missing.join(', ')}`)
|
|
83
|
+
result.skipped.push({ channel, missing })
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
const media = []
|
|
87
|
+
for (const x of files) {
|
|
88
|
+
const path = x.path.endsWith('.png') ? toJpeg(x.path) : x.path
|
|
89
|
+
const name = (x.name ?? basename(path)).toLowerCase(), type = typeOf(path)
|
|
90
|
+
const key = `${slug}/${type === 'image/jpeg' ? `${channel.split('_')[0]}-${name}` : name}`
|
|
91
|
+
const bytes = readFileSync(path)
|
|
92
|
+
if (desk && !uploaded.has(key)) uploaded.set(key, await desk.putMedia(key, bytes, type))
|
|
93
|
+
media.push({ key, sha256: uploaded.get(key) ?? sha(bytes), type })
|
|
94
|
+
}
|
|
95
|
+
const post = { ...text, media }
|
|
96
|
+
result.posts[channel] = post
|
|
97
|
+
if (!desk) {
|
|
98
|
+
log(`--- ${channel}\n${JSON.stringify(post, null, 2)}`)
|
|
99
|
+
continue
|
|
100
|
+
}
|
|
101
|
+
const r = await desk.stage(slug, channel, post)
|
|
102
|
+
log(` ${channel}: staged (${String(r.content_sha).slice(0, 10)}), ${media.length} file(s)`)
|
|
103
|
+
result.staged.push({ channel, content_sha: r.content_sha, files: media.length })
|
|
104
|
+
}
|
|
105
|
+
if (desk) log(`Review and approve on ${desk.origin}/admin`)
|
|
106
|
+
return result
|
|
107
|
+
}
|