@celljs/ta-creator 0.0.0-stage → 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/bin/render.mjs ADDED
@@ -0,0 +1,1181 @@
1
+ // web-src/render.ts
2
+ import { execFile } from "node:child_process";
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
+ }
136
+
137
+ // web-src/episode.ts
138
+ var SIZES = { "16:9": [1920, 1080], "9:16": [1080, 1920], "3:4": [1080, 1440], "1:1": [1080, 1080] };
139
+ var KEYWORDS = new Set("as async await break case catch class const continue def default do elif else except export extends false finally for from function if import in interface let lambda new None null of pass return self static super switch this throw True False true try type typeof undefined var void while with yield".split(" "));
140
+ var COLOURS = { text: "&HDCD3CF&", keyword: "&HEA92C7&", string: "&H6ACE9E&", comment: "&H70635C&", number: "&H64AAFF&", name: "&HF7A27A&" };
141
+ var TOKENS = /(\/\/.*$|#.*$|"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`(?:[^`\\]|\\.)*`?|\b\d+(?:\.\d+)?\b|[A-Za-z_$][\w$]*)/g;
142
+ var EpisodeAss;
143
+ ((EpisodeAss) => {
144
+ function size(aspect) {
145
+ return SIZES[aspect];
146
+ }
147
+ EpisodeAss.size = size;
148
+ function plain(text) {
149
+ return text.replace(/\\/g, "\\​").replace(/\{/g, "\\{").replace(/\}/g, "\\}").replace(/\r?\n/g, " ");
150
+ }
151
+ EpisodeAss.plain = plain;
152
+ function tokens(line) {
153
+ const out = [];
154
+ let at = 0;
155
+ for (const match of line.matchAll(TOKENS)) {
156
+ const token = match[0];
157
+ const index = match.index ?? 0;
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 });
163
+ at = index + token.length;
164
+ }
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");
174
+ }
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;
203
+ function captions(text, start, end, max) {
204
+ const parts = [];
205
+ for (const sentence of text.split(/(?<=[。!?!?;;,,、::])/)) {
206
+ let rest = sentence.replace(/[。,、;;,]$/, "").trim();
207
+ while (rest.length > max) {
208
+ parts.push(rest.slice(0, max));
209
+ rest = rest.slice(max);
210
+ }
211
+ if (rest) {
212
+ parts.push(rest);
213
+ }
214
+ }
215
+ const total = parts.reduce((all, one) => all + one.length, 0) || 1;
216
+ let at = start;
217
+ return parts.map((one) => {
218
+ const from = at;
219
+ at += (end - start) * one.length / total;
220
+ return { text: one, start: from, end: at };
221
+ });
222
+ }
223
+ EpisodeAss.captions = captions;
224
+ function time(seconds) {
225
+ const cs = Math.max(0, Math.round(seconds * 100));
226
+ const two = (n) => String(n).padStart(2, "0");
227
+ return `${Math.floor(cs / 360000)}:${two(Math.floor(cs / 6000) % 60)}:${two(Math.floor(cs / 100) % 60)}.${two(cs % 100)}`;
228
+ }
229
+ EpisodeAss.time = time;
230
+ function columns(line) {
231
+ return [...line].reduce((all, ch) => all + ((ch.codePointAt(0) ?? 0) > 11904 ? 2 : 1), 0);
232
+ }
233
+ EpisodeAss.columns = columns;
234
+ function build(episode, timed, aspect, options = {}) {
235
+ const [width, height] = SIZES[aspect];
236
+ const unit = Math.min(width, height) / 1080;
237
+ const tall = height > width;
238
+ const events = [];
239
+ const add = (layer, start, end, style, text) => events.push(`Dialogue: ${layer},${time(start)},${time(end)},${style},,0,0,0,,${text}`);
240
+ const box = (x, y, w, h, colour, r) => `{\\an7\\pos(${Math.round(x)},${Math.round(y)})\\bord0\\shad0\\c${colour}\\p1}${rounded(w, h, r)}{\\p0}`;
241
+ const margin = Math.round(64 * unit);
242
+ const captionSize = Math.round((tall ? 54 : 46) * unit);
243
+ const captionBottom = Math.round((tall ? 300 : 70) * unit);
244
+ for (const { scene, start, end } of timed) {
245
+ if (scene.code?.lines.length) {
246
+ const lines = scene.code.lines.slice(0, tall ? 22 : 14);
247
+ const panelW = width - margin * 2;
248
+ const longest = Math.max(24, ...lines.map(columns));
249
+ const size2 = Math.min(Math.round((tall ? 40 : 44) * unit), Math.floor((panelW - 64 * unit) / (longest * 0.61)));
250
+ const lineH = Math.round(size2 * 1.55);
251
+ const bar = Math.round(52 * unit);
252
+ const panelH = bar + lineH * lines.length + Math.round(40 * unit);
253
+ const top = Math.round(tall ? Math.max(height * 0.14, height * 0.42 - panelH / 2) : Math.max(margin, (height - captionBottom - captionSize - panelH) / 2));
254
+ add(0, start, end, "Code", box(margin, top, panelW, panelH, "&H241E1C&", 18 * unit));
255
+ for (const [i, colour] of ["&H5F57FF&", "&H2EBDFE&", "&H41C928&"].entries()) {
256
+ add(1, start, end, "Code", box(margin + (24 + i * 26) * unit, top + 20 * unit, 13 * unit, 13 * unit, colour, 6.5 * unit));
257
+ }
258
+ if (scene.code.file) {
259
+ add(1, start, end, "Code", `{\\an8\\pos(${Math.round(width / 2)},${Math.round(top + 13 * unit)})\\fs${Math.round(24 * unit)}\\c&H8E8A87&}${plain(scene.code.file)}`);
260
+ }
261
+ const typing = (end - start) * 0.6;
262
+ lines.forEach((line, i) => {
263
+ const from = start + typing * i / lines.length;
264
+ add(2, from, end, "Code", `{\\an7\\pos(${Math.round(margin + 32 * unit)},${top + bar + Math.round(12 * unit) + lineH * i})\\fs${size2}\\fad(120,0)}${highlight(line)}`);
265
+ });
266
+ } else if (scene.title) {
267
+ const size2 = Math.round((tall ? 84 : 92) * unit);
268
+ const y = Math.round(height * (tall ? 0.36 : 0.4));
269
+ add(2, start, end, "Title", `{\\an5\\pos(${width / 2},${y})\\fs${size2}\\fad(250,0)}${plain(scene.title)}`);
270
+ if (scene.sub) {
271
+ add(2, start + 0.3, end, "Title", `{\\an5\\pos(${width / 2},${y + Math.round(size2 * 1.2)})\\fs${Math.round(size2 * 0.45)}\\b0\\c&HA3A3A3&\\fad(250,0)}${plain(scene.sub)}`);
272
+ }
273
+ }
274
+ if (scene.points?.length && !scene.code?.lines.length) {
275
+ const size2 = Math.round((tall ? 50 : 52) * unit);
276
+ const gap = Math.round(size2 * 1.9);
277
+ const first = Math.round(scene.title ? height * (tall ? 0.36 : 0.4) + size2 * 3 : height * (tall ? 0.28 : 0.22));
278
+ const step = (end - start) * 0.7 / scene.points.length;
279
+ scene.points.forEach((point, i) => {
280
+ add(2, start + step * i, end, "Point", `{\\an7\\pos(${margin * 2},${first + gap * i})\\fs${size2}\\fad(200,0)}{\\c&H6ACE9E&}${i + 1}{\\c&HFFFFFF&} ${plain(point)}`);
281
+ });
282
+ }
283
+ if (options.post) {
284
+ add(5, start, end, "Body", `{\\an2\\q0\\fs${Math.round(40 * unit)}}${plain(scene.say)}`);
285
+ continue;
286
+ }
287
+ for (const caption of captions(scene.say, start, end, tall ? 14 : 22)) {
288
+ add(5, caption.start, caption.end, "Caption", `{\\an2\\pos(${width / 2},${height - captionBottom})\\fs${captionSize}}${plain(caption.text)}`);
289
+ }
290
+ }
291
+ const total = timed.length ? timed[timed.length - 1].end : 0;
292
+ add(9, 0, total, "Label", `{\\an9\\pos(${width - margin / 2},${Math.round(margin / 2 + (tall ? 90 * unit : 0))})\\fs${Math.round(26 * unit)}}${plain(episode.label ?? "AI 合成")}`);
293
+ return [
294
+ "[Script Info]",
295
+ "ScriptType: v4.00+",
296
+ `PlayResX: ${width}`,
297
+ `PlayResY: ${height}`,
298
+ "WrapStyle: 2",
299
+ "ScaledBorderAndShadow: yes",
300
+ "",
301
+ "[V4+ Styles]",
302
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
303
+ "Style: Code,Menlo,40,&H00DCD3CF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,7,0,0,0,1",
304
+ "Style: Title,PingFang SC,90,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,5,0,0,0,1",
305
+ "Style: Point,PingFang SC,50,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,7,0,0,0,1",
306
+ `Style: Caption,PingFang SC,46,&H00FFFFFF,&H000000FF,&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,${Math.max(2, Math.round(3 * unit))},0,2,0,0,0,1`,
307
+ `Style: Body,PingFang SC,40,&H00E6E6E6,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,2,${margin},${margin},${Math.round(90 * unit)},1`,
308
+ "Style: Label,PingFang SC,26,&H40FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,9,0,0,0,1",
309
+ "",
310
+ "[Events]",
311
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
312
+ ...events,
313
+ ""
314
+ ].join(`
315
+ `);
316
+ }
317
+ EpisodeAss.build = build;
318
+ function rounded(w, h, r) {
319
+ const [W, H, R] = [w, h, Math.min(r, w / 2, h / 2)].map((n) => Math.round(n));
320
+ const k = Math.round(R * 0.45);
321
+ return `m ${R} 0 l ${W - R} 0 b ${W - k} 0 ${W} ${k} ${W} ${R} l ${W} ${H - R} b ${W} ${H - k} ${W - k} ${H} ${W - R} ${H} l ${R} ${H} b ${k} ${H} 0 ${H - k} 0 ${H - R} l 0 ${R} b 0 ${k} ${k} 0 ${R} 0`;
322
+ }
323
+ })(EpisodeAss ||= {});
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
+
826
+ // web-src/render.ts
827
+ var EpisodeRender;
828
+ ((EpisodeRender) => {
829
+ const GAP = 0.6;
830
+ const RATE = 185;
831
+ const BACKGROUND = "0x16171c";
832
+ EpisodeRender.VOICE = "zh-CN-XiaoxiaoNeural";
833
+ const NEURAL = /^[a-z]{2,3}-[A-Z]{2}-\w+Neural$/;
834
+ async function run(file, options) {
835
+ const episode = JSON.parse(await readFile2(file, "utf8"));
836
+ if (!episode?.title || !Array.isArray(episode.scenes) || !episode.scenes.length) {
837
+ throw new Error("An episode is { title, scenes: [{ say, code?, title?, sub?, points? }] }.");
838
+ }
839
+ await mkdir(options.out, { recursive: true });
840
+ return options.post ? post(episode, options) : video(episode, options);
841
+ }
842
+ EpisodeRender.run = run;
843
+ async function video(episode, options) {
844
+ const work = await mkdtemp2(join3(tmpdir2(), "ta-creator-"));
845
+ try {
846
+ const wanted = episode.voice ?? EpisodeRender.VOICE;
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.`);
850
+ }
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);
857
+ const timed = [];
858
+ const parts = [];
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;
870
+ for (const [i, scene] of episode.scenes.entries()) {
871
+ const spoken = join3(work, hunyuan ? `${i}.hy.wav` : python ? `${i}.mp3` : `${i}.aiff`);
872
+ const said = scene.say.replace(/`/g, "");
873
+ if (hunyuan) {
874
+ await readHunyuan(hunyuan, HunyuanVoice.voiceOf(wanted), said, spoken);
875
+ } else if (python) {
876
+ await exec(python, ["-m", "edge_tts", "--voice", speaker, "--rate", neuralRate(episode.rate), "--text", said, "--write-media", spoken]);
877
+ } else {
878
+ await exec("say", ["-v", speaker, "-r", String(episode.rate ?? RATE), "-o", spoken, paced(said)]);
879
+ }
880
+ const seconds = await length(spoken) + GAP;
881
+ const padded = join3(work, `${i}.wav`);
882
+ await exec("ffmpeg", [
883
+ "-y",
884
+ "-loglevel",
885
+ "error",
886
+ "-i",
887
+ spoken,
888
+ "-af",
889
+ `apad=whole_dur=${seconds.toFixed(3)}`,
890
+ "-ar",
891
+ "44100",
892
+ "-ac",
893
+ "1",
894
+ padded
895
+ ]);
896
+ timed.push({ scene, start: at, end: at + seconds });
897
+ parts.push(padded);
898
+ at += seconds;
899
+ }
900
+ const list = join3(work, "list.txt");
901
+ await writeFile3(list, parts.map((one) => `file '${one.replace(/'/g, "'\\''")}'`).join(`
902
+ `));
903
+ const voice = join3(options.out, "voice.m4a");
904
+ await exec("ffmpeg", ["-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", list, "-c:a", "aac", "-b:a", "128k", voice]);
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
+ }
911
+ for (const aspect of options.aspects) {
912
+ const [width, height] = EpisodeAss.size(aspect);
913
+ const name = aspect.replace(":", "x");
914
+ const ass = join3(work, `${name}.ass`);
915
+ await writeFile3(ass, EpisodeAss.build(episode, timed, aspect));
916
+ const mp4 = join3(options.out, `${name}.mp4`);
917
+ await exec("ffmpeg", [
918
+ "-y",
919
+ "-loglevel",
920
+ "error",
921
+ "-f",
922
+ "lavfi",
923
+ "-i",
924
+ `color=c=${BACKGROUND}:s=${width}x${height}:r=30:d=${at.toFixed(3)}`,
925
+ "-i",
926
+ voice,
927
+ "-vf",
928
+ `ass=${filterPath(ass)}`,
929
+ "-c:v",
930
+ "libx264",
931
+ "-preset",
932
+ "medium",
933
+ "-crf",
934
+ "20",
935
+ "-pix_fmt",
936
+ "yuv420p",
937
+ "-c:a",
938
+ "copy",
939
+ "-shortest",
940
+ "-movflags",
941
+ "+faststart",
942
+ "-metadata",
943
+ `title=${episode.title}`,
944
+ "-metadata",
945
+ "comment=AIGC: made with AI (picture, voice and captions)",
946
+ mp4
947
+ ]);
948
+ const first = timed.find((one) => one.scene.title) ?? timed[0];
949
+ const cover = join3(options.out, `cover-${name}.png`);
950
+ await exec("ffmpeg", ["-y", "-loglevel", "error", "-ss", String(Math.max(0.1, first.end - 0.2)), "-i", mp4, "-frames:v", "1", cover]);
951
+ made.push(mp4, cover);
952
+ }
953
+ return made;
954
+ } finally {
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();
1041
+ }
1042
+ }
1043
+ async function post(episode, options) {
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
+ }
1069
+ try {
1070
+ const made = [];
1071
+ for (const aspect of options.aspects) {
1072
+ const [width, height] = EpisodeAss.size(aspect);
1073
+ const name = aspect.replace(":", "x");
1074
+ for (const [i, scene] of episode.scenes.entries()) {
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`);
1078
+ await exec("ffmpeg", [
1079
+ "-y",
1080
+ "-loglevel",
1081
+ "error",
1082
+ "-f",
1083
+ "lavfi",
1084
+ "-i",
1085
+ `color=c=${BACKGROUND}:s=${width}x${height}:d=10`,
1086
+ "-ss",
1087
+ "9.9",
1088
+ "-vf",
1089
+ `ass=${filterPath(ass)}`,
1090
+ "-frames:v",
1091
+ "1",
1092
+ png
1093
+ ]);
1094
+ made.push(png);
1095
+ }
1096
+ }
1097
+ return made;
1098
+ } finally {
1099
+ await rm2(work, { recursive: true, force: true });
1100
+ }
1101
+ }
1102
+ function pickVoice(list, wanted) {
1103
+ const voices = list.split(`
1104
+ `).map((line) => /^(.+?)\s{2,}(zh_CN)\s/.exec(line)?.[1].trim()).filter((one) => !!one);
1105
+ const rank = (name) => /高品质|Premium/i.test(name) ? 3 : /增强|Enhanced/i.test(name) ? 2 : /^(Tingting|Lili|Yue)\b/.test(name) ? 1 : 0;
1106
+ const best = (names) => [...names].sort((a, b) => rank(b) - rank(a))[0];
1107
+ const base = wanted?.replace(/\s*[((].*$/, "");
1108
+ return base && best(voices.filter((one) => one.startsWith(base))) || best(voices) || wanted || "Tingting";
1109
+ }
1110
+ EpisodeRender.pickVoice = pickVoice;
1111
+ function paced(text) {
1112
+ return text.replace(/`/g, "").replace(/([,、;:,;:])\s*/g, "$1[[slnc 150]]").replace(/([。!?!?…])\s*/g, "$1[[slnc 300]]");
1113
+ }
1114
+ EpisodeRender.paced = paced;
1115
+ function neuralRate(rate) {
1116
+ const percent = rate ? Math.round((rate / RATE - 1) * 100) : 0;
1117
+ return `${percent >= 0 ? "+" : ""}${Math.max(-50, Math.min(100, percent))}%`;
1118
+ }
1119
+ EpisodeRender.neuralRate = neuralRate;
1120
+ async function edgePython() {
1121
+ const candidates = [process.env.TA_CREATOR_PYTHON, join3(homedir2(), "lemo-opuscar/.venv/bin/python"), "python3"].filter((one) => !!one);
1122
+ for (const one of candidates) {
1123
+ if (await exec(one, ["-c", "import edge_tts"]).then(() => true, () => false)) {
1124
+ return one;
1125
+ }
1126
+ }
1127
+ return;
1128
+ }
1129
+ function srt(timed) {
1130
+ const stamp = (s) => `${EpisodeAss.time(s).replace(/^(\d+):/, (_all, h) => `${h.padStart(2, "0")}:`).replace(".", ",")}0`;
1131
+ return timed.flatMap((one) => EpisodeAss.captions(one.scene.say, one.start, one.end, 22)).map((one, i) => `${i + 1}
1132
+ ${stamp(one.start)} --> ${stamp(one.end)}
1133
+ ${one.text}
1134
+ `).join(`
1135
+ `);
1136
+ }
1137
+ EpisodeRender.srt = srt;
1138
+ function filterPath(path) {
1139
+ return path.replace(/\\/g, "/").replace(/[:',[\]]/g, (char) => `\\${char}`);
1140
+ }
1141
+ async function length(file) {
1142
+ const out = await exec("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file]);
1143
+ return Number.parseFloat(out) || 1;
1144
+ }
1145
+ function exec(command, args) {
1146
+ return new Promise((done, fail) => execFile(command, args, { maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {
1147
+ if (error) {
1148
+ const missing = error.code === "ENOENT";
1149
+ fail(new Error(missing ? `${command} is not on this computer${command.startsWith("ff") ? " (brew install ffmpeg)" : ""}.` : `${command} failed: ${stderr || error.message}`));
1150
+ } else {
1151
+ done(String(stdout));
1152
+ }
1153
+ }));
1154
+ }
1155
+ })(EpisodeRender ||= {});
1156
+ if (process.argv[1]?.endsWith("render.mjs")) {
1157
+ const args = process.argv.slice(2);
1158
+ const flag = (name) => {
1159
+ const at = args.indexOf(name);
1160
+ return at >= 0 ? args.splice(at, 2)[1] : undefined;
1161
+ };
1162
+ const post = args.includes("--post");
1163
+ const aspects = (flag("--aspects") ?? (post ? "3:4" : "16:9,9:16,3:4")).split(",");
1164
+ const out = flag("--out");
1165
+ const file = args.find((one) => !one.startsWith("--"));
1166
+ if (!file || aspects.some((one) => !EpisodeAss.size(one))) {
1167
+ console.error("node render.mjs <episode.json> [--aspects 16:9,9:16,3:4,1:1] [--post] [--out <dir>]");
1168
+ process.exit(2);
1169
+ }
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) => {
1175
+ console.error(error instanceof Error ? error.message : String(error));
1176
+ process.exit(1);
1177
+ });
1178
+ }
1179
+ export {
1180
+ EpisodeRender
1181
+ };