@senseihq/emaki-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +42 -7
  2. package/package.json +4 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin/modules/campaign/README.md +10 -3
  5. package/plugin/modules/campaign/day-script.template.md +2 -1
  6. package/plugin/modules/posting-desk/README.md +2 -2
  7. package/plugin/skills/emaki/references/03-content-model.md +7 -4
  8. package/plugin/skills/emaki/references/04-scene-authoring.md +3 -0
  9. package/plugin/skills/emaki/references/05-voice-and-video.md +41 -8
  10. package/plugin/skills/emaki/references/09-publishing.md +5 -2
  11. package/plugin/skills/story-media/SKILL.md +2 -0
  12. package/plugin/skills/story-publish/SKILL.md +18 -4
  13. package/src/api.js +12 -1
  14. package/src/build-media.js +166 -0
  15. package/src/build-video.js +113 -0
  16. package/src/campaign.js +138 -0
  17. package/src/capture.js +6 -118
  18. package/src/carousel.js +91 -0
  19. package/src/commands/campaign.js +63 -0
  20. package/src/commands/posting.js +74 -0
  21. package/src/commands/production.js +128 -0
  22. package/src/commands/run.js +19 -0
  23. package/src/commands/setup.js +97 -0
  24. package/src/csv.js +42 -0
  25. package/src/day-script.js +66 -0
  26. package/src/desk-client.js +37 -0
  27. package/src/desk-plan.js +57 -0
  28. package/src/film-checks.js +102 -0
  29. package/src/films.js +7 -75
  30. package/src/fit.js +79 -0
  31. package/src/http.js +30 -0
  32. package/src/index.js +10 -184
  33. package/src/init.js +10 -13
  34. package/src/media.js +80 -0
  35. package/src/migrate.js +84 -0
  36. package/src/publish.js +136 -0
  37. package/src/render.js +125 -0
  38. package/src/show-page.js +75 -0
  39. package/src/stage.js +120 -0
  40. package/src/stories.js +66 -0
  41. package/src/takes.js +18 -0
  42. package/src/tts-cloud.js +122 -0
  43. package/src/tts-io.js +51 -0
  44. package/src/tts-offline.js +85 -0
  45. package/src/tts.js +5 -237
  46. package/src/upload/instagram.js +34 -0
  47. package/src/upload/youtube.js +90 -0
  48. package/src/util.js +7 -0
  49. package/src/voice.js +8 -118
  50. package/src/youtube-text.js +58 -0
  51. package/templates/content/films/measure-the-right-work/film.json +9 -0
  52. package/templates/content/films/measure-the-right-work/look.css +1 -0
  53. package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
  54. package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
  55. package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
  56. package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
  57. package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
  58. package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
  59. package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
  60. package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
  61. package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
  62. package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
  63. package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
  64. package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
  65. package/templates/film/look.css +1 -0
@@ -0,0 +1,113 @@
1
+ // The final videos (build.py): the rendered picture, the voice laid into each scene, the score ducked under it,
2
+ // -14 LUFS, captions burned in and shipped as .srt/.vtt, chapters, the description, the web copy and the posters.
3
+ import { copyFileSync, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
4
+ import { join, resolve } from 'node:path'
5
+ import { SUFFIX } from './config.js'
6
+ import { buildArgs, buildPlan, chaptersText, description, ffmeta, planTable, posterSteps, storyLink, webArgs, webNote, ytChapters } from './media.js'
7
+ import { takesFor } from './takes.js'
8
+ import { die, hasAudio, load, mediaLength, pad2, run } from './util.js'
9
+
10
+ const stamp = (t, sep = '.') => {
11
+ const h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60
12
+ return `${pad2(h)}:${pad2(m)}:${s.toFixed(3).padStart(6, '0')}`.replace('.', sep)
13
+ }
14
+
15
+ /** Captions from the voice lines, spread over each take by sentence length. */
16
+ export function captions(takes, starts, lead, length = mediaLength) {
17
+ const vtt = ['WEBVTT', ''], srt = []
18
+ let k = 0
19
+ for (const [sid, [f, line]] of takes) {
20
+ let t0 = starts.get(sid)[0] + lead
21
+ const span = length(f) - 0.1
22
+ const parts = line.text.split(/(?<=[.!?¿¡;:])\s+/).map((x) => x.trim()).filter(Boolean)
23
+ const total = parts.reduce((n, x) => n + x.length, 0)
24
+ for (const x of parts) {
25
+ const dd = (span * x.length) / total
26
+ k++
27
+ vtt.push(`${stamp(t0)} --> ${stamp(t0 + dd)}`, x, '')
28
+ srt.push(String(k), `${stamp(t0, ',')} --> ${stamp(t0 + dd, ',')}`, x, '')
29
+ t0 += dd
30
+ }
31
+ }
32
+ return { vtt: vtt.join('\n'), srt: srt.join('\n') }
33
+ }
34
+
35
+ /** libass lays SRT out on a 384x288 canvas scaled to the video, so these are in 288ths of the height: landscape 16 ≈
36
+ * 60 px text 127 px up; portrait 9 ≈ 60 px text 333 px up (clear of the platform's buttons). */
37
+ const burnIn = (srtPath, layout) => {
38
+ const size = layout === 'landscape' ? 16 : 9, margin = layout === 'landscape' ? 34 : 50
39
+ return `subtitles=${srtPath.replace(/([:\\'])/g, '\\$1')}:force_style='FontName=Inter,FontSize=${size},PrimaryColour=&H00FFFFFF,OutlineColour=&H66000000,BackColour=&H66000000,BorderStyle=3,Outline=5,Shadow=0,MarginV=${margin}'`
40
+ }
41
+
42
+ /** Final videos per orientation (build.py): the rendered picture with the voice laid `lead` s into each scene, the
43
+ * render's music ducked under it, -14 LUFS, captions burned in (and shipped as .srt/.vtt). A take that outruns its
44
+ * scene freezes the scene's last frame until it has finished (buildPlan). `check` prints the plan and builds nothing;
45
+ * `out` is the output folder (default production/<slug>/<locale>/out/). */
46
+ export function build(p, slug, { locale, noCaptions = false, check = false, out: target = undefined, log = console.info, length = mediaLength } = {}) {
47
+ const d = p.filmDir(slug), film = load(join(d, 'film.json'))
48
+ const tp = join(d, `timing.${locale}.json`)
49
+ const tm = existsSync(tp) ? (load(tp).scenes ?? {}) : {}
50
+ const takes = takesFor(p, slug, locale)
51
+ const plan = buildPlan(film, tm, new Map([...takes].map(([sid, [file]]) => [sid, { file, seconds: length(file) }])), p)
52
+ const render = p.prod(slug, locale, 'render')
53
+ const pics = ['landscape', 'portrait'].map((layout) => [layout, join(render, `${slug}-${locale}-${SUFFIX[layout]}.mp4`)])
54
+ .filter(([, f]) => existsSync(f))
55
+ log(`${film.title ?? slug} (${locale}): ${plan.picture.toFixed(1)} s as rendered`)
56
+ planTable(plan).forEach((l) => log(l))
57
+ if (plan.missing.length) log(`missing takes: ${plan.missing.join(', ')}`)
58
+ if (check) {
59
+ if (!pics.length) log(`MISSING: no render in ${p.rel(render)}; run \`emaki render ${slug} --locale ${locale}\``)
60
+ return { built: [], duration: plan.total, plan }
61
+ }
62
+ if (!takes.size) die(`no takes in ${p.rel(p.prod(slug, locale, 'takes'))}; run \`emaki voice\` (or record them) first`)
63
+ if (!pics.length) die(`no render in ${p.rel(render)}; run \`emaki render ${slug} --locale ${locale}\` first`)
64
+ const out = target ? resolve(target) : p.prod(slug, locale, 'out')
65
+ mkdirSync(out, { recursive: true })
66
+ const voiced = new Map([...takes].filter(([sid]) => plan.rows.some((r) => r.id === sid)))
67
+ const starts = new Map(plan.rows.map((r) => [r.id, [r.at, r.tot]]))
68
+ const cap = captions(voiced, starts, p.lead, length)
69
+ const srtPath = join(out, `${slug}-${locale}.srt`)
70
+ writeFileSync(join(out, `${slug}-${locale}.vtt`), cap.vtt)
71
+ writeFileSync(srtPath, cap.srt)
72
+ const inputs = [], filters = []
73
+ ;[...voiced].forEach(([sid, [f]], i) => {
74
+ inputs.push('-i', f)
75
+ const ms = Math.round((starts.get(sid)[0] + p.lead) * 1000)
76
+ filters.push(`[${i}:a]aresample=48000,adelay=${ms}|${ms},apad[v${i}]`)
77
+ })
78
+ const voicePath = join(out, 'voice.wav')
79
+ run('ffmpeg', ['-y', '-v', 'error', ...inputs, '-filter_complex',
80
+ filters.join(';') + ';' + [...voiced].map((_, i) => `[v${i}]`).join('') + `amix=inputs=${voiced.size}:normalize=0,atrim=0:${plan.total.toFixed(3)}[vo]`,
81
+ '-map', '[vo]', '-ac', '2', voicePath])
82
+ const chapters = join(out, 'chapters.ffmeta')
83
+ writeFileSync(chapters, ffmeta(plan.rows))
84
+ const yt = ytChapters(plan.rows)
85
+ writeFileSync(join(out, 'chapters.txt'), chaptersText(yt))
86
+ const story = join(p.content, 'stories', locale, `${slug}.json`)
87
+ const title = (existsSync(story) ? load(story).title : null) ?? film.title ?? slug
88
+ writeFileSync(join(out, 'description.txt'), description({ title, chapters: yt, link: storyLink(p.site, p.cfg, slug, locale) }))
89
+ const built = [], videos = {}
90
+ for (const [layout, pic] of pics) {
91
+ const dst = join(out, `${slug}-${locale}-${SUFFIX[layout]}.mp4`)
92
+ run('ffmpeg', buildArgs({
93
+ pic, voice: voicePath, plan, music: hasAudio(pic), subtitles: noCaptions ? null : burnIn(srtPath, layout),
94
+ chapters, scoreLevel: p.cfg.scoreLevel ?? 0.55, dst
95
+ }))
96
+ log(`built ${p.rel(dst)} (${plan.rows.length} chapters)`)
97
+ built.push((videos[layout] = dst))
98
+ }
99
+ rmSync(chapters, { force: true })
100
+ if (videos.landscape) {
101
+ const web = join(out, `${slug}-${locale}-web.mp4`)
102
+ run('ffmpeg', webArgs(videos.landscape, web))
103
+ log(`built ${p.rel(web)} (${webNote(statSync(web).size)})`)
104
+ built.push(web)
105
+ }
106
+ for (const step of posterSteps({ render, out, slug, locale, built: videos, last: plan.rows.at(-1), exists: existsSync })) {
107
+ if (step.copy) copyFileSync(...step.copy)
108
+ else run('ffmpeg', step.ffmpeg)
109
+ log(` ${p.rel((step.copy ?? step.ffmpeg).at(-1))}`)
110
+ }
111
+ log(`captions: ${p.rel(out)}/${slug}-${locale}.vtt/.srt; chapters.txt, description.txt`)
112
+ return { built, duration: plan.total, plan }
113
+ }
@@ -0,0 +1,138 @@
1
+ // emaki campaign status | shortfilm | posted | due | calendar: a daily series around a theme, from the command line.
2
+ // Sources: <campaign>/calendar.csv (one row per day: the website's date,product,theme,title,status,script or the
3
+ // plugin template's date,day,slug,topic,title,…), <campaign>/days/*.md (the day scripts), content/stories/index.json
4
+ // and <campaign>/published.json (where each piece was posted). <campaign> is emaki.config.json "campaign".
5
+ import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
6
+ import { join, relative } from 'node:path'
7
+ import { SUFFIX } from './config.js'
8
+ import { parseCsv } from './csv.js'
9
+ import { beatsOf, campaignDir, dayScriptPath, slugOfScript } from './day-script.js'
10
+ import { newFilm } from './films.js'
11
+ import { filmFiles, recordLinks, storiesIndex, storyUrl } from './stories.js'
12
+ import { die, exists, load, save } from './util.js'
13
+
14
+ export { parseCsv }
15
+
16
+ /** Today (YYYY-MM-DD) in a time zone. */
17
+ export const todayIn = (timeZone = 'UTC', now = new Date()) =>
18
+ new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(now)
19
+ const siteToday = (p) => todayIn(p.site.timeZone ?? 'UTC')
20
+
21
+ /** The calendar, one normalised row per day: { date, topic, theme, title, slug, script (path or null) }. */
22
+ export function calendarRows(p, locale = p.site.defaultLocale) {
23
+ const f = join(campaignDir(p), 'calendar.csv')
24
+ if (!exists(f)) die(`no ${p.rel(f)}; start one from the plugin's modules/campaign/calendar.csv`)
25
+ return parseCsv(readFileSync(f, 'utf-8')).map((r) => {
26
+ const slug = r.slug || (r.script ? slugOfScript(r.script) : null)
27
+ const named = r.script ? join(campaignDir(p), r.script) : null
28
+ const script = named && exists(named) ? named : slug ? dayScriptPath(p, slug, locale) : null
29
+ return { date: r.date, topic: r.product ?? r.topic ?? '', theme: r.theme ?? '', title: r.title ?? '', slug, script }
30
+ })
31
+ }
32
+
33
+ const ledgerPath = (p) => join(campaignDir(p), 'published.json')
34
+ const ledger = (p) => (exists(ledgerPath(p)) ? load(ledgerPath(p)) : {})
35
+ const stories = (p) => new Set((exists(storiesIndex(p)) ? load(storiesIndex(p)) : []).map((e) => e.slug))
36
+ const pngs = (dir) => (exists(dir) ? readdirSync(dir).filter((n) => n.endsWith('.png')).length : 0)
37
+
38
+ /** What is due from a date (default today, in the site's time zone), and for each day what exists. */
39
+ export function campaignStatus(p, { from, days = 14, locale = p.site.defaultLocale } = {}) {
40
+ from ??= siteToday(p)
41
+ const known = stories(p), led = ledger(p)
42
+ return calendarRows(p, locale).filter((r) => r.date >= from).slice(0, Number(days)).map((r) => {
43
+ const s = r.slug, takes = s ? p.prod(s, locale, 'takes') : null, posted = (s && led[s]) || {}
44
+ return {
45
+ date: r.date, topic: r.topic, title: r.title, slug: s,
46
+ story: Boolean(s && known.has(s)), script: Boolean(r.script),
47
+ film: Boolean(s && exists(join(p.films, s, 'film.json'))),
48
+ takes: takes && exists(takes) ? readdirSync(takes).filter((n) => /^take-\d+\./.test(n)).length : 0,
49
+ render: Boolean(s && exists(p.prod(s, locale, 'render', `${s}-${locale}-${SUFFIX.portrait}.mp4`))),
50
+ built: Boolean(s && filmFiles(p, s, locale).tall),
51
+ carousel: s ? pngs(join(campaignDir(p), 'carousels', s)) : 0,
52
+ posts: { youtube: Boolean(posted.youtube), instagram: Boolean(posted.instagram), x: Boolean(posted.x) }
53
+ }
54
+ })
55
+ }
56
+
57
+ /** One day's piece as JSON, for automation (default today in the site's time zone). */
58
+ export function campaignDue(p, { date, locale = p.site.defaultLocale } = {}) {
59
+ date ??= siteToday(p)
60
+ const r = calendarRows(p, locale).find((x) => x.date === date)
61
+ if (!r) die(`nothing scheduled on ${date}`)
62
+ const s = r.slug
63
+ return {
64
+ date, topic: r.topic, title: r.title, slug: s,
65
+ script: r.script ? p.rel(r.script) : null,
66
+ story: s ? storyUrl(p, s, locale) : null,
67
+ short: s ? p.rel(filmFiles(p, s, locale).expect.tall) : null,
68
+ carousel: s ? p.rel(join(campaignDir(p), 'carousels', s)) : null,
69
+ posted: (s && ledger(p)[s]) || {}
70
+ }
71
+ }
72
+
73
+ /** Records where a piece was posted: <campaign>/published.json and the story's social links (replacing them). */
74
+ export function campaignPosted(p, slug, links = {}, { today } = {}) {
75
+ const ip = storiesIndex(p)
76
+ const entry = (exists(ip) ? load(ip) : []).find((e) => e.slug === slug)
77
+ if (!entry) die(`${slug} is not in ${p.rel(ip)}`)
78
+ const vals = Object.fromEntries(['youtube', 'instagram', 'x'].filter((k) => links[k]).map((k) => [k, links[k]]))
79
+ if (!Object.keys(vals).length) die('nothing to record: pass --youtube ID, --instagram URL and/or --x URL')
80
+ const led = ledger(p)
81
+ led[slug] = { ...led[slug], ...vals, updated: today ?? siteToday(p) }
82
+ save(ledgerPath(p), led)
83
+ const yt = vals.youtube && !/^https?:/.test(vals.youtube)
84
+ ? (entry.video === 'short' ? `https://www.youtube.com/shorts/${vals.youtube}` : `https://www.youtube.com/watch?v=${vals.youtube}`)
85
+ : vals.youtube
86
+ recordLinks(p, slug, { youtube: yt, instagram: vals.instagram, x: vals.x }, { overwrite: true })
87
+ return led[slug]
88
+ }
89
+
90
+ /**
91
+ * Sets up a Short's film from its day script: one scene per voiceover beat (the on-screen column is the scene id when
92
+ * it is one, else beat-N; the last beat is the close), the voice lines from the table, 6 s per scene until
93
+ * `emaki fit` times them to the takes. An existing story keeps its index entry and body; an existing film is refused.
94
+ */
95
+ export function shortFilm(p, slug, { locale = p.site.defaultLocale } = {}) {
96
+ const f = dayScriptPath(p, slug, locale)
97
+ if (!f) die(`no day script for ${slug} in ${p.rel(join(campaignDir(p), 'days'))}/`)
98
+ if (exists(join(p.films, slug))) die(`${p.rel(join(p.films, slug))} already exists; edit its film.json and voice/${locale}.json`)
99
+ const md = readFileSync(f, 'utf-8'), beats = beatsOf(md)
100
+ if (!beats.length) die(`${p.rel(f)} has no voiceover table (| # | Voiceover | On screen |)`)
101
+ const seen = new Set()
102
+ const ids = beats.map((b, i) => {
103
+ let id = i === beats.length - 1 ? 'close' : /^[a-z][a-z0-9-]*$/.test(b.screen) && b.screen !== 'close' ? b.screen : `beat-${b.n}`
104
+ while (seen.has(id)) id = `${id}-${b.n}`
105
+ seen.add(id)
106
+ return id
107
+ })
108
+ const title = md.match(/^# Day \d+ · .+? · .+?: (.+)$/m)?.[1]?.trim()
109
+ newFilm(p, slug, { scenes: ids.join(','), title })
110
+ const fp = join(p.films, slug, 'film.json'), film = load(fp)
111
+ film.scenes = film.scenes.map((s, i) => ({ ...s, name: beats[i].screen.slice(0, 40), dur: 6 }))
112
+ save(fp, film)
113
+ save(join(p.films, slug, 'voice', `${locale}.json`), beats.map((b, i) => ({ scene: ids[i], text: b.text, say: null })))
114
+ return { slug, scenes: ids.length, path: p.rel(fp) }
115
+ }
116
+
117
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
118
+ const dayLabel = (iso) => { const d = new Date(iso + 'T00:00:00Z'); return `${DAYS[d.getUTCDay()]} ${MONTHS[d.getUTCMonth()]} ${String(d.getUTCDate()).padStart(2, '0')}` }
119
+
120
+ /** Rewrites <campaign>/CALENDAR.md from calendar.csv: a section per week, a row per day, links to the day scripts. */
121
+ export function campaignCalendar(p) {
122
+ const rows = calendarRows(p), dir = campaignDir(p)
123
+ if (!rows.length) die('calendar.csv has no days')
124
+ const t0 = Date.parse(rows[0].date + 'T00:00:00Z')
125
+ const md = ['# Campaign calendar', '', `${rows.length} days, ${rows[0].date} → ${rows.at(-1).date}. Expanded: ${rows.filter((r) => r.script).length}. Edit calendar.csv, then \`emaki campaign calendar\` to rewrite this file.`]
126
+ let week = 0
127
+ for (const r of rows) {
128
+ const wk = Math.floor((Date.parse(r.date + 'T00:00:00Z') - t0) / 86400000 / 7) + 1
129
+ if (wk !== week) {
130
+ week = wk
131
+ md.push('', `## Week ${wk} · ${r.date} · ${r.topic}${r.theme ? `: ${r.theme}` : ''}`, '', '| Date | Title | |', '|---|---|---|')
132
+ }
133
+ md.push(`| ${dayLabel(r.date)} | ${r.title} | ${r.script ? `[script](${relative(dir, r.script)})` : ''} |`)
134
+ }
135
+ const out = join(dir, 'CALENDAR.md')
136
+ writeFileSync(out, md.join('\n') + '\n')
137
+ return { path: p.rel(out), days: rows.length }
138
+ }
package/src/capture.js CHANGED
@@ -1,71 +1,14 @@
1
1
  // sheet and render drive the site's capture page in headless Chromium: /show/<slug>?capture=1 installs
2
2
  // window.__show = { meta, ready, seek(t), audio() } (installCapture in @senseihq/emaki; ShowPage in each wrapper).
3
3
  // Playwright is an optional dependency: `npm i -D playwright && npx playwright install chromium`.
4
- import { spawn } from 'node:child_process'
5
- import { mkdirSync, renameSync, writeFileSync, readFileSync } from 'node:fs'
6
- import { connect } from 'node:net'
4
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
7
5
  import { join } from 'node:path'
8
- import { SIZES, SUFFIX } from './config.js'
9
- import { die, run } from './util.js'
6
+ import { chromium, openShow, openSite } from './show-page.js'
7
+ import { die } from './util.js'
10
8
 
11
- async function chromium() {
12
- try {
13
- return (await import('playwright')).chromium
14
- } catch {
15
- return die('sheet and render need Playwright: npm i -D playwright && npx playwright install chromium')
16
- }
17
- }
18
-
19
- const portOpen = (port) => new Promise((ok) => {
20
- const s = connect({ port, host: '127.0.0.1' })
21
- s.setTimeout(500)
22
- s.once('connect', () => { s.destroy(); ok(true) })
23
- s.once('error', () => ok(false))
24
- s.once('timeout', () => { s.destroy(); ok(false) })
25
- })
26
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
27
-
28
- /** The site to capture: `url` if given (must answer), else the dev server (emaki.config.json devCommand), started if
29
- * nothing listens on the port yet and stopped afterwards. */
30
- export async function openSite(p, url) {
31
- const port = p.cfg.port ?? 5199
32
- let proc = null
33
- const base = (url ?? `http://localhost:${port}`).replace(/\/$/, '')
34
- if (url) {
35
- try {
36
- await fetch(url, { signal: AbortSignal.timeout(10000) })
37
- } catch (e) {
38
- die(`the site at ${url} is not responding (${e.message}); start it, or leave out --url to let emaki start it`)
39
- }
40
- } else if (!(await portOpen(port))) {
41
- const cmd = (p.cfg.devCommand ?? 'npm run dev -- --port {port} --strictPort').replaceAll('{port}', String(port))
42
- proc = spawn(cmd, { shell: true, cwd: p.root, stdio: 'ignore', detached: process.platform !== 'win32' })
43
- let up = false
44
- for (let i = 0; i < 120 && !(up = await portOpen(port)); i++) await sleep(500)
45
- if (!up) { stop(); die(`the dev server did not start (${cmd})`) }
46
- }
47
- function stop() {
48
- if (!proc) return
49
- try { process.kill(-proc.pid) } catch { proc.kill() }
50
- }
51
- const showPath = p.cfg.showPath ?? '/show/{slug}?capture=1&o={layout}&locale={locale}'
52
- return {
53
- base,
54
- show: (slug, layout, locale) => base + showPath.replaceAll('{slug}', slug).replaceAll('{layout}', layout).replaceAll('{locale}', locale),
55
- close: stop
56
- }
57
- }
58
-
59
- async function openShow(browser, site, slug, layout, locale) {
60
- const [width, height] = SIZES[layout]
61
- const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 })
62
- const errors = []
63
- page.on('pageerror', (e) => errors.push(String(e)))
64
- await page.goto(site.show(slug, layout, locale))
65
- await page.waitForFunction(() => window.__show, null, { timeout: 30000 })
66
- await page.evaluate(() => window.__show.ready)
67
- return { page, meta: await page.evaluate(() => window.__show.meta), errors }
68
- }
9
+ // The capture page (show-page.js) and render (render.js), re-exported: carousel, the CLI and the API import them here.
10
+ export { chromium, openSite }
11
+ export { render } from './render.js'
69
12
 
70
13
  /** A contact sheet: each scene's final picture (or --at scene:t,...) in both orientations, side by side. */
71
14
  export async function sheet(p, slug, { locale, url, at, log = console.info } = {}) {
@@ -112,58 +55,3 @@ export async function sheet(p, slug, { locale, url, at, log = console.info } = {
112
55
  site.close()
113
56
  }
114
57
  }
115
-
116
- /** Frame-by-frame capture to MP4 (the score as its audio), plus a cover JPEG per orientation. */
117
- export async function render(p, slug, { locale, url, o = 'both', fps = 30, log = console.info } = {}) {
118
- p.filmDir(slug)
119
- const layouts = o === 'both' ? ['landscape', 'portrait'] : [o]
120
- const out = p.prod(slug, locale, 'render')
121
- mkdirSync(out, { recursive: true })
122
- const site = await openSite(p, url), made = []
123
- const browser = await (await chromium()).launch()
124
- try {
125
- let score
126
- for (const layout of layouts) {
127
- const { page, meta, errors } = await openShow(browser, site, slug, layout, locale)
128
- if (score === undefined) {
129
- const b64 = await page.evaluate(() => window.__show.audio())
130
- score = b64 ? join(out, 'score.wav') : null
131
- if (b64) writeFileSync(score, Buffer.from(b64, 'base64'))
132
- }
133
- const frames = Math.round(meta.duration * fps)
134
- const dst = join(out, `${slug}-${locale}-${SUFFIX[layout]}.mp4`), tmp = dst.replace(/\.mp4$/, '.part.mp4')
135
- const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',
136
- ...(score ? ['-i', score] : []), '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p',
137
- ...(score ? ['-c:a', 'aac', '-b:a', '192k'] : []), '-t', (frames / fps).toFixed(3), '-movflags', '+faststart', tmp],
138
- { stdio: ['pipe', 'inherit', 'inherit'] })
139
- const done = new Promise((ok, bad) => { ff.on('close', (c) => (c ? bad(new Error('ffmpeg failed')) : ok())); ff.on('error', bad) })
140
- const t0 = Date.now()
141
- for (let i = 0; i < frames; i++) {
142
- await page.evaluate((t) => window.__show.seek(t), i / fps)
143
- const jpg = await page.screenshot({ type: 'jpeg', quality: 94 })
144
- if (!ff.stdin.write(jpg)) await new Promise((r) => ff.stdin.once('drain', r))
145
- if (i % (fps * 10) === 0) log(` ${layout} ${(i / fps).toFixed(1).padStart(6)}s / ${meta.duration.toFixed(1)}s`)
146
- }
147
- ff.stdin.end()
148
- await done.catch((e) => die(e.message))
149
- if (errors.length) die('the page reported errors: ' + errors.slice(0, 3).join('; '))
150
- renameSync(tmp, dst)
151
- await page.evaluate((t) => window.__show.seek(t), meta.cover)
152
- const cover = join(out, `${slug}-${locale}-cover-${SUFFIX[layout]}.jpg`)
153
- writeFileSync(cover, await page.screenshot({ type: 'jpeg', quality: 92 }))
154
- log(` wrote ${p.rel(dst)} (${frames} frames, ${Math.round((Date.now() - t0) / 1000)}s) and ${p.rel(cover)}`)
155
- if (layout === 'landscape' && p.cfg.coversDir) {
156
- const siteCover = join(p.root, p.cfg.coversDir, locale === p.site.defaultLocale ? `${slug}.jpg` : `${slug}.${locale}.jpg`)
157
- mkdirSync(join(siteCover, '..'), { recursive: true })
158
- run('ffmpeg', ['-y', '-loglevel', 'error', '-i', cover, '-vf', 'scale=1600:-2', '-q:v', '3', siteCover])
159
- log(` cover for the site: ${p.rel(siteCover)}`)
160
- }
161
- made.push(dst)
162
- await page.close()
163
- }
164
- return made
165
- } finally {
166
- await browser.close()
167
- site.close()
168
- }
169
- }
@@ -0,0 +1,91 @@
1
+ // emaki carousel <slug…> | --all: render a campaign day's Instagram carousel (1080×1350 PNGs) from the numbered lines
2
+ // of its day script's "Instagram carousel" section, into <campaign>/carousels/<slug>/slide-01.png …, which
3
+ // `emaki stage` turns into JPEG and stages. Needs Playwright with Chromium.
4
+ //
5
+ // The look is a paper card in the Zen-Sumi palette. emaki.config.json "carousel" adjusts it: marks ({ topic: "構" }),
6
+ // mark (default), footer (default: the site's address), swipe and last (the corner line), or template (an HTML file
7
+ // of your own with {text} {i} {total} {topic} {mark} {size} {cls} {bar} {swipe} {footer}).
8
+ import { mkdirSync, readdirSync, readFileSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { chromium } from './capture.js'
11
+ import { campaignDir, dayScriptPath, slidesOf, slugOfScript, topicOf } from './day-script.js'
12
+ import { die, exists, pad2 } from './util.js'
13
+
14
+ const PAGE = `<!doctype html><html><head><meta charset="utf-8">
15
+ <link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400&family=Inter:wght@400;600&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet">
16
+ <style>
17
+ html,body{margin:0;width:1080px;height:1350px;background:#F3F0E9;color:#1F1916}
18
+ body{position:relative;font-family:Inter,system-ui,sans-serif;
19
+ background-image:radial-gradient(circle at 18px 18px,#DCD7CD 2px,transparent 2.5px);background-size:36px 36px}
20
+ .k{position:absolute;left:84px;top:78px;font-family:'Hiragino Mincho ProN','Yu Mincho',serif;font-size:76px;color:#C25237;line-height:1}
21
+ .p{position:absolute;left:184px;top:104px;font:500 22px 'JetBrains Mono',monospace;letter-spacing:.14em;text-transform:uppercase;color:#7F7975}
22
+ .n{position:absolute;right:84px;top:104px;font:500 22px 'JetBrains Mono',monospace;color:#7F7975}
23
+ .card{position:absolute;left:84px;right:84px;top:250px;bottom:250px;display:flex;align-items:center;padding:0 64px;
24
+ background:#FCFAF6;border:2px solid #DCD7CD;border-radius:28px}
25
+ .t{font-family:Fraunces,Georgia,serif;font-weight:400;font-size:{size}px;line-height:1.14;letter-spacing:-.02em;white-space:pre-line}
26
+ .first .t{font-weight:300}
27
+ .bar{position:absolute;left:148px;bottom:310px;width:120px;height:6px;border-radius:3px;background:#C25237}
28
+ .u{position:absolute;left:84px;bottom:120px;font:500 26px 'JetBrains Mono',monospace;color:#C25237}
29
+ .s{position:absolute;right:84px;bottom:120px;font:600 24px Inter,sans-serif;color:#48413D}
30
+ </style></head><body class="{cls}">
31
+ <div class="k">{mark}</div><div class="p">{topic}</div><div class="n">{i} / {total}</div>
32
+ <div class="card"><div class="t">{text}</div></div>{bar}
33
+ <div class="u">{footer}</div><div class="s">{swipe}</div>
34
+ </body></html>`
35
+
36
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
37
+
38
+ /** The slides and the topic of a day's carousel. */
39
+ export function carouselSlides(p, slug, locale = p.site.defaultLocale) {
40
+ const f = dayScriptPath(p, slug, locale)
41
+ if (!f) die(`no day script for ${slug} in ${p.rel(join(campaignDir(p), 'days'))}/`)
42
+ const md = readFileSync(f, 'utf-8')
43
+ return { topic: topicOf(md), slides: slidesOf(md) }
44
+ }
45
+
46
+ /** One slide's page. Slide 1 is set large with the accent bar; longer text is set smaller. */
47
+ export function slideHtml(p, text, i, total, topic) {
48
+ const c = p.cfg.carousel ?? {}
49
+ const tpl = c.template ? readFileSync(join(p.root, c.template), 'utf-8') : PAGE
50
+ const n = text.length, size = i === 1 ? 92 : n < 60 ? 72 : n < 110 ? 60 : 50
51
+ const vals = {
52
+ size, cls: i === 1 ? 'first' : '', mark: esc(c.marks?.[topic] ?? c.mark ?? ''), topic: esc(topic), i, total, text: esc(text),
53
+ bar: i === 1 ? '<div class="bar"></div>' : '', footer: esc(c.footer ?? (p.site.url ?? '').replace(/^https?:\/\//, '').replace(/\/$/, '')),
54
+ swipe: esc(i < total ? (c.swipe ?? 'Swipe →') : (c.last ?? 'Full story: link in bio'))
55
+ }
56
+ return tpl.replace(/\{(\w+)\}/g, (m, k) => (k in vals ? String(vals[k]) : m))
57
+ }
58
+
59
+ /** Headless Chromium at the carousel's size; shoot(html, file) writes one PNG. */
60
+ async function openChromium() {
61
+ const browser = await (await chromium()).launch()
62
+ const page = await browser.newPage({ viewport: { width: 1080, height: 1350 } })
63
+ return {
64
+ shoot: async (html, file) => { await page.setContent(html, { waitUntil: 'networkidle' }); await page.screenshot({ path: file }) },
65
+ close: () => browser.close()
66
+ }
67
+ }
68
+
69
+ export async function carousel(p, slugs = [], { all = false, locale = p.site.defaultLocale, open = openChromium, log = console.info } = {}) {
70
+ const days = join(campaignDir(p), 'days')
71
+ if (all) slugs = exists(days) ? readdirSync(days).filter((n) => /^day-\d+-.+\.md$/.test(n)).sort().map(slugOfScript) : []
72
+ if (!slugs.length) die('name a slug, or --all for every day script')
73
+ const work = slugs.map((slug) => {
74
+ const s = carouselSlides(p, slug, locale)
75
+ if (!s.slides.length) die(`${slug}: no carousel slides (numbered lines under "## N · Instagram carousel")`)
76
+ return { slug, ...s }
77
+ })
78
+ const shot = await open(), made = []
79
+ try {
80
+ for (const w of work) {
81
+ const dir = join(campaignDir(p), 'carousels', w.slug)
82
+ mkdirSync(dir, { recursive: true })
83
+ for (const [k, text] of w.slides.entries()) await shot.shoot(slideHtml(p, text, k + 1, w.slides.length, w.topic), join(dir, `slide-${pad2(k + 1)}.png`))
84
+ log(`${w.slug}: ${w.slides.length} slides → ${p.rel(dir)}`)
85
+ made.push({ slug: w.slug, slides: w.slides.length, dir: p.rel(dir) })
86
+ }
87
+ } finally {
88
+ await shot.close()
89
+ }
90
+ return made
91
+ }
@@ -0,0 +1,63 @@
1
+ // emaki campaign status | shortfilm | posted | due | calendar: the daily series from the command line.
2
+ import { act, P } from './run.js'
3
+
4
+ const yes = (b) => (b ? 'yes' : ' - ')
5
+
6
+ /** One day of campaign status: what exists for it, or that it has no day script yet. */
7
+ function statusRow(r) {
8
+ const head = `${r.date} ${r.topic.slice(0, 11).padEnd(11)} ${r.title.slice(0, 46).padEnd(46)}`
9
+ if (!r.script) return `${head} (no day script yet)`
10
+ const posts = ['youtube', 'instagram', 'x'].map((k) => (r.posts[k] ? k[0].toUpperCase() : '·')).join('')
11
+ return `${head} ${yes(r.story)} ${yes(r.film)} ${String(r.takes).padStart(4)} ${yes(r.render)} ${yes(r.built)} ${String(r.carousel).padStart(3)} ${posts}`
12
+ }
13
+
14
+ /** The campaign commands. */
15
+ export function campaignCommands(prog) {
16
+ prog.command('campaign status')
17
+ .describe('What is due, and for each day what exists: story, film, takes, render, Short, carousel, posts.')
18
+ .option('--days', 'How many days', 14)
19
+ .option('--from', 'First date YYYY-MM-DD (default: today in the site\'s time zone)')
20
+ .action(act(async (o) => {
21
+ const { campaignStatus } = await import('../campaign.js')
22
+ console.info(`${'date'.padEnd(10)} ${'topic'.padEnd(11)} ${'title'.padEnd(46)} story film takes rndr short car posts`)
23
+ for (const r of campaignStatus(P(), { from: o.from && String(o.from), days: Number(o.days) })) console.info(statusRow(r))
24
+ console.info('\nposts: Y = YouTube, I = Instagram, X = X; · = not yet')
25
+ }))
26
+
27
+ prog.command('campaign shortfilm <slug>')
28
+ .describe('Set up a Short\'s film (scenes and voice lines) from its day script\'s voiceover table.')
29
+ .option('--locale', 'Locale (default: the site default)')
30
+ .action(act(async (slug, o) => {
31
+ const { shortFilm } = await import('../campaign.js')
32
+ const r = shortFilm(P(), slug, { locale: o.locale })
33
+ console.info(`wrote ${r.path}: ${r.scenes} beats. Next: build the scenes, then \`emaki voice ${slug}\`, \`emaki fit ${slug}\`, \`emaki render ${slug} --o portrait\`.`)
34
+ }))
35
+
36
+ prog.command('campaign posted <slug>')
37
+ .describe('Record where a piece was posted: the campaign ledger and the story\'s social links.')
38
+ .option('--youtube', 'Video id or URL')
39
+ .option('--instagram', 'Post URL')
40
+ .option('--x', 'Post URL')
41
+ .action(act(async (slug, o) => {
42
+ const { campaignPosted } = await import('../campaign.js')
43
+ const s = (v) => (v === undefined || v === true ? undefined : String(v))
44
+ const r = campaignPosted(P(), slug, { youtube: s(o.youtube), instagram: s(o.instagram), x: s(o.x) })
45
+ console.info(`recorded ${slug}: ${JSON.stringify(r)}. Commit content/stories/index.json; the next build links the posts.`)
46
+ }))
47
+
48
+ prog.command('campaign due')
49
+ .describe('The piece for one day (default today in the site\'s time zone), as JSON, for automation.')
50
+ .option('--date', 'YYYY-MM-DD')
51
+ .action(act(async (o) => {
52
+ const { campaignDue } = await import('../campaign.js')
53
+ console.info(JSON.stringify(campaignDue(P(), { date: o.date && String(o.date) }), null, 2))
54
+ }))
55
+
56
+ prog.command('campaign calendar')
57
+ .describe('Rewrite CALENDAR.md in the campaign folder from calendar.csv.')
58
+ .action(act(async () => {
59
+ const { campaignCalendar } = await import('../campaign.js')
60
+ const r = campaignCalendar(P())
61
+ console.info(`wrote ${r.path} (${r.days} days)`)
62
+ }))
63
+ }
@@ -0,0 +1,74 @@
1
+ // emaki stage (+ status, requests, reply), publish, carousel: after the build, stage for approval on the posting desk,
2
+ // or publish straight to a platform. Credentials come from the environment only (STAGER_*, MEDIA_URL_SECRET, YT_*,
3
+ // IG_*; see the README).
4
+ import { MotionError } from '../util.js'
5
+ import { act, P } from './run.js'
6
+
7
+ const list = (v) => [v ?? []].flat().flatMap((x) => String(x).split(',')).map((x) => x.trim()).filter(Boolean)
8
+
9
+ /** Staging on the desk, publishing, and the carousel. */
10
+ export function postingCommands(prog) {
11
+ prog.command('stage <slug>')
12
+ .describe('Upload a finished piece\'s media and post text to the posting desk for approval (STAGER_CLIENT_ID/SECRET).')
13
+ .option('--channels', 'youtube,instagram_reel,instagram_carousel,x (default: all)')
14
+ .option('--locale', 'Locale (default: the site default)')
15
+ .option('--dry-run', 'Print the posts; send nothing', false)
16
+ .action(act(async (slug, o) => {
17
+ const { stage } = await import('../stage.js')
18
+ await stage(P(), slug, { locale: o.locale, channels: o.channels ? list(o.channels) : undefined, dryRun: o['dry-run'] })
19
+ }))
20
+
21
+ prog.command('stage status [slug]')
22
+ .describe('Report each piece\'s script and what is produced to the desk\'s plan.')
23
+ .option('--locale', 'Locale (default: the site default)')
24
+ .action(act(async (slug, o) => {
25
+ const { productionStatus } = await import('../desk-plan.js')
26
+ await productionStatus(P(), slug, { locale: o.locale })
27
+ }))
28
+
29
+ prog.command('stage requests')
30
+ .describe('The open motion requests from the desk, with their threads.')
31
+ .action(act(async () => {
32
+ const { deskRequests } = await import('../desk-plan.js')
33
+ await deskRequests(P())
34
+ }))
35
+
36
+ prog.command('stage reply <id> [text]')
37
+ .describe('Answer a motion request; --working or --done moves it on.')
38
+ .option('--working', 'Mark it working', false)
39
+ .option('--done', 'Mark it done', false)
40
+ .action(act(async (id, text, o) => {
41
+ if (o.working && o.done) throw new MotionError('--working or --done, not both')
42
+ const { deskReply } = await import('../desk-plan.js')
43
+ await deskReply(P(), id, text ?? '', { status: o.done ? 'done' : o.working ? 'working' : undefined })
44
+ }))
45
+
46
+ prog.command('publish <channel> [slug]')
47
+ .describe('Post a finished film straight to youtube or instagram and record the link (YT_* / IG_* keys).')
48
+ .option('--locale', 'Locale (default: the site default)')
49
+ .option('--privacy', 'YouTube: public | unlisted | private', 'unlisted')
50
+ .option('--update', 'YouTube: refresh this uploaded video id in place (no re-upload)')
51
+ .option('--force-new', 'YouTube: upload even when an id is already recorded', false)
52
+ .option('--description-mode', 'With --update: prepend | replace', 'prepend')
53
+ .option('--video-url', 'Instagram: public MP4 URL (skips staging on the desk)')
54
+ .option('--cover-url', 'Instagram: public JPEG URL for the cover (with --video-url)')
55
+ .option('--dry-run', 'Print exactly what would post; touch nothing', false)
56
+ .option('--verify', 'Check the credentials (read-only) and name the account', false)
57
+ .action(act(async (channel, slug, o) => {
58
+ if (!o.verify && !slug) throw new MotionError('a slug is required (or --verify)')
59
+ const { publish } = await import('../publish.js')
60
+ await publish(P(), channel, slug, {
61
+ locale: o.locale, privacy: o.privacy, update: o.update && String(o.update), forceNew: o['force-new'], descriptionMode: o['description-mode'],
62
+ videoUrl: o['video-url'], coverUrl: o['cover-url'], dryRun: o['dry-run'], verify: o.verify
63
+ })
64
+ }))
65
+
66
+ prog.command('carousel [slug]')
67
+ .describe('Render a campaign day\'s Instagram carousel (1080×1350 PNGs) from its day script (needs Playwright).')
68
+ .option('--all', 'Every day script', false)
69
+ .option('--locale', 'Locale (default: the site default)')
70
+ .action(act(async (slug, o) => {
71
+ const { carousel } = await import('../carousel.js')
72
+ await carousel(P(), [slug, ...o._].filter(Boolean).map(String), { all: o.all, locale: o.locale })
73
+ }))
74
+ }