@celljs/ta-creator 4.31.0 → 4.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/render.mjs CHANGED
@@ -1,8 +1,159 @@
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
+ socket.addEventListener("close", () => {
39
+ for (const one of this.waiting.values()) {
40
+ one.fail(new Error("The browser closed."));
41
+ }
42
+ this.waiting.clear();
43
+ });
44
+ }
45
+ static find() {
46
+ const candidates = [
47
+ process.env.TA_CREATOR_CHROME,
48
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
49
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
50
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
51
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
52
+ "/usr/bin/google-chrome",
53
+ "/usr/bin/chromium",
54
+ "/usr/bin/chromium-browser",
55
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
56
+ "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
57
+ ];
58
+ return candidates.find((one) => !!one && existsSync(one));
59
+ }
60
+ static async open(path) {
61
+ if (typeof WebSocket !== "function") {
62
+ throw new Error("Drawing the pictures needs Node 22 or later (its WebSocket).");
63
+ }
64
+ const profile = await mkdtemp(join(tmpdir(), "ta-creator-chrome-"));
65
+ const child = spawn(path, [
66
+ "--headless=new",
67
+ "--remote-debugging-port=0",
68
+ `--user-data-dir=${profile}`,
69
+ "--hide-scrollbars",
70
+ "--force-device-scale-factor=1",
71
+ "--no-first-run",
72
+ "--no-default-browser-check",
73
+ "--mute-audio",
74
+ "about:blank"
75
+ ], { stdio: ["ignore", "ignore", "pipe"] });
76
+ try {
77
+ return await StageBrowser.attach(child, profile);
78
+ } catch (error) {
79
+ child.kill();
80
+ await rm(profile, { recursive: true, force: true }).catch(() => {
81
+ return;
82
+ });
83
+ throw error;
84
+ }
85
+ }
86
+ static async attach(child, profile) {
87
+ const endpoint = await new Promise((done, fail) => {
88
+ let said = "";
89
+ const timer = setTimeout(() => fail(new Error(`The browser did not start: ${said.slice(-300)}`)), 20000);
90
+ child.stderr?.on("data", (chunk) => {
91
+ said += String(chunk);
92
+ const found = /DevTools listening on (ws:\/\/\S+)/.exec(said);
93
+ if (found) {
94
+ clearTimeout(timer);
95
+ done(found[1]);
96
+ }
97
+ });
98
+ child.on("error", (error) => {
99
+ clearTimeout(timer);
100
+ fail(error);
101
+ });
102
+ child.on("exit", () => {
103
+ clearTimeout(timer);
104
+ fail(new Error(`The browser ended before it started: ${said.slice(-300)}`));
105
+ });
106
+ });
107
+ const socket = new WebSocket(endpoint);
108
+ await new Promise((done, fail) => {
109
+ socket.addEventListener("open", () => done(), { once: true });
110
+ socket.addEventListener("error", () => fail(new Error("Could not reach the browser.")), { once: true });
111
+ });
112
+ const browser = new StageBrowser(child, socket, profile);
113
+ const { targetId } = await browser.send("Target.createTarget", { url: "about:blank" });
114
+ const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true });
115
+ browser.session = sessionId;
116
+ return browser;
117
+ }
118
+ send(method, params = {}) {
119
+ const id = this.next++;
120
+ return new Promise((done, fail) => {
121
+ this.waiting.set(id, { done, fail });
122
+ this.socket.send(JSON.stringify(this.session ? { id, method, params, sessionId: this.session } : { id, method, params }));
123
+ });
124
+ }
125
+ async load(html, width, height) {
126
+ await this.send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false });
127
+ const file = join(this.profile, `page-${width}x${height}.html`);
128
+ await writeFile(file, html);
129
+ await this.send("Page.navigate", { url: pathToFileURL(file).href });
130
+ for (let i = 0;i < 100; i++) {
131
+ const { result } = await this.send("Runtime.evaluate", { expression: "document.readyState", returnByValue: true });
132
+ if (result.value === "complete") {
133
+ return;
134
+ }
135
+ await new Promise((done) => setTimeout(done, 50));
136
+ }
137
+ }
138
+ async shoot(body, path) {
139
+ await this.send("Runtime.evaluate", {
140
+ expression: `document.body.innerHTML = ${JSON.stringify(body)}; document.fonts.ready.then(() => new Promise(r => requestAnimationFrame(() => r(1))))`,
141
+ awaitPromise: true
142
+ });
143
+ const { data } = await this.send("Page.captureScreenshot", { format: "png" });
144
+ await writeFile(path, Buffer.from(data, "base64"));
145
+ }
146
+ async close() {
147
+ try {
148
+ this.socket.close();
149
+ } finally {
150
+ this.child.kill();
151
+ await rm(this.profile, { recursive: true, force: true }).catch(() => {
152
+ return;
153
+ });
154
+ }
155
+ }
156
+ }
6
157
 
7
158
  // web-src/episode.ts
8
159
  var SIZES = { "16:9": [1920, 1080], "9:16": [1080, 1920], "3:4": [1080, 1440], "1:1": [1080, 1080] };
@@ -19,20 +170,57 @@ var EpisodeAss;
19
170
  return text.replace(/\\/g, "\\​").replace(/\{/g, "\\{").replace(/\}/g, "\\}").replace(/\r?\n/g, " ");
20
171
  }
21
172
  EpisodeAss.plain = plain;
22
- function highlight(line) {
23
- let out = "";
173
+ function tokens(line) {
174
+ const out = [];
24
175
  let at = 0;
25
176
  for (const match of line.matchAll(TOKENS)) {
26
177
  const token = match[0];
27
178
  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);
179
+ if (index > at) {
180
+ out.push({ text: line.slice(at, index) });
181
+ }
182
+ 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;
183
+ out.push(kind ? { text: token, kind } : { text: token });
31
184
  at = index + token.length;
32
185
  }
33
- return (out + plain(line.slice(at))).replace(/ /g, "\\h");
186
+ if (at < line.length) {
187
+ out.push({ text: line.slice(at) });
188
+ }
189
+ return out;
190
+ }
191
+ EpisodeAss.tokens = tokens;
192
+ function highlight(line) {
193
+ const out = tokens(line).map((one) => one.kind ? `{\\c${COLOURS[one.kind]}}${plain(one.text)}{\\c${COLOURS.text}}` : plain(one.text)).join("");
194
+ return out.replace(/ /g, "\\h");
34
195
  }
35
196
  EpisodeAss.highlight = highlight;
197
+ function subtitles(timed, aspect) {
198
+ const [width, height] = SIZES[aspect];
199
+ const unit = Math.min(width, height) / 1080;
200
+ const tall = height > width;
201
+ const size2 = Math.round((tall ? 52 : 46) * unit);
202
+ const bottom = Math.round((tall ? 150 : 64) * unit);
203
+ 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)}`));
204
+ return [
205
+ "[Script Info]",
206
+ "ScriptType: v4.00+",
207
+ `PlayResX: ${width}`,
208
+ `PlayResY: ${height}`,
209
+ "WrapStyle: 2",
210
+ "ScaledBorderAndShadow: yes",
211
+ "",
212
+ "[V4+ Styles]",
213
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
214
+ `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`,
215
+ "",
216
+ "[Events]",
217
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
218
+ ...events,
219
+ ""
220
+ ].join(`
221
+ `);
222
+ }
223
+ EpisodeAss.subtitles = subtitles;
36
224
  function captions(text, start, end, max) {
37
225
  const parts = [];
38
226
  for (const sentence of text.split(/(?<=[。!?!?;;,,、::])/)) {
@@ -155,6 +343,508 @@ var EpisodeAss;
155
343
  }
156
344
  })(EpisodeAss ||= {});
157
345
 
346
+ // web-src/hunyuan.ts
347
+ import { readFile, writeFile as writeFile2 } from "node:fs/promises";
348
+ import { homedir } from "node:os";
349
+ import { join as join2 } from "node:path";
350
+ var HunyuanVoice;
351
+ ((HunyuanVoice) => {
352
+ HunyuanVoice.NAME = /^hunyuan(?::([\w-]+))?$/;
353
+ const RATE = 24000;
354
+ function voiceOf(name) {
355
+ const found = HunyuanVoice.NAME.exec(name);
356
+ return found ? found[1] || "f1" : undefined;
357
+ }
358
+ HunyuanVoice.voiceOf = voiceOf;
359
+ async function service(file = join2(homedir(), ".ta/agent/voices.json")) {
360
+ if (process.env.TA_CREATOR_HUNYUAN_URL) {
361
+ return { url: process.env.TA_CREATOR_HUNYUAN_URL, key: process.env.TA_CREATOR_HUNYUAN_KEY };
362
+ }
363
+ try {
364
+ const kept = JSON.parse(await readFile(file, "utf8"));
365
+ const one = kept.services?.find((each) => each.type === "hy-realtime" && typeof each.options?.url === "string");
366
+ return one ? { url: String(one.options?.url), key: typeof one.options?.apiKey === "string" ? one.options.apiKey : undefined } : undefined;
367
+ } catch {
368
+ return;
369
+ }
370
+ }
371
+ HunyuanVoice.service = service;
372
+ function wav(pcm, rate = RATE) {
373
+ const head = Buffer.alloc(44);
374
+ head.write("RIFF", 0);
375
+ head.writeUInt32LE(36 + pcm.length, 4);
376
+ head.write("WAVEfmt ", 8);
377
+ head.writeUInt32LE(16, 16);
378
+ head.writeUInt16LE(1, 20);
379
+ head.writeUInt16LE(1, 22);
380
+ head.writeUInt32LE(rate, 24);
381
+ head.writeUInt32LE(rate * 2, 28);
382
+ head.writeUInt16LE(2, 32);
383
+ head.writeUInt16LE(16, 34);
384
+ head.write("data", 36);
385
+ head.writeUInt32LE(pcm.length, 40);
386
+ return Buffer.concat([head, pcm]);
387
+ }
388
+ HunyuanVoice.wav = wav;
389
+ function read(service2, voice, text, out, timeout = 60000) {
390
+ return new Promise((done, fail) => {
391
+ const socket = new WebSocket(service2.url, { headers: { Authorization: `Bearer ${service2.key || "ta"}` } });
392
+ const chunks = [];
393
+ let over = false;
394
+ const end = (error) => {
395
+ if (over) {
396
+ return;
397
+ }
398
+ over = true;
399
+ clearTimeout(timer);
400
+ socket.close();
401
+ if (error) {
402
+ fail(error);
403
+ } else if (!chunks.length) {
404
+ fail(new Error("Hunyuan read nothing."));
405
+ } else {
406
+ writeFile2(out, wav(Buffer.concat(chunks))).then(() => done(), fail);
407
+ }
408
+ };
409
+ const timer = setTimeout(() => end(new Error("Hunyuan did not finish reading in time.")), timeout);
410
+ const send = (message) => socket.send(JSON.stringify(message));
411
+ socket.addEventListener("error", () => end(new Error(`Could not reach Hunyuan at ${service2.url}.`)));
412
+ socket.addEventListener("close", () => end(new Error("Hunyuan closed before it finished reading.")));
413
+ socket.addEventListener("message", (event) => {
414
+ const message = JSON.parse(String(event.data));
415
+ switch (message.type) {
416
+ case "session.created":
417
+ send({
418
+ type: "session.update",
419
+ session: {
420
+ instructions: "Read what you are given as it is written.",
421
+ output_modalities: ["audio"],
422
+ audio: {
423
+ input: { format: { type: "audio/pcm", rate: 16000 }, turn_detection: { type: "server_vad", create_response: false } },
424
+ output: { format: { type: "audio/pcm", rate: RATE }, voice }
425
+ }
426
+ }
427
+ });
428
+ break;
429
+ case "session.updated":
430
+ send({ type: "response.create", response: { input_scope: "independent", input_text: text, output_modalities: ["audio"] } });
431
+ break;
432
+ case "response.output_audio.delta":
433
+ case "response.audio.delta":
434
+ chunks.push(Buffer.from(message.delta ?? "", "base64"));
435
+ break;
436
+ case "response.done":
437
+ end();
438
+ break;
439
+ case "error":
440
+ end(new Error(`Hunyuan: ${message.error?.message ?? "an error"}`));
441
+ break;
442
+ }
443
+ });
444
+ });
445
+ }
446
+ HunyuanVoice.read = read;
447
+ })(HunyuanVoice ||= {});
448
+
449
+ // web-src/stage.ts
450
+ var BEAT = 0.5;
451
+ var OPENING = 2.2;
452
+ var BODY = [
453
+ "..........####......",
454
+ "........##########..",
455
+ "........###########.",
456
+ ".......#############",
457
+ ".......#############",
458
+ ".##....#############",
459
+ "###....#############",
460
+ "##.....#############",
461
+ "##.....#####........",
462
+ "###....###########..",
463
+ "####..############..",
464
+ "##################..",
465
+ ".################...",
466
+ ".##############.....",
467
+ "..############......",
468
+ "...##########.......",
469
+ "....########........"
470
+ ];
471
+ var LEGS = {
472
+ stand: ["....###...###.......", "...###....###.......", "...####...####......"],
473
+ tuck: ["....###..###........", "....##...##........."],
474
+ none: []
475
+ };
476
+ var ARMS = {
477
+ down: [
478
+ [15, 13],
479
+ [16, 13],
480
+ [16, 14]
481
+ ],
482
+ up: [
483
+ [17, 12],
484
+ [18, 11],
485
+ [18, 10]
486
+ ],
487
+ out: [
488
+ [16, 13],
489
+ [17, 13],
490
+ [18, 12]
491
+ ]
492
+ };
493
+ var EYES = {
494
+ n: {
495
+ w: [
496
+ [10, 3],
497
+ [10, 4]
498
+ ],
499
+ p: [
500
+ [11, 3],
501
+ [11, 4]
502
+ ]
503
+ },
504
+ l: {
505
+ w: [
506
+ [11, 3],
507
+ [11, 4]
508
+ ],
509
+ p: [
510
+ [10, 3],
511
+ [10, 4]
512
+ ]
513
+ },
514
+ d: {
515
+ w: [
516
+ [10, 3],
517
+ [11, 3]
518
+ ],
519
+ p: [
520
+ [10, 4],
521
+ [11, 4]
522
+ ]
523
+ },
524
+ happy: {
525
+ w: [],
526
+ p: [
527
+ [9, 4],
528
+ [10, 3],
529
+ [11, 3],
530
+ [12, 4]
531
+ ]
532
+ }
533
+ };
534
+ var GREEN = "#10B981";
535
+ var SHADE = "#0A8F62";
536
+ var EpisodeStage;
537
+ ((EpisodeStage) => {
538
+ function dino(size, pose = {}, white = false) {
539
+ const cells = new Map;
540
+ const put = (c, r, v) => cells.set(`${c},${r}`, v);
541
+ const paint = (rows, top) => {
542
+ for (const [r, row] of rows.entries()) {
543
+ for (const [c, ch] of [...row].entries()) {
544
+ if (ch === "#") {
545
+ put(c, top + r, GREEN);
546
+ }
547
+ }
548
+ }
549
+ };
550
+ paint(BODY, 0);
551
+ paint(LEGS[pose.legs ?? "stand"] ?? LEGS.stand, 17);
552
+ for (const [c, r] of ARMS[pose.arms ?? "down"] ?? ARMS.down) {
553
+ put(c, r, GREEN);
554
+ }
555
+ for (const key of [...cells.keys()]) {
556
+ const [c, r] = key.split(",").map(Number);
557
+ if (!cells.has(`${c},${r + 1}`) && r < 19) {
558
+ put(c, r, SHADE);
559
+ }
560
+ }
561
+ put(13, 8, "#EFFFF8");
562
+ put(16, 8, "#EFFFF8");
563
+ const eyes = EYES[pose.eyes ?? "n"] ?? EYES.n;
564
+ for (const [c, r] of eyes.w) {
565
+ put(c, r, "#EFFFF8");
566
+ }
567
+ for (const [c, r] of eyes.p) {
568
+ put(c, r, "#0A2A1F");
569
+ }
570
+ const rects = [...cells].map(([key, v]) => {
571
+ const [c, r] = key.split(",");
572
+ const fill = white ? v === GREEN || v === SHADE ? "#fff" : GREEN : v;
573
+ return `<rect x="${c}" y="${r}" width="1.04" height="1.04" fill="${fill}"/>`;
574
+ }).join("");
575
+ return `<svg class="dino" viewBox="0 0 20 20" style="width:${size}rem;height:${size}rem" shape-rendering="crispEdges">${rects}</svg>`;
576
+ }
577
+ EpisodeStage.dino = dino;
578
+ function html(text) {
579
+ return text.replace(/[&<>"]/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[ch] ?? ch);
580
+ }
581
+ EpisodeStage.html = html;
582
+ function code(line) {
583
+ const prompt = /^(\s*)\$ /.exec(line);
584
+ const rest = prompt ? line.slice(prompt[0].length) : line;
585
+ const body = EpisodeAss.tokens(rest).map((one) => one.kind ? `<span class="k-${one.kind}">${html(one.text)}</span>` : html(one.text)).join("");
586
+ return (prompt ? `${prompt[1]}<span class="k-prompt">$</span> ` : "") + body || "&nbsp;";
587
+ }
588
+ EpisodeStage.code = code;
589
+ function kind(scene) {
590
+ return scene.phone?.lines.length ? "phone" : scene.code?.lines.length ? "code" : scene.points?.length ? "points" : "title";
591
+ }
592
+ EpisodeStage.kind = kind;
593
+ function last(scene) {
594
+ switch (kind(scene)) {
595
+ case "phone":
596
+ return (scene.phone?.lines.length ?? 0) + (scene.phone?.notify ? 1 : 0);
597
+ case "code":
598
+ return scene.code?.lines.length ?? 0;
599
+ case "points":
600
+ return scene.points?.length ?? 0;
601
+ default:
602
+ return scene.sub ? 1 : 0;
603
+ }
604
+ }
605
+ EpisodeStage.last = last;
606
+ function steps(scene) {
607
+ const end = last(scene);
608
+ switch (kind(scene)) {
609
+ case "code":
610
+ case "phone": {
611
+ const lines = (scene.phone ?? scene.code)?.lines.length ?? 1;
612
+ const typed = Array.from({ length: lines }, (_, i) => (kind(scene) === "code" ? 0.6 : 0.5) * (i / lines));
613
+ return end > lines ? [...typed, 0.7] : typed;
614
+ }
615
+ case "points":
616
+ return Array.from({ length: end }, (_, i) => 0.7 * (i / end));
617
+ default:
618
+ return end ? [0, 0.12] : [0];
619
+ }
620
+ }
621
+ EpisodeStage.steps = steps;
622
+ function first(scene) {
623
+ return kind(scene) === "title" ? 0 : 1;
624
+ }
625
+ EpisodeStage.first = first;
626
+ function timeline(timed, opening2 = 0) {
627
+ const out = [];
628
+ const hold = (scene, step, from, to) => {
629
+ for (let at = from, pose = 0;at < to - 0.000001; at += BEAT, pose = 1 - pose) {
630
+ out.push({ shot: { scene, step, pose }, seconds: Math.min(BEAT, to - at) });
631
+ }
632
+ };
633
+ if (opening2) {
634
+ hold(-1, 0, 0, opening2);
635
+ }
636
+ timed.forEach(({ scene, start, end }, i) => {
637
+ const at = steps(scene).map((share) => start + share * (end - start));
638
+ const base = first(scene);
639
+ for (const [k, from] of at.entries()) {
640
+ hold(i, base + k, from, at[k + 1] ?? end);
641
+ }
642
+ });
643
+ return out;
644
+ }
645
+ EpisodeStage.timeline = timeline;
646
+ function page(aspect) {
647
+ const [width, height] = EpisodeAss.size(aspect);
648
+ const rem = Math.min(width, height) / 1080 * 10;
649
+ 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>';
650
+ }
651
+ EpisodeStage.page = page;
652
+ function frame(episode, shot, aspect, options = {}) {
653
+ const [width, height] = EpisodeAss.size(aspect);
654
+ const wide = width > height;
655
+ const label = `<div class="ai">${html(episode.label ?? "AI 合成")}</div>`;
656
+ if (shot.scene < 0) {
657
+ return `<div class="stage ink opening">${label}${opening(episode, shot, wide)}</div>`;
658
+ }
659
+ const scene = episode.scenes[shot.scene];
660
+ const what = kind(scene);
661
+ const look = scene.look ?? episode.look ?? (what === "code" ? "ink" : what === "points" ? "sketch" : "paper");
662
+ const step = Math.min(shot.step, last(scene));
663
+ 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);
664
+ const words = options.post ? `<div class="words">${html(scene.say)}</div>` : "";
665
+ return '<div class="stage ' + look + (options.post ? " post" : "") + '">' + SKETCH + label + brand(episode) + '<div class="main scene-' + what + '">' + body + "</div>" + words + "</div>";
666
+ }
667
+ EpisodeStage.frame = frame;
668
+ function cover(episode, aspect) {
669
+ const [width, height] = EpisodeAss.size(aspect);
670
+ const wide = width > height;
671
+ const [head, tail] = episode.title.split(/[::]/);
672
+ const lines = episode.cover?.lines?.length ? episode.cover.lines : [head];
673
+ const sub = episode.cover?.sub ?? tail ?? "";
674
+ const longest = Math.max(...lines.map(EpisodeAss.columns)) / 2;
675
+ const room = wide ? 100 : 94;
676
+ const size = Math.min(wide ? 15 : 13, room / Math.max(4, longest) * (lines.length > 1 ? 1 : 1.9));
677
+ const tag = episode.series ? `<div class="tag">${html(episode.series.split(/\s*[·•]\s*/)[0])}${episode.number ? ` · 第 ${episode.number} 期` : ""}</div>` : "";
678
+ const notify = episode.scenes.find((one) => one.phone?.notify)?.phone?.notify;
679
+ const tags = (episode.cover?.tags ?? []).slice(0, 4).map((one) => `<span>${html(one)}</span>`).join("");
680
+ 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>";
681
+ }
682
+ EpisodeStage.cover = cover;
683
+ function brand(episode) {
684
+ if (!episode.series) {
685
+ return "";
686
+ }
687
+ return `<div class="brand">${episode.number ? `<b>第 ${episode.number} 期</b>` : ""}${html(episode.series)}</div>`;
688
+ }
689
+ function opening(episode, shot, wide) {
690
+ const jump = shot.pose ? ' style="transform:translateY(-4rem)"' : "";
691
+ const sparks = [
692
+ [28, 26, "#F2C14E"],
693
+ [70, 20, "#3ECF8E"],
694
+ [72, 48, "#F2C14E"],
695
+ [26, 52, "#3ECF8E"]
696
+ ].map(([x, y, c]) => `<i class="spark" style="left:${x}%;top:${y}%;color:${c}"></i>`).join("");
697
+ const name = episode.series ?? episode.title;
698
+ const sub = episode.series ? (episode.number ? `第 ${episode.number} 期 · ` : "") + episode.title.split(/[::]/)[0] : "";
699
+ 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>";
700
+ }
701
+ const STEP = /^(第.{1,3}[步招点个]|窍门.{1,2}|技巧.{1,2}|步骤.{1,2}|Step \d+|Tip \d+)$/i;
702
+ function host(scene, step, pose, wide) {
703
+ const title = scene.title ?? "";
704
+ const badge = STEP.test(title);
705
+ const first2 = badge ? `<div class="badge big">${html(title)}</div>` : `<div class="bubble big">${html(title)}</div>`;
706
+ const second = scene.sub && step >= 1 ? `<div class="bubble${badge ? " big" : " soft"}">${html(scene.sub)}</div>` : "";
707
+ const dinoPose = pose ? { arms: "out", eyes: "happy" } : { arms: "down", eyes: "n" };
708
+ return '<div class="host' + (pose ? " up" : "") + '">' + dino(wide ? 50 : 54, dinoPose) + '<div class="shadow"></div></div><div class="talk">' + first2 + second + "</div>";
709
+ }
710
+ function terminal(scene, step, pose, wide) {
711
+ const lines = (scene.code?.lines ?? []).slice(0, wide ? 14 : 22);
712
+ const shown = lines.slice(0, step);
713
+ const longest = Math.max(24, ...lines.map(EpisodeAss.columns));
714
+ const room = wide ? scene.note ? 118 : 150 : 96;
715
+ const size = Math.max(2.2, Math.min(wide ? 4 : 3.8, room / (longest * 0.6)));
716
+ const typing = step < lines.length;
717
+ const rows = shown.map((line, i) => `<div>${code(line)}${i === shown.length - 1 ? `<span class="cursor${typing || pose ? "" : " off"}"></span>` : ""}</div>`).join("");
718
+ const note = scene.note ? `<div class="note">${html(scene.note)}</div>` : "";
719
+ const peek = `<div class="peek">${dino(wide ? 20 : 14, { eyes: pose ? "d" : "l", legs: "none" })}</div>`;
720
+ 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;
721
+ }
722
+ function phone(scene, step, pose, wide) {
723
+ const lines = (scene.phone?.lines ?? []).slice(0, 16);
724
+ const shown = lines.slice(0, Math.min(step, lines.length));
725
+ const notified = scene.phone?.notify && step > lines.length;
726
+ const longest = Math.max(20, ...lines.map(EpisodeAss.columns));
727
+ const size = Math.max(1.8, Math.min(wide ? 3 : 3.4, (wide ? 36 : 54) / (longest * 0.6)));
728
+ const rows = shown.map((line, i) => `<div>${code(line)}${i === shown.length - 1 && !notified ? '<span class="cursor"></span>' : ""}</div>`).join("");
729
+ 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>" : "";
730
+ const note = scene.note ? `<div class="bubble">${html(scene.note)}</div>` : "";
731
+ const dinoPose = notified ? { arms: "up", eyes: "happy" } : pose ? { arms: "out", eyes: "n" } : { arms: "down", eyes: "d" };
732
+ 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>';
733
+ }
734
+ function points(scene, step, pose, wide) {
735
+ 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("");
736
+ const done = step >= (scene.points?.length ?? 0);
737
+ const dinoPose = done ? { arms: "up", eyes: "happy" } : pose ? { arms: "out", eyes: "n" } : { arms: "down", eyes: "d" };
738
+ 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>';
739
+ }
740
+ 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>';
741
+ const CSS = `
742
+ *{box-sizing:border-box;margin:0;padding:0}
743
+ body{overflow:hidden;font-family:"PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;-webkit-font-smoothing:antialiased}
744
+ .stage{position:absolute;inset:0;overflow:hidden;display:flex;flex-direction:column;--fg:#0A2A1F;--dim:#3d5a4f;color:var(--fg)}
745
+ .paper{background:#F4EFE4}
746
+ .paper:before{content:"";position:absolute;inset:0;background-image:radial-gradient(#d9d1bf .2rem,transparent .2rem);background-size:3.6rem 3.6rem;opacity:.8}
747
+ .ink{background:radial-gradient(120% 90% at 70% 10%,#173b2f 0%,#0d1a16 55%,#0a1210 100%);--fg:#fff;--dim:#bfe9d9}
748
+ .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}
749
+ .sketch{background:#FBF6EA;--fg:#222}
750
+ .sketch:before{content:"";position:absolute;inset:0;background:repeating-linear-gradient(transparent 0 4.6rem,#bcd3e8 4.6rem 4.8rem);opacity:.9}
751
+ .sketch:after{content:"";position:absolute;top:0;bottom:0;left:12rem;width:.3rem;background:#e8a0a0}
752
+ .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}
753
+ .tall .ai{top:9rem}
754
+ .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}
755
+ .tall .brand{margin-top:9.2rem}
756
+ .ink .brand{color:#3ECF8E}
757
+ .brand b{background:#10B981;color:#fff;border-radius:1rem;padding:.4rem 1.2rem;font-size:2.4rem}
758
+ .main{position:relative;z-index:2;flex:1;display:flex;align-items:center;justify-content:center;gap:5rem;padding:3rem 8rem 15rem}
759
+ .tall .main{flex-direction:column;padding:4rem 6rem 30rem;gap:4rem}
760
+ .post .main{padding-bottom:4rem}
761
+ .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}
762
+ .dino{display:block}
763
+ .host{position:relative;flex:none;transition:none}
764
+ .host.up{transform:translateY(-1.2rem)}
765
+ .host .shadow{margin:-1.2rem auto 0;width:70%;height:2rem;border-radius:50%;background:rgba(0,0,0,.18)}
766
+ .ink .host .shadow{background:rgba(0,0,0,.4)}
767
+ .talk{display:flex;flex-direction:column;gap:4rem;align-items:flex-start;max-width:58%}
768
+ .tall .talk{max-width:100%;align-items:center;order:-1}
769
+ .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}
770
+ .bubble.big{font-size:8.4rem}
771
+ .bubble.soft{background:#E6F7EF;font-size:5rem}
772
+ .wide .talk .bubble:after{content:"";position:absolute;left:-3.2rem;bottom:3rem;border:1.6rem solid transparent;border-right:2.2rem solid #0A2A1F}
773
+ .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}
774
+ .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}
775
+ .tall .window{flex:none;width:100%;margin-top:12rem;min-height:60%}
776
+ .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}
777
+ .window .bar i{width:1.6rem;height:1.6rem;border-radius:50%;background:#ff5f57}
778
+ .window .bar i:nth-child(2){background:#febc2e}.window .bar i:nth-child(3){background:#28c840}
779
+ .window .bar span{margin-left:1rem}
780
+ .lines{font-family:Menlo,"JetBrains Mono",monospace;line-height:1.6;color:#d8e1e8;padding:2.8rem 3.4rem;white-space:pre}
781
+ .k-prompt{color:#3ECF8E}.k-comment{color:#6b7b88}.k-string{color:#F2C14E}.k-number{color:#ffaa64}.k-keyword{color:#c792ea}.k-name{color:#7aa2f7}
782
+ .cursor{display:inline-block;width:.55em;height:1.1em;background:#3ECF8E;vertical-align:-.18em;margin-left:.2em}
783
+ .cursor.off{opacity:0}
784
+ .peek{position:absolute;right:6rem;bottom:100%;margin-bottom:-.6rem}
785
+ .wide .scene-code{align-items:stretch;padding-top:16rem}
786
+ .wide .scene-code .window{margin-top:0}
787
+ .wide .scene-code .note{align-self:center}
788
+ .screen.notified .lines{padding-top:22rem}
789
+ .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}
790
+ .paper .note,.sketch .note{box-shadow:.8rem .8rem 0 #0A2A1F;border:.5rem solid #0A2A1F}
791
+ .tall .note{width:100%}
792
+ .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}
793
+ .tall .phone{height:auto;width:62%;flex:1;aspect-ratio:auto}
794
+ .screen{position:relative;width:100%;height:100%;border-radius:5.2rem;overflow:hidden;background:#0f1418;display:flex;flex-direction:column}
795
+ .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}
796
+ .screen .lines{flex:1;padding:12rem 2.6rem 0;white-space:pre-wrap;word-break:break-all;color:#cfe}
797
+ .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}
798
+ .keys span{background:#2d363e;border-radius:1.2rem;padding:.8rem 1.4rem}
799
+ .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}
800
+ .notify .icon{width:6.4rem;height:6.4rem;border-radius:1.6rem;background:#10B981;flex:none;display:flex;align-items:center;justify-content:center}
801
+ .notify b{font-size:2.6rem;color:#111}.notify p{font-size:2.4rem;color:#444;margin-top:.2rem;line-height:1.35}
802
+ .scene-phone .side,.scene-points .side{display:flex;flex-direction:column;align-items:center;gap:4rem}
803
+ .scene-phone{gap:8rem}
804
+ .tall .scene-phone .side{flex-direction:row;align-items:flex-end;width:100%;justify-content:space-between}
805
+ .tall .scene-phone .bubble{font-size:4rem}
806
+ .hand{filter:url(#wob)}
807
+ .list{flex:1;padding-left:8rem}
808
+ .tall .list{padding-left:10rem;flex:none;width:100%}
809
+ .list h1{font-size:8.4rem;color:#1d3b8f;transform:rotate(-2deg);margin-bottom:5rem}
810
+ .list ol{list-style:none;display:flex;flex-direction:column;gap:5rem}
811
+ .list li{position:relative;font-size:6.4rem;font-weight:700;filter:url(#wob)}
812
+ .tall .list li{font-size:5.6rem}
813
+ .list .num{margin-right:1.6rem}
814
+ .list .mark{position:absolute;left:-1rem;bottom:-1.4rem;height:1.8rem;background:#F2C14E;opacity:.6;border-radius:.9rem;z-index:-1}
815
+ .say{font-size:4.6rem;font-weight:700;color:#0A8F62;transform:rotate(4deg)}
816
+ .opening{align-items:center;justify-content:center}
817
+ .opening .glow{position:absolute;inset:0;background:radial-gradient(circle at 50% 42%,rgba(16,185,129,.38),transparent 45%)}
818
+ .opening .center{position:relative;display:flex;flex-direction:column;align-items:center;gap:3rem;z-index:2}
819
+ .opening h1{font-size:11rem;font-weight:800;color:#fff;letter-spacing:.6rem;text-align:center;line-height:1.2}
820
+ .tall .opening h1{font-size:9rem}
821
+ .opening h1 em{font-style:normal;color:#10B981}
822
+ .opening h2{font-size:4.4rem;color:#9fd9c3;font-weight:600;text-align:center}
823
+ .spark{position:absolute;width:5rem;height:5rem;z-index:1}
824
+ .spark:before,.spark:after{content:"";position:absolute;background:currentColor}
825
+ .spark:before{left:2rem;top:0;width:1rem;height:5rem}.spark:after{top:2rem;left:0;width:5rem;height:1rem}
826
+ .cover{background:#10B981;color:#fff;flex-direction:row}
827
+ .cover .blob{position:absolute;right:-12rem;top:-12rem;width:90rem;height:90rem;border-radius:50%;background:#0FA372}
828
+ .tall .cover .blob{right:auto;left:-20rem;top:auto;bottom:-26rem}
829
+ .cover .text{position:relative;z-index:2;padding:8rem 0 0 9rem;width:62%}
830
+ .tall .cover .text{width:100%;padding:9rem 7rem 0}
831
+ .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}
832
+ .cover h1{margin-top:5rem;line-height:1.12;font-weight:800;text-shadow:.8rem .8rem 0 #06281c}
833
+ .cover h2{margin-top:4rem;font-size:5.6rem;font-weight:800;color:#06281c}
834
+ .cover .tags{margin-top:5rem;display:flex;gap:1.8rem;flex-wrap:wrap}
835
+ .cover .tags span{background:#06281c;font-size:4rem;font-weight:700;padding:1rem 2.6rem;border-radius:99rem}
836
+ .cover .props{position:absolute;inset:0;z-index:1}
837
+ .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}
838
+ .tall .cover .phone.mini{width:38rem;right:6rem;bottom:-4rem}
839
+ .cover .phone.mini .screen{border-radius:3.8rem}
840
+ .cover .phone.mini .island{width:10rem;height:3rem}
841
+ .cover .phone.mini .notify{top:6rem;padding:1.4rem}
842
+ .cover .phone.mini .icon{width:5rem;height:5rem}
843
+ .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))}
844
+ .tall .cover .host{right:auto;left:8rem;bottom:8rem}
845
+ `;
846
+ })(EpisodeStage ||= {});
847
+
158
848
  // web-src/render.ts
159
849
  var EpisodeRender;
160
850
  ((EpisodeRender) => {
@@ -164,7 +854,7 @@ var EpisodeRender;
164
854
  EpisodeRender.VOICE = "zh-CN-XiaoxiaoNeural";
165
855
  const NEURAL = /^[a-z]{2,3}-[A-Z]{2}-\w+Neural$/;
166
856
  async function run(file, options) {
167
- const episode = JSON.parse(await readFile(file, "utf8"));
857
+ const episode = JSON.parse(await readFile2(file, "utf8"));
168
858
  if (!episode?.title || !Array.isArray(episode.scenes) || !episode.scenes.length) {
169
859
  throw new Error("An episode is { title, scenes: [{ say, code?, title?, sub?, points? }] }.");
170
860
  }
@@ -173,27 +863,44 @@ var EpisodeRender;
173
863
  }
174
864
  EpisodeRender.run = run;
175
865
  async function video(episode, options) {
176
- const work = await mkdtemp(join(tmpdir(), "ta-creator-"));
866
+ const work = await mkdtemp2(join3(tmpdir2(), "ta-creator-"));
177
867
  try {
178
868
  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}.`);
869
+ const hunyuan = HunyuanVoice.voiceOf(wanted) ? await HunyuanVoice.service() : undefined;
870
+ if (HunyuanVoice.voiceOf(wanted) && !hunyuan) {
871
+ console.error(`No Hy Realtime in Ta's voice settings (or TA_CREATOR_HUNYUAN_URL): read in ${EpisodeRender.VOICE} instead.`);
872
+ }
873
+ const neural = hunyuan ? undefined : NEURAL.test(wanted) ? wanted : HunyuanVoice.voiceOf(wanted) ? EpisodeRender.VOICE : undefined;
874
+ const python = neural ? await edgePython() : undefined;
875
+ if (neural && !python) {
876
+ console.error(`No Python with edge-tts here (set TA_CREATOR_PYTHON): read in this computer's speech instead of ${neural}.`);
182
877
  }
183
- const speaker = python ? wanted : pickVoice(await exec("say", ["-v", "?"]), NEURAL.test(wanted) ? undefined : wanted);
878
+ const speaker = hunyuan ? "" : python ? neural : pickVoice(await exec("say", ["-v", "?"]), neural || HunyuanVoice.voiceOf(wanted) ? undefined : wanted);
184
879
  const timed = [];
185
880
  const parts = [];
186
- let at = 0;
881
+ const chrome = StageBrowser.find();
882
+ const opening = chrome && episode.series ? OPENING : 0;
883
+ if (!chrome) {
884
+ console.error("No Chrome, Edge, Brave or Chromium here (set TA_CREATOR_CHROME): drawn plainly, without the host and the devices.");
885
+ }
886
+ if (opening) {
887
+ const sting = join3(work, "sting.wav");
888
+ await exec("ffmpeg", ["-y", "-loglevel", "error", "-f", "lavfi", "-i", `aevalsrc=exprs='${CHIME}':s=44100:d=${opening}`, "-ac", "1", sting]);
889
+ parts.push(sting);
890
+ }
891
+ let at = opening;
187
892
  for (const [i, scene] of episode.scenes.entries()) {
188
- const spoken = join(work, python ? `${i}.mp3` : `${i}.aiff`);
893
+ const spoken = join3(work, hunyuan ? `${i}.hy.wav` : python ? `${i}.mp3` : `${i}.aiff`);
189
894
  const said = scene.say.replace(/`/g, "");
190
- if (python) {
895
+ if (hunyuan) {
896
+ await readHunyuan(hunyuan, HunyuanVoice.voiceOf(wanted), said, spoken);
897
+ } else if (python) {
191
898
  await exec(python, ["-m", "edge_tts", "--voice", speaker, "--rate", neuralRate(episode.rate), "--text", said, "--write-media", spoken]);
192
899
  } else {
193
900
  await exec("say", ["-v", speaker, "-r", String(episode.rate ?? RATE), "-o", spoken, paced(said)]);
194
901
  }
195
902
  const seconds = await length(spoken) + GAP;
196
- const padded = join(work, `${i}.wav`);
903
+ const padded = join3(work, `${i}.wav`);
197
904
  await exec("ffmpeg", [
198
905
  "-y",
199
906
  "-loglevel",
@@ -212,19 +919,23 @@ var EpisodeRender;
212
919
  parts.push(padded);
213
920
  at += seconds;
214
921
  }
215
- const list = join(work, "list.txt");
216
- await writeFile(list, parts.map((one) => `file '${one.replace(/'/g, "'\\''")}'`).join(`
922
+ const list = join3(work, "list.txt");
923
+ await writeFile3(list, parts.map((one) => `file '${one.replace(/'/g, "'\\''")}'`).join(`
217
924
  `));
218
- const voice = join(options.out, "voice.m4a");
925
+ const voice = join3(options.out, "voice.m4a");
219
926
  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")];
927
+ await writeFile3(join3(options.out, "captions.srt"), srt(timed));
928
+ const made = [voice, join3(options.out, "captions.srt")];
929
+ if (chrome) {
930
+ made.push(...await staged(chrome, episode, timed, opening, voice, work, options));
931
+ return made;
932
+ }
222
933
  for (const aspect of options.aspects) {
223
934
  const [width, height] = EpisodeAss.size(aspect);
224
935
  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`);
936
+ const ass = join3(work, `${name}.ass`);
937
+ await writeFile3(ass, EpisodeAss.build(episode, timed, aspect));
938
+ const mp4 = join3(options.out, `${name}.mp4`);
228
939
  await exec("ffmpeg", [
229
940
  "-y",
230
941
  "-loglevel",
@@ -257,26 +968,135 @@ var EpisodeRender;
257
968
  mp4
258
969
  ]);
259
970
  const first = timed.find((one) => one.scene.title) ?? timed[0];
260
- const cover = join(options.out, `cover-${name}.png`);
971
+ const cover = join3(options.out, `cover-${name}.png`);
261
972
  await exec("ffmpeg", ["-y", "-loglevel", "error", "-ss", String(Math.max(0.1, first.end - 0.2)), "-i", mp4, "-frames:v", "1", cover]);
262
973
  made.push(mp4, cover);
263
974
  }
264
975
  return made;
265
976
  } finally {
266
- await rm(work, { recursive: true, force: true });
977
+ await rm2(work, { recursive: true, force: true });
978
+ }
979
+ }
980
+ async function readHunyuan(service, voice, text, out) {
981
+ try {
982
+ await HunyuanVoice.read(service, voice, text, out);
983
+ } catch {
984
+ await HunyuanVoice.read(service, voice, text, out);
985
+ }
986
+ }
987
+ const CHIME = [
988
+ "0.26*sin(2*PI*784*t)*exp(-5*t)",
989
+ "0.24*gt(t,0.16)*sin(2*PI*988*t)*exp(-5*(t-0.16))",
990
+ "0.24*gt(t,0.32)*sin(2*PI*1175*t)*exp(-3*(t-0.32))"
991
+ ].join("+");
992
+ async function staged(chrome, episode, timed, opening, voice, work, options) {
993
+ const made = [];
994
+ const browser = await StageBrowser.open(chrome);
995
+ try {
996
+ const total = timed.length ? timed[timed.length - 1].end : opening;
997
+ for (const aspect of options.aspects) {
998
+ const [width, height] = EpisodeAss.size(aspect);
999
+ const name = aspect.replace(":", "x");
1000
+ await browser.load(EpisodeStage.page(aspect), width, height);
1001
+ const timeline = EpisodeStage.timeline(timed, opening);
1002
+ const drawn = new Map;
1003
+ const picture = async (shot) => {
1004
+ const key = `${shot.scene}-${shot.step}-${shot.pose}`;
1005
+ let file = drawn.get(key);
1006
+ if (!file) {
1007
+ file = join3(work, `${name}-${key}.png`);
1008
+ await browser.shoot(EpisodeStage.frame(episode, shot, aspect), file);
1009
+ drawn.set(key, file);
1010
+ }
1011
+ return file;
1012
+ };
1013
+ const list = [];
1014
+ for (const one of timeline) {
1015
+ list.push(`file '${(await picture(one.shot)).replace(/'/g, "'\\''")}'`, `duration ${one.seconds.toFixed(3)}`);
1016
+ }
1017
+ list.push(list[list.length - 2]);
1018
+ const listFile = join3(work, `${name}.txt`);
1019
+ await writeFile3(listFile, list.join(`
1020
+ `));
1021
+ const ass = join3(work, `${name}.ass`);
1022
+ await writeFile3(ass, EpisodeAss.subtitles(timed, aspect));
1023
+ const mp4 = join3(options.out, `${name}.mp4`);
1024
+ await exec("ffmpeg", [
1025
+ "-y",
1026
+ "-loglevel",
1027
+ "error",
1028
+ "-f",
1029
+ "concat",
1030
+ "-safe",
1031
+ "0",
1032
+ "-i",
1033
+ listFile,
1034
+ "-i",
1035
+ voice,
1036
+ "-vf",
1037
+ `fps=30,format=yuv420p,ass=${filterPath(ass)}`,
1038
+ "-t",
1039
+ total.toFixed(3),
1040
+ "-c:v",
1041
+ "libx264",
1042
+ "-preset",
1043
+ "medium",
1044
+ "-crf",
1045
+ "20",
1046
+ "-c:a",
1047
+ "copy",
1048
+ "-movflags",
1049
+ "+faststart",
1050
+ "-metadata",
1051
+ `title=${episode.title}`,
1052
+ "-metadata",
1053
+ "comment=AIGC: made with AI (picture, voice and captions)",
1054
+ mp4
1055
+ ]);
1056
+ const cover = join3(options.out, `cover-${name}.png`);
1057
+ await browser.shoot(EpisodeStage.cover(episode, aspect), cover);
1058
+ made.push(mp4, cover);
1059
+ }
1060
+ return made;
1061
+ } finally {
1062
+ await browser.close();
267
1063
  }
268
1064
  }
269
1065
  async function post(episode, options) {
270
- const work = await mkdtemp(join(tmpdir(), "ta-creator-"));
1066
+ const work = await mkdtemp2(join3(tmpdir2(), "ta-creator-"));
1067
+ const chrome = StageBrowser.find();
1068
+ if (chrome) {
1069
+ const browser = await StageBrowser.open(chrome);
1070
+ try {
1071
+ const made = [];
1072
+ for (const aspect of options.aspects) {
1073
+ const [width, height] = EpisodeAss.size(aspect);
1074
+ const name = aspect.replace(":", "x");
1075
+ await browser.load(EpisodeStage.page(aspect), width, height);
1076
+ const cover = join3(options.out, `post-${name}-00.png`);
1077
+ await browser.shoot(EpisodeStage.cover(episode, aspect), cover);
1078
+ made.push(cover);
1079
+ for (const [i, scene] of episode.scenes.entries()) {
1080
+ const png = join3(options.out, `post-${name}-${String(i + 1).padStart(2, "0")}.png`);
1081
+ await browser.shoot(EpisodeStage.frame(episode, { scene: i, step: EpisodeStage.last(scene), pose: 0 }, aspect, { post: true }), png);
1082
+ made.push(png);
1083
+ }
1084
+ }
1085
+ return made;
1086
+ } finally {
1087
+ await browser.close();
1088
+ await rm2(work, { recursive: true, force: true });
1089
+ }
1090
+ }
271
1091
  try {
272
1092
  const made = [];
273
1093
  for (const aspect of options.aspects) {
274
1094
  const [width, height] = EpisodeAss.size(aspect);
275
1095
  const name = aspect.replace(":", "x");
276
1096
  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`);
1097
+ const ass = join3(work, `${name}-${i}.ass`);
1098
+ await writeFile3(ass, EpisodeAss.build(episode, [{ scene, start: 0, end: 10 }], aspect, { post: true }));
1099
+ const png = join3(options.out, `post-${name}-${String(i + 1).padStart(2, "0")}.png`);
280
1100
  await exec("ffmpeg", [
281
1101
  "-y",
282
1102
  "-loglevel",
@@ -298,7 +1118,7 @@ var EpisodeRender;
298
1118
  }
299
1119
  return made;
300
1120
  } finally {
301
- await rm(work, { recursive: true, force: true });
1121
+ await rm2(work, { recursive: true, force: true });
302
1122
  }
303
1123
  }
304
1124
  function pickVoice(list, wanted) {
@@ -320,7 +1140,7 @@ var EpisodeRender;
320
1140
  }
321
1141
  EpisodeRender.neuralRate = neuralRate;
322
1142
  async function edgePython() {
323
- const candidates = [process.env.TA_CREATOR_PYTHON, join(homedir(), "lemo-opuscar/.venv/bin/python"), "python3"].filter((one) => !!one);
1143
+ const candidates = [process.env.TA_CREATOR_PYTHON, join3(homedir2(), "lemo-opuscar/.venv/bin/python"), "python3"].filter((one) => !!one);
324
1144
  for (const one of candidates) {
325
1145
  if (await exec(one, ["-c", "import edge_tts"]).then(() => true, () => false)) {
326
1146
  return one;
@@ -329,7 +1149,7 @@ var EpisodeRender;
329
1149
  return;
330
1150
  }
331
1151
  function srt(timed) {
332
- const stamp = (s) => EpisodeAss.time(s).replace(/^(\d+):/, (_all, h) => `${h.padStart(2, "0")}:`).replace(".", ",") + "0";
1152
+ const stamp = (s) => `${EpisodeAss.time(s).replace(/^(\d+):/, (_all, h) => `${h.padStart(2, "0")}:`).replace(".", ",")}0`;
333
1153
  return timed.flatMap((one) => EpisodeAss.captions(one.scene.say, one.start, one.end, 22)).map((one, i) => `${i + 1}
334
1154
  ${stamp(one.start)} --> ${stamp(one.end)}
335
1155
  ${one.text}
@@ -369,8 +1189,11 @@ if (process.argv[1]?.endsWith("render.mjs")) {
369
1189
  console.error("node render.mjs <episode.json> [--aspects 16:9,9:16,3:4,1:1] [--post] [--out <dir>]");
370
1190
  process.exit(2);
371
1191
  }
372
- EpisodeRender.run(resolve(file), { aspects, post, out: resolve(out ?? join(file, "..")) }).then((made) => console.log(made.join(`
373
- `)), (error) => {
1192
+ EpisodeRender.run(resolve(file), { aspects, post, out: resolve(out ?? join3(file, "..")) }).then((made) => {
1193
+ console.log(made.join(`
1194
+ `));
1195
+ process.exit(0);
1196
+ }, (error) => {
374
1197
  console.error(error instanceof Error ? error.message : String(error));
375
1198
  process.exit(1);
376
1199
  });