@biunow/agent-biuvibe 1.0.1 → 1.0.3

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/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
4
  import {
5
5
  createAgentServer,
6
6
  ensureDir,
@@ -14,9 +14,14 @@ import {
14
14
  isIntermediateMp4,
15
15
  readJson,
16
16
  } from '../lib/host.mjs';
17
- import { findRecipe, loadRecipes, recipeView } from '../../_shared/studio/recipes.mjs';
18
-
17
+ import { audienceLine, modelTitle, toEnglishPrompt } from '../studio/to-english-prompt.mjs';
19
18
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
19
+ const recipeFile = [
20
+ path.join(root, 'studio', 'recipes.mjs'),
21
+ path.resolve(root, '..', '_shared', 'studio', 'recipes.mjs'),
22
+ ].find((file) => fs.existsSync(file));
23
+ if (!recipeFile) throw new Error('找不到风格提示词模块 studio/recipes.mjs');
24
+ const { findRecipe, loadRecipes, recipeView } = await import(pathToFileURL(recipeFile).href);
20
25
  const COLUMNS = readJson(path.join(root, 'data', 'columns.json'), []);
21
26
  const RECIPES = loadRecipes(path.join(root, '风格提示词.md'));
22
27
 
@@ -124,9 +129,17 @@ createAgentServer({
124
129
  const durationLine = durationSec == null
125
130
  ? 'Duration: decide from the content, usually 45–90s, never over 180s.'
126
131
  : `Duration target: ~${durationSec}s, never over 180s.`;
127
- const durationKick = durationSec == null
128
- ? '时长按内容决定,一般 45–90 秒,不得超过 180 秒。'
129
- : `目标约 ${durationSec} 秒,不得超过 180 秒。`;
132
+ let promptEn = prompt;
133
+ let lookEn = String(column.line || '');
134
+ let titleEn = title;
135
+ try {
136
+ promptEn = await toEnglishPrompt(prompt);
137
+ if (/[\u4e00-\u9fff]/.test(lookEn)) lookEn = await toEnglishPrompt(lookEn);
138
+ titleEn = await modelTitle(title, prompt, promptEn);
139
+ } catch {
140
+ sendJson(res, 503, { error: '英文提示词没有生成,请再试一次' });
141
+ return true;
142
+ }
130
143
  const filmSlug = `${slugify(title)}-${Date.now().toString(36)}`;
131
144
 
132
145
  const job = jobs.create({
@@ -154,9 +167,9 @@ createAgentServer({
154
167
  const uploads = await saveUploads(cfg.workspace, job.id, files);
155
168
  const brief = {
156
169
  agent: 'biuvibe',
157
- title,
170
+ title: titleEn,
158
171
  style: column.slug,
159
- styleName: column.cn,
172
+ styleName: column.en || column.slug,
160
173
  skill: column.skill,
161
174
  sample: column.sample,
162
175
  card: column.card,
@@ -164,7 +177,7 @@ createAgentServer({
164
177
  screen: column.screen,
165
178
  voice: !!column.voice,
166
179
  music: !!column.music,
167
- prompt,
180
+ prompt: promptEn,
168
181
  storyboard,
169
182
  durationMode: durationSec == null ? 'auto' : 'fixed',
170
183
  durationSec,
@@ -176,9 +189,9 @@ createAgentServer({
176
189
  fs.writeFileSync(
177
190
  path.join(filmDir, 'TREATMENT.md'),
178
191
  [
179
- `# ${title}`,
192
+ `# ${titleEn}`,
180
193
  '',
181
- `Column: **${column.cn}** (\`${column.slug}\`)`,
194
+ `Column: **${column.en || column.slug}** (\`${column.slug}\`)`,
182
195
  `Screen: ${column.screen}`,
183
196
  durationLine,
184
197
  `Preview first: ${storyboard ? 'yes' : 'no'}`,
@@ -187,11 +200,11 @@ createAgentServer({
187
200
  '',
188
201
  '## Prompt',
189
202
  '',
190
- prompt,
203
+ promptEn,
191
204
  '',
192
205
  '## Look',
193
206
  '',
194
- column.line || '',
207
+ lookEn,
195
208
  '',
196
209
  '## Assets',
197
210
  '',
@@ -222,23 +235,24 @@ createAgentServer({
222
235
  );
223
236
 
224
237
  const kickoffPrompt = [
225
- '按 biuvibe skill 做一条知识短片直到成片。',
226
- `项目目录:${filmDir}`,
227
- `阅读 brief.json 与 TREATMENT.md。栏目 ${column.cn}(${column.slug})。${column.skill ? `技能 ${column.skill}。` : `配方 ${column.card}。`}样片 ${column.sample}。`,
228
- storyboard ? '先给出卡点稿再出片。' : '不用中途停顿。',
229
- durationKick,
230
- column.music ? '配乐只用 assets 里上传的文件,测重拍后再切镜。' : '这是口播栏目,只用上传的录音。',
231
- `选题:${prompt}`,
232
- '成片必须复制到项目目录,和 brief.json 放在一起。引擎 out 目录里的文件不是交付。',
233
- '完成后告诉我 MP4 路径。',
238
+ 'Follow the biuvibe skill and finish the knowledge film.',
239
+ `Project folder: ${filmDir}`,
240
+ `Read brief.json and TREATMENT.md. Column ${column.en || column.slug} (${column.slug}). ${column.skill ? `Skill ${column.skill}.` : `Recipe ${column.card}.`} Sample ${column.sample}.`,
241
+ storyboard ? 'Show the beat sheet before the full film.' : 'Do not pause midway.',
242
+ durationLine,
243
+ column.music ? 'Use only the music file in assets. Measure the downbeats before cutting.' : 'This is a voiceover column. Use only the uploaded recording.',
244
+ audienceLine(prompt),
245
+ `Creative brief: ${promptEn}`,
246
+ 'Copy the finished mp4 into the project folder, beside brief.json. A file in the engine out folder is not the delivery.',
247
+ 'When done, tell me the MP4 path.',
234
248
  ].join('\n');
235
249
  const kickoff = path.join(filmDir, 'START_IN_DSH.md');
236
250
  fs.writeFileSync(
237
251
  kickoff,
238
252
  [
239
- '# 在 DSH 中继续',
253
+ '# Continue in DSH',
240
254
  '',
241
- '面板会自动在 DSH 对话中启用 **biuvibe** skill 并发送下列需求;若未自动开拍,请手动粘贴:',
255
+ 'The panel enables the **biuvibe** skill and sends the brief below. Paste it if shooting did not start:',
242
256
  '',
243
257
  '```',
244
258
  kickoffPrompt,
package/lib/host.mjs CHANGED
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { spawn } from 'node:child_process';
11
11
  import crypto from 'node:crypto';
12
+ import { optimizePrompt } from '../studio/optimize-prompt.mjs';
12
13
 
13
14
  export function env() {
14
15
  return {
@@ -23,6 +24,7 @@ export function env() {
23
24
  callbackUrl: process.env.PANEL_CALLBACK_URL || '',
24
25
  callbackToken: process.env.PANEL_CALLBACK_TOKEN || '',
25
26
  canExport: process.env.PANEL_CAN_EXPORT !== '0',
27
+ member: process.env.PANEL_MEMBER === '1',
26
28
  product: process.env.PANEL_PRODUCT || '',
27
29
  };
28
30
  }
@@ -666,6 +668,7 @@ export function createAgentServer({ root, studioDir, api }) {
666
668
  version: cfg.version,
667
669
  product: cfg.product,
668
670
  canExport: cfg.canExport,
671
+ member: cfg.member === true,
669
672
  engineRoot: cfg.engineRoot || null,
670
673
  enginePresent: !!(cfg.engineRoot && fs.existsSync(cfg.engineRoot)),
671
674
  workspace: cfg.workspace,
@@ -714,6 +717,21 @@ export function createAgentServer({ root, studioDir, api }) {
714
717
  return sendJson(res, 200, { ok: true, id });
715
718
  }
716
719
 
720
+ if (pathname === '/api/optimize-prompt' && req.method === 'POST') {
721
+ if (cfg.member !== true) {
722
+ sendJson(res, 403, { error: '会员专属,请先开通会员' });
723
+ return;
724
+ }
725
+ try {
726
+ const body = await readJsonBody(req);
727
+ sendJson(res, 200, optimizePrompt(body));
728
+ } catch (error) {
729
+ const message = error instanceof SyntaxError ? '请求无法读取' : (error.message || '无法优化提示词');
730
+ sendJson(res, error.status || 400, { error: message });
731
+ }
732
+ return;
733
+ }
734
+
717
735
  if (api) {
718
736
  const handled = await api({ req, res, url, pathname, cfg, jobs, root, sendJson, readJsonBody, readBody });
719
737
  if (handled) return;
package/manifest.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "id": "biuvibe",
4
4
  "name": "BiuVibe",
5
- "version": "1.0.1",
5
+ "version": "1.0.3",
6
6
  "publisher": "Biunow",
7
7
  "description": "BiuVibe 知识短片:选一种画风,写下要讲的事,配上你有权使用的音乐或口播。",
8
8
  "entry": {
@@ -44,8 +44,8 @@
44
44
  "requiresEntitlement": "export"
45
45
  },
46
46
  "integrity": {
47
- "sha256": "f39920924137268c3def56344d8346d2346e127c3c7313f641212d72a0265ff3",
48
- "signature": "jxWSe1JPNjPmGYIP/3c2mYSBI7NJVRHhPIz4dcfQMot+8aSdiI6JyktI7h0xO1C6slYF/oBn/UjhcOFu9tDFAA==",
47
+ "sha256": "1672d00aada0471d3a33ff56f4462c1009ae7105c8284c4bfacba8ef716552a7",
48
+ "signature": "FA6h9TIz+gcyyHQk/Xh/X4UBV44R2Iy1EokjWWW582GcUdakGmvoq3W1B2qCK9Mjr4FFwThAjffvg/vzXxQ2CA==",
49
49
  "signedBy": "publisher-key"
50
50
  }
51
51
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biunow/agent-biuvibe",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "BiuVibe",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
package/studio/app.js CHANGED
@@ -254,6 +254,7 @@
254
254
  onChange: (value) => applyStyle(value),
255
255
  });
256
256
  if (picked) applyStyle(picked.slug);
257
+ if (Composer.claimCasePrompt) Composer.claimCasePrompt();
257
258
  await refreshJobs();
258
259
  setInterval(refreshJobs, 2000);
259
260
  void health;
@@ -112,7 +112,27 @@ button:disabled { cursor: not-allowed; opacity: .5; }
112
112
  width: 100%; min-height: 190px; border: 0; resize: vertical; outline: 0;
113
113
  padding: 18px 22px 8px; font-size: 15px; line-height: 1.7; background: transparent; color: var(--ink);
114
114
  }
115
- .composer textarea::placeholder { color: #a3a39f; }
115
+ .composer textarea::placeholder { color: #a3a39f; }
116
+
117
+ .prompt-stage { position: relative; }
118
+ .prompt-stage textarea { padding-bottom: 48px; }
119
+ .optimize {
120
+ position: absolute; right: 14px; bottom: 12px; z-index: 2;
121
+ border: 1px solid var(--line-strong); background: #fff; color: var(--ink);
122
+ border-radius: 999px; padding: 6px 12px; font-size: 12px; font-weight: 650;
123
+ box-shadow: 0 1px 2px rgb(0 0 0 / 6%);
124
+ }
125
+ .optimize:hover { background: var(--accent-soft); border-color: var(--accent-deep); }
126
+ .optimize.is-locked { opacity: .55; }
127
+ .optimize.is-locked:hover { background: #fff; border-color: var(--line-strong); }
128
+ .optimize-tip {
129
+ position: absolute; right: 14px; bottom: 48px; z-index: 3;
130
+ background: #111; color: #fff; border-radius: 10px; padding: 8px 10px;
131
+ font-size: 12px; line-height: 1.4; white-space: nowrap;
132
+ box-shadow: 0 8px 24px rgb(0 0 0 / 18%);
133
+ }
134
+ .optimize-tip[hidden] { display: none !important; }
135
+
116
136
  .composer-foot {
117
137
  display: flex; align-items: center; justify-content: space-between; gap: 12px;
118
138
  padding: 10px 12px 12px 14px; border-top: 1px solid #f0f0ed; flex-wrap: wrap;
@@ -285,6 +285,7 @@
285
285
  const RECIPE_LEVEL = { off: '无', optional: '可选', required: '必须' };
286
286
 
287
287
  function paintRecipe(state, recipe, hint, keepText) {
288
+ currentRecipe = recipe || null;
288
289
  const prompt = document.getElementById('prompt');
289
290
  let bar = document.getElementById('needBar');
290
291
  if (!bar && prompt) {
@@ -312,9 +313,11 @@
312
313
  }
313
314
  const narr = (recipe && recipe.narration) || 'optional';
314
315
  const att = (recipe && recipe.attachment) || 'optional';
316
+ const audio = recipe && recipe.audio;
315
317
  flags.innerHTML =
316
318
  `<span class="need-flag ${narr}">旁白 · ${RECIPE_LEVEL[narr] || narr}</span>` +
317
- `<span class="need-flag ${att}">附件 · ${RECIPE_LEVEL[att] || att}</span>`;
319
+ `<span class="need-flag ${att}">附件 · ${RECIPE_LEVEL[att] || att}</span>` +
320
+ (audio ? `<span class="need-flag ${audio}">音频驱动 · ${RECIPE_LEVEL[audio] || audio}</span>` : '');
318
321
  const text = String((recipe && recipe.prompt) || '').trim();
319
322
  if (prompt && text && !keepText) {
320
323
  prompt.value = text;
@@ -345,5 +348,133 @@
345
348
  addChip,
346
349
  titleFromPrompt,
347
350
  paintRecipe,
351
+ claimCasePrompt,
348
352
  };
353
+
354
+ let casePromptText = '';
355
+ let studioReadyForCase = false;
356
+
357
+ function writeCasePrompt() {
358
+ const prompt = document.getElementById('prompt');
359
+ const text = String(casePromptText || '').trim();
360
+ if (!studioReadyForCase || !prompt || !text || prompt.value === text) return;
361
+ prompt.value = text;
362
+ prompt.dispatchEvent(new Event('input'));
363
+ }
364
+
365
+ window.addEventListener('message', (event) => {
366
+ if (event.source !== window.parent) return;
367
+ const data = event.data || {};
368
+ if (data.type !== 'bn-case-prompt') return;
369
+ casePromptText = String(data.prompt || '');
370
+ writeCasePrompt();
371
+ });
372
+
373
+ function claimCasePrompt() {
374
+ studioReadyForCase = true;
375
+ writeCasePrompt();
376
+ }
377
+ let currentRecipe = null;
378
+
379
+ let optimizeMember = false;
380
+ let optimizeTipTimer = 0;
381
+
382
+ function showOptimizeTip(message) {
383
+ const tip = document.getElementById('optimizeTip');
384
+ if (!tip) return;
385
+ tip.hidden = false;
386
+ tip.textContent = message;
387
+ window.clearTimeout(optimizeTipTimer);
388
+ optimizeTipTimer = window.setTimeout(() => {
389
+ tip.hidden = true;
390
+ }, 2600);
391
+ }
392
+
393
+ async function onOptimizePrompt() {
394
+ const btn = document.getElementById('optimizeBtn');
395
+ const prompt = document.getElementById('prompt');
396
+ if (!btn || !prompt) return;
397
+ if (!optimizeMember) {
398
+ showOptimizeTip('会员专属,请先开通会员');
399
+ return;
400
+ }
401
+ if (btn.dataset.busy === '1') return;
402
+ btn.dataset.busy = '1';
403
+ const previous = btn.textContent;
404
+ btn.textContent = '优化中';
405
+ try {
406
+ const recipe = currentRecipe || {};
407
+ const data = await api('/api/optimize-prompt', {
408
+ method: 'POST',
409
+ headers: { 'content-type': 'application/json' },
410
+ body: JSON.stringify({
411
+ text: prompt.value,
412
+ templatePrompt: recipe.prompt || '',
413
+ narration: recipe.narration || '',
414
+ attachment: recipe.attachment || '',
415
+ }),
416
+ });
417
+ const next = String((data && data.prompt) || '').trim();
418
+ if (!next) throw new Error('没有得到可用的提示词');
419
+ prompt.value = next;
420
+ prompt.dispatchEvent(new Event('input'));
421
+ if (data && data.kept) showOptimizeTip('没选模板,按你写的原文出片');
422
+ } catch (error) {
423
+ const message = (error && error.message) || '无法优化提示词';
424
+ if (message.indexOf('会员专属') >= 0) {
425
+ optimizeMember = false;
426
+ btn.classList.add('is-locked');
427
+ btn.setAttribute('aria-disabled', 'true');
428
+ showOptimizeTip('会员专属,请先开通会员');
429
+ } else {
430
+ const err = document.getElementById('err');
431
+ if (err) {
432
+ err.hidden = false;
433
+ err.textContent = message;
434
+ } else {
435
+ showOptimizeTip(message);
436
+ }
437
+ }
438
+ } finally {
439
+ btn.dataset.busy = '';
440
+ btn.textContent = previous || '优化提示词';
441
+ }
442
+ }
443
+
444
+ function mountOptimize() {
445
+ const prompt = document.getElementById('prompt');
446
+ if (!prompt || document.getElementById('optimizeBtn')) return;
447
+ const stage = document.createElement('div');
448
+ stage.className = 'prompt-stage';
449
+ prompt.parentNode.insertBefore(stage, prompt);
450
+ stage.appendChild(prompt);
451
+ const btn = document.createElement('button');
452
+ btn.type = 'button';
453
+ btn.id = 'optimizeBtn';
454
+ btn.className = 'optimize is-locked';
455
+ btn.setAttribute('aria-disabled', 'true');
456
+ btn.textContent = '优化提示词';
457
+ const tip = document.createElement('div');
458
+ tip.id = 'optimizeTip';
459
+ tip.className = 'optimize-tip';
460
+ tip.hidden = true;
461
+ stage.appendChild(btn);
462
+ stage.appendChild(tip);
463
+ btn.addEventListener('click', () => {
464
+ void onOptimizePrompt();
465
+ });
466
+ fetch('/api/health')
467
+ .then((res) => res.json())
468
+ .then((data) => {
469
+ optimizeMember = !!(data && data.member === true);
470
+ btn.classList.toggle('is-locked', !optimizeMember);
471
+ btn.setAttribute('aria-disabled', optimizeMember ? 'false' : 'true');
472
+ })
473
+ .catch(() => {
474
+ optimizeMember = false;
475
+ });
476
+ }
477
+
478
+ mountOptimize();
479
+
349
480
  })(window);
@@ -0,0 +1,84 @@
1
+ /** 把用户原话收成当前模板能直接出片的一句。会员接口才调用。 */
2
+
3
+ function same(a, b) {
4
+ return String(a || '').replace(/\s+/g, '') === String(b || '').replace(/\s+/g, '');
5
+ }
6
+
7
+ function quotes(text) {
8
+ return [...String(text || '').matchAll(/「([^」]+)」/g)]
9
+ .map((match) => match[1].trim())
10
+ .filter(Boolean);
11
+ }
12
+
13
+ function clip(text, max = 80) {
14
+ const chars = [...String(text || '').replace(/\s+/g, ' ').trim()];
15
+ if (chars.length <= max) return chars.join('');
16
+ return chars.slice(0, max).join('').replace(/[,,、::;;\s]+$/u, '');
17
+ }
18
+
19
+ function topicFromFreeText(text) {
20
+ let value = String(text || '').replace(/\s+/g, ' ').trim();
21
+ value = value.replace(/^用[\u4e00-\u9fffA-Za-z0-9]{1,16}讲/, '');
22
+ value = value.replace(/^[「『"']+|[」』"']+$/g, '').trim();
23
+ const sentence = (value.split(/[。!?!?]/)[0] || value).trim();
24
+ return sentence.replace(/^[「『"']+|[」』"']+$/g, '').trim();
25
+ }
26
+
27
+ function fail(message) {
28
+ const error = new Error(message);
29
+ error.code = 'PROMPT';
30
+ throw error;
31
+ }
32
+
33
+ export function optimizePrompt(input) {
34
+ const text = String(input?.text || '').trim();
35
+ const skeleton = String(input?.templatePrompt || '').trim();
36
+ const narration = String(input?.narration || '');
37
+ const attachment = String(input?.attachment || '');
38
+ if (!text) fail('先写下要讲的事');
39
+ if (!(skeleton && /「[^」]*」/.test(skeleton))) return { prompt: cap(text), kept: true };
40
+
41
+ const samples = quotes(skeleton);
42
+ let topic = quotes(text).find((quote) => !samples.some((sample) => same(sample, quote))) || '';
43
+ if (!topic) {
44
+ const free = topicFromFreeText(text);
45
+ const stillSample = !free || samples.some((sample) => same(sample, free)) || (skeleton && same(text, skeleton));
46
+ if (stillSample) fail(skeleton ? '先把引号里换成你要讲的事' : '先写下要讲的事');
47
+ topic = free;
48
+ }
49
+ topic = clip(topic);
50
+ if (!topic) fail('先写下要讲的事');
51
+
52
+ let prompt = skeleton.replace(/「[^」]*」/, `「${topic}」`);
53
+ const detail = extraDetail(text, skeleton, topic);
54
+ if (detail) prompt = `${prompt.replace(/。?$/, '。')}${detail}。`;
55
+ if (narration === 'off' && !/没有口播|不要口播|没有旁白|不要旁白/.test(prompt)) prompt += '没有口播。';
56
+ if (narration === 'required' && !/口播|旁白/.test(prompt)) prompt += '口播用你上传的录音。';
57
+ if (attachment === 'required' && !/附件|上传/.test(prompt)) prompt += '必须的附件跟这一条一起交。';
58
+ return { prompt: cap(prompt.replace(/[ \t]+/g, ' ').trim()) };
59
+ }
60
+
61
+ function extraDetail(text, skeleton, topic) {
62
+ const known = skeleton.replace(/\s+/g, '');
63
+ const sentences = String(text || '')
64
+ .replace(/\s+/g, ' ')
65
+ .split(/[。!?!?]/)
66
+ .map((sentence) => sentence.trim())
67
+ .filter(Boolean);
68
+ for (const sentence of sentences) {
69
+ const bare = sentence
70
+ .replace(/^用[\u4e00-\u9fffA-Za-z0-9]{1,16}讲/, '')
71
+ .replace(/[「」『』]/g, '')
72
+ .trim();
73
+ if (!bare || same(bare, topic)) continue;
74
+ if (known.includes(bare.replace(/\s+/g, ''))) continue;
75
+ if (/另外|再讲|同时再|以及/.test(bare)) continue;
76
+ return clip(bare, 48);
77
+ }
78
+ return '';
79
+ }
80
+
81
+ function cap(prompt) {
82
+ if ([...prompt].length <= 4000) return prompt;
83
+ return [...prompt].slice(0, 4000).join('');
84
+ }
@@ -0,0 +1,47 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { optimizePrompt } from './optimize-prompt.mjs';
4
+
5
+ const skeleton = '用灯火史话讲「古代驿站为什么能把一封信送到这么远」。火光里先给结论,再给一个能记住的细节,没有口播。';
6
+
7
+ test('空内容要求先写要讲的事', () => {
8
+ assert.throws(() => optimizePrompt({ text: ' ', templatePrompt: skeleton }), /先写下要讲的事/);
9
+ });
10
+
11
+ test('没改模板例句时要求换成自己的事', () => {
12
+ assert.throws(() => optimizePrompt({ text: skeleton, templatePrompt: skeleton }), /先把引号里换成你要讲的事/);
13
+ });
14
+
15
+ test('自由输入收进当前模板,并保留模板后半句', () => {
16
+ const got = optimizePrompt({ text: '古代人都想当皇帝', templatePrompt: skeleton });
17
+ assert.equal(
18
+ got.prompt,
19
+ '用灯火史话讲「古代人都想当皇帝」。火光里先给结论,再给一个能记住的细节,没有口播。',
20
+ );
21
+ });
22
+
23
+ test('改过引号后仍锁回模板句式', () => {
24
+ const got = optimizePrompt({
25
+ text: '用灯火史话讲「古代人都想当皇帝」。另外再讲科举和驿站。',
26
+ templatePrompt: skeleton,
27
+ });
28
+ assert.equal(got.prompt.includes('古代人都想当皇帝'), true);
29
+ assert.equal(got.prompt.includes('没有口播'), true);
30
+ assert.equal(got.prompt.includes('科举'), false);
31
+ });
32
+
33
+ test('没选模板时保留原文,不压成套话', () => {
34
+ const text = '飞机上为什么要开飞行模式。先讲信号会干扰导航,再说规定,最后说实际影响。';
35
+ const got = optimizePrompt({ text, narration: 'required' });
36
+ assert.equal(got.prompt, text);
37
+ assert.equal(got.kept, true);
38
+ });
39
+
40
+ test('模板句后面留下用户写的那一个细节', () => {
41
+ const got = optimizePrompt({
42
+ text: '用灯火史话讲「古代人都想当皇帝」。嘴里说一句想反,唐律也要流二千里。',
43
+ templatePrompt: skeleton,
44
+ });
45
+ assert.equal(got.prompt.includes('没有口播'), true);
46
+ assert.equal(got.prompt.includes('嘴里说一句想反,唐律也要流二千里'), true);
47
+ });
@@ -81,6 +81,7 @@ export function recipeView(recipe, extras = {}) {
81
81
  blurb: recipe?.blurb || '',
82
82
  narration: extras.narration || 'optional',
83
83
  attachment: extras.attachment || 'optional',
84
+ audio: extras.audio || '',
84
85
  hint: extras.hint || recipe?.blurb || '',
85
86
  };
86
87
  }
@@ -0,0 +1,149 @@
1
+ /** 把用户看到的中文提示词收成交给大模型的英文提示词。画风名保持原样,方便对上模板。 */
2
+
3
+ const REPLACEMENTS = [
4
+ [/there is no word of mouth/gi, 'no voiceover'],
5
+ [/no word of mouth/gi, 'no voiceover'],
6
+ [/word of mouth/gi, 'voiceover'],
7
+ [/no spoken words?/gi, 'no voiceover'],
8
+ [/without spoken words?/gi, 'no voiceover'],
9
+ [/no oral (?:broadcast|narration)/gi, 'no voiceover'],
10
+ [/without oral (?:broadcast|narration)/gi, 'with no voiceover'],
11
+ [/oral broadcast/gi, 'voiceover'],
12
+ [/there was no voiceover/gi, 'no voiceover'],
13
+ [/horizontal screen/gi, 'landscape frame'],
14
+ [/vertical screen/gi, 'portrait frame'],
15
+ ];
16
+
17
+ const SOURCE_FLAGS = [
18
+ [/没有口播|不要口播|无口播|没有旁白|不要旁白|无旁白|不依赖旁白|不要另起旁白|全程靠字幕/, 'No voiceover.'],
19
+ [/口播用你上传的录音|只用上传的录音/, 'Use the uploaded recording as the voiceover.'],
20
+ [/横屏/, 'Landscape frame.'],
21
+ [/竖屏/, 'Portrait frame.'],
22
+ [/中英字幕/, 'On-screen subtitles in Chinese and English.'],
23
+ [/必须的附件/, 'The required attachment is part of this film.'],
24
+ ];
25
+
26
+ export function filmLanguage(text) {
27
+ return /[\u4e00-\u9fff]/.test(String(text || '')) ? 'Chinese' : 'English';
28
+ }
29
+
30
+ export function audienceLine(text) {
31
+ const language = filmLanguage(text);
32
+ return `On-screen text and narration language: ${language}. Write the on-screen title and every spoken or written sentence in ${language}.`;
33
+ }
34
+
35
+ function enforceFlags(source, english) {
36
+ let out = polishEnglish(english);
37
+ for (const [pattern, sentence] of SOURCE_FLAGS) {
38
+ if (!pattern.test(source)) continue;
39
+ const key = sentence.replace(/\.$/, '').toLowerCase();
40
+ if (!out.toLowerCase().includes(key)) out = polishEnglish(`${out} ${sentence}`);
41
+ }
42
+ return out;
43
+ }
44
+
45
+ export async function modelTitle(title, source, englishBrief, fetchImpl = globalThis.fetch) {
46
+ const raw = String(title || '').trim();
47
+ const brief = String(englishBrief || '').trim();
48
+ if (raw && !/[\u4e00-\u9fff]/.test(raw)) return raw.slice(0, 120);
49
+ if ((!raw || String(source || '').trim().startsWith(raw)) && brief) {
50
+ const subject = brief.match(/Subject:\s*"([^"]+)"/);
51
+ if (subject && subject[1] && !/[\u4e00-\u9fff]/.test(subject[1])) return subject[1].replace(/[.。\s]+$/g, '').slice(0, 120);
52
+ const line = brief.replace(/^Use the [\s\S]+? style\.\s*/i, '').split('\n')[0].trim();
53
+ if (line && !/[\u4e00-\u9fff]/.test(line)) return line.slice(0, 120);
54
+ }
55
+ if (!raw) return 'Untitled';
56
+ const translated = await toEnglishPrompt(raw, fetchImpl);
57
+ return (translated || 'Untitled').slice(0, 120);
58
+ }
59
+
60
+ export function polishEnglish(text) {
61
+ let out = String(text || '');
62
+ for (const [pattern, to] of REPLACEMENTS) out = out.replace(pattern, to);
63
+ return out.replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim();
64
+ }
65
+
66
+ export function parseMyMemory(payload) {
67
+ const data = typeof payload === 'string' ? JSON.parse(payload) : payload;
68
+ if (!data || Number(data.responseStatus) >= 400) return '';
69
+ const text = data.responseData && data.responseData.translatedText;
70
+ if (!text || /MYMEMORY WARNING|QUERY LENGTH LIMIT/i.test(text)) return '';
71
+ return String(text)
72
+ .replace(/&quot;/g, '"')
73
+ .replace(/&#39;|&apos;/g, "'")
74
+ .replace(/&amp;/g, '&')
75
+ .replace(/&lt;/g, '<')
76
+ .replace(/&gt;/g, '>')
77
+ .trim();
78
+ }
79
+
80
+ function chunks(text) {
81
+ const parts = String(text || '').split(/(?<=[。!?!?\n])/);
82
+ const out = [];
83
+ let buf = '';
84
+ const push = (value) => {
85
+ const piece = value.trim();
86
+ if (piece) out.push(piece);
87
+ };
88
+ for (const part of parts) {
89
+ const next = buf + part;
90
+ if (Buffer.byteLength(next, 'utf8') > 420 && buf) {
91
+ push(buf);
92
+ buf = part;
93
+ } else {
94
+ buf = next;
95
+ }
96
+ }
97
+ push(buf);
98
+ return out.flatMap((piece) => {
99
+ if (Buffer.byteLength(piece, 'utf8') <= 420) return [piece];
100
+ const chars = [...piece];
101
+ const slices = [];
102
+ let current = '';
103
+ for (const char of chars) {
104
+ if (Buffer.byteLength(current + char, 'utf8') > 420) {
105
+ slices.push(current);
106
+ current = char;
107
+ } else current += char;
108
+ }
109
+ if (current) slices.push(current);
110
+ return slices;
111
+ });
112
+ }
113
+
114
+ async function translatePiece(text, fetchImpl) {
115
+ const pieces = [];
116
+ for (const piece of chunks(text)) {
117
+ if (!/[\u4e00-\u9fff]/.test(piece)) {
118
+ pieces.push(piece);
119
+ continue;
120
+ }
121
+ const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(piece)}&langpair=zh-CN|en`;
122
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(12000) });
123
+ if (!res.ok) throw new Error('英文提示词没有生成');
124
+ const english = polishEnglish(parseMyMemory(await res.json()));
125
+ if (!english || /[\u4e00-\u9fff]/.test(english)) throw new Error('英文提示词没有生成');
126
+ pieces.push(english);
127
+ }
128
+ const joined = polishEnglish(pieces.join(' '));
129
+ if (!joined) throw new Error('英文提示词没有生成');
130
+ return joined;
131
+ }
132
+
133
+ export async function toEnglishPrompt(text, fetchImpl = globalThis.fetch) {
134
+ const source = String(text || '').trim();
135
+ if (!source) return '';
136
+ if (!/[\u4e00-\u9fff]/.test(source)) return source;
137
+ const framed = source.match(/^用([\s\S]{1,40}?)讲「([^」]+)」\s*[。.]?\s*([\s\S]*)$/);
138
+ if (framed) {
139
+ const topicEn = (await translatePiece(framed[2], fetchImpl)).replace(/[.。\s]+$/g, '');
140
+ const tailEn = framed[3].trim() ? await translatePiece(framed[3], fetchImpl) : '';
141
+ return enforceFlags(source, `Use the ${framed[1].trim()} style. Subject: "${topicEn}".${tailEn ? ` ${tailEn}` : ''}`);
142
+ }
143
+ const ref = source.match(/^选\s*(ref\d+)\s*[。.]?\s*([\s\S]*)$/i);
144
+ if (ref) {
145
+ const body = ref[2].trim() ? await translatePiece(ref[2], fetchImpl) : '';
146
+ return enforceFlags(source, `Lock ${ref[1]}. ${body}`);
147
+ }
148
+ return enforceFlags(source, await translatePiece(source, fetchImpl));
149
+ }
@@ -0,0 +1,72 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { audienceLine, filmLanguage, modelTitle, parseMyMemory, polishEnglish, toEnglishPrompt } from './to-english-prompt.mjs';
4
+
5
+ test('已经是英文时不请求翻译', async () => {
6
+ let called = false;
7
+ const got = await toEnglishPrompt('Keep the sentences short.', async () => {
8
+ called = true;
9
+ return { ok: true, json: async () => ({}) };
10
+ });
11
+ assert.equal(got, 'Keep the sentences short.');
12
+ assert.equal(called, false);
13
+ });
14
+
15
+ test('模板句保留画风名,主题和后半句译成英文', async () => {
16
+ const fetchImpl = async (url) => {
17
+ const q = decodeURIComponent(url.split('q=')[1].split('&')[0]);
18
+ const translated = q.includes('古代人')
19
+ ? 'why everyone in antiquity wanted to be emperor'
20
+ : 'State the conclusion first in the firelight, then one memorable detail. No oral broadcast.';
21
+ return { ok: true, json: async () => ({ responseStatus: 200, responseData: { translatedText: translated } }) };
22
+ };
23
+ const got = await toEnglishPrompt(
24
+ '用灯火史话讲「古代人都想当皇帝」。火光里先给结论,再给一个能记住的细节,没有口播。',
25
+ fetchImpl,
26
+ );
27
+ assert.equal(got.includes('灯火史话'), true);
28
+ assert.equal(got.includes('why everyone in antiquity wanted to be emperor'), true);
29
+ assert.equal(got.includes('no voiceover'), true);
30
+ assert.equal(/[\u4e00-\u9fff]/.test(got.replace('灯火史话', '')), false);
31
+ });
32
+
33
+ test('口播被收成 voiceover', () => {
34
+ assert.equal(polishEnglish('There was no oral broadcast.'), 'no voiceover.');
35
+ assert.equal(polishEnglish('There is no word of mouth.'), 'no voiceover.');
36
+ });
37
+
38
+ test('原文里的没有口播,译文漏掉时也会补上', async () => {
39
+ const fetchImpl = async () => ({
40
+ ok: true,
41
+ json: async () => ({ responseStatus: 200, responseData: { translatedText: 'A short film about bees.' } }),
42
+ });
43
+ const got = await toEnglishPrompt('讲蜜蜂。没有口播。', fetchImpl);
44
+ assert.equal(got.includes('No voiceover.'), true);
45
+ });
46
+
47
+ test('片名从英文主题来,不再把中文原句交给模型', async () => {
48
+ let called = false;
49
+ const source = '用灯火史话讲「古代人都想当皇帝」。没有口播。';
50
+ const title = await modelTitle(
51
+ source.slice(0, 40),
52
+ source,
53
+ 'Use the 灯火史话 style. Subject: "why everyone wanted to be emperor". No voiceover.',
54
+ async () => {
55
+ called = true;
56
+ return { ok: true, json: async () => ({}) };
57
+ },
58
+ );
59
+ assert.equal(title, 'why everyone wanted to be emperor');
60
+ assert.equal(called, false);
61
+ });
62
+
63
+ test('解析翻译结果', () => {
64
+ assert.equal(parseMyMemory({ responseStatus: 200, responseData: { translatedText: 'Hello &amp; welcome' } }), 'Hello & welcome');
65
+ assert.equal(parseMyMemory({ responseStatus: 200, responseData: { translatedText: 'MYMEMORY WARNING: too long' } }), '');
66
+ });
67
+
68
+ test('成片语言跟着用户原文', () => {
69
+ assert.equal(filmLanguage('古代人都想当皇帝'), 'Chinese');
70
+ assert.equal(filmLanguage('airplane mode'), 'English');
71
+ assert.equal(audienceLine('古代人').includes('in Chinese'), true);
72
+ });