zziang commited on
Commit
50e9802
·
verified ·
1 Parent(s): 4fdeafe

Upload kaggle/director_lora_data.mjs with huggingface_hub

Browse files
Files changed (1) hide show
  1. kaggle/director_lora_data.mjs +439 -0
kaggle/director_lora_data.mjs ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Build and verify the director LoRA corpus against the LIVE browser protocol.
2
+ //
3
+ // The radio-script SFT set (kaggle/director_probe.py MODE=collect) teaches six
4
+ // lines of "开场:... / 叙述:...". The browser never asks for that. It asks for
5
+ // [memory] + [plan] + [continue]/[pause] + 0-3 spoken lines, and it parses the
6
+ // answer with director.js. Training on the radio format would teach the model
7
+ // to emit labels that cleanSpoken() then strips or throws away.
8
+ //
9
+ // So prompts come from the real Director class, and targets are accepted only
10
+ // if the real Director.parse() says they are clean. Same ruler on both sides.
11
+ //
12
+ // Usage (run locally, then push the outputs into the HF bundle):
13
+ // node kaggle/director_lora_data.mjs prompts --n 4000 --out kaggle/out/director_prompts.jsonl
14
+ // node kaggle/director_lora_data.mjs verify \
15
+ // --prompts kaggle/out/director_prompts.jsonl \
16
+ // --raw kaggle/out/director_raw.jsonl \
17
+ // --out kaggle/out/director_sft.jsonl
18
+ //
19
+ // `raw` is one JSON object per line: {"id": "...", "raw": "<model output>"}.
20
+ // The generator of `raw` (base self-sampling or a larger teacher) lives on
21
+ // Kaggle; this script only decides what is good enough to train on.
22
+
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ import { Director } from '../director.js';
27
+ import { STORIES, CHAT } from './director_lora_corpus.mjs';
28
+
29
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
30
+ const ROOT = path.resolve(HERE, '..');
31
+ const GENRES = JSON.parse(fs.readFileSync(path.join(ROOT, 'config/genres.json'), 'utf8')).genres;
32
+
33
+ const TOPICS = [
34
+ '雨夜的末班公交', '一家很老的唱片店', '海边的灯塔', '凌晨的便利店',
35
+ '搬家时翻出的旧照片', '楼下那棵一直没有开花的树', '深夜的收音机',
36
+ '一场没有下完的雨', '旧公寓的电梯', '凌晨四点的菜市场', '山顶的观景台',
37
+ '一个人的火锅店', '医院走廊的灯', '江边的长椅', '落了灰的钢琴',
38
+ '雨天的出租车', '深夜的洗衣房', '开在二楼的旧书店', '废弃的火车站',
39
+ '冬天的第一个霜降', '阳台上的那盆绿萝', '深夜的加油站', '清晨的面包房',
40
+ '海边的小旅馆', '老街的修表摊', '天台上的风', '没有寄出的信',
41
+ '一只总在窗边的猫', '雨停之后的马路', '深夜的游泳池', '断电的夜晚',
42
+ '巷子尽头的路灯', '夏天最后一场雨', '老式闹钟的指针', '凌晨的公交站',
43
+ '一条很长的隧道', '停电的电梯间', '小城的电影院', '合上的日记本',
44
+ '厨房里烧开的水', '旧毛衣的口袋', '修好的那盏台灯', '雪停后的清晨',
45
+ ];
46
+
47
+ const QUESTIONS = [
48
+ '外面还在下雨吗', '你为什么总放这首歌', '现在几点了',
49
+ '能说说海边吗', '你有没有想念过谁', '这封信后来寄出去了吗',
50
+ '灯怎么忽然暗了', '你是谁', '今天有点累', '睡不着',
51
+ '陪我说会儿话', '那个人后来回来了吗', '窗台上那盆花开了吗',
52
+ '你还记得那家旧书店吗', '外面的车声怎么停了', '这首歌叫什么名字',
53
+ '雨会下到天亮吗', '刚才那句话是什么意思', '你也听过钟声吗',
54
+ ];
55
+
56
+ // These flip Director state in app.js (NEW_STORY_RE / CONTINUE_STORY_RE /
57
+ // STOP_RE / RESUME_RE), so a plain chat prompt would be off-distribution.
58
+ const STATE_FLIP = /讲(?:个|一个|一段)?故事|说(?:个|一个|一段)?故事|睡前故事|换个故事|新故事|继续讲|接着讲|不要停|晚安|别说了|回到剧本|继续读|接着读|停一下/;
59
+ const PLAIN_QUESTIONS = QUESTIONS.filter((q) => !STATE_FLIP.test(q));
60
+
61
+ const STORY_OPENERS = [
62
+ '讲个故事吧', '说个故事', '来段睡前故事', '换个故事', '讲一个关于旧车站的故事',
63
+ ];
64
+
65
+ const PLAN_SETS = [
66
+ ['她在末班车站等一个不会来的人', '雨把时刻表泡得看不清', '一个卖花的老太太收摊',
67
+ '她替老太太拎起铁桶', '末班车终于亮着灯拐过街角'],
68
+ ['灯塔守夜人发现灯芯裂了', '他翻出三十年前的修理手册', '海面漂来一只空木箱',
69
+ '箱子里是一叠没寄出的信', '天亮前灯重新亮起来'],
70
+ ['旧书店在清仓', '男孩买到一本写满批注的书', '批注和他在同一页停住',
71
+ '他按书里的地址找过去', '门牌还在,人已经搬走很久'],
72
+ ['停电那晚整栋楼都醒了', '有人把蜡烛放在楼梯口', '邻居们第一次互相报名字',
73
+ '电来的那一刻谁都没动', '蜡烛一直留到烧完'],
74
+ ['修表摊的老匠人收了最后一个徒弟', '徒弟想换掉所有旧零件', '老匠人让他先听声音',
75
+ '第一只被修好的表走慢了两分钟', '他们决定不调回来'],
76
+ ];
77
+
78
+ const DOC_SNIPPET = '书页片段:《城与年》第七章\n'
79
+ + '雨季过去的第三天,河滩上留下许多细小的贝壳。她沿着水线慢慢走,'
80
+ + '鞋跟陷进湿沙里,每一步都发出很轻的声响。远处的摆渡人把船拴好,'
81
+ + '抬头��了一眼云,又低下头去。';
82
+
83
+ const SPOKEN_HISTORY = [
84
+ '灯亮起来的时候,站台只剩她一个。',
85
+ '她把伞收好,听见远处有车进站。',
86
+ '雨顺着棚檐滴下来,一滴一滴落在铁轨上。',
87
+ '卖花的老太太把最后一把白菊抱进怀里。',
88
+ '他翻过那页,纸角上还留着一小块水渍。',
89
+ '走廊尽头的窗没关严,风把窗帘推得轻轻晃。',
90
+ ];
91
+
92
+ function rng(seed) {
93
+ let s = seed >>> 0;
94
+ return () => {
95
+ s = (s * 1664525 + 1013904223) >>> 0;
96
+ return s / 4294967296;
97
+ };
98
+ }
99
+
100
+ function pick(r, arr) { return arr[Math.floor(r() * arr.length) % arr.length]; }
101
+
102
+ function newDirector(genre) {
103
+ const d = new Director({ genres: GENRES });
104
+ d.setGenre(genre);
105
+ return d;
106
+ }
107
+
108
+ function seedHistory(d, r, n = 3) {
109
+ for (let i = 0; i < n; i++) {
110
+ d.history.push({ role: i % 2 ? 'assistant' : 'user',
111
+ text: pick(r, i % 2 ? SPOKEN_HISTORY : PLAIN_QUESTIONS) });
112
+ }
113
+ d.memory = pick(r, [
114
+ '她在末班车站等人,雨还没停。',
115
+ '灯塔的灯芯裂了,守夜人正在翻旧手册。',
116
+ '旧书店清仓,男孩买到一本写满批注的书。',
117
+ ]);
118
+ }
119
+
120
+ function startStory(d, r, beat) {
121
+ d.beginStory();
122
+ d.program.plan = pick(r, PLAN_SETS);
123
+ d.program.planAsked = true;
124
+ d.program.beat = beat;
125
+ d.memory = `故事进行到第 ${beat + 1} 拍:${d.program.plan[Math.min(beat, 4)]}`;
126
+ seedHistory(d, r, 2 + Math.floor(r() * 3));
127
+ }
128
+
129
+ function storyFirst(d, r) {
130
+ d.beginStory();
131
+ return { userText: pick(r, STORY_OPENERS), autonomous: false };
132
+ }
133
+
134
+ // One build() per scenario. Each mutates a fresh Director into the state the
135
+ // app would be in, then returns the exact arguments Director.next() passes to
136
+ // messages().
137
+ const SCENES = [
138
+ { name: 'chat_idle', genre: 'sleep', weight: 14, max: 280,
139
+ build: (d, r) => { if (r() < 0.5) seedHistory(d, r); return { autonomous: true }; } },
140
+ { name: 'chat_question', genre: 'sleep', weight: 14, max: 280,
141
+ build: (d, r) => { if (r() < 0.6) seedHistory(d, r, 2);
142
+ return { userText: pick(r, PLAIN_QUESTIONS), autonomous: false }; } },
143
+ { name: 'chat_followup', genre: 'sleep', weight: 8, max: 280,
144
+ build: (d, r) => { seedHistory(d, r, 5); return { autonomous: true }; } },
145
+ { name: 'chat_strict', genre: 'sleep', weight: 6, max: 240,
146
+ build: (d, r) => { seedHistory(d, r, 2);
147
+ return { autonomous: true, strict: true }; } },
148
+ { name: 'story_plan', genre: 'story', weight: 10, max: 440,
149
+ build: storyFirst },
150
+ { name: 'story_beat', genre: 'story', weight: 16, max: 340,
151
+ build: (d, r) => { startStory(d, r, 1 + Math.floor(r() * 20));
152
+ return { autonomous: true }; } },
153
+ { name: 'story_continue', genre: 'story', weight: 8, max: 340,
154
+ build: (d, r) => { startStory(d, r, 2 + Math.floor(r() * 12));
155
+ return { userText: '继续讲', autonomous: false }; } },
156
+ { name: 'story_barge', genre: 'story', weight: 5, max: 340,
157
+ build: (d, r) => { startStory(d, r, 3 + Math.floor(r() * 10));
158
+ return { userText: pick(r, PLAIN_QUESTIONS), autonomous: false }; } },
159
+ { name: 'story_strict', genre: 'story', weight: 4, max: 240,
160
+ build: (d, r) => { startStory(d, r, 4 + Math.floor(r() * 8));
161
+ return { autonomous: true, strict: true }; } },
162
+ { name: 'document_idle', genre: 'sleep', weight: 5, max: 280,
163
+ build: (d, r) => { seedHistory(d, r, 2);
164
+ return { autonomous: true, extraContext: DOC_SNIPPET }; } },
165
+ { name: 'document_question', genre: 'sleep', weight: 5, max: 280,
166
+ build: (d, r) => { seedHistory(d, r, 2);
167
+ return { userText: pick(r, PLAIN_QUESTIONS), autonomous: false,
168
+ extraContext: DOC_SNIPPET }; } },
169
+ { name: 'document_resume', genre: 'sleep', weight: 5, max: 280,
170
+ build: (d, r) => { seedHistory(d, r, 3);
171
+ return { userText: '回到剧本', autonomous: false,
172
+ extraContext: `你在朗读《城与年》。\n${DOC_SNIPPET}` }; } },
173
+ ];
174
+
175
+ function arg(name, fallback) {
176
+ const i = process.argv.indexOf(`--${name}`);
177
+ return i > 0 ? process.argv[i + 1] : fallback;
178
+ }
179
+
180
+ function readJsonl(file) {
181
+ return fs.readFileSync(file, 'utf8').split('\n')
182
+ .filter((l) => l.trim()).map((l) => JSON.parse(l));
183
+ }
184
+
185
+ function writeJsonl(file, rows) {
186
+ fs.mkdirSync(path.dirname(file), { recursive: true });
187
+ fs.writeFileSync(file, rows.map((r) => JSON.stringify(r, null, 0)).join('\n') + '\n');
188
+ }
189
+
190
+ function prompts() {
191
+ const n = Number(arg('n', 4000));
192
+ const seed = Number(arg('seed', 20261106));
193
+ const out = arg('out', path.join(HERE, 'out', 'director_prompts.jsonl'));
194
+ const r = rng(seed);
195
+ const total = SCENES.reduce((s, x) => s + x.weight, 0);
196
+ const rows = [];
197
+ const counts = {};
198
+ for (let i = 0; i < n; i++) {
199
+ let t = r() * total, s = SCENES[0];
200
+ for (const cand of SCENES) { t -= cand.weight; if (t <= 0) { s = cand; break; } }
201
+ const d = newDirector(s.genre);
202
+ const opts = s.build(d, r);
203
+ const messages = d.messages(opts);
204
+ counts[s.name] = (counts[s.name] || 0) + 1;
205
+ rows.push({
206
+ id: `d${String(i).padStart(5, '0')}`,
207
+ kind: s.name,
208
+ genre: s.genre,
209
+ beat: d.program.beat,
210
+ plan_wanted: d.wantsPlan(),
211
+ max_new_tokens: s.max,
212
+ messages,
213
+ });
214
+ }
215
+ writeJsonl(out, rows);
216
+ console.log(`wrote ${rows.length} prompts -> ${out}`);
217
+ console.log(counts);
218
+ }
219
+
220
+ // Strict on purpose. cleanSpoken() in the app repairs dirty output at playback
221
+ // time; a training target must NOT need that repair, or the model learns to
222
+ // rely on it and the dirty-format rate goes up instead of down.
223
+ const DIRTY = /```|\|.*\||^\s*[-*#>]|你[::]|用户[::]|旁白[::]|叙述者[::]|作为\s*AI|<\|[^|>]*\|>|([^)]*)|\([^)]*\)|(?:用户|对话|会话|节目)(?:已|结束)/m;
224
+
225
+ function judge(prompt, raw) {
226
+ const d = newDirector(prompt.genre);
227
+ // llm.worker.js decodes with skip_special_tokens:false, Kaggle samplers do
228
+ // not. Drop chat markers at the edges; the trainer appends EOS itself.
229
+ const text = String(raw || '').replace(/<\|[^|>]*\|>/g, ' ').trim();
230
+ const p = d.parse(text, d.maxChars());
231
+ const bad = [];
232
+ const strict = prompt.kind.endsWith('_strict');
233
+ if (!text) bad.push('empty');
234
+ if (!p.lines.length) bad.push('no_lines');
235
+ if (p.lines.length > 3) bad.push('too_many_lines');
236
+ if (p.pause) bad.push('early_pause');
237
+ if (!strict && !p.memory) bad.push('no_memory');
238
+ else if (p.memory && !d.goodMemory(p.memory)) bad.push('meta_memory');
239
+ if (!strict && !p.explicitContinue) bad.push('no_control');
240
+ if (strict && /\[(?:memory|continue|pause|plan)\]/i.test(text)) bad.push('strict_has_tags');
241
+ if (prompt.plan_wanted && p.plan.length < 5) bad.push('missing_plan');
242
+ if (DIRTY.test(text)) bad.push('dirty');
243
+ if (/[\u4e00-\u9fff]/.test(text) === false) bad.push('not_chinese');
244
+ if (/[A-Za-z0-9]/.test(p.lines.join(''))) bad.push('latin_or_digit');
245
+ const keys = p.lines.map((s) => s.replace(/[\s,,。!?!?、;;…::]/g, ''));
246
+ if (new Set(keys).size !== keys.length) bad.push('repeated_line');
247
+ for (const line of p.lines) {
248
+ if (line.length > d.maxChars() + 2) bad.push('long_line');
249
+ }
250
+ return { bad, parsed: p, text };
251
+ }
252
+
253
+ function verify() {
254
+ const promptsFile = arg('prompts', path.join(HERE, 'out', 'director_prompts.jsonl'));
255
+ const rawFile = arg('raw', path.join(HERE, 'out', 'director_raw.jsonl'));
256
+ const out = arg('out', path.join(HERE, 'out', 'director_sft.jsonl'));
257
+ const allPrompts = readJsonl(promptsFile);
258
+ const byId = new Map(allPrompts.map((p) => [p.id, p]));
259
+ const raws = readJsonl(rawFile);
260
+ const kept = [];
261
+ const seenResponse = new Set();
262
+ const reasons = {};
263
+ const dedup = process.argv.includes('--dedup');
264
+ let missing = 0, dupes = 0;
265
+ for (const row of raws) {
266
+ const prompt = byId.get(row.id);
267
+ if (!prompt) { missing++; continue; }
268
+ const { bad, text } = judge(prompt, row.raw);
269
+ if (bad.length) {
270
+ for (const b of bad) reasons[b] = (reasons[b] || 0) + 1;
271
+ continue;
272
+ }
273
+ if (dedup && seenResponse.has(text)) { dupes++; continue; }
274
+ seenResponse.add(text);
275
+ kept.push({ id: row.id, kind: prompt.kind, genre: prompt.genre,
276
+ messages: prompt.messages,
277
+ response: text });
278
+ }
279
+ let final = kept;
280
+ const target = Number(arg('target', 0));
281
+ if (target > 0) {
282
+ const kindCount = {};
283
+ for (const p of allPrompts) kindCount[p.kind] = (kindCount[p.kind] || 0) + 1;
284
+ const groups = {};
285
+ for (const row of kept) (groups[row.kind] ||= []).push(row);
286
+ final = [];
287
+ for (const [kind, rows] of Object.entries(groups)) {
288
+ const quota = Math.max(1, Math.round(target * (kindCount[kind] || 0) / allPrompts.length));
289
+ final.push(...rows.slice(0, quota));
290
+ }
291
+ const sr = rng(Number(arg('seed', 20261107)));
292
+ for (let i = final.length - 1; i > 0; i--) {
293
+ const j = Math.floor(sr() * (i + 1));
294
+ [final[i], final[j]] = [final[j], final[i]];
295
+ }
296
+ }
297
+ writeJsonl(out, final);
298
+ const finalKinds = {};
299
+ for (const row of final) finalKinds[row.kind] = (finalKinds[row.kind] || 0) + 1;
300
+ console.log(`kept ${final.length} (from ${raws.length} raw, ${kept.length} clean, ${dupes} dupes dropped, ${missing} missing id)`);
301
+ console.log('by kind', finalKinds);
302
+ if (Object.keys(reasons).length) console.log('rejects', reasons);
303
+ }
304
+
305
+ function findStory(sys) {
306
+ const m = sys.match(/计划:\n1\.\s*([^\n]+)/);
307
+ if (!m) return null;
308
+ return STORIES.find((s) => s.plan[0] === m[1].trim()) || null;
309
+ }
310
+
311
+ function pickVar(r, arr, k) { return arr[(Math.floor(r() * arr.length) + k) % arr.length]; }
312
+
313
+ // Free recombination at sentence level. Each sentence keeps the memory of the
314
+ // group it came from, so the [memory] line still matches the beat. For the
315
+ // question pool only group-opening sentences may lead the answer.
316
+ function pairsOf(pool, headed) {
317
+ return {
318
+ all: pool.flatMap((x) => x.lines.map((line, i) => ({
319
+ line, memory: x.memory, head: headed && i === 0,
320
+ }))),
321
+ heads: pool.map((x) => ({ line: x.lines[0], memory: x.memory, head: true })),
322
+ };
323
+ }
324
+
325
+ const CHAT_PAIRS = {
326
+ idle: pairsOf(CHAT.idle, false),
327
+ question: pairsOf(CHAT.question, true),
328
+ document: pairsOf(CHAT.document, false),
329
+ strict: pairsOf([...CHAT.idle, ...CHAT.question, ...CHAT.document,
330
+ ...CHAT.strict.map((lines) => ({ memory: '', lines }))], false),
331
+ };
332
+
333
+ function composeFree(r, pairSet, variant) {
334
+ const pool = pairSet.heads.length ? pairSet.heads : pairSet.all;
335
+ const i = Math.floor(r() * pool.length) + variant * 5;
336
+ const a = pool[i % pool.length];
337
+ const j = Math.floor(r() * pairSet.all.length) + variant * 11;
338
+ const c = pairSet.all[j % pairSet.all.length];
339
+ const lines = (variant % 5 === 4) ? [a.line]
340
+ : [...new Set([a.line, c.line])];
341
+ // Keep [memory] off the spoken line. Otherwise the model learns to write the
342
+ // state twice: once as a tag, once aloud as the first sentence.
343
+ const memPool = [...new Set(pairSet.all.map((x) => x.memory).filter(Boolean))];
344
+ let memory = a.memory;
345
+ for (let t = 0; t < 5 && memPool.length > 1; t++) {
346
+ const cand = memPool[(Math.floor(r() * memPool.length) + t) % memPool.length];
347
+ if (cand !== a.memory) { memory = cand; break; }
348
+ }
349
+ return { memory, lines };
350
+ }
351
+
352
+ function envelope(memory, lines) {
353
+ return `[memory] ${memory}\n[continue]\n${lines.join('\n')}`;
354
+ }
355
+
356
+ // Rebuild a beat from a three-beat window. Sentences stay in narrative order,
357
+ // but which ones land in this answer changes, so 2k rows do not collapse into
358
+ // a couple hundred memorised strings.
359
+ function storyWindow(s, idx) {
360
+ const out = [];
361
+ for (let j = idx - 1; j <= idx + 1; j++) {
362
+ out.push(s.beats[(j + s.beats.length) % s.beats.length]);
363
+ }
364
+ return out;
365
+ }
366
+
367
+ function composeWindow(r, items, variant) {
368
+ const pool = items.flatMap((x) => x.lines);
369
+ const count = 2 + (variant % 2);
370
+ const start = (Math.floor(r() * 3) + variant * 2) % (pool.length - count + 1);
371
+ const memory = items[(variant + 1) % items.length].memory;
372
+ return envelope(memory, pool.slice(start, start + count));
373
+ }
374
+
375
+ function responseFor(p, r, variant) {
376
+ const sys = p.messages[0].content;
377
+ if (p.kind.endsWith('_strict')) {
378
+ const c = composeFree(r, CHAT_PAIRS.strict, variant);
379
+ return c.lines.join('\n');
380
+ }
381
+ if (p.kind === 'story_plan') {
382
+ const s = pickVar(r, STORIES, variant);
383
+ const o = pickVar(r, s.openings, variant);
384
+ const pool = [...o.lines, ...storyWindow(s, variant % 3).flatMap((x) => x.lines)];
385
+ const start = (Math.floor(r() * 4) + variant) % (pool.length - 1);
386
+ const spoken = pool.slice(start, start + 2);
387
+ return `[memory] ${o.memory}\n${s.plan.map((x) => `[plan] ${x}`).join('\n')}\n`
388
+ + `[continue]\n${spoken.join('\n')}`;
389
+ }
390
+ if (p.kind.startsWith('story_')) {
391
+ const s = findStory(sys) || pickVar(r, STORIES, variant);
392
+ const m = sys.match(/第 (\d+) 拍/);
393
+ const beat = m ? Number(m[1]) : 2;
394
+ const idx = (Math.max(1, beat) - 1 + variant) % s.beats.length;
395
+ return composeWindow(r, storyWindow(s, idx), variant);
396
+ }
397
+ const pairSet = p.kind.startsWith('document_') ? CHAT_PAIRS.document
398
+ : p.kind === 'chat_question' ? CHAT_PAIRS.question : CHAT_PAIRS.idle;
399
+ const c = composeFree(r, pairSet, variant);
400
+ return envelope(c.memory, c.lines);
401
+ }
402
+
403
+ function assemble() {
404
+ const promptsFile = arg('prompts', path.join(HERE, 'out', 'director_prompts.jsonl'));
405
+ const out = arg('out', path.join(HERE, 'out', 'director_raw.jsonl'));
406
+ const seed = Number(arg('seed', 20261107));
407
+ const rows = readJsonl(promptsFile);
408
+ const r = rng(seed);
409
+ const seen = new Set();
410
+ const raws = [];
411
+ const rejects = {};
412
+ let accepted = 0;
413
+ for (const p of rows) {
414
+ let raw = '';
415
+ for (let k = 0; k < 10; k++) {
416
+ raw = responseFor(p, r, k);
417
+ if (!seen.has(raw)) break;
418
+ }
419
+ seen.add(raw);
420
+ const { bad } = judge(p, raw);
421
+ if (bad.length) for (const x of bad) rejects[x] = (rejects[x] || 0) + 1;
422
+ else accepted++;
423
+ raws.push({ id: p.id, raw });
424
+ }
425
+ writeJsonl(out, raws);
426
+ console.log(`assembled ${raws.length} responses -> ${out}`);
427
+ console.log(`unique ${seen.size} (${(seen.size / raws.length * 100).toFixed(1)}%)`);
428
+ console.log(`verify preview: ${accepted}/${raws.length} (${(accepted / raws.length * 100).toFixed(1)}%) would pass`);
429
+ if (Object.keys(rejects).length) console.log('rejects', rejects);
430
+ }
431
+
432
+ const cmd = process.argv[2];
433
+ if (cmd === 'prompts') prompts();
434
+ else if (cmd === 'assemble') assemble();
435
+ else if (cmd === 'verify') verify();
436
+ else {
437
+ console.log('usage: director_lora_data.mjs prompts|assemble|verify [--n --seed --out --prompts --raw]');
438
+ process.exit(1);
439
+ }