@celljs/ta-creator 4.31.0 → 4.32.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.en.md CHANGED
@@ -4,11 +4,11 @@ The content creation package of Ta (built in and off by default, `pi.offByDefaul
4
4
 
5
5
  - **The Creator page**: a row of the double's list opens it, five columns: topics, making, to review, published, numbers. One at a time on a phone, a board on a computer. The first time you say what the channel is about and where you publish (Bilibili, Xiaohongshu, Channels, Douyin, Kuaishou, YouTube and Official Accounts to start from; change or add any), and may start a 30-day goal.
6
6
  - **Hot topics** (scheduled tasks the server of the package makes, at 8, 12 and 18 each day): news of the field while it is hot, how-tos, and good work abroad explained; you are told of one of heat 85 or more. A work explained names and links its source and quotes it shortly; it is translated whole only when its licence allows it.
7
- - **Making** (creator-make): topic → script → `episode.json` → `bin/render.mjs`: code typed in, titles and points, the voice of this computer's speech, captions burned in, the label "AI 合成" on every picture, in 16:9, 9:16 and 3:4 with covers, or the pictures of a post; ffmpeg alone, no dependency added.
7
+ - **Making** (creator-make): topic → script → `episode.json` → `bin/render.mjs`: a pixel dinosaur hosting it, the series' opening and one cover for all, code typed in a terminal, a phone showing progress and a notification, a summing up written by hand, the voice read aloud, captions burned in, the label "AI 合成" on every picture, in 16:9, 9:16 and 3:4 with covers, or the pictures of a post; the pictures drawn by this computer's browser without a window (plainly without one), with ffmpeg; no dependency added.
8
8
  - **The review card** (```ta-creator-review`): each platform's version, its title and words, and the checks, in one card on your phone; pass it or ask for a change.
9
9
  - **Filled in up to Publish** (creator-publish): once passed, Ta opens each platform's page for creators in your browser, uploads the files, fills in the title, words and tags, ticks the declaration of AI content, and stops before Publish for you to press it. It never signs in for you, publishes, answers comments or inflates numbers.
10
10
  - **The review each Monday**: each platform against the week before, what worked, the time it took you (past your cap, fewer topics are offered), the goal, and three topics for the week.
11
11
 
12
12
  ## Data
13
13
 
14
- The data of the package (`pi.storage`, written by its server alone): `settings` (niche, platforms, sources, goal, weekly minutes cap, voice), `items` (each piece from topic to published; at most 200 topics never made are kept), `weeks` (each platform's numbers and your minutes, 26 weeks kept), `tasks` (the scheduled tasks made; one removed is not made again). Ta and the tasks change them with `ta call @celljs/ta-creator <method>`.
14
+ The data of the package (`pi.storage`, written by its server alone): `settings` (niche, platforms, sources, goal, weekly minutes cap, voice), `items` (each piece from topic to published; at most 200 topics never made are kept), `weeks` (each platform's numbers and your minutes, 26 weeks kept), `tasks` (the scheduled tasks made; one removed is not made again). Ta and the tasks change them with `ta call @celljs/ta-creator <method>`.
package/README.md CHANGED
@@ -4,11 +4,11 @@ Ta 的内容创作行业包(随 Ta 内置、默认关闭:`pi.offByDefault`
4
4
 
5
5
  - **创作者页**:分身列表里的「创作者」一行打开,五栏:选题、制作中、待审、已发布、数据。手机上分段切换,电脑上是看板。首次打开先写内容号做什么、选发在哪些平台(内置 B站、小红书、视频号、抖音、快手、YouTube、公众号,可改可加),可开启 30 天目标。
6
6
  - **热点选题**(`pi.host` 建的定时任务,每天 8、12、18 点):按领域看信息源与当天新闻,找热点、实操、国外好内容的解读三类选题;热度 ≥ 85 时提醒你。解读注明出处并附链接、只短引用,许可允许才全文翻译。
7
- - **出片**(creator-make):选题 → 脚本 → `episode.json` → `bin/render.mjs`:代码逐行打出、标题与要点、本机系统语音配音、字幕烧进画面、每个画面带「AI 合成」标识,按平台出 16:9 / 9:16 / 3:4 视频与封面,或图文图片;只用本机 ffmpeg,不新增依赖。
7
+ - **出片**(creator-make):选题 → 脚本 → `episode.json` → `bin/render.mjs`:像素恐龙主播 + 栏目片头与统一封面,终端里逐行打代码、手机里看进度和弹通知、手绘笔记本做总结,本机配音、字幕烧进画面、每个画面带「AI 合成」标识,按平台出 16:9 / 9:16 / 3:4 视频与封面,或图文图片;画面由本机浏览器无窗口绘制(没有浏览器就出朴素版),只用本机 ffmpeg 与浏览器,不新增依赖。
8
8
  - **审稿卡**(```ta-creator-review`):手机上一张卡看各平台版本、标题文案、检查项;「通过」或「改一句」。
9
9
  - **填到发布前**(creator-publish):通过后 Ta 在你的浏览器里打开各平台创作者中心,上传文件、填标题文案话题、勾选 AI 生成声明,停在发布按钮前,由你来点。不替你登录、不点发布、不回评论、不刷量。
10
10
  - **每周一复盘**:各平台数据对比上周、什么有效、本周花了你多少时间(超过上限就少给选题)、目标进度、本周三个选题。
11
11
 
12
12
  ## 数据
13
13
 
14
- 包数据(`pi.storage`,只由服务端写):`settings`(领域、平台、信息源、目标、每周时间上限、配音)、`items`(选题到已发布的每条内容,最多保留 200 条未做的选题)、`weeks`(每周各平台数据与你花的时间,保留 26 周)、`tasks`(建过的定时任务,删掉的不再重建)。Ta 与定时任务用 `ta call @celljs/ta-creator <方法>` 改它们。
14
+ 包数据(`pi.storage`,只由服务端写):`settings`(领域、平台、信息源、目标、每周时间上限、配音)、`items`(选题到已发布的每条内容,最多保留 200 条未做的选题)、`weeks`(每周各平台数据与你花的时间,保留 26 周)、`tasks`(建过的定时任务,删掉的不再重建)。Ta 与定时任务用 `ta call @celljs/ta-creator <方法>` 改它们。
package/bin/render.mjs CHANGED
@@ -1,8 +1,138 @@
1
1
  // web-src/render.ts
2
2
  import { execFile } from "node:child_process";
3
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
- import { homedir, tmpdir } from "node:os";
5
- import { join, resolve } from "node:path";
3
+ import { mkdir, mkdtemp as mkdtemp2, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
4
+ import { homedir as homedir2, tmpdir as tmpdir2 } from "node:os";
5
+ import { join as join3, resolve } from "node:path";
6
+
7
+ // web-src/browser.ts
8
+ import { spawn } from "node:child_process";
9
+ import { existsSync } from "node:fs";
10
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+
15
+ class StageBrowser {
16
+ child;
17
+ socket;
18
+ profile;
19
+ next = 1;
20
+ session = "";
21
+ waiting = new Map;
22
+ constructor(child, socket, profile) {
23
+ this.child = child;
24
+ this.socket = socket;
25
+ this.profile = profile;
26
+ socket.addEventListener("message", (event) => {
27
+ const message = JSON.parse(String(event.data));
28
+ const one = message.id === undefined ? undefined : this.waiting.get(message.id);
29
+ if (one && message.id !== undefined) {
30
+ this.waiting.delete(message.id);
31
+ if (message.error) {
32
+ one.fail(new Error(message.error.message));
33
+ } else {
34
+ one.done(message.result ?? {});
35
+ }
36
+ }
37
+ });
38
+ }
39
+ static find() {
40
+ const candidates = [
41
+ process.env.TA_CREATOR_CHROME,
42
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
43
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
44
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
45
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
46
+ "/usr/bin/google-chrome",
47
+ "/usr/bin/chromium",
48
+ "/usr/bin/chromium-browser",
49
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
50
+ "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
51
+ ];
52
+ return candidates.find((one) => !!one && existsSync(one));
53
+ }
54
+ static async open(path) {
55
+ if (typeof WebSocket !== "function") {
56
+ throw new Error("Drawing the pictures needs Node 22 or later (its WebSocket).");
57
+ }
58
+ const profile = await mkdtemp(join(tmpdir(), "ta-creator-chrome-"));
59
+ const child = spawn(path, [
60
+ "--headless=new",
61
+ "--remote-debugging-port=0",
62
+ `--user-data-dir=${profile}`,
63
+ "--hide-scrollbars",
64
+ "--force-device-scale-factor=1",
65
+ "--no-first-run",
66
+ "--no-default-browser-check",
67
+ "--mute-audio",
68
+ "about:blank"
69
+ ], { stdio: ["ignore", "ignore", "pipe"] });
70
+ const endpoint = await new Promise((done, fail) => {
71
+ let said = "";
72
+ const timer = setTimeout(() => fail(new Error(`The browser did not start: ${said.slice(-300)}`)), 20000);
73
+ child.stderr?.on("data", (chunk) => {
74
+ said += String(chunk);
75
+ const found = /DevTools listening on (ws:\/\/\S+)/.exec(said);
76
+ if (found) {
77
+ clearTimeout(timer);
78
+ done(found[1]);
79
+ }
80
+ });
81
+ child.on("error", (error) => {
82
+ clearTimeout(timer);
83
+ fail(error);
84
+ });
85
+ });
86
+ const socket = new WebSocket(endpoint);
87
+ await new Promise((done, fail) => {
88
+ socket.addEventListener("open", () => done(), { once: true });
89
+ socket.addEventListener("error", () => fail(new Error("Could not reach the browser.")), { once: true });
90
+ });
91
+ const browser = new StageBrowser(child, socket, profile);
92
+ const { targetId } = await browser.send("Target.createTarget", { url: "about:blank" });
93
+ const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true });
94
+ browser.session = sessionId;
95
+ return browser;
96
+ }
97
+ send(method, params = {}) {
98
+ const id = this.next++;
99
+ return new Promise((done, fail) => {
100
+ this.waiting.set(id, { done, fail });
101
+ this.socket.send(JSON.stringify(this.session ? { id, method, params, sessionId: this.session } : { id, method, params }));
102
+ });
103
+ }
104
+ async load(html, width, height) {
105
+ await this.send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false });
106
+ const file = join(this.profile, `page-${width}x${height}.html`);
107
+ await writeFile(file, html);
108
+ await this.send("Page.navigate", { url: pathToFileURL(file).href });
109
+ for (let i = 0;i < 100; i++) {
110
+ const { result } = await this.send("Runtime.evaluate", { expression: "document.readyState", returnByValue: true });
111
+ if (result.value === "complete") {
112
+ return;
113
+ }
114
+ await new Promise((done) => setTimeout(done, 50));
115
+ }
116
+ }
117
+ async shoot(body, path) {
118
+ await this.send("Runtime.evaluate", {
119
+ expression: `document.body.innerHTML = ${JSON.stringify(body)}; document.fonts.ready.then(() => new Promise(r => requestAnimationFrame(() => r(1))))`,
120
+ awaitPromise: true
121
+ });
122
+ const { data } = await this.send("Page.captureScreenshot", { format: "png" });
123
+ await writeFile(path, Buffer.from(data, "base64"));
124
+ }
125
+ async close() {
126
+ try {
127
+ this.socket.close();
128
+ } finally {
129
+ this.child.kill();
130
+ await rm(this.profile, { recursive: true, force: true }).catch(() => {
131
+ return;
132
+ });
133
+ }
134
+ }
135
+ }
6
136
 
7
137
  // web-src/episode.ts
8
138
  var SIZES = { "16:9": [1920, 1080], "9:16": [1080, 1920], "3:4": [1080, 1440], "1:1": [1080, 1080] };
@@ -19,20 +149,57 @@ var EpisodeAss;
19
149
  return text.replace(/\\/g, "\\​").replace(/\{/g, "\\{").replace(/\}/g, "\\}").replace(/\r?\n/g, " ");
20
150
  }
21
151
  EpisodeAss.plain = plain;
22
- function highlight(line) {
23
- let out = "";
152
+ function tokens(line) {
153
+ const out = [];
24
154
  let at = 0;
25
155
  for (const match of line.matchAll(TOKENS)) {
26
156
  const token = match[0];
27
157
  const index = match.index ?? 0;
28
- out += plain(line.slice(at, index));
29
- const colour = /^(\/\/|#)/.test(token) ? COLOURS.comment : /^["'`]/.test(token) ? COLOURS.string : /^\d/.test(token) ? COLOURS.number : KEYWORDS.has(token) ? COLOURS.keyword : /^\s*\(/.test(line.slice(index + token.length)) ? COLOURS.name : undefined;
30
- out += colour ? `{\\c${colour}}${plain(token)}{\\c${COLOURS.text}}` : plain(token);
158
+ if (index > at) {
159
+ out.push({ text: line.slice(at, index) });
160
+ }
161
+ const kind = /^(\/\/|#)/.test(token) ? "comment" : /^["'`]/.test(token) ? "string" : /^\d/.test(token) ? "number" : KEYWORDS.has(token) ? "keyword" : /^\s*\(/.test(line.slice(index + token.length)) ? "name" : undefined;
162
+ out.push(kind ? { text: token, kind } : { text: token });
31
163
  at = index + token.length;
32
164
  }
33
- return (out + plain(line.slice(at))).replace(/ /g, "\\h");
165
+ if (at < line.length) {
166
+ out.push({ text: line.slice(at) });
167
+ }
168
+ return out;
169
+ }
170
+ EpisodeAss.tokens = tokens;
171
+ function highlight(line) {
172
+ const out = tokens(line).map((one) => one.kind ? `{\\c${COLOURS[one.kind]}}${plain(one.text)}{\\c${COLOURS.text}}` : plain(one.text)).join("");
173
+ return out.replace(/ /g, "\\h");
34
174
  }
35
175
  EpisodeAss.highlight = highlight;
176
+ function subtitles(timed, aspect) {
177
+ const [width, height] = SIZES[aspect];
178
+ const unit = Math.min(width, height) / 1080;
179
+ const tall = height > width;
180
+ const size2 = Math.round((tall ? 52 : 46) * unit);
181
+ const bottom = Math.round((tall ? 150 : 64) * unit);
182
+ const events = timed.flatMap((one) => captions(one.scene.say, one.start, one.end, tall ? 14 : 22).map((caption) => `Dialogue: 5,${time(caption.start)},${time(caption.end)},Caption,,0,0,0,,{\\an2\\pos(${width / 2},${height - bottom})\\fs${size2}}${plain(caption.text)}`));
183
+ return [
184
+ "[Script Info]",
185
+ "ScriptType: v4.00+",
186
+ `PlayResX: ${width}`,
187
+ `PlayResY: ${height}`,
188
+ "WrapStyle: 2",
189
+ "ScaledBorderAndShadow: yes",
190
+ "",
191
+ "[V4+ Styles]",
192
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
193
+ `Style: Caption,PingFang SC,${size2},&H00FFFFFF,&H000000FF,&H2B12150E,&H2B12150E,-1,0,0,0,100,100,0,0,3,${Math.round(14 * unit)},0,2,0,0,0,1`,
194
+ "",
195
+ "[Events]",
196
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
197
+ ...events,
198
+ ""
199
+ ].join(`
200
+ `);
201
+ }
202
+ EpisodeAss.subtitles = subtitles;
36
203
  function captions(text, start, end, max) {
37
204
  const parts = [];
38
205
  for (const sentence of text.split(/(?<=[。!?!?;;,,、::])/)) {
@@ -155,6 +322,507 @@ var EpisodeAss;
155
322
  }
156
323
  })(EpisodeAss ||= {});
157
324
 
325
+ // web-src/hunyuan.ts
326
+ import { readFile, writeFile as writeFile2 } from "node:fs/promises";
327
+ import { homedir } from "node:os";
328
+ import { join as join2 } from "node:path";
329
+ var HunyuanVoice;
330
+ ((HunyuanVoice) => {
331
+ HunyuanVoice.NAME = /^hunyuan(?::([\w-]+))?$/;
332
+ const RATE = 24000;
333
+ function voiceOf(name) {
334
+ const found = HunyuanVoice.NAME.exec(name);
335
+ return found ? found[1] || "f1" : undefined;
336
+ }
337
+ HunyuanVoice.voiceOf = voiceOf;
338
+ async function service(file = join2(homedir(), ".ta/agent/voices.json")) {
339
+ if (process.env.TA_CREATOR_HUNYUAN_URL) {
340
+ return { url: process.env.TA_CREATOR_HUNYUAN_URL, key: process.env.TA_CREATOR_HUNYUAN_KEY };
341
+ }
342
+ try {
343
+ const kept = JSON.parse(await readFile(file, "utf8"));
344
+ const one = kept.services?.find((each) => each.type === "hy-realtime" && typeof each.options?.url === "string");
345
+ return one ? { url: String(one.options?.url), key: typeof one.options?.apiKey === "string" ? one.options.apiKey : undefined } : undefined;
346
+ } catch {
347
+ return;
348
+ }
349
+ }
350
+ HunyuanVoice.service = service;
351
+ function wav(pcm, rate = RATE) {
352
+ const head = Buffer.alloc(44);
353
+ head.write("RIFF", 0);
354
+ head.writeUInt32LE(36 + pcm.length, 4);
355
+ head.write("WAVEfmt ", 8);
356
+ head.writeUInt32LE(16, 16);
357
+ head.writeUInt16LE(1, 20);
358
+ head.writeUInt16LE(1, 22);
359
+ head.writeUInt32LE(rate, 24);
360
+ head.writeUInt32LE(rate * 2, 28);
361
+ head.writeUInt16LE(2, 32);
362
+ head.writeUInt16LE(16, 34);
363
+ head.write("data", 36);
364
+ head.writeUInt32LE(pcm.length, 40);
365
+ return Buffer.concat([head, pcm]);
366
+ }
367
+ HunyuanVoice.wav = wav;
368
+ function read(service2, voice, text, out, timeout = 60000) {
369
+ return new Promise((done, fail) => {
370
+ const socket = new WebSocket(service2.url, { headers: { Authorization: `Bearer ${service2.key || "ta"}` } });
371
+ const chunks = [];
372
+ let over = false;
373
+ const end = (error) => {
374
+ if (over) {
375
+ return;
376
+ }
377
+ over = true;
378
+ clearTimeout(timer);
379
+ socket.close();
380
+ if (error) {
381
+ fail(error);
382
+ } else if (!chunks.length) {
383
+ fail(new Error("Hunyuan read nothing."));
384
+ } else {
385
+ writeFile2(out, wav(Buffer.concat(chunks))).then(() => done(), fail);
386
+ }
387
+ };
388
+ const timer = setTimeout(() => end(new Error("Hunyuan did not finish reading in time.")), timeout);
389
+ const send = (message) => socket.send(JSON.stringify(message));
390
+ socket.addEventListener("error", () => end(new Error(`Could not reach Hunyuan at ${service2.url}.`)));
391
+ socket.addEventListener("message", (event) => {
392
+ const message = JSON.parse(String(event.data));
393
+ switch (message.type) {
394
+ case "session.created":
395
+ send({
396
+ type: "session.update",
397
+ session: {
398
+ instructions: "Read what you are given as it is written.",
399
+ output_modalities: ["audio"],
400
+ audio: {
401
+ input: { format: { type: "audio/pcm", rate: 16000 }, turn_detection: { type: "server_vad", create_response: false } },
402
+ output: { format: { type: "audio/pcm", rate: RATE }, voice }
403
+ }
404
+ }
405
+ });
406
+ break;
407
+ case "session.updated":
408
+ send({ type: "response.create", response: { input_scope: "independent", input_text: text, output_modalities: ["audio"] } });
409
+ break;
410
+ case "response.output_audio.delta":
411
+ case "response.audio.delta":
412
+ chunks.push(Buffer.from(message.delta ?? "", "base64"));
413
+ break;
414
+ case "response.done":
415
+ end();
416
+ break;
417
+ case "error":
418
+ end(new Error(`Hunyuan: ${message.error?.message ?? "an error"}`));
419
+ break;
420
+ }
421
+ });
422
+ });
423
+ }
424
+ HunyuanVoice.read = read;
425
+ })(HunyuanVoice ||= {});
426
+
427
+ // web-src/stage.ts
428
+ var BEAT = 0.5;
429
+ var OPENING = 2.2;
430
+ var BODY = [
431
+ "..........####......",
432
+ "........##########..",
433
+ "........###########.",
434
+ ".......#############",
435
+ ".......#############",
436
+ ".##....#############",
437
+ "###....#############",
438
+ "##.....#############",
439
+ "##.....#####........",
440
+ "###....###########..",
441
+ "####..############..",
442
+ "##################..",
443
+ ".################...",
444
+ ".##############.....",
445
+ "..############......",
446
+ "...##########.......",
447
+ "....########........"
448
+ ];
449
+ var LEGS = {
450
+ stand: ["....###...###.......", "...###....###.......", "...####...####......"],
451
+ tuck: ["....###..###........", "....##...##........."],
452
+ none: []
453
+ };
454
+ var ARMS = {
455
+ down: [
456
+ [15, 13],
457
+ [16, 13],
458
+ [16, 14]
459
+ ],
460
+ up: [
461
+ [17, 12],
462
+ [18, 11],
463
+ [18, 10]
464
+ ],
465
+ out: [
466
+ [16, 13],
467
+ [17, 13],
468
+ [18, 12]
469
+ ]
470
+ };
471
+ var EYES = {
472
+ n: {
473
+ w: [
474
+ [10, 3],
475
+ [10, 4]
476
+ ],
477
+ p: [
478
+ [11, 3],
479
+ [11, 4]
480
+ ]
481
+ },
482
+ l: {
483
+ w: [
484
+ [11, 3],
485
+ [11, 4]
486
+ ],
487
+ p: [
488
+ [10, 3],
489
+ [10, 4]
490
+ ]
491
+ },
492
+ d: {
493
+ w: [
494
+ [10, 3],
495
+ [11, 3]
496
+ ],
497
+ p: [
498
+ [10, 4],
499
+ [11, 4]
500
+ ]
501
+ },
502
+ happy: {
503
+ w: [],
504
+ p: [
505
+ [9, 4],
506
+ [10, 3],
507
+ [11, 3],
508
+ [12, 4]
509
+ ]
510
+ }
511
+ };
512
+ var GREEN = "#10B981";
513
+ var SHADE = "#0A8F62";
514
+ var EpisodeStage;
515
+ ((EpisodeStage) => {
516
+ function dino(size, pose = {}, white = false) {
517
+ const cells = new Map;
518
+ const put = (c, r, v) => cells.set(`${c},${r}`, v);
519
+ const paint = (rows, top) => {
520
+ for (const [r, row] of rows.entries()) {
521
+ for (const [c, ch] of [...row].entries()) {
522
+ if (ch === "#") {
523
+ put(c, top + r, GREEN);
524
+ }
525
+ }
526
+ }
527
+ };
528
+ paint(BODY, 0);
529
+ paint(LEGS[pose.legs ?? "stand"] ?? LEGS.stand, 17);
530
+ for (const [c, r] of ARMS[pose.arms ?? "down"] ?? ARMS.down) {
531
+ put(c, r, GREEN);
532
+ }
533
+ for (const key of [...cells.keys()]) {
534
+ const [c, r] = key.split(",").map(Number);
535
+ if (!cells.has(`${c},${r + 1}`) && r < 19) {
536
+ put(c, r, SHADE);
537
+ }
538
+ }
539
+ put(13, 8, "#EFFFF8");
540
+ put(16, 8, "#EFFFF8");
541
+ const eyes = EYES[pose.eyes ?? "n"] ?? EYES.n;
542
+ for (const [c, r] of eyes.w) {
543
+ put(c, r, "#EFFFF8");
544
+ }
545
+ for (const [c, r] of eyes.p) {
546
+ put(c, r, "#0A2A1F");
547
+ }
548
+ const rects = [...cells].map(([key, v]) => {
549
+ const [c, r] = key.split(",");
550
+ const fill = white ? v === GREEN || v === SHADE ? "#fff" : GREEN : v;
551
+ return `<rect x="${c}" y="${r}" width="1.04" height="1.04" fill="${fill}"/>`;
552
+ }).join("");
553
+ return `<svg class="dino" viewBox="0 0 20 20" style="width:${size}rem;height:${size}rem" shape-rendering="crispEdges">${rects}</svg>`;
554
+ }
555
+ EpisodeStage.dino = dino;
556
+ function html(text) {
557
+ return text.replace(/[&<>"]/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[ch] ?? ch);
558
+ }
559
+ EpisodeStage.html = html;
560
+ function code(line) {
561
+ const prompt = /^(\s*)\$ /.exec(line);
562
+ const rest = prompt ? line.slice(prompt[0].length) : line;
563
+ const body = EpisodeAss.tokens(rest).map((one) => one.kind ? `<span class="k-${one.kind}">${html(one.text)}</span>` : html(one.text)).join("");
564
+ return (prompt ? `${prompt[1]}<span class="k-prompt">$</span> ` : "") + body || "&nbsp;";
565
+ }
566
+ EpisodeStage.code = code;
567
+ function kind(scene) {
568
+ return scene.phone?.lines.length ? "phone" : scene.code?.lines.length ? "code" : scene.points?.length ? "points" : "title";
569
+ }
570
+ EpisodeStage.kind = kind;
571
+ function last(scene) {
572
+ switch (kind(scene)) {
573
+ case "phone":
574
+ return (scene.phone?.lines.length ?? 0) + (scene.phone?.notify ? 1 : 0);
575
+ case "code":
576
+ return scene.code?.lines.length ?? 0;
577
+ case "points":
578
+ return scene.points?.length ?? 0;
579
+ default:
580
+ return scene.sub ? 1 : 0;
581
+ }
582
+ }
583
+ EpisodeStage.last = last;
584
+ function steps(scene) {
585
+ const end = last(scene);
586
+ switch (kind(scene)) {
587
+ case "code":
588
+ case "phone": {
589
+ const lines = (scene.phone ?? scene.code)?.lines.length ?? 1;
590
+ const typed = Array.from({ length: lines }, (_, i) => (kind(scene) === "code" ? 0.6 : 0.5) * (i / lines));
591
+ return end > lines ? [...typed, 0.7] : typed;
592
+ }
593
+ case "points":
594
+ return Array.from({ length: end }, (_, i) => 0.7 * (i / end));
595
+ default:
596
+ return end ? [0, 0.12] : [0];
597
+ }
598
+ }
599
+ EpisodeStage.steps = steps;
600
+ function first(scene) {
601
+ return kind(scene) === "title" ? 0 : 1;
602
+ }
603
+ EpisodeStage.first = first;
604
+ function timeline(timed, opening2 = 0) {
605
+ const out = [];
606
+ const hold = (scene, step, from, to) => {
607
+ for (let at = from, pose = 0;at < to - 0.000001; at += BEAT, pose = 1 - pose) {
608
+ out.push({ shot: { scene, step, pose }, seconds: Math.min(BEAT, to - at) });
609
+ }
610
+ };
611
+ if (opening2) {
612
+ hold(-1, 0, 0, opening2);
613
+ }
614
+ timed.forEach(({ scene, start, end }, i) => {
615
+ const at = steps(scene).map((share) => start + share * (end - start));
616
+ const base = first(scene);
617
+ for (const [k, from] of at.entries()) {
618
+ hold(i, base + k, from, at[k + 1] ?? end);
619
+ }
620
+ });
621
+ return out;
622
+ }
623
+ EpisodeStage.timeline = timeline;
624
+ function page(aspect) {
625
+ const [width, height] = EpisodeAss.size(aspect);
626
+ const rem = Math.min(width, height) / 1080 * 10;
627
+ return '<!doctype html><html><head><meta charset="utf-8"><style>html{font-size:' + rem + "px}" + CSS + '</style></head><body class="' + (width > height ? "wide" : "tall") + '" style="width:' + width + "px;height:" + height + 'px"></body></html>';
628
+ }
629
+ EpisodeStage.page = page;
630
+ function frame(episode, shot, aspect, options = {}) {
631
+ const [width, height] = EpisodeAss.size(aspect);
632
+ const wide = width > height;
633
+ const label = `<div class="ai">${html(episode.label ?? "AI 合成")}</div>`;
634
+ if (shot.scene < 0) {
635
+ return `<div class="stage ink opening">${label}${opening(episode, shot, wide)}</div>`;
636
+ }
637
+ const scene = episode.scenes[shot.scene];
638
+ const what = kind(scene);
639
+ const look = scene.look ?? episode.look ?? (what === "code" ? "ink" : what === "points" ? "sketch" : "paper");
640
+ const step = Math.min(shot.step, last(scene));
641
+ const body = what === "code" ? terminal(scene, step, shot.pose, wide) : what === "phone" ? phone(scene, step, shot.pose, wide) : what === "points" ? points(scene, step, shot.pose, wide) : host(scene, step, shot.pose, wide);
642
+ const words = options.post ? `<div class="words">${html(scene.say)}</div>` : "";
643
+ return '<div class="stage ' + look + (options.post ? " post" : "") + '">' + SKETCH + label + brand(episode) + '<div class="main scene-' + what + '">' + body + "</div>" + words + "</div>";
644
+ }
645
+ EpisodeStage.frame = frame;
646
+ function cover(episode, aspect) {
647
+ const [width, height] = EpisodeAss.size(aspect);
648
+ const wide = width > height;
649
+ const [head, tail] = episode.title.split(/[::]/);
650
+ const lines = episode.cover?.lines?.length ? episode.cover.lines : [head];
651
+ const sub = episode.cover?.sub ?? tail ?? "";
652
+ const longest = Math.max(...lines.map(EpisodeAss.columns)) / 2;
653
+ const room = wide ? 100 : 94;
654
+ const size = Math.min(wide ? 15 : 13, room / Math.max(4, longest) * (lines.length > 1 ? 1 : 1.9));
655
+ const tag = episode.series ? `<div class="tag">${html(episode.series.split(/\s*[·•]\s*/)[0])}${episode.number ? ` · 第 ${episode.number} 期` : ""}</div>` : "";
656
+ const notify = episode.scenes.find((one) => one.phone?.notify)?.phone?.notify;
657
+ const tags = (episode.cover?.tags ?? []).slice(0, 4).map((one) => `<span>${html(one)}</span>`).join("");
658
+ return '<div class="stage cover">' + '<div class="ai">' + html(episode.label ?? "AI 合成") + '</div><div class="blob"></div><div class="text">' + tag + '<h1 style="font-size:' + size.toFixed(2) + 'rem">' + lines.map(html).join("<br>") + "</h1>" + (sub ? `<h2>${html(sub)}</h2>` : "") + (tags ? `<div class="tags">${tags}</div>` : "") + '</div><div class="props">' + (notify ? '<div class="phone mini"><div class="screen"><div class="island"></div><div class="notify"><div class="icon">' + dino(3.6, { eyes: "happy" }, true) + "</div><div><b>" + html(notify.title) + "</b><p>" + html(notify.text) + "</p></div></div></div></div>" : "") + '<div class="host">' + dino(wide ? 44 : 46, { arms: "out", eyes: "happy" }, true) + "</div></div></div>";
659
+ }
660
+ EpisodeStage.cover = cover;
661
+ function brand(episode) {
662
+ if (!episode.series) {
663
+ return "";
664
+ }
665
+ return `<div class="brand">${episode.number ? `<b>第 ${episode.number} 期</b>` : ""}${html(episode.series)}</div>`;
666
+ }
667
+ function opening(episode, shot, wide) {
668
+ const jump = shot.pose ? ' style="transform:translateY(-4rem)"' : "";
669
+ const sparks = [
670
+ [28, 26, "#F2C14E"],
671
+ [70, 20, "#3ECF8E"],
672
+ [72, 48, "#F2C14E"],
673
+ [26, 52, "#3ECF8E"]
674
+ ].map(([x, y, c]) => `<i class="spark" style="left:${x}%;top:${y}%;color:${c}"></i>`).join("");
675
+ const name = episode.series ?? episode.title;
676
+ const sub = episode.series ? (episode.number ? `第 ${episode.number} 期 · ` : "") + episode.title.split(/[::]/)[0] : "";
677
+ return '<div class="glow"></div>' + sparks + '<div class="center"><div class="jump"' + jump + ">" + dino(wide ? 36 : 44, { arms: "up", eyes: "happy", legs: shot.pose ? "tuck" : "stand" }) + "</div><h1>" + html(name).replace(/\s*[·•]\s*/, "<em> · </em>") + "</h1>" + (sub ? `<h2>${html(sub)}</h2>` : "") + "</div>";
678
+ }
679
+ const STEP = /^(第.{1,3}[步招点个]|窍门.{1,2}|技巧.{1,2}|步骤.{1,2}|Step \d+|Tip \d+)$/i;
680
+ function host(scene, step, pose, wide) {
681
+ const title = scene.title ?? "";
682
+ const badge = STEP.test(title);
683
+ const first2 = badge ? `<div class="badge big">${html(title)}</div>` : `<div class="bubble big">${html(title)}</div>`;
684
+ const second = scene.sub && step >= 1 ? `<div class="bubble${badge ? " big" : " soft"}">${html(scene.sub)}</div>` : "";
685
+ const dinoPose = pose ? { arms: "out", eyes: "happy" } : { arms: "down", eyes: "n" };
686
+ return '<div class="host' + (pose ? " up" : "") + '">' + dino(wide ? 50 : 54, dinoPose) + '<div class="shadow"></div></div><div class="talk">' + first2 + second + "</div>";
687
+ }
688
+ function terminal(scene, step, pose, wide) {
689
+ const lines = (scene.code?.lines ?? []).slice(0, wide ? 14 : 22);
690
+ const shown = lines.slice(0, step);
691
+ const longest = Math.max(24, ...lines.map(EpisodeAss.columns));
692
+ const room = wide ? scene.note ? 118 : 150 : 96;
693
+ const size = Math.max(2.2, Math.min(wide ? 4 : 3.8, room / (longest * 0.6)));
694
+ const typing = step < lines.length;
695
+ const rows = shown.map((line, i) => `<div>${code(line)}${i === shown.length - 1 ? `<span class="cursor${typing || pose ? "" : " off"}"></span>` : ""}</div>`).join("");
696
+ const note = scene.note ? `<div class="note">${html(scene.note)}</div>` : "";
697
+ const peek = `<div class="peek">${dino(wide ? 20 : 14, { eyes: pose ? "d" : "l", legs: "none" })}</div>`;
698
+ return '<div class="window">' + peek + '<div class="bar"><i></i><i></i><i></i><span>' + html(scene.code?.file ?? "zsh") + '</span></div><div class="lines" style="font-size:' + size.toFixed(2) + 'rem">' + rows + "</div></div>" + note;
699
+ }
700
+ function phone(scene, step, pose, wide) {
701
+ const lines = (scene.phone?.lines ?? []).slice(0, 16);
702
+ const shown = lines.slice(0, Math.min(step, lines.length));
703
+ const notified = scene.phone?.notify && step > lines.length;
704
+ const longest = Math.max(20, ...lines.map(EpisodeAss.columns));
705
+ const size = Math.max(1.8, Math.min(wide ? 3 : 3.4, (wide ? 36 : 54) / (longest * 0.6)));
706
+ const rows = shown.map((line, i) => `<div>${code(line)}${i === shown.length - 1 && !notified ? '<span class="cursor"></span>' : ""}</div>`).join("");
707
+ const notify = notified ? '<div class="notify"><div class="icon">' + dino(4.6, { eyes: "happy" }, true) + "</div><div><b>" + html(scene.phone?.notify?.title ?? "") + " · 刚刚</b><p>" + html(scene.phone?.notify?.text ?? "") + "</p></div></div>" : "";
708
+ const note = scene.note ? `<div class="bubble">${html(scene.note)}</div>` : "";
709
+ const dinoPose = notified ? { arms: "up", eyes: "happy" } : pose ? { arms: "out", eyes: "n" } : { arms: "down", eyes: "d" };
710
+ return '<div class="side">' + note + '<div class="host' + (pose ? " up" : "") + '">' + dino(wide ? 40 : 22, dinoPose) + '<div class="shadow"></div></div></div><div class="phone"><div class="screen' + (notified ? " notified" : "") + '"><div class="island"></div>' + notify + '<div class="lines" style="font-size:' + size.toFixed(2) + 'rem">' + rows + '</div><div class="keys"><span>esc</span><span>tab</span><span>ctrl</span><span>↑</span><span>↓</span></div></div></div>';
711
+ }
712
+ function points(scene, step, pose, wide) {
713
+ const items = (scene.points ?? []).slice(0, step).map((one, i) => '<li><span class="num">' + "①②③④⑤⑥⑦⑧⑨"[i] + "</span>" + html(one) + '<i class="mark" style="width:' + (60 + i * 13 % 30) + '%"></i></li>').join("");
714
+ const done = step >= (scene.points?.length ?? 0);
715
+ const dinoPose = done ? { arms: "up", eyes: "happy" } : pose ? { arms: "out", eyes: "n" } : { arms: "down", eyes: "d" };
716
+ return '<div class="list"><h1 class="hand">' + html(scene.title ?? "") + "</h1><ol>" + items + '</ol></div><div class="side">' + (scene.sub && done ? `<div class="hand say">${html(scene.sub)}</div>` : "") + '<div class="host hand' + (pose ? " up" : "") + '">' + dino(wide ? 36 : 26, dinoPose) + '<div class="shadow"></div></div></div>';
717
+ }
718
+ const SKETCH = '<svg width="0" height="0" style="position:absolute"><filter id="wob"><feTurbulence baseFrequency=".03" numOctaves="2" seed="3"/><feDisplacementMap in="SourceGraphic" scale="6"/></filter></svg>';
719
+ const CSS = `
720
+ *{box-sizing:border-box;margin:0;padding:0}
721
+ body{overflow:hidden;font-family:"PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;-webkit-font-smoothing:antialiased}
722
+ .stage{position:absolute;inset:0;overflow:hidden;display:flex;flex-direction:column;--fg:#0A2A1F;--dim:#3d5a4f;color:var(--fg)}
723
+ .paper{background:#F4EFE4}
724
+ .paper:before{content:"";position:absolute;inset:0;background-image:radial-gradient(#d9d1bf .2rem,transparent .2rem);background-size:3.6rem 3.6rem;opacity:.8}
725
+ .ink{background:radial-gradient(120% 90% at 70% 10%,#173b2f 0%,#0d1a16 55%,#0a1210 100%);--fg:#fff;--dim:#bfe9d9}
726
+ .ink:before{content:"";position:absolute;inset:0;background-image:linear-gradient(rgba(16,185,129,.08) 1px,transparent 1px),linear-gradient(90deg,rgba(16,185,129,.08) 1px,transparent 1px);background-size:4.8rem 4.8rem}
727
+ .sketch{background:#FBF6EA;--fg:#222}
728
+ .sketch:before{content:"";position:absolute;inset:0;background:repeating-linear-gradient(transparent 0 4.6rem,#bcd3e8 4.6rem 4.8rem);opacity:.9}
729
+ .sketch:after{content:"";position:absolute;top:0;bottom:0;left:12rem;width:.3rem;background:#e8a0a0}
730
+ .ai{position:absolute;right:3.2rem;top:2.8rem;font-size:2.4rem;color:#fff;background:rgba(0,0,0,.42);padding:.6rem 1.4rem;border-radius:1rem;z-index:20}
731
+ .tall .ai{top:9rem}
732
+ .brand{position:relative;z-index:5;margin:3rem 0 0 4rem;display:flex;align-items:center;gap:1.2rem;font-weight:700;font-size:3rem;color:#0A8F62;height:5rem}
733
+ .tall .brand{margin-top:9.2rem}
734
+ .ink .brand{color:#3ECF8E}
735
+ .brand b{background:#10B981;color:#fff;border-radius:1rem;padding:.4rem 1.2rem;font-size:2.4rem}
736
+ .main{position:relative;z-index:2;flex:1;display:flex;align-items:center;justify-content:center;gap:5rem;padding:3rem 8rem 15rem}
737
+ .tall .main{flex-direction:column;padding:4rem 6rem 30rem;gap:4rem}
738
+ .post .main{padding-bottom:4rem}
739
+ .words{position:relative;z-index:3;margin:0 6rem 6rem;background:rgba(14,21,18,.86);color:#fff;font-size:4rem;line-height:1.55;font-weight:600;padding:3rem 3.6rem;border-radius:2.4rem}
740
+ .dino{display:block}
741
+ .host{position:relative;flex:none;transition:none}
742
+ .host.up{transform:translateY(-1.2rem)}
743
+ .host .shadow{margin:-1.2rem auto 0;width:70%;height:2rem;border-radius:50%;background:rgba(0,0,0,.18)}
744
+ .ink .host .shadow{background:rgba(0,0,0,.4)}
745
+ .talk{display:flex;flex-direction:column;gap:4rem;align-items:flex-start;max-width:58%}
746
+ .tall .talk{max-width:100%;align-items:center;order:-1}
747
+ .bubble{position:relative;background:#fff;border:.5rem solid #0A2A1F;border-radius:2.6rem;padding:2.4rem 3.2rem;font-size:4.6rem;line-height:1.35;font-weight:700;color:#0A2A1F;box-shadow:.8rem .8rem 0 #0A2A1F}
748
+ .bubble.big{font-size:8.4rem}
749
+ .bubble.soft{background:#E6F7EF;font-size:5rem}
750
+ .wide .talk .bubble:after{content:"";position:absolute;left:-3.2rem;bottom:3rem;border:1.6rem solid transparent;border-right:2.2rem solid #0A2A1F}
751
+ .badge{display:inline-block;background:#F2C14E;color:#0A2A1F;font-weight:800;border-radius:1.6rem;padding:1rem 3rem;border:.5rem solid #0A2A1F;box-shadow:.8rem .8rem 0 #0A2A1F;font-size:6rem}
752
+ .window{position:relative;flex:1;max-width:150rem;align-self:stretch;margin-top:8rem;background:#11161a;border-radius:2.2rem;box-shadow:0 3rem 8rem rgba(0,0,0,.4),0 0 0 .2rem rgba(255,255,255,.06);display:flex;flex-direction:column}
753
+ .tall .window{flex:none;width:100%;margin-top:12rem;min-height:60%}
754
+ .window .bar{height:5.6rem;background:#1c2329;border-radius:2.2rem 2.2rem 0 0;display:flex;align-items:center;gap:1.2rem;padding:0 2.2rem;color:#8a99a6;font-size:2.4rem}
755
+ .window .bar i{width:1.6rem;height:1.6rem;border-radius:50%;background:#ff5f57}
756
+ .window .bar i:nth-child(2){background:#febc2e}.window .bar i:nth-child(3){background:#28c840}
757
+ .window .bar span{margin-left:1rem}
758
+ .lines{font-family:Menlo,"JetBrains Mono",monospace;line-height:1.6;color:#d8e1e8;padding:2.8rem 3.4rem;white-space:pre}
759
+ .k-prompt{color:#3ECF8E}.k-comment{color:#6b7b88}.k-string{color:#F2C14E}.k-number{color:#ffaa64}.k-keyword{color:#c792ea}.k-name{color:#7aa2f7}
760
+ .cursor{display:inline-block;width:.55em;height:1.1em;background:#3ECF8E;vertical-align:-.18em;margin-left:.2em}
761
+ .cursor.off{opacity:0}
762
+ .peek{position:absolute;right:6rem;bottom:100%;margin-bottom:-.6rem}
763
+ .wide .scene-code{align-items:stretch;padding-top:16rem}
764
+ .wide .scene-code .window{margin-top:0}
765
+ .wide .scene-code .note{align-self:center}
766
+ .screen.notified .lines{padding-top:22rem}
767
+ .note{flex:none;width:44rem;background:#10B981;color:#fff;border-radius:2.2rem;padding:3rem;font-size:4.4rem;line-height:1.4;font-weight:700;box-shadow:.8rem .8rem 0 #06281c}
768
+ .paper .note,.sketch .note{box-shadow:.8rem .8rem 0 #0A2A1F;border:.5rem solid #0A2A1F}
769
+ .tall .note{width:100%}
770
+ .phone{position:relative;flex:none;height:calc(100vh - 28rem);aspect-ratio:.56;background:#0b0f12;border-radius:7rem;padding:2.2rem;box-shadow:0 4rem 9rem rgba(0,0,0,.4),inset 0 0 0 .4rem #2a3238}
771
+ .tall .phone{height:auto;width:62%;flex:1;aspect-ratio:auto}
772
+ .screen{position:relative;width:100%;height:100%;border-radius:5.2rem;overflow:hidden;background:#0f1418;display:flex;flex-direction:column}
773
+ .island{position:absolute;left:50%;top:1.8rem;transform:translateX(-50%);width:15rem;height:4.4rem;background:#000;border-radius:2.4rem;z-index:3}
774
+ .screen .lines{flex:1;padding:12rem 2.6rem 0;white-space:pre-wrap;word-break:break-all;color:#cfe}
775
+ .keys{height:11rem;background:#1c2329;display:flex;gap:1rem;align-items:center;justify-content:center;font-family:Menlo,monospace;font-size:2.2rem;color:#cfe}
776
+ .keys span{background:#2d363e;border-radius:1.2rem;padding:.8rem 1.4rem}
777
+ .notify{position:absolute;left:1.8rem;right:1.8rem;top:7rem;background:rgba(245,245,245,.97);border-radius:2.8rem;padding:2rem 2.4rem;display:flex;gap:1.8rem;align-items:center;box-shadow:0 1.4rem 3rem rgba(0,0,0,.35);z-index:4}
778
+ .notify .icon{width:6.4rem;height:6.4rem;border-radius:1.6rem;background:#10B981;flex:none;display:flex;align-items:center;justify-content:center}
779
+ .notify b{font-size:2.6rem;color:#111}.notify p{font-size:2.4rem;color:#444;margin-top:.2rem;line-height:1.35}
780
+ .scene-phone .side,.scene-points .side{display:flex;flex-direction:column;align-items:center;gap:4rem}
781
+ .scene-phone{gap:8rem}
782
+ .tall .scene-phone .side{flex-direction:row;align-items:flex-end;width:100%;justify-content:space-between}
783
+ .tall .scene-phone .bubble{font-size:4rem}
784
+ .hand{filter:url(#wob)}
785
+ .list{flex:1;padding-left:8rem}
786
+ .tall .list{padding-left:10rem;flex:none;width:100%}
787
+ .list h1{font-size:8.4rem;color:#1d3b8f;transform:rotate(-2deg);margin-bottom:5rem}
788
+ .list ol{list-style:none;display:flex;flex-direction:column;gap:5rem}
789
+ .list li{position:relative;font-size:6.4rem;font-weight:700;filter:url(#wob)}
790
+ .tall .list li{font-size:5.6rem}
791
+ .list .num{margin-right:1.6rem}
792
+ .list .mark{position:absolute;left:-1rem;bottom:-1.4rem;height:1.8rem;background:#F2C14E;opacity:.6;border-radius:.9rem;z-index:-1}
793
+ .say{font-size:4.6rem;font-weight:700;color:#0A8F62;transform:rotate(4deg)}
794
+ .opening{align-items:center;justify-content:center}
795
+ .opening .glow{position:absolute;inset:0;background:radial-gradient(circle at 50% 42%,rgba(16,185,129,.38),transparent 45%)}
796
+ .opening .center{position:relative;display:flex;flex-direction:column;align-items:center;gap:3rem;z-index:2}
797
+ .opening h1{font-size:11rem;font-weight:800;color:#fff;letter-spacing:.6rem;text-align:center;line-height:1.2}
798
+ .tall .opening h1{font-size:9rem}
799
+ .opening h1 em{font-style:normal;color:#10B981}
800
+ .opening h2{font-size:4.4rem;color:#9fd9c3;font-weight:600;text-align:center}
801
+ .spark{position:absolute;width:5rem;height:5rem;z-index:1}
802
+ .spark:before,.spark:after{content:"";position:absolute;background:currentColor}
803
+ .spark:before{left:2rem;top:0;width:1rem;height:5rem}.spark:after{top:2rem;left:0;width:5rem;height:1rem}
804
+ .cover{background:#10B981;color:#fff;flex-direction:row}
805
+ .cover .blob{position:absolute;right:-12rem;top:-12rem;width:90rem;height:90rem;border-radius:50%;background:#0FA372}
806
+ .tall .cover .blob{right:auto;left:-20rem;top:auto;bottom:-26rem}
807
+ .cover .text{position:relative;z-index:2;padding:8rem 0 0 9rem;width:62%}
808
+ .tall .cover .text{width:100%;padding:9rem 7rem 0}
809
+ .cover .tag{display:inline-block;font-size:4rem;font-weight:800;color:#06281c;background:#F2C14E;padding:1rem 2.6rem;border-radius:1.6rem;border:.5rem solid #06281c;box-shadow:.7rem .7rem 0 #06281c}
810
+ .cover h1{margin-top:5rem;line-height:1.12;font-weight:800;text-shadow:.8rem .8rem 0 #06281c}
811
+ .cover h2{margin-top:4rem;font-size:5.6rem;font-weight:800;color:#06281c}
812
+ .cover .tags{margin-top:5rem;display:flex;gap:1.8rem;flex-wrap:wrap}
813
+ .cover .tags span{background:#06281c;font-size:4rem;font-weight:700;padding:1rem 2.6rem;border-radius:99rem}
814
+ .cover .props{position:absolute;inset:0;z-index:1}
815
+ .cover .phone.mini{position:absolute;height:auto;width:33rem;aspect-ratio:.49;right:17rem;bottom:10rem;transform:rotate(8deg);padding:1.6rem;border-radius:5rem}
816
+ .tall .cover .phone.mini{width:38rem;right:6rem;bottom:-4rem}
817
+ .cover .phone.mini .screen{border-radius:3.8rem}
818
+ .cover .phone.mini .island{width:10rem;height:3rem}
819
+ .cover .phone.mini .notify{top:6rem;padding:1.4rem}
820
+ .cover .phone.mini .icon{width:5rem;height:5rem}
821
+ .cover .host{position:absolute;right:42rem;bottom:6rem;filter:drop-shadow(.6rem 0 0 #06281c) drop-shadow(-.6rem 0 0 #06281c) drop-shadow(0 .6rem 0 #06281c) drop-shadow(0 -.6rem 0 #06281c) drop-shadow(1rem 1.2rem 0 rgba(6,40,28,.35))}
822
+ .tall .cover .host{right:auto;left:8rem;bottom:8rem}
823
+ `;
824
+ })(EpisodeStage ||= {});
825
+
158
826
  // web-src/render.ts
159
827
  var EpisodeRender;
160
828
  ((EpisodeRender) => {
@@ -164,7 +832,7 @@ var EpisodeRender;
164
832
  EpisodeRender.VOICE = "zh-CN-XiaoxiaoNeural";
165
833
  const NEURAL = /^[a-z]{2,3}-[A-Z]{2}-\w+Neural$/;
166
834
  async function run(file, options) {
167
- const episode = JSON.parse(await readFile(file, "utf8"));
835
+ const episode = JSON.parse(await readFile2(file, "utf8"));
168
836
  if (!episode?.title || !Array.isArray(episode.scenes) || !episode.scenes.length) {
169
837
  throw new Error("An episode is { title, scenes: [{ say, code?, title?, sub?, points? }] }.");
170
838
  }
@@ -173,27 +841,44 @@ var EpisodeRender;
173
841
  }
174
842
  EpisodeRender.run = run;
175
843
  async function video(episode, options) {
176
- const work = await mkdtemp(join(tmpdir(), "ta-creator-"));
844
+ const work = await mkdtemp2(join3(tmpdir2(), "ta-creator-"));
177
845
  try {
178
846
  const wanted = episode.voice ?? EpisodeRender.VOICE;
179
- const python = NEURAL.test(wanted) ? await edgePython() : undefined;
180
- if (NEURAL.test(wanted) && !python) {
181
- console.error(`No Python with edge-tts here (set TA_CREATOR_PYTHON): read in this computer's speech instead of ${wanted}.`);
847
+ const hunyuan = HunyuanVoice.voiceOf(wanted) ? await HunyuanVoice.service() : undefined;
848
+ if (HunyuanVoice.voiceOf(wanted) && !hunyuan) {
849
+ console.error(`No Hy Realtime in Ta's voice settings (or TA_CREATOR_HUNYUAN_URL): read in ${EpisodeRender.VOICE} instead.`);
182
850
  }
183
- const speaker = python ? wanted : pickVoice(await exec("say", ["-v", "?"]), NEURAL.test(wanted) ? undefined : wanted);
851
+ const neural = hunyuan ? undefined : NEURAL.test(wanted) ? wanted : HunyuanVoice.voiceOf(wanted) ? EpisodeRender.VOICE : undefined;
852
+ const python = neural ? await edgePython() : undefined;
853
+ if (neural && !python) {
854
+ console.error(`No Python with edge-tts here (set TA_CREATOR_PYTHON): read in this computer's speech instead of ${neural}.`);
855
+ }
856
+ const speaker = hunyuan ? "" : python ? neural : pickVoice(await exec("say", ["-v", "?"]), neural || HunyuanVoice.voiceOf(wanted) ? undefined : wanted);
184
857
  const timed = [];
185
858
  const parts = [];
186
- let at = 0;
859
+ const chrome = StageBrowser.find();
860
+ const opening = chrome && episode.series ? OPENING : 0;
861
+ if (!chrome) {
862
+ console.error("No Chrome, Edge, Brave or Chromium here (set TA_CREATOR_CHROME): drawn plainly, without the host and the devices.");
863
+ }
864
+ if (opening) {
865
+ const sting = join3(work, "sting.wav");
866
+ await exec("ffmpeg", ["-y", "-loglevel", "error", "-f", "lavfi", "-i", `aevalsrc=exprs='${CHIME}':s=44100:d=${opening}`, "-ac", "1", sting]);
867
+ parts.push(sting);
868
+ }
869
+ let at = opening;
187
870
  for (const [i, scene] of episode.scenes.entries()) {
188
- const spoken = join(work, python ? `${i}.mp3` : `${i}.aiff`);
871
+ const spoken = join3(work, hunyuan ? `${i}.hy.wav` : python ? `${i}.mp3` : `${i}.aiff`);
189
872
  const said = scene.say.replace(/`/g, "");
190
- if (python) {
873
+ if (hunyuan) {
874
+ await readHunyuan(hunyuan, HunyuanVoice.voiceOf(wanted), said, spoken);
875
+ } else if (python) {
191
876
  await exec(python, ["-m", "edge_tts", "--voice", speaker, "--rate", neuralRate(episode.rate), "--text", said, "--write-media", spoken]);
192
877
  } else {
193
878
  await exec("say", ["-v", speaker, "-r", String(episode.rate ?? RATE), "-o", spoken, paced(said)]);
194
879
  }
195
880
  const seconds = await length(spoken) + GAP;
196
- const padded = join(work, `${i}.wav`);
881
+ const padded = join3(work, `${i}.wav`);
197
882
  await exec("ffmpeg", [
198
883
  "-y",
199
884
  "-loglevel",
@@ -212,19 +897,23 @@ var EpisodeRender;
212
897
  parts.push(padded);
213
898
  at += seconds;
214
899
  }
215
- const list = join(work, "list.txt");
216
- await writeFile(list, parts.map((one) => `file '${one.replace(/'/g, "'\\''")}'`).join(`
900
+ const list = join3(work, "list.txt");
901
+ await writeFile3(list, parts.map((one) => `file '${one.replace(/'/g, "'\\''")}'`).join(`
217
902
  `));
218
- const voice = join(options.out, "voice.m4a");
903
+ const voice = join3(options.out, "voice.m4a");
219
904
  await exec("ffmpeg", ["-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", list, "-c:a", "aac", "-b:a", "128k", voice]);
220
- await writeFile(join(options.out, "captions.srt"), srt(timed));
221
- const made = [voice, join(options.out, "captions.srt")];
905
+ await writeFile3(join3(options.out, "captions.srt"), srt(timed));
906
+ const made = [voice, join3(options.out, "captions.srt")];
907
+ if (chrome) {
908
+ made.push(...await staged(chrome, episode, timed, opening, voice, work, options));
909
+ return made;
910
+ }
222
911
  for (const aspect of options.aspects) {
223
912
  const [width, height] = EpisodeAss.size(aspect);
224
913
  const name = aspect.replace(":", "x");
225
- const ass = join(work, `${name}.ass`);
226
- await writeFile(ass, EpisodeAss.build(episode, timed, aspect));
227
- const mp4 = join(options.out, `${name}.mp4`);
914
+ const ass = join3(work, `${name}.ass`);
915
+ await writeFile3(ass, EpisodeAss.build(episode, timed, aspect));
916
+ const mp4 = join3(options.out, `${name}.mp4`);
228
917
  await exec("ffmpeg", [
229
918
  "-y",
230
919
  "-loglevel",
@@ -257,26 +946,135 @@ var EpisodeRender;
257
946
  mp4
258
947
  ]);
259
948
  const first = timed.find((one) => one.scene.title) ?? timed[0];
260
- const cover = join(options.out, `cover-${name}.png`);
949
+ const cover = join3(options.out, `cover-${name}.png`);
261
950
  await exec("ffmpeg", ["-y", "-loglevel", "error", "-ss", String(Math.max(0.1, first.end - 0.2)), "-i", mp4, "-frames:v", "1", cover]);
262
951
  made.push(mp4, cover);
263
952
  }
264
953
  return made;
265
954
  } finally {
266
- await rm(work, { recursive: true, force: true });
955
+ await rm2(work, { recursive: true, force: true });
956
+ }
957
+ }
958
+ async function readHunyuan(service, voice, text, out) {
959
+ try {
960
+ await HunyuanVoice.read(service, voice, text, out);
961
+ } catch {
962
+ await HunyuanVoice.read(service, voice, text, out);
963
+ }
964
+ }
965
+ const CHIME = [
966
+ "0.26*sin(2*PI*784*t)*exp(-5*t)",
967
+ "0.24*gt(t,0.16)*sin(2*PI*988*t)*exp(-5*(t-0.16))",
968
+ "0.24*gt(t,0.32)*sin(2*PI*1175*t)*exp(-3*(t-0.32))"
969
+ ].join("+");
970
+ async function staged(chrome, episode, timed, opening, voice, work, options) {
971
+ const made = [];
972
+ const browser = await StageBrowser.open(chrome);
973
+ try {
974
+ const total = timed.length ? timed[timed.length - 1].end : opening;
975
+ for (const aspect of options.aspects) {
976
+ const [width, height] = EpisodeAss.size(aspect);
977
+ const name = aspect.replace(":", "x");
978
+ await browser.load(EpisodeStage.page(aspect), width, height);
979
+ const timeline = EpisodeStage.timeline(timed, opening);
980
+ const drawn = new Map;
981
+ const picture = async (shot) => {
982
+ const key = `${shot.scene}-${shot.step}-${shot.pose}`;
983
+ let file = drawn.get(key);
984
+ if (!file) {
985
+ file = join3(work, `${name}-${key}.png`);
986
+ await browser.shoot(EpisodeStage.frame(episode, shot, aspect), file);
987
+ drawn.set(key, file);
988
+ }
989
+ return file;
990
+ };
991
+ const list = [];
992
+ for (const one of timeline) {
993
+ list.push(`file '${(await picture(one.shot)).replace(/'/g, "'\\''")}'`, `duration ${one.seconds.toFixed(3)}`);
994
+ }
995
+ list.push(list[list.length - 2]);
996
+ const listFile = join3(work, `${name}.txt`);
997
+ await writeFile3(listFile, list.join(`
998
+ `));
999
+ const ass = join3(work, `${name}.ass`);
1000
+ await writeFile3(ass, EpisodeAss.subtitles(timed, aspect));
1001
+ const mp4 = join3(options.out, `${name}.mp4`);
1002
+ await exec("ffmpeg", [
1003
+ "-y",
1004
+ "-loglevel",
1005
+ "error",
1006
+ "-f",
1007
+ "concat",
1008
+ "-safe",
1009
+ "0",
1010
+ "-i",
1011
+ listFile,
1012
+ "-i",
1013
+ voice,
1014
+ "-vf",
1015
+ `fps=30,format=yuv420p,ass=${filterPath(ass)}`,
1016
+ "-t",
1017
+ total.toFixed(3),
1018
+ "-c:v",
1019
+ "libx264",
1020
+ "-preset",
1021
+ "medium",
1022
+ "-crf",
1023
+ "20",
1024
+ "-c:a",
1025
+ "copy",
1026
+ "-movflags",
1027
+ "+faststart",
1028
+ "-metadata",
1029
+ `title=${episode.title}`,
1030
+ "-metadata",
1031
+ "comment=AIGC: made with AI (picture, voice and captions)",
1032
+ mp4
1033
+ ]);
1034
+ const cover = join3(options.out, `cover-${name}.png`);
1035
+ await browser.shoot(EpisodeStage.cover(episode, aspect), cover);
1036
+ made.push(mp4, cover);
1037
+ }
1038
+ return made;
1039
+ } finally {
1040
+ await browser.close();
267
1041
  }
268
1042
  }
269
1043
  async function post(episode, options) {
270
- const work = await mkdtemp(join(tmpdir(), "ta-creator-"));
1044
+ const work = await mkdtemp2(join3(tmpdir2(), "ta-creator-"));
1045
+ const chrome = StageBrowser.find();
1046
+ if (chrome) {
1047
+ const browser = await StageBrowser.open(chrome);
1048
+ try {
1049
+ const made = [];
1050
+ for (const aspect of options.aspects) {
1051
+ const [width, height] = EpisodeAss.size(aspect);
1052
+ const name = aspect.replace(":", "x");
1053
+ await browser.load(EpisodeStage.page(aspect), width, height);
1054
+ const cover = join3(options.out, `post-${name}-00.png`);
1055
+ await browser.shoot(EpisodeStage.cover(episode, aspect), cover);
1056
+ made.push(cover);
1057
+ for (const [i, scene] of episode.scenes.entries()) {
1058
+ const png = join3(options.out, `post-${name}-${String(i + 1).padStart(2, "0")}.png`);
1059
+ await browser.shoot(EpisodeStage.frame(episode, { scene: i, step: EpisodeStage.last(scene), pose: 0 }, aspect, { post: true }), png);
1060
+ made.push(png);
1061
+ }
1062
+ }
1063
+ return made;
1064
+ } finally {
1065
+ await browser.close();
1066
+ await rm2(work, { recursive: true, force: true });
1067
+ }
1068
+ }
271
1069
  try {
272
1070
  const made = [];
273
1071
  for (const aspect of options.aspects) {
274
1072
  const [width, height] = EpisodeAss.size(aspect);
275
1073
  const name = aspect.replace(":", "x");
276
1074
  for (const [i, scene] of episode.scenes.entries()) {
277
- const ass = join(work, `${name}-${i}.ass`);
278
- await writeFile(ass, EpisodeAss.build(episode, [{ scene, start: 0, end: 10 }], aspect, { post: true }));
279
- const png = join(options.out, `post-${name}-${String(i + 1).padStart(2, "0")}.png`);
1075
+ const ass = join3(work, `${name}-${i}.ass`);
1076
+ await writeFile3(ass, EpisodeAss.build(episode, [{ scene, start: 0, end: 10 }], aspect, { post: true }));
1077
+ const png = join3(options.out, `post-${name}-${String(i + 1).padStart(2, "0")}.png`);
280
1078
  await exec("ffmpeg", [
281
1079
  "-y",
282
1080
  "-loglevel",
@@ -298,7 +1096,7 @@ var EpisodeRender;
298
1096
  }
299
1097
  return made;
300
1098
  } finally {
301
- await rm(work, { recursive: true, force: true });
1099
+ await rm2(work, { recursive: true, force: true });
302
1100
  }
303
1101
  }
304
1102
  function pickVoice(list, wanted) {
@@ -320,7 +1118,7 @@ var EpisodeRender;
320
1118
  }
321
1119
  EpisodeRender.neuralRate = neuralRate;
322
1120
  async function edgePython() {
323
- const candidates = [process.env.TA_CREATOR_PYTHON, join(homedir(), "lemo-opuscar/.venv/bin/python"), "python3"].filter((one) => !!one);
1121
+ const candidates = [process.env.TA_CREATOR_PYTHON, join3(homedir2(), "lemo-opuscar/.venv/bin/python"), "python3"].filter((one) => !!one);
324
1122
  for (const one of candidates) {
325
1123
  if (await exec(one, ["-c", "import edge_tts"]).then(() => true, () => false)) {
326
1124
  return one;
@@ -329,7 +1127,7 @@ var EpisodeRender;
329
1127
  return;
330
1128
  }
331
1129
  function srt(timed) {
332
- const stamp = (s) => EpisodeAss.time(s).replace(/^(\d+):/, (_all, h) => `${h.padStart(2, "0")}:`).replace(".", ",") + "0";
1130
+ const stamp = (s) => `${EpisodeAss.time(s).replace(/^(\d+):/, (_all, h) => `${h.padStart(2, "0")}:`).replace(".", ",")}0`;
333
1131
  return timed.flatMap((one) => EpisodeAss.captions(one.scene.say, one.start, one.end, 22)).map((one, i) => `${i + 1}
334
1132
  ${stamp(one.start)} --> ${stamp(one.end)}
335
1133
  ${one.text}
@@ -369,8 +1167,11 @@ if (process.argv[1]?.endsWith("render.mjs")) {
369
1167
  console.error("node render.mjs <episode.json> [--aspects 16:9,9:16,3:4,1:1] [--post] [--out <dir>]");
370
1168
  process.exit(2);
371
1169
  }
372
- EpisodeRender.run(resolve(file), { aspects, post, out: resolve(out ?? join(file, "..")) }).then((made) => console.log(made.join(`
373
- `)), (error) => {
1170
+ EpisodeRender.run(resolve(file), { aspects, post, out: resolve(out ?? join3(file, "..")) }).then((made) => {
1171
+ console.log(made.join(`
1172
+ `));
1173
+ process.exit(0);
1174
+ }, (error) => {
374
1175
  console.error(error instanceof Error ? error.message : String(error));
375
1176
  process.exit(1);
376
1177
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-creator",
3
- "version": "4.31.0",
3
+ "version": "4.32.0",
4
4
  "description": "A pi package for Ta: a channel of content without showing your face, hot topics of your field found three times a day, videos and posts made for each platform, reviewed on your phone and filled in for you up to Publish",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -29,8 +29,8 @@
29
29
  "watch": "tsc -b -w --preserveWatchOutput"
30
30
  },
31
31
  "devDependencies": {
32
- "@celljs/ta-protocol": "4.31.0",
33
- "@celljs/ta-web": "4.31.0",
32
+ "@celljs/ta-protocol": "4.32.0",
33
+ "@celljs/ta-web": "4.32.0",
34
34
  "@types/react": "^19.3.0"
35
35
  },
36
36
  "publishConfig": {
@@ -36,17 +36,28 @@ people in the news, films and shows of others, or anything of the user's employe
36
36
  `~/workspace/ai-coding-channel/episodes/<number>-<short-name>/` unless the user keeps them elsewhere:
37
37
 
38
38
  ```json
39
- { "title": "...",
39
+ { "title": "Before the colon: after it", "series": "the series' name", "number": 3,
40
+ "cover": { "lines": ["two short", "lines"], "sub": "a line under it", "tags": ["tmux", "ssh"] },
40
41
  "scenes": [
41
- { "title": "A title", "sub": "a line under it", "say": "what the voice says" },
42
- { "code": { "file": "date.ts", "lines": ["const a = 1;"] }, "say": "..." },
43
- { "title": "Sum up", "points": ["one", "two", "three"], "say": "..." } ] }
42
+ { "title": "第一步", "sub": "a line under it", "say": "what the voice says" },
43
+ { "code": { "file": "mac.sh", "lines": ["$ tmux new -s agent"] }, "note": "the key to remember", "say": "..." },
44
+ { "phone": { "lines": ["$ ssh me@my-mac"], "notify": { "title": "Agent", "text": "完成了 ✓" } }, "note": "...", "say": "..." },
45
+ { "title": "Sum up", "points": ["one", "two", "three"], "sub": "下期见~", "say": "..." } ] }
44
46
  ```
45
47
 
46
- Each scene lasts as long as its `say`; code is typed in a line at a time; at most 14 lines (22 when tall), 60
47
- columns. The voice is the neural voice Xiaoxiao (`zh-CN-XiaoxiaoNeural`, read online by edge-tts, from a Python that has
48
+ The channel is known by its look, the same every time: a pixel dinosaur hosts it, the series opens each piece with
49
+ its chime, and each cover is the series' green with the title large. Keep `series` and its numbering as in the last
50
+ `episode.json` of the channel (the user named it; never invent another), `number` one more. A title scene is the
51
+ host speaking it in bubbles (a title as `第一步`, `窍门二` is a badge); `code` is a terminal typed a line at a time
52
+ (at most 14 lines, 22 when tall, 60 columns; a line starting `$ ` is a command); `phone` is a phone showing a
53
+ terminal, its `notify` coming in at the end; `points` are written in a notebook by hand. `note` puts a short line
54
+ beside the terminal or the phone. Mix them: never two scenes alike in a row, a device every other scene or so.
55
+ `look` (`paper`, `ink`, `sketch`) changes the background of one scene or, on the piece, of all. Each scene lasts as
56
+ long as its `say`. The voice is the neural voice Xiaoxiao (`zh-CN-XiaoxiaoNeural`, read online by edge-tts, from a Python that has
48
57
  it: `TA_CREATOR_PYTHON`, `~/lemo-opuscar/.venv/bin/python` or `python3`), unless `settings` or `voice` names
49
- another neural voice or a voice of this computer's speech (`say -v '?'`), which it falls back to without edge-tts.
58
+ another: `hunyuan` (or `hunyuan:<voice>`) is the voice of Tencent Hunyuan, more like a person, read by the Hy Realtime
59
+ service of Ta's voice settings (falling back to Xiaoxiao without one); another neural voice; or a voice of this
60
+ computer's speech (`say -v '?'`), which it falls back to without edge-tts.
50
61
  Write `say` as one speaks: short sentences with commas. Never the user's own voice unless they asked and agreed.
51
62
  Then make it, the shapes of the platforms picked:
52
63
 
@@ -56,7 +67,9 @@ people in the news, films and shows of others, or anything of the user's employe
56
67
  ```
57
68
 
58
69
  (the script is in this package, relative to this file). It needs ffmpeg (`brew install ffmpeg`): when it is missing,
59
- ask the user to install it. It writes `<shape>.mp4` (`16x9.mp4`, `9x16.mp4`, `3x4.mp4`), `cover-<shape>.png`,
70
+ ask the user to install it. It draws the pictures with the browser of this computer (Chrome, Edge, Brave or
71
+ Chromium, without a window; `TA_CREATOR_CHROME` names another); without one it draws them plainly, without the host,
72
+ and you tell the user so. It writes `<shape>.mp4` (`16x9.mp4`, `9x16.mp4`, `3x4.mp4`), `cover-<shape>.png`,
60
73
  `captions.srt` and `voice.m4a`; with `--post`, `post-<shape>-01.png`… Every picture carries the label "AI 合成";
61
74
  the captions are burned in. Look at a few frames (`ffmpeg -ss <s> -i 16x9.mp4 -frames:v 1 f.png`) before going on.
62
75
  A screen recording may stand for a scene when the user made one; never record their screen yourself.