-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
421 lines (389 loc) · 15.5 KB
/
index.js
File metadata and controls
421 lines (389 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
const fs = require('fs');
const path = require('path');
const { loadLocalEnvFiles } = require('./env');
const { loadConfig } = require('./config');
const { loadSource } = require('./input');
const { buildStoryboardPrompt, parseStoryboardResponse } = require('./prompts');
const { sanitizeCanonicalStoryText } = require('./story-text');
const { generateTextWithProvider, generateImageWithProvider, supportsImageReferenceInput } = require('./providers');
const { composeComicSheet } = require('./compose');
const {
STYLE_REFERENCE_PROMPT_LINES,
PANEL_IMAGE_PROMPT_LINES,
NO_TEXT_RULE_BLOCK
} = require('./data/prompt-templates');
function isConsistencyEnabled(settings) {
const raw = settings && settings.consistency;
if (raw == null) return false;
if (typeof raw === 'boolean') return raw;
const v = String(raw).trim().toLowerCase();
return v === '1' || v === 'true' || v === 'yes' || v === 'on';
}
function buildStyleReferencePrompt(storyboard, settings) {
const title = String(storyboard?.title || 'Comic Summary').trim();
const summary = buildStorySummaryContext(storyboard);
const objective = String(settings?.objective || 'summarize').trim();
const objectiveDescription = String(settings?.objective_description || '').trim();
const objectiveName = String(settings?.objective_name || objective).trim();
const style = String(settings?.style_prompt || '').trim();
const styleDescription = String(settings?.style_description || style).trim();
const styleName = String(settings?.style_name || 'custom').trim();
const language = String(settings?.output_language || 'en').trim();
const detail = String(settings?.detail_level || 'low').trim();
const objectiveOverride = String(settings?.objective_prompt_overrides?.[objective] || '').trim();
const customStoryPrompt = String(settings?.custom_story_prompt || '').trim();
const customPanelPrompt = String(settings?.custom_panel_prompt || '').trim();
const out = [
STYLE_REFERENCE_PROMPT_LINES.intro,
`Story title: ${title}`,
`Story summary: ${summary || 'No summary provided.'}`,
`Objective: ${objective}`,
`Objective name: ${objectiveName}`,
objectiveDescription ? `Objective description: ${objectiveDescription}` : '',
`Style: ${style}`,
`Style name: ${styleName}`,
styleDescription ? `Style description: ${styleDescription}` : '',
`Output language: ${language}`,
`Detail level: ${detail}`,
STYLE_REFERENCE_PROMPT_LINES.sceneRule
].filter(Boolean);
if (objectiveOverride) {
out.push(`Objective-specific guidance: ${objectiveOverride}`);
}
if (customStoryPrompt) {
out.push(`Custom story guidance: ${customStoryPrompt}`);
}
if (customPanelPrompt) {
out.push(`Custom panel guidance: ${customPanelPrompt}`);
}
out.push(...NO_TEXT_RULE_BLOCK);
return out.join('\n');
}
function buildPanelImagePrompt(panel, index, total, settings, storyboard, opts = {}) {
const storySummary = buildStorySummaryContext(storyboard, panel);
const shortSummary = storySummary.length > 280 ? `${storySummary.slice(0, 280)}...` : storySummary;
const panelSpecificPrompt = String(panel?.image_prompt || '').trim();
const styleName = String(settings.style_name || 'custom').trim();
const styleDescription = String(settings.style_description || settings.style_prompt || '').trim();
const out = [
`Background: ${shortSummary || 'No summary provided.'}`,
`Image description: ${panelSpecificPrompt || panel.caption}`,
`Style: ${settings.style_prompt}`,
`Style name: ${styleName}`,
styleDescription ? `Style description: ${styleDescription}` : '',
PANEL_IMAGE_PROMPT_LINES.sceneRule,
...NO_TEXT_RULE_BLOCK
].filter(Boolean);
if (opts && opts.hasStyleReferenceImage) {
out.push(PANEL_IMAGE_PROMPT_LINES.styleLock1);
out.push(PANEL_IMAGE_PROMPT_LINES.styleLock2);
out.push(PANEL_IMAGE_PROMPT_LINES.styleLock3);
out.push(PANEL_IMAGE_PROMPT_LINES.styleLock4);
}
const customPanelPrompt = String(settings.custom_panel_prompt || '').trim();
if (customPanelPrompt) {
out.push(`Custom user panel prompt: ${customPanelPrompt}`);
}
return out.join('\n');
}
function detectImageKind(buffer) {
if (!Buffer.isBuffer(buffer) || buffer.length < 12) return '';
if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) return 'png';
if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) return 'jpeg';
if (buffer.slice(0, 6).toString('ascii') === 'GIF87a' || buffer.slice(0, 6).toString('ascii') === 'GIF89a') return 'gif';
if (
buffer.slice(0, 4).toString('ascii') === 'RIFF' &&
buffer.slice(8, 12).toString('ascii') === 'WEBP'
) return 'webp';
return '';
}
function validateGeneratedReferenceImage(image) {
if (!image || typeof image !== 'object') {
throw new Error('Consistency summary image is missing');
}
const buffer = image.buffer;
if (!Buffer.isBuffer(buffer) || !buffer.length) {
throw new Error('Consistency summary image buffer is empty');
}
const mimeType = String(image.mimeType || '').trim().toLowerCase();
if (!mimeType.startsWith('image/')) {
throw new Error(`Consistency summary image mime type is invalid: ${mimeType || 'unknown'}`);
}
const kind = detectImageKind(buffer);
if (!kind) {
throw new Error('Consistency summary image bytes are invalid (unknown image signature)');
}
return { kind, mimeType, bytes: buffer.length };
}
function buildStorySummaryContext(storyboard, panel = null) {
const explicit = String(storyboard?.description || '').trim().replace(/\s+/g, ' ');
if (explicit) return explicit;
const panelCaptions = Array.isArray(storyboard?.panels)
? storyboard.panels
.map((p) => String(p?.caption || '').trim())
.filter(Boolean)
.slice(0, 4)
: [];
if (panelCaptions.length) return panelCaptions.join(' ');
const panelCaption = String(panel?.caption || '').trim();
if (panelCaption) return panelCaption;
return 'No summary provided.';
}
async function generateConsistencyReferenceImage(config, storyboard) {
const consistencyOn = isConsistencyEnabled(config?.generation);
if (!consistencyOn) return { enabled: false, used: false, reason: 'disabled' };
if (!supportsImageReferenceInput(config?.providers?.image || {})) {
const provider = String(config?.providers?.image?.provider || 'unknown').trim().toLowerCase();
const model = String(config?.providers?.image?.model || 'unknown').trim();
throw new Error(
`Consistency is enabled, but image provider/model does not support reference images: ${provider}/${model}`
);
}
const prompt = buildStyleReferencePrompt(storyboard, config.generation || {});
const image = await withRetries(
() => generateImageWithProvider(config.providers.image, prompt, config.runtime),
config.runtime.retries,
'Consistency summary image'
);
validateGeneratedReferenceImage(image);
return { enabled: true, used: true, reason: 'ok', prompt, image };
}
async function mapWithConcurrency(items, concurrency, mapper) {
const out = new Array(items.length);
let idx = 0;
let active = 0;
return new Promise((resolve, reject) => {
const launch = () => {
if (idx >= items.length && active === 0) {
resolve(out);
return;
}
while (active < concurrency && idx < items.length) {
const current = idx;
idx += 1;
active += 1;
Promise.resolve(mapper(items[current], current))
.then((result) => {
out[current] = result;
active -= 1;
launch();
})
.catch((error) => reject(error));
}
};
launch();
});
}
async function withRetries(fn, retries, label) {
let lastError = null;
const attempts = Math.max(1, Number(retries || 0) + 1);
for (let i = 0; i < attempts; i += 1) {
try {
return await fn(i);
} catch (error) {
lastError = error;
if (i < attempts - 1) {
// Short backoff for throughput-oriented CLI.
await new Promise((r) => setTimeout(r, 250 + (i * 200)));
}
}
}
throw new Error(`${label || 'Operation'} failed after ${attempts} attempts: ${lastError?.message || lastError}`);
}
async function generateStoryboardWithRetries(config, prompt, panelCount) {
let lastRawText = '';
const storyboard = await withRetries(
async () => {
const raw = await generateTextWithProvider(config.providers.text, prompt, config.runtime);
lastRawText = String(raw || '');
return parseStoryboardResponse(lastRawText, panelCount);
},
config.runtime.retries,
'Storyboard generation'
);
return { storyboard, storyboardRawText: lastRawText };
}
async function runComicEngine(options) {
const startedAt = Date.now();
const rootDir = options.rootDir || process.cwd();
loadLocalEnvFiles(rootDir);
const loaded = loadConfig(options.configPath);
const config = loaded.config;
const source = loadSource(options.inputPath, config.input);
const canonicalSourceText = sanitizeCanonicalStoryText(source.text, {
maxChars: Number(config?.input?.max_chars || 12000)
});
const effectiveTitle = String(options.titleOverride || source.title || 'Comic Summary');
const storyboardPrompt = buildStoryboardPrompt({
sourceTitle: effectiveTitle,
sourceLabel: source.sourceLabel,
sourceText: canonicalSourceText,
panelCount: config.generation.panel_count,
objective: config.generation.objective,
objectiveDescription: config.generation.objective_description,
stylePrompt: config.generation.style_prompt,
outputLanguage: config.generation.output_language,
objectivePromptOverride: config.generation?.objective_prompt_overrides?.[config.generation.objective],
customStoryPrompt: config.generation.custom_story_prompt
});
const generatedStoryboard = await generateStoryboardWithRetries(
config,
storyboardPrompt,
config.generation.panel_count
);
const storyboardRawText = generatedStoryboard.storyboardRawText;
const storyboard = generatedStoryboard.storyboard;
if (effectiveTitle) storyboard.title = effectiveTitle;
const consistencyRef = await generateConsistencyReferenceImage(config, storyboard);
const panelImages = await mapWithConcurrency(
storyboard.panels,
config.runtime.image_concurrency,
async (panel, index) => withRetries(
() => generateImageWithProvider(
config.providers.image,
buildPanelImagePrompt(panel, index, storyboard.panels.length, config.generation, storyboard, {
hasStyleReferenceImage: Boolean(consistencyRef.used)
}),
config.runtime,
consistencyRef.used ? { referenceImage: consistencyRef.image } : {}
),
config.runtime.retries,
`Panel image ${index + 1}`
)
);
const composed = await composeComicSheet({
storyboard,
panelImages,
source: source.sourceLabel,
outputConfig: config.output,
outputPath: options.outputPath
});
const result = {
configPath: loaded.path,
inputPath: source.inputPath,
outputPath: composed.outputPath,
storyboardTitle: storyboard.title,
panelCount: storyboard.panels.length,
imageBytes: composed.bytes,
width: composed.width,
height: composed.height,
elapsedMs: Date.now() - startedAt,
consistency: {
enabled: Boolean(consistencyRef.enabled),
used: Boolean(consistencyRef.used),
reason: String(consistencyRef.reason || '')
}
};
if (options.debugDir) {
const debugDir = path.resolve(options.debugDir);
fs.mkdirSync(debugDir, { recursive: true });
fs.writeFileSync(path.join(debugDir, 'storyboard.raw.txt'), storyboardRawText, 'utf8');
fs.writeFileSync(path.join(debugDir, 'storyboard.json'), JSON.stringify(storyboard, null, 2), 'utf8');
fs.writeFileSync(path.join(debugDir, 'result.json'), JSON.stringify(result, null, 2), 'utf8');
}
return result;
}
async function runComicEnginePanels(options) {
const startedAt = Date.now();
const rootDir = options.rootDir || process.cwd();
loadLocalEnvFiles(rootDir);
const loaded = loadConfig(options.configPath);
const config = loaded.config;
const source = loadSource(options.inputPath, config.input);
const canonicalSourceText = sanitizeCanonicalStoryText(source.text, {
maxChars: Number(config?.input?.max_chars || 12000)
});
const effectiveTitle = String(options.titleOverride || source.title || 'Comic Summary');
const storyboardPrompt = buildStoryboardPrompt({
sourceTitle: effectiveTitle,
sourceLabel: source.sourceLabel,
sourceText: canonicalSourceText,
panelCount: config.generation.panel_count,
objective: config.generation.objective,
objectiveDescription: config.generation.objective_description,
stylePrompt: config.generation.style_prompt,
outputLanguage: config.generation.output_language,
objectivePromptOverride: config.generation?.objective_prompt_overrides?.[config.generation.objective],
customStoryPrompt: config.generation.custom_story_prompt
});
const generatedStoryboard = await generateStoryboardWithRetries(
config,
storyboardPrompt,
config.generation.panel_count
);
const storyboardRawText = generatedStoryboard.storyboardRawText;
const storyboard = generatedStoryboard.storyboard;
if (effectiveTitle) storyboard.title = effectiveTitle;
const consistencyRef = await generateConsistencyReferenceImage(config, storyboard);
const panelImages = await mapWithConcurrency(
storyboard.panels,
config.runtime.image_concurrency,
async (panel, index) => {
const imagePrompt = buildPanelImagePrompt(panel, index, storyboard.panels.length, config.generation, storyboard, {
hasStyleReferenceImage: Boolean(consistencyRef.used)
});
const image = await withRetries(
() => generateImageWithProvider(
config.providers.image,
imagePrompt,
config.runtime,
consistencyRef.used ? { referenceImage: consistencyRef.image } : {}
),
config.runtime.retries,
`Panel image ${index + 1}`
);
if (typeof options.onPanelReady === 'function') {
await options.onPanelReady({
index,
total: storyboard.panels.length,
panel,
imagePrompt,
image
});
}
return image;
}
);
const result = {
configPath: loaded.path,
inputPath: source.inputPath,
storyboardTitle: storyboard.title,
panelCount: storyboard.panels.length,
elapsedMs: Date.now() - startedAt,
storyboard,
panelImages,
consistency: {
enabled: Boolean(consistencyRef.enabled),
used: Boolean(consistencyRef.used),
reason: String(consistencyRef.reason || '')
},
consistencyReferenceImage: consistencyRef.used ? consistencyRef.image : null
};
if (options.debugDir) {
const debugDir = path.resolve(options.debugDir);
fs.mkdirSync(debugDir, { recursive: true });
fs.writeFileSync(path.join(debugDir, 'storyboard.raw.txt'), storyboardRawText, 'utf8');
fs.writeFileSync(path.join(debugDir, 'storyboard.json'), JSON.stringify(storyboard, null, 2), 'utf8');
fs.writeFileSync(path.join(debugDir, 'result.panels.json'), JSON.stringify({
configPath: result.configPath,
inputPath: result.inputPath,
panelCount: result.panelCount,
elapsedMs: result.elapsedMs
}, null, 2), 'utf8');
}
return result;
}
module.exports = {
runComicEngine,
runComicEnginePanels,
isConsistencyEnabled,
buildStyleReferencePrompt,
buildStorySummaryContext,
generateConsistencyReferenceImage,
validateGeneratedReferenceImage,
buildPanelImagePrompt,
mapWithConcurrency,
withRetries,
generateStoryboardWithRetries,
sanitizeCanonicalStoryText
};