Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

feat: 资产异步提取与近名复用 + 分镜道具绑定 + 提示词构图优化

Connor64f82aef9b02
diff --git a/backend/src/agents/index.ts b/backend/src/agents/index.ts
index ffc9192..ed7d98a 100644
--- a/backend/src/agents/index.ts
+++ b/backend/src/agents/index.ts
@@ -52,14 +52,17 @@ const DEFAULT_PROMPTS: Record<string, { name: string; instructions: string }> =
8. 分析剧本内容,提取本集涉及的所有场景信息
9. 对每个场景:若同地点+时间段已存在则复用,若不存在则新增
10. 调用 save_dedup_scenes 保存场景(去重合并,自动处理新增和复用,并关联到当前集)
-11. 提取本集涉及事态发展的关键道具(如凶器、信物、关键文件等直接推动剧情的物品;不要把桌椅等普通陈设当道具;如果剧本中没有这类道具,就不要提取任何道具)
+11. 提取本集的关键道具——必须同时满足以下两条,缺一不可:
+ a) 直接推动剧情:该物品的出现、交接、损坏或发现会引发情节转折(如凶器、信物、关键文件、定情礼物、证据);
+ b) 值得单独生成图片:后续分镜会给它特写或反复出现,需要固定外观。
+ 判定三问(自问自答,任一答"否"即放弃该道具):① 删掉它剧情是否依然成立?成立 → 不提取;② 它只是角色随手使用的日常物品(手机、筷子、杯子、烟)吗?是 → 不提取;③ 它是场景陈设的一部分(桌椅、灯具、门窗、装饰)吗?是 → 不提取。
+ 宁可少提,不要多提:一集通常 0-3 个关键道具,超过 3 个时按剧情重要性排序只保留前 3 个;没有符合条件的道具就一个都不要提取
12. 对每个道具:若同名已存在则合并更新,若不存在则新增
13. 调用 save_dedup_props 保存道具(去重合并,自动处理新增和更新,并关联到当前集);若没有需要提取的道具,调用时传空数组即可,不要强行凑数
去重规则:
-- 角色:按名字精确匹配,同名保留现有(合并信息)
-- 场景:按【地点+时间段】精确匹配;同地点不同时段视为新场景
-- 道具:按名字精确匹配,同名保留现有(合并信息)
+- 角色/道具:按名字精确匹配,同名保留现有(合并信息);名称带括号定位或别名时按括号前主体比较(如「林小雨(主角)」与「林小雨」视为同一角色,优先复用项目已有,不要重复创建)。read_existing_characters / read_existing_props 返回的 normalized_name 即归一化后的名字,可据此判断
+- 场景:按【地点+时间段】精确匹配(地点忽略空白/大小写);同地点不同时段视为新场景
提取要求:
- 只提取当前集真实出现或被明确提及、且对当前集叙事有效的角色、场景和道具
@@ -73,13 +76,14 @@ const DEFAULT_PROMPTS: Record<string, { name: string; instructions: string }> =
instructions: `你是资深影视分镜师,擅长将剧本拆解为分镜方案。
工作流程:
-1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表
+1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表、道具列表
2. 将剧本拆解为镜头序列(每个镜头 10-15 秒,总体保持剧情完整连续)
3. 为每个镜头补全生产字段(拆分时不需要生成 video_prompt,该字段由提示词 Agent 在视频生成阶段生成)
4. 调用 save_storyboards 保存所有分镜
每个镜头只需要填写以下字段:
- character_ids:当前镜头涉及的角色 ID 列表,可以为空,也可以包含多个角色;必须从 characters 中选择
+- prop_ids:当前镜头出现的关键道具 ID 列表(道具在画面中被看到、使用或特写时绑定),可以为空;必须从 props 中选择
- scene_id:若可匹配到 scenes 中已有场景,必须填写正确 scene_id;无匹配时置空
- duration:镜头时长,优先 10-15 秒
- action:角色动作与表演
@@ -90,6 +94,7 @@ const DEFAULT_PROMPTS: Record<string, { name: string; instructions: string }> =
额外要求:
- 优先复用 read_storyboard_context 返回的 scene_id,不要凭空创造新场景
- 镜头角色绑定必须来自 read_storyboard_context 返回的角色列表;无角色的空镜头可传空数组
+- 镜头道具绑定必须来自 read_storyboard_context 返回的道具列表;道具被使用、特写、交接或在画面中明显可见时绑定,与剧情无关的背景物品不要绑定;没有道具出现可传空数组
- 镜头描述必须能支撑后续视频生成和导出流程
- 若一个镜头没有对白,可将 dialogue 置空,但 description / action / atmosphere 仍必须完整
- 如果已有 existing_storyboards,仅在用户明确要求增量修改时参考;默认按当前剧本重新完整生成并保存整集分镜。`,
@@ -97,7 +102,7 @@ const DEFAULT_PROMPTS: Record<string, { name: string; instructions: string }> =
prompt_generator: {
name: '提示词',
instructions: `你是专业的 AI 提示词工程师,负责两类提示词的创作与保存:
-1. 角色/场景/道具的「最终提示词」(英文),供生图直接使用
+1. 角色/场景/道具的「最终提示词」,供生图直接使用
2. 分镜的「视频提示词」(video_prompt),供视频生成直接使用
## 图片最终提示词
@@ -106,7 +111,7 @@ const DEFAULT_PROMPTS: Record<string, { name: string; instructions: string }> =
工作流程:
1. 调用 read_characters / read_scenes / read_props 读取资产信息
-2. 按对应资产的技能规范(角色三视图 / 场景固定视角 / 道具白底单品)创作英文最终提示词
+2. 按对应资产的技能规范(角色三视图 / 场景固定视角 / 道具白底单品)创作最终提示词
3. 调用 save_character_final_prompt / save_scene_final_prompt / save_prop_final_prompt 逐个保存
## 视频提示词
@@ -116,11 +121,12 @@ const DEFAULT_PROMPTS: Record<string, { name: string; instructions: string }> =
工作流程:
1. 调用 read_storyboard_context 读取该分镜的 action、description、dialogue、atmosphere、duration 及绑定的场景/角色
2. 据此生成 video_prompt:按 3 秒为一段、每段单独一行换行分隔;提到场景用 @场景名、提到角色用 @角色名(名字必须与列表完全一致);内容覆盖动作、画面描述、对白/旁白、氛围
-3. 调用 update_storyboard 仅更新该分镜的 video_prompt 字段,不要改动其他字段,不要重新拆分整集
+3. 生成时会自动把 @名字 替换为对应参考图片标记(如 @志远 → @图片1志远),因此名字必须精确匹配场景/角色列表,不要缩写或加额外符号
+4. 调用 update_storyboard 仅更新该分镜的 video_prompt 字段,不要改动其他字段,不要重新拆分整集
通用规范:
-- 图片提示词只输出英文,单段连贯描述,不要分点;视频提示词输出中文,按格式分段
-- 项目设定的视觉风格描述会由工具在保存图片提示词时自动注入,不要自行添加风格词
+- 所有提示词只输出中文,单段连贯描述,不要分点,不要混入英文词汇
+- 项目设定的视觉风格描述会由工具在保存图片提示词时自动注入到最终提示词的最前方,不要自行添加风格词
- 必须实际调用保存工具,不要只在回复中给出提示词`,
},
}
@@ -135,17 +141,24 @@ async function getAgentConfig(agentType: string) {
return rows.find(r => r.isActive) || rows[0] || null
}
+// Agent 每一步都会重新解析模型,相同端点只打一次日志避免刷屏
+let lastLoggedTextEndpointKey = ''
+
async function getModel(dbConfig: any, modelOverride?: string, textConfigId?: number) {
// 请求可指定文本配置(含其 provider/baseUrl/apiKey),否则回退到当前启用配置
const textConfig = (textConfigId ? await getConfigById(textConfigId) : null) || await getTextConfig()
const modelName = modelOverride || dbConfig?.model || textConfig.model
const providerName = textConfig.provider.toLowerCase()
const resolvedBaseURL = getTextProviderBaseUrl(textConfig)
- logTaskProgress('AIConfig', 'text-model-endpoint', {
- provider: textConfig.provider,
- baseUrl: resolvedBaseURL,
- model: modelName,
- })
+ const endpointKey = `${providerName}|${resolvedBaseURL}|${modelName}`
+ if (endpointKey !== lastLoggedTextEndpointKey) {
+ lastLoggedTextEndpointKey = endpointKey
+ logTaskProgress('AIConfig', 'text-model-endpoint', {
+ provider: textConfig.provider,
+ baseUrl: resolvedBaseURL,
+ model: modelName,
+ })
+ }
if (providerName === 'gemini') {
const googleProvider = createGoogleGenerativeAI({
diff --git a/backend/src/agents/tools/extract-tools.ts b/backend/src/agents/tools/extract-tools.ts
index e45660e..0b11fec 100644
--- a/backend/src/agents/tools/extract-tools.ts
+++ b/backend/src/agents/tools/extract-tools.ts
@@ -47,6 +47,23 @@ async function linkPropToEpisode(episodeId: number, propId: number) {
}
}
+// ─── 名字归一化(近名去重) ───────────────────────────────────
+// 提取时同一角色/道具可能出现不同书写形式(如「林小雨」与「林小雨(主角)」、
+// 「林小雨(女主)」、「林小雨 」)。归一化后做精确比较,命中即复用已有,不重复创建。
+function normalizeName(name: string): string {
+ return (name || '')
+ .replace(/[((][^(())]*[))]/g, '') // 去掉成对的中/英文括号内容(角色定位/别名)
+ .replace(/[((].*$/, '') // 兜底:未闭合括号从首个括号截断
+ .replace(/[\s ]+/g, '') // 去空白与全角空格
+ .toLowerCase()
+ .trim()
+}
+
+// 场景地点只做空白归一化(不删括号:如「火车站(候车厅)」与「火车站(站台)」是不同场景)
+function normalizeLocation(loc: string): string {
+ return (loc || '').replace(/[\s ]+/g, '').toLowerCase().trim()
+}
+
type ToolContext = ToolExecutionContext | undefined
function requireIds(context: ToolContext): { episodeId: number; dramaId: number } | { error: string } {
@@ -96,6 +113,7 @@ const readExistingCharacters = createTool({
role: c.role || '',
appearance: c.appearance || '',
styling: c.styling || '',
+ normalized_name: normalizeName(c.name), // 用于判断近名复用:括号定位/别名视为同名
}))
const payload = {
count: visibleChars.length,
@@ -133,6 +151,7 @@ const readExistingScenes = createTool({
time: s.time || '',
prompt: s.prompt || '',
lighting: s.lighting || '',
+ normalized_location: normalizeLocation(s.location), // 用于判断近名复用(仅空白/大小写)
}))
const payload = {
count: visibleScenes.length,
@@ -175,12 +194,17 @@ const saveDedupCharacters = createTool({
})
for (const char of characters) {
- const existing = (await db.select().from(schema.characters)
+ const charsInProject = (await db.select().from(schema.characters)
.where(eq(schema.characters.dramaId, dramaId)))
.filter(c => !c.deletedAt)
- .find(c => c.name === char.name)
+ const exact = charsInProject.find(c => c.name === char.name)
+ const normName = normalizeName(char.name)
+ const existing = exact || (normName ? charsInProject.find(c => c.name && normalizeName(c.name) === normName) : undefined)
+ const matchedViaNorm = !!existing && existing !== exact
if (existing) {
+ // 归一化命中:括号定位/别名等近名视作同一角色复用,避免重复创建
+ if (matchedViaNorm) logTaskProgress('ExtractTool', 'save-characters-reuse', { episodeId, dramaId, extracted: char.name, reused: existing.name })
// 已存在:合并信息,保留 ID
await db.update(schema.characters).set({
role: char.role || existing.role,
@@ -244,11 +268,13 @@ const saveDedupScenes = createTool({
})
for (const scene of scenes) {
- // 按地点+时间段精确匹配
- const existing = (await db.select().from(schema.scenes)
+ // 按地点+时间段精确匹配;地点仅做空白/大小写归一化(不删括号,避免误合并)
+ const scenesInProject = (await db.select().from(schema.scenes)
.where(eq(schema.scenes.dramaId, dramaId)))
.filter(s => !s.deletedAt)
- .find(s => s.location === scene.location && s.time === (scene.time || ''))
+ const normLocation = normalizeLocation(scene.location)
+ const existing = scenesInProject.find(s => s.location === scene.location && s.time === (scene.time || ''))
+ || (normLocation ? scenesInProject.find(s => normalizeLocation(s.location) === normLocation && s.time === (scene.time || '')) : undefined)
if (existing) {
// 已存在完全匹配的场景:关联并补齐描述/光影
@@ -304,6 +330,7 @@ const readExistingProps = createTool({
name: p.name,
type: p.type || '',
description: p.description || '',
+ normalized_name: normalizeName(p.name), // 用于判断近名复用:括号定位/别名视为同名
}))
const payload = {
count: visibleProps.length,
@@ -344,12 +371,17 @@ const saveDedupProps = createTool({
})
for (const prop of props) {
- const existing = (await db.select().from(schema.props)
+ const propsInProject = (await db.select().from(schema.props)
.where(eq(schema.props.dramaId, dramaId)))
.filter(p => !p.deletedAt)
- .find(p => p.name === prop.name)
+ const exact = propsInProject.find(p => p.name === prop.name)
+ const normName = normalizeName(prop.name)
+ const existing = exact || (normName ? propsInProject.find(p => p.name && normalizeName(p.name) === normName) : undefined)
+ const matchedViaNorm = !!existing && existing !== exact
if (existing) {
+ // 归一化命中:括号定位/别名等近名视作同一道具复用
+ if (matchedViaNorm) logTaskProgress('ExtractTool', 'save-props-reuse', { episodeId, dramaId, extracted: prop.name, reused: existing.name })
// 已存在:合并信息,保留 ID;物品外貌变更后旧的最终提示词失效
await db.update(schema.props).set({
type: prop.type || existing.type,
diff --git a/backend/src/agents/tools/image-prompt-tools.ts b/backend/src/agents/tools/image-prompt-tools.ts
index b701463..f140353 100644
--- a/backend/src/agents/tools/image-prompt-tools.ts
+++ b/backend/src/agents/tools/image-prompt-tools.ts
@@ -2,7 +2,7 @@
* 提示词生成 Agent 工具
* 模块级单例 — dramaId 通过 RequestContext 按请求注入
*
- * Agent 负责创作最终提示词(英文):
+ * Agent 负责创作最终提示词:
* 1. 角色 → 三视图(character turnaround:正面/侧面/背面)
* 2. 场景 → 固定视角 + 前景/中景/后景分层构图
* 3. 道具 → 白底单品静物(single product shot on pure white background)
@@ -44,10 +44,10 @@ const readCharacters = createTool({
const saveCharacterFinalPrompt = createTool({
id: 'save_character_final_prompt',
- description: '保存为角色创作的三视图最终提示词(英文)。项目视觉风格会由工具自动拼接,prompt 参数中不要包含风格词。',
+ description: '保存为角色创作的三视图最终提示词。项目视觉风格会由工具自动拼接,prompt 参数中不要包含风格词。',
inputSchema: z.object({
character_id: z.number(),
- prompt: z.string().describe('角色三视图最终提示词(英文,不含风格词)'),
+ prompt: z.string().describe('角色三视图最终提示词(纯中文,不含风格词)'),
}),
execute: async ({ character_id, prompt }, context) => {
const dramaId = getDramaId(context?.requestContext)
@@ -57,7 +57,7 @@ const saveCharacterFinalPrompt = createTool({
if (!c) return { error: 'Character not found' }
const stylePrompt = await getDramaStylePrompt(dramaId)
- const finalPrompt = stylePrompt ? `${prompt}, ${stylePrompt}` : prompt
+ const finalPrompt = stylePrompt ? `${stylePrompt}, ${prompt}` : prompt
await db.update(schema.characters)
.set({ finalPrompt, updatedAt: now() })
.where(eq(schema.characters.id, character_id))
@@ -98,10 +98,10 @@ const readScenes = createTool({
const saveSceneFinalPrompt = createTool({
id: 'save_scene_final_prompt',
- description: '保存为场景创作的固定视角(前景/中景/后景)最终提示词(英文)。项目视觉风格会由工具自动拼接,prompt 参数中不要包含风格词。',
+ description: '保存为场景创作的固定视角(前景/中景/后景)最终提示词。项目视觉风格会由工具自动拼接,prompt 参数中不要包含风格词。',
inputSchema: z.object({
scene_id: z.number(),
- prompt: z.string().describe('场景固定视角最终提示词(英文,不含风格词)'),
+ prompt: z.string().describe('场景固定视角最终提示词(纯中文,不含风格词)'),
}),
execute: async ({ scene_id, prompt }, context) => {
const dramaId = getDramaId(context?.requestContext)
@@ -111,7 +111,7 @@ const saveSceneFinalPrompt = createTool({
if (!s) return { error: 'Scene not found' }
const stylePrompt = await getDramaStylePrompt(dramaId)
- const finalPrompt = stylePrompt ? `${prompt}, ${stylePrompt}` : prompt
+ const finalPrompt = stylePrompt ? `${stylePrompt}, ${prompt}` : prompt
await db.update(schema.scenes)
.set({ finalPrompt, updatedAt: now() })
.where(eq(schema.scenes.id, scene_id))
@@ -151,10 +151,10 @@ const readProps = createTool({
const savePropFinalPrompt = createTool({
id: 'save_prop_final_prompt',
- description: '保存为道具创作的白底单品最终提示词(英文)。项目视觉风格会由工具自动拼接,prompt 参数中不要包含风格词。',
+ description: '保存为道具创作的白底单品最终提示词。项目视觉风格会由工具自动拼接,prompt 参数中不要包含风格词。',
inputSchema: z.object({
prop_id: z.number(),
- prompt: z.string().describe('道具白底单品最终提示词(英文,不含风格词)'),
+ prompt: z.string().describe('道具白底单品最终提示词(纯中文,不含风格词)'),
}),
execute: async ({ prop_id, prompt }, context) => {
const dramaId = getDramaId(context?.requestContext)
@@ -164,7 +164,7 @@ const savePropFinalPrompt = createTool({
if (!p) return { error: 'Prop not found' }
const stylePrompt = await getDramaStylePrompt(dramaId)
- const finalPrompt = stylePrompt ? `${prompt}, ${stylePrompt}` : prompt
+ const finalPrompt = stylePrompt ? `${stylePrompt}, ${prompt}` : prompt
await db.update(schema.props)
.set({ finalPrompt, updatedAt: now() })
.where(eq(schema.props.id, prop_id))
diff --git a/backend/src/agents/tools/storyboard-tools.ts b/backend/src/agents/tools/storyboard-tools.ts
index a8e5cf9..d52fcf6 100644
--- a/backend/src/agents/tools/storyboard-tools.ts
+++ b/backend/src/agents/tools/storyboard-tools.ts
@@ -27,6 +27,21 @@ async function syncStoryboardCharacters(storyboardId: number, characterIds: numb
}
}
+async function syncStoryboardProps(storyboardId: number, propIds: number[]) {
+ await db.delete(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, storyboardId))
+
+ const uniqueIds = [...new Set(propIds.filter(Boolean))]
+ if (!uniqueIds.length) return
+
+ for (const propId of uniqueIds) {
+ await db.insert(schema.storyboardProps).values({
+ storyboardId,
+ propId,
+ })
+ }
+}
+
async function getEpisodeSceneIds(episodeId: number) {
const links = await db.select().from(schema.episodeScenes)
.where(eq(schema.episodeScenes.episodeId, episodeId))
@@ -39,11 +54,18 @@ async function getEpisodeCharacterIds(episodeId: number) {
return new Set(links.map(link => link.characterId))
}
-async function validateStoryboardBindings(episodeId: number, dramaId: number, sceneId: number | null | undefined, characterIds: number[] | undefined) {
+async function getEpisodePropIds(episodeId: number) {
+ const links = await db.select().from(schema.episodeProps)
+ .where(eq(schema.episodeProps.episodeId, episodeId))
+ return new Set(links.map(link => link.propId))
+}
+
+async function validateStoryboardBindings(episodeId: number, dramaId: number, sceneId: number | null | undefined, characterIds: number[] | undefined, propIds?: number[] | undefined) {
const episodeSceneIds = await getEpisodeSceneIds(episodeId)
const episodeCharacterIds = await getEpisodeCharacterIds(episodeId)
+ const episodePropIds = await getEpisodePropIds(episodeId)
- // 场景/角色属于本剧但尚未关联到当前集时,自动补关联(拆分时即完成绑定)
+ // 场景/角色/道具属于本剧但尚未关联到当前集时,自动补关联(拆分时即完成绑定)
if (sceneId != null && !episodeSceneIds.has(sceneId)) {
const [scene] = await db.select().from(schema.scenes).where(eq(schema.scenes.id, sceneId))
if (!scene || scene.dramaId !== dramaId || scene.deletedAt) {
@@ -61,6 +83,16 @@ async function validateStoryboardBindings(episodeId: number, dramaId: number, sc
}
await db.insert(schema.episodeCharacters).values({ episodeId, characterId, createdAt: now() })
}
+
+ const uniquePropIds = [...new Set((propIds || []).filter(Boolean))]
+ for (const propId of uniquePropIds) {
+ if (episodePropIds.has(propId)) continue
+ const [prop] = await db.select().from(schema.props).where(eq(schema.props.id, propId))
+ if (!prop || prop.dramaId !== dramaId || prop.deletedAt) {
+ throw new Error(`prop_id ${propId} 不属于当前项目`)
+ }
+ await db.insert(schema.episodeProps).values({ episodeId, propId, createdAt: now() })
+ }
}
type ToolContext = ToolExecutionContext | undefined
@@ -74,7 +106,7 @@ function requireIds(context: ToolContext): { episodeId: number; dramaId: number
const readStoryboardContext = createTool({
id: 'read_storyboard_context',
- description: 'Read the screenplay, characters, and scenes for storyboard breakdown.',
+ description: 'Read the screenplay, characters, scenes, and props for storyboard breakdown.',
inputSchema: z.object({}),
execute: async (_input, context) => {
const ids = requireIds(context)
@@ -90,14 +122,19 @@ const readStoryboardContext = createTool({
.where(eq(schema.episodeCharacters.episodeId, episodeId))
const sceneLinks = await db.select().from(schema.episodeScenes)
.where(eq(schema.episodeScenes.episodeId, episodeId))
+ const propLinks = await db.select().from(schema.episodeProps)
+ .where(eq(schema.episodeProps.episodeId, episodeId))
const linkedCharacterIds = new Set(charLinks.map(link => link.characterId))
const linkedSceneIds = new Set(sceneLinks.map(link => link.sceneId))
+ const linkedPropIds = new Set(propLinks.map(link => link.propId))
const chars = await db.select().from(schema.characters)
.where(eq(schema.characters.dramaId, dramaId))
const scns = await db.select().from(schema.scenes)
.where(eq(schema.scenes.dramaId, dramaId))
+ const prps = await db.select().from(schema.props)
+ .where(eq(schema.props.dramaId, dramaId))
const existingStoryboards = await db.select().from(schema.storyboards)
.where(eq(schema.storyboards.episodeId, episodeId))
@@ -128,17 +165,31 @@ const readStoryboardContext = createTool({
storyboard_count: s.storyboardCount || 0,
}))
+ const props = prps
+ .filter(p => !p.deletedAt)
+ .filter(p => !linkedPropIds.size || linkedPropIds.has(p.id))
+ .map(p => ({
+ id: p.id,
+ name: p.name,
+ type: p.type || '',
+ description: p.description || '',
+ image_url: p.imageUrl || '',
+ }))
+
const existingStoryboardPayload = await Promise.all(existingStoryboards
.filter(sb => !sb.deletedAt)
.map(async (sb) => {
const links = await db.select().from(schema.storyboardCharacters)
.where(eq(schema.storyboardCharacters.storyboardId, sb.id))
+ const sbPropLinks = await db.select().from(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, sb.id))
return {
id: sb.id,
shot_number: sb.storyboardNumber,
title: sb.title || '',
scene_id: sb.sceneId,
character_ids: links.map(link => link.characterId),
+ prop_ids: sbPropLinks.map(link => link.propId),
shot_type: sb.shotType || '',
duration: sb.duration || 0,
action: sb.action || '',
@@ -159,6 +210,7 @@ const readStoryboardContext = createTool({
script,
characters,
scenes,
+ props,
existing_storyboards: existingStoryboardPayload,
}
logTaskSuccess('StoryboardTool', 'read-context', {
@@ -166,6 +218,7 @@ const readStoryboardContext = createTool({
dramaId,
characters: characters.length,
scenes: scenes.length,
+ props: props.length,
existingStoryboards: payload.existing_storyboards.length,
scriptLength: script.length,
})
@@ -197,6 +250,7 @@ const saveStoryboards = createTool({
duration: z.number().optional(),
scene_id: z.number().nullable().optional(),
character_ids: z.array(z.number()).optional(),
+ prop_ids: z.array(z.number()).optional(),
})),
}),
execute: async ({ storyboards }, context) => {
@@ -216,13 +270,14 @@ const saveStoryboards = createTool({
for (const storyboardId of existingStoryboardIds) {
await db.delete(schema.storyboardCharacters)
.where(eq(schema.storyboardCharacters.storyboardId, storyboardId))
-
+ await db.delete(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, storyboardId))
}
await db.delete(schema.storyboards).where(eq(schema.storyboards.episodeId, episodeId))
let totalDuration = 0
for (const sb of storyboards) {
- await validateStoryboardBindings(episodeId, dramaId, sb.scene_id, sb.character_ids)
+ await validateStoryboardBindings(episodeId, dramaId, sb.scene_id, sb.character_ids, sb.prop_ids)
const res = await db.insert(schema.storyboards).values({
episodeId,
storyboardNumber: sb.shot_number,
@@ -238,6 +293,7 @@ const saveStoryboards = createTool({
createdAt: ts, updatedAt: ts,
})
await syncStoryboardCharacters(getInsertId(res), sb.character_ids || [])
+ await syncStoryboardProps(getInsertId(res), sb.prop_ids || [])
totalDuration += sb.duration || 10
}
@@ -276,6 +332,7 @@ const updateStoryboard = createTool({
dialogue: z.string().optional(),
scene_id: z.number().nullable().optional(),
character_ids: z.array(z.number()).optional(),
+ prop_ids: z.array(z.number()).optional(),
duration: z.number().optional(),
}),
execute: async ({ storyboard_id, ...fields }, context) => {
@@ -296,11 +353,18 @@ const updateStoryboard = createTool({
.where(eq(schema.storyboardCharacters.storyboardId, storyboard_id)))
.map(link => link.characterId)
+ const currentPropIds = 'prop_ids' in fields
+ ? fields.prop_ids
+ : (await db.select().from(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, storyboard_id)))
+ .map(link => link.propId)
+
await validateStoryboardBindings(
episodeId,
dramaId,
'scene_id' in fields ? fields.scene_id : storyboard.sceneId,
currentCharacterIds,
+ currentPropIds,
)
const updates: Record<string, any> = { updatedAt: now() }
@@ -323,11 +387,13 @@ const updateStoryboard = createTool({
if ('duration' in fields) updates.duration = fields.duration
await db.update(schema.storyboards).set(updates).where(eq(schema.storyboards.id, storyboard_id))
if ('character_ids' in fields) await syncStoryboardCharacters(storyboard_id, fields.character_ids || [])
+ if ('prop_ids' in fields) await syncStoryboardProps(storyboard_id, fields.prop_ids || [])
logTaskSuccess('StoryboardTool', 'update-complete', {
episodeId,
storyboardId: storyboard_id,
updatedFields: Object.keys(updates),
characterIds: 'character_ids' in fields ? (fields.character_ids || []).join(',') : undefined,
+ propIds: 'prop_ids' in fields ? (fields.prop_ids || []).join(',') : undefined,
})
return { message: `Storyboard ${storyboard_id} updated` }
},
diff --git a/backend/src/db/mysql-schema.ts b/backend/src/db/mysql-schema.ts
index a85ae3e..f674830 100644
--- a/backend/src/db/mysql-schema.ts
+++ b/backend/src/db/mysql-schema.ts
@@ -33,6 +33,7 @@ export const mysqlSchemaStatements = [
thumbnail TEXT,
image_config_id INT,
video_config_id INT,
+ resolution VARCHAR(16) DEFAULT '720p',
created_at VARCHAR(64) NOT NULL,
updated_at VARCHAR(64) NOT NULL,
deleted_at VARCHAR(64)
@@ -144,6 +145,13 @@ export const mysqlSchemaStatements = [
INDEX idx_storyboard_characters_character_id (character_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
+ `CREATE TABLE IF NOT EXISTS storyboard_props (
+ storyboard_id INT NOT NULL,
+ prop_id INT NOT NULL,
+ PRIMARY KEY (storyboard_id, prop_id),
+ INDEX idx_storyboard_props_prop_id (prop_id)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
+
`CREATE TABLE IF NOT EXISTS ai_service_configs (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
service_type VARCHAR(64) NOT NULL,
@@ -205,75 +213,29 @@ export const mysqlSchemaStatements = [
deleted_at VARCHAR(64)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
- `CREATE TABLE IF NOT EXISTS image_generations (
+ `CREATE TABLE IF NOT EXISTS sys_task (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
+ type VARCHAR(16) NOT NULL,
storyboard_id INT,
drama_id INT,
scene_id INT,
character_id INT,
prop_id INT,
- image_type TEXT,
- frame_type TEXT,
provider VARCHAR(64),
prompt TEXT,
- negative_prompt TEXT,
model TEXT,
- size TEXT,
- quality TEXT,
- style VARCHAR(64),
- steps INT,
- cfg_scale DOUBLE,
- seed INT,
- image_url TEXT,
- minio_url TEXT,
- local_path TEXT,
- status VARCHAR(64) DEFAULT 'pending',
+ params TEXT,
task_id TEXT,
- error_msg TEXT,
- width INT,
- height INT,
- reference_images TEXT,
- created_at VARCHAR(64) NOT NULL,
- updated_at VARCHAR(64) NOT NULL,
- completed_at VARCHAR(64)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
-
- `CREATE TABLE IF NOT EXISTS video_generations (
- id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- storyboard_id INT,
- drama_id INT,
- provider VARCHAR(64),
- prompt TEXT,
- model TEXT,
- image_gen_id INT,
- reference_mode TEXT,
- image_url TEXT,
- first_frame_url TEXT,
- last_frame_url TEXT,
- reference_image_urls TEXT,
- reference_video_urls TEXT,
- reference_audio_urls TEXT,
- generate_audio TINYINT(1) DEFAULT 1,
- duration INT,
- fps INT,
- resolution TEXT,
- aspect_ratio TEXT,
- style VARCHAR(64),
- motion_level INT,
- camera_motion TEXT,
- seed INT,
- video_url TEXT,
- minio_url TEXT,
+ result_url TEXT,
local_path TEXT,
- status VARCHAR(64) DEFAULT 'pending',
- task_id TEXT,
+ status VARCHAR(64) DEFAULT 'processing',
error_msg TEXT,
- width INT,
- height INT,
created_at VARCHAR(64) NOT NULL,
updated_at VARCHAR(64) NOT NULL,
completed_at VARCHAR(64),
- deleted_at VARCHAR(64)
+ INDEX idx_sys_task_type (type),
+ INDEX idx_sys_task_drama_id (drama_id),
+ INDEX idx_sys_task_storyboard_id (storyboard_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`,
`CREATE TABLE IF NOT EXISTS video_merges (
@@ -341,15 +303,21 @@ export const mysqlSchemaStatements = [
export const mysqlColumnBackfillStatements = [
{ table: 'dramas', column: 'aspect_ratio', sql: "ALTER TABLE `dramas` ADD COLUMN `aspect_ratio` VARCHAR(16) DEFAULT '16:9'" },
+ { table: 'episodes', column: 'resolution', sql: "ALTER TABLE `episodes` ADD COLUMN `resolution` VARCHAR(16) DEFAULT '720p'" },
{ table: 'characters', column: 'styling', sql: 'ALTER TABLE `characters` ADD COLUMN `styling` TEXT' },
{ table: 'characters', column: 'final_prompt', sql: 'ALTER TABLE `characters` ADD COLUMN `final_prompt` TEXT' },
{ table: 'characters', column: 'personality', sql: 'ALTER TABLE `characters` ADD COLUMN `personality` TEXT' },
{ table: 'props', column: 'final_prompt', sql: 'ALTER TABLE `props` ADD COLUMN `final_prompt` TEXT' },
{ table: 'scenes', column: 'lighting', sql: 'ALTER TABLE `scenes` ADD COLUMN `lighting` TEXT' },
{ table: 'scenes', column: 'final_prompt', sql: 'ALTER TABLE `scenes` ADD COLUMN `final_prompt` TEXT' },
- { table: 'video_generations', column: 'reference_video_urls', sql: 'ALTER TABLE `video_generations` ADD COLUMN `reference_video_urls` TEXT' },
- { table: 'video_generations', column: 'reference_audio_urls', sql: 'ALTER TABLE `video_generations` ADD COLUMN `reference_audio_urls` TEXT' },
- { table: 'video_generations', column: 'generate_audio', sql: 'ALTER TABLE `video_generations` ADD COLUMN `generate_audio` TINYINT(1) DEFAULT 1' },
+]
+
+// 废弃表清理:image_generations / video_generations 已并入 sys_task(不迁移历史);
+// ai_voices 为 TTS 功能移除后的孤儿表
+export const mysqlDropTableStatements = [
+ 'DROP TABLE IF EXISTS `image_generations`',
+ 'DROP TABLE IF EXISTS `video_generations`',
+ 'DROP TABLE IF EXISTS `ai_voices`',
]
export const mysqlDataCleanupStatements = [
@@ -461,6 +429,9 @@ export async function initMySqlSchema(pool: Pool) {
for (const statement of mysqlColumnBackfillStatements) {
await ensureMySqlColumn(pool, statement.table, statement.column, statement.sql)
}
+ for (const statement of mysqlDropTableStatements) {
+ await pool.query(statement)
+ }
for (const cleanup of mysqlDataCleanupStatements) {
await pool.query(cleanup.sql, cleanup.params)
}
diff --git a/backend/src/db/schema.ts b/backend/src/db/schema.ts
index 425dbb2..a27a6c7 100644
--- a/backend/src/db/schema.ts
+++ b/backend/src/db/schema.ts
@@ -35,6 +35,7 @@ export const episodes = mysqlTable('episodes', {
thumbnail: text('thumbnail'),
imageConfigId: int('image_config_id'),
videoConfigId: int('video_config_id'),
+ resolution: varchar('resolution', { length: 16 }).default('720p'),
createdAt: varchar('created_at', { length: 64 }).notNull(),
updatedAt: varchar('updated_at', { length: 64 }).notNull(),
deletedAt: varchar('deleted_at', { length: 64 }),
@@ -143,6 +144,13 @@ export const storyboardCharacters = mysqlTable('storyboard_characters', {
pk: primaryKey({ columns: [table.storyboardId, table.characterId] }),
}))
+export const storyboardProps = mysqlTable('storyboard_props', {
+ storyboardId: int('storyboard_id').notNull(),
+ propId: int('prop_id').notNull(),
+}, (table) => ({
+ pk: primaryKey({ columns: [table.storyboardId, table.propId] }),
+}))
+
export const aiServiceConfigs = mysqlTable('ai_service_configs', {
id: int('id').primaryKey().autoincrement(),
serviceType: varchar('service_type', { length: 64 }).notNull(),
@@ -205,75 +213,29 @@ export const agentConfigs = mysqlTable('agent_configs', {
deletedAt: varchar('deleted_at', { length: 64 }),
})
-export const imageGenerations = mysqlTable('image_generations', {
+// 统一生成任务表:图片/视频生成共用,type 区分,生成参数存 params(JSON)
+export const sysTask = mysqlTable('sys_task', {
id: int('id').primaryKey().autoincrement(),
+ type: varchar('type', { length: 16 }).notNull(), // image | video
storyboardId: int('storyboard_id'),
dramaId: int('drama_id'),
sceneId: int('scene_id'),
characterId: int('character_id'),
propId: int('prop_id'),
- imageType: text('image_type'),
- frameType: text('frame_type'),
provider: varchar('provider', { length: 64 }),
prompt: text('prompt'),
- negativePrompt: text('negative_prompt'),
model: text('model'),
- size: text('size'),
- quality: text('quality'),
- style: varchar('style', { length: 64 }),
- steps: int('steps'),
- cfgScale: double('cfg_scale'),
- seed: int('seed'),
- imageUrl: text('image_url'),
- minioUrl: text('minio_url'),
- localPath: text('local_path'),
- status: varchar('status', { length: 64 }).default('pending'),
+ // image: {size, frameType, referenceImages[]}
+ // video: {referenceMode, referenceImageUrls[], referenceVideoUrls[], referenceAudioUrls[], generateAudio, duration, aspectRatio}
+ params: text('params'),
taskId: text('task_id'),
- errorMsg: text('error_msg'),
- width: int('width'),
- height: int('height'),
- referenceImages: text('reference_images'),
- createdAt: varchar('created_at', { length: 64 }).notNull(),
- updatedAt: varchar('updated_at', { length: 64 }).notNull(),
- completedAt: varchar('completed_at', { length: 64 }),
-})
-
-export const videoGenerations = mysqlTable('video_generations', {
- id: int('id').primaryKey().autoincrement(),
- storyboardId: int('storyboard_id'),
- dramaId: int('drama_id'),
- provider: varchar('provider', { length: 64 }),
- prompt: text('prompt'),
- model: text('model'),
- imageGenId: int('image_gen_id'),
- referenceMode: text('reference_mode'),
- imageUrl: text('image_url'),
- firstFrameUrl: text('first_frame_url'),
- lastFrameUrl: text('last_frame_url'),
- referenceImageUrls: text('reference_image_urls'),
- referenceVideoUrls: text('reference_video_urls'),
- referenceAudioUrls: text('reference_audio_urls'),
- generateAudio: int('generate_audio').default(1),
- duration: int('duration'),
- fps: int('fps'),
- resolution: text('resolution'),
- aspectRatio: text('aspect_ratio'),
- style: varchar('style', { length: 64 }),
- motionLevel: int('motion_level'),
- cameraMotion: text('camera_motion'),
- seed: int('seed'),
- videoUrl: text('video_url'),
- minioUrl: text('minio_url'),
+ resultUrl: text('result_url'),
localPath: text('local_path'),
- status: varchar('status', { length: 64 }).default('pending'),
- taskId: text('task_id'),
+ status: varchar('status', { length: 64 }).default('processing'),
errorMsg: text('error_msg'),
- width: int('width'),
- height: int('height'),
createdAt: varchar('created_at', { length: 64 }).notNull(),
updatedAt: varchar('updated_at', { length: 64 }).notNull(),
completedAt: varchar('completed_at', { length: 64 }),
- deletedAt: varchar('deleted_at', { length: 64 }),
})
export const videoMerges = mysqlTable('video_merges', {
diff --git a/backend/src/index.ts b/backend/src/index.ts
index 2fbfdcf..1e7fbe2 100644
--- a/backend/src/index.ts
+++ b/backend/src/index.ts
@@ -11,8 +11,7 @@ import episodes from './routes/episodes.js'
import storyboards from './routes/storyboards.js'
import scenes from './routes/scenes.js'
import characters from './routes/characters.js'
-import images from './routes/images.js'
-import videos from './routes/videos.js'
+import tasks from './routes/tasks.js'
import upload from './routes/upload.js'
import aiConfigs, { aiProviders } from './routes/aiConfigs.js'
import stylePresets from './routes/stylePresets.js'
@@ -46,8 +45,7 @@ api.route('/episodes', episodes)
api.route('/storyboards', storyboards)
api.route('/scenes', scenes)
api.route('/characters', characters)
-api.route('/images', images)
-api.route('/videos', videos)
+api.route('/tasks', tasks)
api.route('/upload', upload)
api.route('/ai-configs', aiConfigs)
api.route('/ai-providers', aiProviders)
diff --git a/backend/src/routes/characters.ts b/backend/src/routes/characters.ts
index b9a648c..0026bf6 100644
--- a/backend/src/routes/characters.ts
+++ b/backend/src/routes/characters.ts
@@ -1,8 +1,9 @@
import { Hono } from 'hono'
-import { eq } from 'drizzle-orm'
-import { db, schema } from '../db/index.js'
-import { success, badRequest, now } from '../utils/response.js'
-import { generateImage } from '../services/image-generation.js'
+import { and, eq } from 'drizzle-orm'
+import { db, getInsertId, schema } from '../db/index.js'
+import { success, created, badRequest, now } from '../utils/response.js'
+import { toSnakeCase } from '../utils/transform.js'
+import { generateImage } from '../services/generation.js'
import { getDramaStylePrompt } from '../services/style-preset.js'
import { ensureCharacterFinalPrompt } from '../services/final-prompt.js'
import { logTaskError, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
@@ -10,8 +11,37 @@ import { logTaskError, logTaskStart, logTaskSuccess } from '../utils/task-logger
const app = new Hono()
const CHARACTER_IMAGE_SIZE = '1920x1080'
+// POST /characters — 手动新增角色(传入 episode_id 时关联到该集)
+app.post('/', async (c) => {
+ const body = await c.req.json()
+ if (!body.drama_id) return badRequest(c, 'drama_id required')
+ if (!body.name?.trim()) return badRequest(c, 'name required')
+ const ts = now()
+ const res = await db.insert(schema.characters).values({
+ name: body.name.trim(),
+ role: body.role || '',
+ description: body.description || '',
+ appearance: body.appearance || '',
+ styling: body.styling || '',
+ dramaId: body.drama_id,
+ createdAt: ts,
+ updatedAt: ts,
+ })
+ const charId = getInsertId(res)
+ if (body.episode_id) {
+ const existing = await db.select().from(schema.episodeCharacters)
+ .where(and(eq(schema.episodeCharacters.episodeId, Number(body.episode_id)), eq(schema.episodeCharacters.characterId, charId)))
+ if (!existing.length) {
+ await db.insert(schema.episodeCharacters).values({ episodeId: Number(body.episode_id), characterId: charId, createdAt: ts })
+ }
+ }
+ const [row] = await db.select().from(schema.characters).where(eq(schema.characters.id, charId))
+ return created(c, toSnakeCase(row))
+})
+
function characterImagePrompt(char: typeof schema.characters.$inferSelect, stylePrompt = '') {
return [
+ stylePrompt || '',
char.name,
char.appearance || char.description || '人物立绘',
char.styling || '',
@@ -20,7 +50,6 @@ function characterImagePrompt(char: typeof schema.characters.$inferSelect, style
'正面',
'高质量',
'白色背景',
- stylePrompt || '',
].filter(Boolean).join(', ')
}
@@ -62,7 +91,7 @@ app.post('/:id/generate-image', async (c) => {
if (!ep) return badRequest(c, 'Episode not found')
const stylePrompt = await getDramaStylePrompt(char.dramaId)
- const finalPrompt = await ensureCharacterFinalPrompt(char, ep.id)
+ const finalPrompt = await ensureCharacterFinalPrompt(char, ep.id, false, { model: body.text_model, configId: body.text_config_id ?? undefined })
const prompt = finalPrompt || characterImagePrompt(char, stylePrompt)
try {
logTaskStart('CharacterImage', 'generate', { characterId: id, episodeId: ep.id, dramaId: char.dramaId })
@@ -87,7 +116,7 @@ app.post('/:id/generate-prompt', async (c) => {
if (!ep) return badRequest(c, 'Episode not found')
logTaskStart('FinalPrompt', 'character-generate', { characterId: id, episodeId: ep.id, force: !!body.force })
- const finalPrompt = await ensureCharacterFinalPrompt(char, ep.id, !!body.force)
+ const finalPrompt = await ensureCharacterFinalPrompt(char, ep.id, !!body.force, { model: body.text_model, configId: body.text_config_id ?? undefined })
if (!finalPrompt) {
logTaskError('FinalPrompt', 'character-generate', { characterId: id, error: 'agent returned empty prompt' })
return badRequest(c, '最终提示词生成失败,请重试')
@@ -108,7 +137,7 @@ app.post('/batch-generate-images', async (c) => {
for (const cid of ids) {
const [char] = await db.select().from(schema.characters).where(eq(schema.characters.id, cid))
if (!char) continue
- const finalPrompt = await ensureCharacterFinalPrompt(char, ep.id)
+ const finalPrompt = await ensureCharacterFinalPrompt(char, ep.id, false, { model: body.text_model, configId: body.text_config_id ?? undefined })
const prompt = finalPrompt || characterImagePrompt(char, stylePrompt)
try {
const genId = await generateImage({ characterId: cid, dramaId: char.dramaId, prompt, model: body.model, size: CHARACTER_IMAGE_SIZE, configId: body.config_id ?? ep.imageConfigId ?? undefined })
diff --git a/backend/src/routes/episodes.ts b/backend/src/routes/episodes.ts
index dd24444..38aff58 100644
--- a/backend/src/routes/episodes.ts
+++ b/backend/src/routes/episodes.ts
@@ -5,6 +5,7 @@ import { success, notFound, badRequest, now } from '../utils/response.js'
import { toSnakeCaseArray, toSnakeCase } from '../utils/transform.js'
import { getActiveConfigId } from '../services/ai.js'
import { EXTRACT_TARGETS, getExtractionStatus, startExtraction, type ExtractTarget } from '../services/extraction.js'
+import { getVideoPromptBatchStatus, startVideoPromptBatch } from '../services/video-prompts.js'
const app = new Hono()
@@ -32,6 +33,8 @@ app.post('/', async (c) => {
title: body.title || `第${nextNum}集`,
imageConfigId,
videoConfigId,
+ // 视频分辨率在创建集时固定(480p/720p),后续可通过 PUT 修改
+ resolution: body.resolution === '480p' ? '480p' : '720p',
createdAt: ts,
updatedAt: ts,
})
@@ -44,6 +47,7 @@ app.post('/', async (c) => {
title: ep.title,
image_config_id: ep.imageConfigId,
video_config_id: ep.videoConfigId,
+ resolution: ep.resolution,
})
})
@@ -52,12 +56,15 @@ app.put('/:id', async (c) => {
const id = Number(c.req.param('id'))
const body = await c.req.json()
- const allowed = ['content', 'script_content', 'title', 'description', 'status']
+ const allowed = ['content', 'script_content', 'title', 'description', 'status', 'resolution']
const updates: Record<string, any> = {}
for (const key of allowed) {
if (key in body) updates[key] = body[key]
}
if (Object.keys(updates).length === 0) return badRequest(c, 'no valid fields')
+ if ('resolution' in updates && !['480p', '720p'].includes(updates.resolution)) {
+ return badRequest(c, 'resolution 只支持 480p / 720p')
+ }
// Map snake_case to camelCase for drizzle
const drizzleUpdates: Record<string, any> = { updatedAt: now() }
@@ -66,6 +73,7 @@ app.put('/:id', async (c) => {
if ('title' in updates) drizzleUpdates.title = updates.title
if ('description' in updates) drizzleUpdates.description = updates.description
if ('status' in updates) drizzleUpdates.status = updates.status
+ if ('resolution' in updates) drizzleUpdates.resolution = updates.resolution
await db.update(schema.episodes).set(drizzleUpdates).where(eq(schema.episodes.id, id))
return success(c)
@@ -125,7 +133,7 @@ app.post('/:id/extract', async (c) => {
if (!EXTRACT_TARGETS.includes(target)) return badRequest(c, 'target 必须是 characters / scenes / props')
const [ep] = await db.select().from(schema.episodes).where(eq(schema.episodes.id, id))
if (!ep) return notFound(c, '剧集不存在')
- const started = startExtraction(ep.id, ep.dramaId, target)
+ const started = startExtraction(ep.id, ep.dramaId, target, { model: body.model || undefined, configId: body.config_id ?? undefined })
return success(c, { target, status: 'running', already_running: !started })
})
@@ -135,6 +143,27 @@ app.get('/:id/extract-status', async (c) => {
return success(c, getExtractionStatus(id))
})
+// POST /episodes/:id/generate-video-prompts — 异步批量为缺少视频提示词的分镜生成(立即返回,前端轮询状态)
+app.post('/:id/generate-video-prompts', async (c) => {
+ const id = Number(c.req.param('id'))
+ const body = await c.req.json().catch(() => ({}))
+ const [ep] = await db.select().from(schema.episodes).where(eq(schema.episodes.id, id))
+ if (!ep) return notFound(c, '剧集不存在')
+ const storyboardIds = Array.isArray(body.storyboard_ids)
+ ? body.storyboard_ids.map(Number).filter((n: number) => Number.isInteger(n) && n > 0)
+ : undefined
+ const result = await startVideoPromptBatch(ep.id, ep.dramaId, { model: body.model || undefined, configId: body.config_id ?? undefined }, storyboardIds)
+ if (result.total === -1) return success(c, { status: 'running', already_running: true })
+ if (!result.started) return success(c, { status: 'idle', total: 0 })
+ return success(c, { status: 'running', total: result.total })
+})
+
+// GET /episodes/:id/video-prompts-status — 查询批量视频提示词任务状态
+app.get('/:id/video-prompts-status', async (c) => {
+ const id = Number(c.req.param('id'))
+ return success(c, getVideoPromptBatchStatus(id))
+})
+
// GET /episodes/:episode_id/storyboards
app.get('/:episode_id/storyboards', async (c) => {
const episodeId = Number(c.req.param('episode_id'))
@@ -150,18 +179,36 @@ app.get('/:episode_id/storyboards', async (c) => {
charIdsByStoryboard.set(link.storyboardId, arr)
}
+ const propLinks = await db.select().from(schema.storyboardProps)
+ const propIdsByStoryboard = new Map<number, number[]>()
+ for (const link of propLinks) {
+ const arr = propIdsByStoryboard.get(link.storyboardId) || []
+ arr.push(link.propId)
+ propIdsByStoryboard.set(link.storyboardId, arr)
+ }
+
const episodeCharLinks = await db.select().from(schema.episodeCharacters)
.where(eq(schema.episodeCharacters.episodeId, episodeId))
const episodeCharIds = episodeCharLinks.map(link => link.characterId)
const allChars = (await db.select().from(schema.characters))
.filter(ch => episodeCharIds.includes(ch.id) && !ch.deletedAt)
+ const episodePropLinks = await db.select().from(schema.episodeProps)
+ .where(eq(schema.episodeProps.episodeId, episodeId))
+ const episodePropIds = episodePropLinks.map(link => link.propId)
+ const allProps = (await db.select().from(schema.props))
+ .filter(p => episodePropIds.includes(p.id) && !p.deletedAt)
+
return success(c, rows.map((row) => ({
...toSnakeCase(row),
character_ids: charIdsByStoryboard.get(row.id) || [],
+ prop_ids: propIdsByStoryboard.get(row.id) || [],
characters: allChars
.filter(ch => (charIdsByStoryboard.get(row.id) || []).includes(ch.id))
.map(ch => toSnakeCase(ch)),
+ props: allProps
+ .filter(p => (propIdsByStoryboard.get(row.id) || []).includes(p.id))
+ .map(p => toSnakeCase(p)),
})))
})
diff --git a/backend/src/routes/images.ts b/backend/src/routes/images.ts
deleted file mode 100644
index 3198dfb..0000000
--- a/backend/src/routes/images.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { Hono } from 'hono'
-import { eq } from 'drizzle-orm'
-import { db, schema } from '../db/index.js'
-import { success, created, now, badRequest } from '../utils/response.js'
-import { generateImage } from '../services/image-generation.js'
-import { logTaskError, logTaskPayload, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
-
-const app = new Hono()
-
-// POST /images — Generate image
-app.post('/', async (c) => {
- const body = await c.req.json()
- if (!body.prompt) return badRequest(c, 'prompt is required')
-
- try {
- let configId: number | undefined = body.config_id
- if (body.storyboard_id) {
- const [sb] = await db.select().from(schema.storyboards).where(eq(schema.storyboards.id, Number(body.storyboard_id)))
- if (sb) {
- const [ep] = await db.select().from(schema.episodes).where(eq(schema.episodes.id, sb.episodeId))
- if (ep?.imageConfigId != null) configId = ep.imageConfigId
- }
- }
-
- logTaskStart('ImageAPI', 'generate', {
- storyboardId: body.storyboard_id,
- sceneId: body.scene_id,
- characterId: body.character_id,
- dramaId: body.drama_id,
- frameType: body.frame_type,
- })
- logTaskPayload('ImageAPI', 'request body', body)
- const id = await generateImage({
- storyboardId: body.storyboard_id,
- dramaId: body.drama_id,
- sceneId: body.scene_id,
- characterId: body.character_id,
- prompt: body.prompt,
- model: body.model,
- size: body.size,
- referenceImages: body.reference_images,
- frameType: body.frame_type,
- configId,
- })
-
- const [record] = await db.select().from(schema.imageGenerations)
- .where(eq(schema.imageGenerations.id, id))
- logTaskSuccess('ImageAPI', 'generate', { generationId: id, provider: record?.provider })
- return created(c, record)
- } catch (err: any) {
- logTaskError('ImageAPI', 'generate', { error: err.message })
- return badRequest(c, err.message)
- }
-})
-
-// GET /images/:id
-app.get('/:id', async (c) => {
- const id = Number(c.req.param('id'))
- const [row] = await db.select().from(schema.imageGenerations)
- .where(eq(schema.imageGenerations.id, id))
- return success(c, row || null)
-})
-
-// GET /images — List by storyboard_id or drama_id
-app.get('/', async (c) => {
- const storyboardId = c.req.query('storyboard_id')
- const dramaId = c.req.query('drama_id')
-
- let rows = await db.select().from(schema.imageGenerations)
-
- if (storyboardId) rows = rows.filter(r => r.storyboardId === Number(storyboardId))
- if (dramaId) rows = rows.filter(r => r.dramaId === Number(dramaId))
-
- return success(c, rows)
-})
-
-// DELETE /images/:id
-app.delete('/:id', async (c) => {
- const id = Number(c.req.param('id'))
- await db.delete(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
- return success(c)
-})
-
-export default app
diff --git a/backend/src/routes/props.ts b/backend/src/routes/props.ts
index c6df434..00dbf29 100644
--- a/backend/src/routes/props.ts
+++ b/backend/src/routes/props.ts
@@ -1,8 +1,9 @@
import { Hono } from 'hono'
-import { eq } from 'drizzle-orm'
-import { db, schema } from '../db/index.js'
-import { success, badRequest, now } from '../utils/response.js'
-import { generateImage } from '../services/image-generation.js'
+import { and, eq } from 'drizzle-orm'
+import { db, getInsertId, schema } from '../db/index.js'
+import { success, created, badRequest, now } from '../utils/response.js'
+import { toSnakeCase } from '../utils/transform.js'
+import { generateImage } from '../services/generation.js'
import { getDramaStylePrompt } from '../services/style-preset.js'
import { ensurePropFinalPrompt } from '../services/final-prompt.js'
import { logTaskError, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
@@ -11,6 +12,39 @@ const app = new Hono()
// 道具图:白底单品静物,方形画布
const PROP_IMAGE_SIZE = '1024x1024'
+// POST /props — 手动新增道具(传入 episode_id 时关联到该集)
+app.post('/', async (c) => {
+ const body = await c.req.json()
+ if (!body.drama_id) return badRequest(c, 'drama_id required')
+ if (!body.name?.trim()) return badRequest(c, 'name required')
+ const ts = now()
+ const res = await db.insert(schema.props).values({
+ name: body.name.trim(),
+ type: body.type || '',
+ description: body.description || '',
+ dramaId: body.drama_id,
+ createdAt: ts,
+ updatedAt: ts,
+ })
+ const propId = getInsertId(res)
+ if (body.episode_id) {
+ const existing = await db.select().from(schema.episodeProps)
+ .where(and(eq(schema.episodeProps.episodeId, Number(body.episode_id)), eq(schema.episodeProps.propId, propId)))
+ if (!existing.length) {
+ await db.insert(schema.episodeProps).values({ episodeId: Number(body.episode_id), propId, createdAt: ts })
+ }
+ }
+ const [row] = await db.select().from(schema.props).where(eq(schema.props.id, propId))
+ return created(c, toSnakeCase(row))
+})
+
+// DELETE /props/:id — 软删除
+app.delete('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ await db.update(schema.props).set({ deletedAt: now(), updatedAt: now() }).where(eq(schema.props.id, id))
+ return success(c)
+})
+
// PUT /props/:id — 更新道具(物品外貌/类型/最终提示词)
app.put('/:id', async (c) => {
const id = Number(c.req.param('id'))
@@ -31,6 +65,7 @@ app.put('/:id', async (c) => {
/** 本地兜底提示词:白底单品,不掺杂其他元素 */
function propImagePrompt(prop: typeof schema.props.$inferSelect, stylePrompt = '') {
return [
+ stylePrompt || '',
`single product photo of ${prop.name}`,
prop.description || '',
'isolated on a pure white background',
@@ -38,7 +73,6 @@ function propImagePrompt(prop: typeof schema.props.$inferSelect, stylePrompt = '
'soft even studio lighting',
'high detail',
'no text, no watermark',
- stylePrompt || '',
].filter(Boolean).join(', ')
}
@@ -54,7 +88,7 @@ app.post('/:id/generate-prompt', async (c) => {
if (!ep) return badRequest(c, 'Episode not found')
logTaskStart('FinalPrompt', 'prop-generate', { propId: id, episodeId: ep.id, force: !!body.force })
- const finalPrompt = await ensurePropFinalPrompt(prop, ep.id, !!body.force)
+ const finalPrompt = await ensurePropFinalPrompt(prop, ep.id, !!body.force, { model: body.text_model, configId: body.text_config_id ?? undefined })
if (!finalPrompt) {
logTaskError('FinalPrompt', 'prop-generate', { propId: id, error: 'agent returned empty prompt' })
return badRequest(c, '最终提示词生成失败,请重试')
@@ -75,7 +109,7 @@ app.post('/:id/generate-image', async (c) => {
if (!ep) return badRequest(c, 'Episode not found')
const stylePrompt = await getDramaStylePrompt(prop.dramaId)
- const finalPrompt = await ensurePropFinalPrompt(prop, ep.id)
+ const finalPrompt = await ensurePropFinalPrompt(prop, ep.id, false, { model: body.text_model, configId: body.text_config_id ?? undefined })
const prompt = finalPrompt || propImagePrompt(prop, stylePrompt)
try {
logTaskStart('PropImage', 'generate', { propId: id, episodeId: ep.id, dramaId: prop.dramaId })
diff --git a/backend/src/routes/scenes.ts b/backend/src/routes/scenes.ts
index 92b40b6..f7615fd 100644
--- a/backend/src/routes/scenes.ts
+++ b/backend/src/routes/scenes.ts
@@ -1,30 +1,40 @@
import { Hono } from 'hono'
-import { eq } from 'drizzle-orm'
+import { and, eq } from 'drizzle-orm'
import { db, getInsertId, schema } from '../db/index.js'
import { success, created, badRequest, now } from '../utils/response.js'
-import { generateImage } from '../services/image-generation.js'
+import { generateImage } from '../services/generation.js'
import { getDramaStylePrompt } from '../services/style-preset.js'
import { ensureSceneFinalPrompt } from '../services/final-prompt.js'
import { logTaskError, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
const app = new Hono()
-// POST /scenes
+// POST /scenes — 手动新增场景(传入 episode_id 时关联到该集)
app.post('/', async (c) => {
const body = await c.req.json()
+ if (!body.drama_id) return badRequest(c, 'drama_id required')
+ if (!body.location?.trim()) return badRequest(c, 'location required')
const ts = now()
const res = await db.insert(schema.scenes).values({
dramaId: body.drama_id,
episodeId: body.episode_id,
- location: body.location,
+ location: body.location.trim(),
time: body.time || '',
prompt: body.prompt || body.description || body.location,
lighting: body.lighting || '',
createdAt: ts,
updatedAt: ts,
})
+ const sceneId = getInsertId(res)
+ if (body.episode_id) {
+ const existing = await db.select().from(schema.episodeScenes)
+ .where(and(eq(schema.episodeScenes.episodeId, Number(body.episode_id)), eq(schema.episodeScenes.sceneId, sceneId)))
+ if (!existing.length) {
+ await db.insert(schema.episodeScenes).values({ episodeId: Number(body.episode_id), sceneId, createdAt: ts })
+ }
+ }
const [result] = await db.select().from(schema.scenes)
- .where(eq(schema.scenes.id, getInsertId(res)))
+ .where(eq(schema.scenes.id, sceneId))
return created(c, result)
})
@@ -58,13 +68,13 @@ app.post('/:id/generate-image', async (c) => {
if (!ep) return badRequest(c, 'Episode not found')
const stylePrompt = await getDramaStylePrompt(scene.dramaId)
- const finalPrompt = await ensureSceneFinalPrompt(scene, ep.id)
+ const finalPrompt = await ensureSceneFinalPrompt(scene, ep.id, false, { model: body.text_model, configId: body.text_config_id ?? undefined })
const prompt = finalPrompt || [
+ stylePrompt || '',
scene.location,
scene.time || '',
scene.prompt || '高质量场景',
scene.lighting || '电影感光影',
- stylePrompt || '',
].filter(Boolean).join(', ')
try {
logTaskStart('SceneImage', 'generate', { sceneId: id, episodeId: ep.id, dramaId: scene.dramaId, location: scene.location })
@@ -91,7 +101,7 @@ app.post('/:id/generate-prompt', async (c) => {
if (!ep) return badRequest(c, 'Episode not found')
logTaskStart('FinalPrompt', 'scene-generate', { sceneId: id, episodeId: ep.id, force: !!body.force })
- const finalPrompt = await ensureSceneFinalPrompt(scene, ep.id, !!body.force)
+ const finalPrompt = await ensureSceneFinalPrompt(scene, ep.id, !!body.force, { model: body.text_model, configId: body.text_config_id ?? undefined })
if (!finalPrompt) {
logTaskError('FinalPrompt', 'scene-generate', { sceneId: id, error: 'agent returned empty prompt' })
return badRequest(c, '最终提示词生成失败,请重试')
@@ -100,10 +110,10 @@ app.post('/:id/generate-prompt', async (c) => {
return success(c, { final_prompt: finalPrompt })
})
-// DELETE /scenes/:id
+// DELETE /scenes/:id — 软删除(保留历史生成记录)
app.delete('/:id', async (c) => {
const id = Number(c.req.param('id'))
- await db.delete(schema.scenes).where(eq(schema.scenes.id, id))
+ await db.update(schema.scenes).set({ deletedAt: now(), updatedAt: now() }).where(eq(schema.scenes.id, id))
return success(c)
})
diff --git a/backend/src/routes/storyboards.ts b/backend/src/routes/storyboards.ts
index bcea832..a4a6f27 100644
--- a/backend/src/routes/storyboards.ts
+++ b/backend/src/routes/storyboards.ts
@@ -29,13 +29,37 @@ async function getStoryboardCharacterIds(storyboardId: number) {
return links.map(link => link.characterId)
}
-async function validateStoryboardBindings(episodeId: number, sceneId: number | null | undefined, characterIds: number[] | undefined) {
+async function syncStoryboardProps(storyboardId: number, propIds: number[]) {
+ await db.delete(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, storyboardId))
+
+ const uniqueIds = [...new Set((propIds || []).filter(Boolean))]
+ if (!uniqueIds.length) return
+
+ for (const propId of uniqueIds) {
+ await db.insert(schema.storyboardProps).values({
+ storyboardId,
+ propId,
+ })
+ }
+}
+
+async function getStoryboardPropIds(storyboardId: number) {
+ const links = await db.select().from(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, storyboardId))
+ return links.map(link => link.propId)
+}
+
+async function validateStoryboardBindings(episodeId: number, sceneId: number | null | undefined, characterIds: number[] | undefined, propIds?: number[] | undefined) {
const sceneLinks = await db.select().from(schema.episodeScenes)
.where(eq(schema.episodeScenes.episodeId, episodeId))
const episodeSceneIds = new Set(sceneLinks.map(link => link.sceneId))
const characterLinks = await db.select().from(schema.episodeCharacters)
.where(eq(schema.episodeCharacters.episodeId, episodeId))
const episodeCharacterIds = new Set(characterLinks.map(link => link.characterId))
+ const propLinks = await db.select().from(schema.episodeProps)
+ .where(eq(schema.episodeProps.episodeId, episodeId))
+ const episodePropIds = new Set(propLinks.map(link => link.propId))
if (sceneId != null && !episodeSceneIds.has(sceneId)) {
throw new Error('scene_id 必须来自当前集已关联场景')
@@ -45,6 +69,11 @@ async function validateStoryboardBindings(episodeId: number, sceneId: number | n
if (invalidCharacterIds.length) {
throw new Error('character_ids 必须来自当前集已关联角色')
}
+
+ const invalidPropIds = (propIds || []).filter(id => !episodePropIds.has(id))
+ if (invalidPropIds.length) {
+ throw new Error('prop_ids 必须来自当前集已关联道具')
+ }
}
// POST /storyboards
@@ -58,7 +87,7 @@ app.post('/', async (c) => {
characterIds: body.character_ids,
})
logTaskPayload('StoryboardAPI', 'create body', body)
- await validateStoryboardBindings(body.episode_id, body.scene_id, body.character_ids)
+ await validateStoryboardBindings(body.episode_id, body.scene_id, body.character_ids, body.prop_ids)
const res = await db.insert(schema.storyboards).values({
episodeId: body.episode_id,
storyboardNumber: body.storyboard_number || 1,
@@ -72,6 +101,7 @@ app.post('/', async (c) => {
updatedAt: ts,
})
await syncStoryboardCharacters(getInsertId(res), body.character_ids || [])
+ await syncStoryboardProps(getInsertId(res), body.prop_ids || [])
const [result] = await db.select().from(schema.storyboards)
.where(eq(schema.storyboards.id, getInsertId(res)))
logTaskSuccess('StoryboardAPI', 'create', {
@@ -82,6 +112,7 @@ app.post('/', async (c) => {
return created(c, {
...toSnakeCase(result),
character_ids: await getStoryboardCharacterIds(result.id),
+ prop_ids: await getStoryboardPropIds(result.id),
})
})
@@ -116,14 +147,17 @@ app.put('/:id', async (c) => {
storyboard.episodeId,
'scene_id' in body ? body.scene_id : storyboard.sceneId,
'character_ids' in body ? body.character_ids : await getStoryboardCharacterIds(id),
+ 'prop_ids' in body ? body.prop_ids : await getStoryboardPropIds(id),
)
await db.update(schema.storyboards).set(updates).where(eq(schema.storyboards.id, id))
if ('character_ids' in body) await syncStoryboardCharacters(id, body.character_ids || [])
+ if ('prop_ids' in body) await syncStoryboardProps(id, body.prop_ids || [])
logTaskSuccess('StoryboardAPI', 'update', {
storyboardId: id,
updatedFields: Object.keys(updates),
characterIds: body.character_ids,
+ propIds: body.prop_ids,
})
return success(c)
})
@@ -133,6 +167,7 @@ app.delete('/:id', async (c) => {
const id = Number(c.req.param('id'))
logTaskStart('StoryboardAPI', 'delete', { storyboardId: id })
await db.delete(schema.storyboardCharacters).where(eq(schema.storyboardCharacters.storyboardId, id))
+ await db.delete(schema.storyboardProps).where(eq(schema.storyboardProps.storyboardId, id))
await db.delete(schema.storyboards).where(eq(schema.storyboards.id, id))
logTaskSuccess('StoryboardAPI', 'delete', { storyboardId: id })
return success(c)
diff --git a/backend/src/routes/tasks.ts b/backend/src/routes/tasks.ts
new file mode 100644
index 0000000..e0f93a6
--- /dev/null
+++ b/backend/src/routes/tasks.ts
@@ -0,0 +1,128 @@
+import { Hono } from 'hono'
+import { eq } from 'drizzle-orm'
+import { db, schema } from '../db/index.js'
+import { success, created, badRequest } from '../utils/response.js'
+import { generateImage, generateVideo } from '../services/generation.js'
+import { logTaskError, logTaskPayload, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
+
+const app = new Hono()
+
+type TaskType = 'image' | 'video'
+
+// POST /tasks — 发起生成任务(body.type: image | video)
+app.post('/', async (c) => {
+ const body = await c.req.json()
+ const type = body.type as TaskType
+ if (type !== 'image' && type !== 'video') return badRequest(c, 'type 必须为 image 或 video')
+
+ if (type === 'image') {
+ if (!body.prompt) return badRequest(c, 'prompt is required')
+ } else {
+ // 视频生成只保留多模态参考:校验素材上限与必填项
+ const imgs = body.reference_image_urls?.length || 0
+ const vids = body.reference_video_urls?.length || 0
+ const auds = body.reference_audio_urls?.length || 0
+ if (imgs > 9 || vids > 3 || auds > 3) {
+ return badRequest(c, '参考素材超限:图片≤9、视频≤3、音频≤3')
+ }
+ if (auds > 0 && imgs + vids === 0) {
+ return badRequest(c, '参考音频需要至少 1 个参考图片或视频')
+ }
+ if (imgs + vids + auds === 0 && !body.prompt) {
+ return badRequest(c, '多模态参考模式需要至少一个参考素材或 prompt')
+ }
+ }
+
+ try {
+ // 集锁定的生成配置优先于请求指定;视频分辨率同样锁定到集
+ let configId: number | undefined = body.config_id
+ let episodeResolution: string | undefined
+ if (body.storyboard_id) {
+ const [sb] = await db.select().from(schema.storyboards).where(eq(schema.storyboards.id, Number(body.storyboard_id)))
+ if (sb) {
+ const [ep] = await db.select().from(schema.episodes).where(eq(schema.episodes.id, sb.episodeId))
+ const locked = type === 'image' ? ep?.imageConfigId : ep?.videoConfigId
+ if (locked != null) configId = locked
+ if (type === 'video' && ep?.resolution) episodeResolution = ep.resolution
+ }
+ }
+
+ logTaskStart('TaskAPI', 'generate', {
+ type,
+ storyboardId: body.storyboard_id,
+ sceneId: body.scene_id,
+ characterId: body.character_id,
+ dramaId: body.drama_id,
+ })
+ logTaskPayload('TaskAPI', 'request body', body)
+
+ const id = type === 'image'
+ ? await generateImage({
+ storyboardId: body.storyboard_id,
+ dramaId: body.drama_id,
+ sceneId: body.scene_id,
+ characterId: body.character_id,
+ prompt: body.prompt,
+ model: body.model,
+ size: body.size,
+ referenceImages: body.reference_images,
+ frameType: body.frame_type,
+ configId,
+ })
+ : await generateVideo({
+ storyboardId: body.storyboard_id,
+ dramaId: body.drama_id,
+ prompt: body.prompt,
+ model: body.model,
+ referenceMode: 'reference',
+ referenceImageUrls: body.reference_image_urls,
+ referenceVideoUrls: body.reference_video_urls,
+ referenceAudioUrls: body.reference_audio_urls,
+ generateAudio: body.generate_audio,
+ duration: body.duration,
+ aspectRatio: body.aspect_ratio,
+ resolution: episodeResolution || body.resolution,
+ configId,
+ })
+
+ const [record] = await db.select().from(schema.sysTask)
+ .where(eq(schema.sysTask.id, id))
+ logTaskSuccess('TaskAPI', 'generate', { taskId: id, type, provider: record?.provider })
+ return created(c, record)
+ } catch (err: any) {
+ logTaskError('TaskAPI', 'generate', { type, error: err.message })
+ return badRequest(c, err.message)
+ }
+})
+
+// GET /tasks/:id — 轮询任务状态
+app.get('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ const [row] = await db.select().from(schema.sysTask)
+ .where(eq(schema.sysTask.id, id))
+ return success(c, row || null)
+})
+
+// GET /tasks — 按 type / storyboard_id / drama_id 过滤
+app.get('/', async (c) => {
+ const type = c.req.query('type')
+ const storyboardId = c.req.query('storyboard_id')
+ const dramaId = c.req.query('drama_id')
+
+ let rows = await db.select().from(schema.sysTask)
+
+ if (type) rows = rows.filter(r => r.type === type)
+ if (storyboardId) rows = rows.filter(r => r.storyboardId === Number(storyboardId))
+ if (dramaId) rows = rows.filter(r => r.dramaId === Number(dramaId))
+
+ return success(c, rows)
+})
+
+// DELETE /tasks/:id
+app.delete('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ await db.delete(schema.sysTask).where(eq(schema.sysTask.id, id))
+ return success(c)
+})
+
+export default app
diff --git a/backend/src/routes/videos.ts b/backend/src/routes/videos.ts
deleted file mode 100644
index a61dcc0..0000000
--- a/backend/src/routes/videos.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { Hono } from 'hono'
-import { eq } from 'drizzle-orm'
-import { db, schema } from '../db/index.js'
-import { success, created, badRequest } from '../utils/response.js'
-import { generateVideo } from '../services/video-generation.js'
-import { logTaskError, logTaskPayload, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
-
-const app = new Hono()
-
-// POST /videos — Generate video
-app.post('/', async (c) => {
- const body = await c.req.json()
-
- // 生成模式只保留多模态参考:校验素材上限与必填项
- const imgs = body.reference_image_urls?.length || 0
- const vids = body.reference_video_urls?.length || 0
- const auds = body.reference_audio_urls?.length || 0
- if (imgs > 9 || vids > 3 || auds > 3) {
- return badRequest(c, '参考素材超限:图片≤9、视频≤3、音频≤3')
- }
- if (auds > 0 && imgs + vids === 0) {
- return badRequest(c, '参考音频需要至少 1 个参考图片或视频')
- }
- if (imgs + vids + auds === 0 && !body.prompt) {
- return badRequest(c, '多模态参考模式需要至少一个参考素材或 prompt')
- }
-
- try {
- let configId: number | undefined = body.config_id
- if (body.storyboard_id) {
- const [sb] = await db.select().from(schema.storyboards).where(eq(schema.storyboards.id, Number(body.storyboard_id)))
- if (sb) {
- const [ep] = await db.select().from(schema.episodes).where(eq(schema.episodes.id, sb.episodeId))
- if (ep?.videoConfigId != null) configId = ep.videoConfigId
- }
- }
-
- logTaskStart('VideoAPI', 'generate', {
- storyboardId: body.storyboard_id,
- dramaId: body.drama_id,
- referenceMode: 'reference',
- duration: body.duration,
- })
- logTaskPayload('VideoAPI', 'request body', body)
- const id = await generateVideo({
- storyboardId: body.storyboard_id,
- dramaId: body.drama_id,
- prompt: body.prompt,
- model: body.model,
- referenceMode: 'reference',
- referenceImageUrls: body.reference_image_urls,
- referenceVideoUrls: body.reference_video_urls,
- referenceAudioUrls: body.reference_audio_urls,
- generateAudio: body.generate_audio,
- duration: body.duration,
- aspectRatio: body.aspect_ratio,
- configId,
- })
-
- const [record] = await db.select().from(schema.videoGenerations)
- .where(eq(schema.videoGenerations.id, id))
- logTaskSuccess('VideoAPI', 'generate', { generationId: id, provider: record?.provider })
- return created(c, record)
- } catch (err: any) {
- logTaskError('VideoAPI', 'generate', { error: err.message })
- return badRequest(c, err.message)
- }
-})
-
-// GET /videos/:id
-app.get('/:id', async (c) => {
- const id = Number(c.req.param('id'))
- const [row] = await db.select().from(schema.videoGenerations)
- .where(eq(schema.videoGenerations.id, id))
- return success(c, row || null)
-})
-
-// GET /videos — List by storyboard_id or drama_id
-app.get('/', async (c) => {
- const storyboardId = c.req.query('storyboard_id')
- const dramaId = c.req.query('drama_id')
-
- let rows = await db.select().from(schema.videoGenerations)
-
- if (storyboardId) rows = rows.filter(r => r.storyboardId === Number(storyboardId))
- if (dramaId) rows = rows.filter(r => r.dramaId === Number(dramaId))
-
- return success(c, rows)
-})
-
-// DELETE /videos/:id
-app.delete('/:id', async (c) => {
- const id = Number(c.req.param('id'))
- await db.delete(schema.videoGenerations).where(eq(schema.videoGenerations.id, id))
- return success(c)
-})
-
-export default app
diff --git a/backend/src/services/adapters/types.ts b/backend/src/services/adapters/types.ts
index babe4fe..d16397c 100644
--- a/backend/src/services/adapters/types.ts
+++ b/backend/src/services/adapters/types.ts
@@ -99,6 +99,7 @@ export interface VideoGenerationRecord {
generateAudio?: number | boolean | null
duration?: number | null
aspectRatio?: string | null
+ resolution?: string | null
// ... 其他字段
}
diff --git a/backend/src/services/adapters/volcengine-video.ts b/backend/src/services/adapters/volcengine-video.ts
index 2620c1d..54bf8d5 100644
--- a/backend/src/services/adapters/volcengine-video.ts
+++ b/backend/src/services/adapters/volcengine-video.ts
@@ -76,6 +76,7 @@ export class VolcEngineVideoAdapter implements VideoProviderAdapter {
generate_audio: record.generateAudio !== 0 && record.generateAudio !== false,
ratio: record.aspectRatio || 'adaptive',
duration: this.normalizeDuration(record.duration),
+ resolution: record.resolution === '480p' ? '480p' : '720p',
watermark: false,
}
diff --git a/backend/src/services/ai.ts b/backend/src/services/ai.ts
index 035577f..129a4a1 100644
--- a/backend/src/services/ai.ts
+++ b/backend/src/services/ai.ts
@@ -44,6 +44,10 @@ export function getTextProviderBaseUrl(config: AIConfig) {
return config.baseUrl
}
+// Agent 多步循环会逐步重复解析同一配置,相同配置只打一次日志避免刷屏
+const lastLoggedActiveConfigKey = new Map<string, string>()
+const lastLoggedConfigByIdKey = new Map<number, string>()
+
export async function getActiveConfig(serviceType: ServiceType): Promise<AIConfig | null> {
const rows = (await db.select().from(schema.aiServiceConfigs)
.where(eq(schema.aiServiceConfigs.serviceType, serviceType))
@@ -58,13 +62,17 @@ export async function getActiveConfig(serviceType: ServiceType): Promise<AIConfi
}
const models = active.model ? JSON.parse(active.model) : []
- logTaskProgress('AIConfig', 'active-config-selected', {
- serviceType,
- configId: active.id,
- provider: active.provider,
- model: models[0] || '',
- priority: active.priority,
- })
+ const logKey = `${active.id}:${models[0] || ''}`
+ if (lastLoggedActiveConfigKey.get(serviceType) !== logKey) {
+ lastLoggedActiveConfigKey.set(serviceType, logKey)
+ logTaskProgress('AIConfig', 'active-config-selected', {
+ serviceType,
+ configId: active.id,
+ provider: active.provider,
+ model: models[0] || '',
+ priority: active.priority,
+ })
+ }
return {
provider: active.provider || '',
baseUrl: active.baseUrl,
@@ -107,12 +115,16 @@ export async function getConfigById(id: number): Promise<AIConfig | null> {
return null
}
const models = row.model ? JSON.parse(row.model) : []
- logTaskProgress('AIConfig', 'config-by-id-selected', {
- configId: id,
- provider: row.provider,
- model: models[0] || '',
- serviceType: row.serviceType,
- })
+ const logKey = `${row.provider}:${models[0] || ''}:${row.serviceType}`
+ if (lastLoggedConfigByIdKey.get(id) !== logKey) {
+ lastLoggedConfigByIdKey.set(id, logKey)
+ logTaskProgress('AIConfig', 'config-by-id-selected', {
+ configId: id,
+ provider: row.provider,
+ model: models[0] || '',
+ serviceType: row.serviceType,
+ })
+ }
return {
provider: row.provider || '',
baseUrl: row.baseUrl,
diff --git a/backend/src/services/extraction.ts b/backend/src/services/extraction.ts
index 793188f..4b0f8a1 100644
--- a/backend/src/services/extraction.ts
+++ b/backend/src/services/extraction.ts
@@ -5,7 +5,7 @@
*/
import { mastra } from '../mastra/index.js'
import { buildAgentRequestContext } from '../agents/context.js'
-import { logTaskError, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
+import { logTaskError, logTaskProgress, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
export type ExtractTarget = 'characters' | 'scenes' | 'props'
export const EXTRACT_TARGETS: ExtractTarget[] = ['characters', 'scenes', 'props']
@@ -22,30 +22,55 @@ const keyOf = (episodeId: number, target: string) => `${episodeId}:${target}`
/** 每类资产的提取指令:限定只提取该类型,并要求与已有数据去重合并 */
const EXTRACT_MESSAGES: Record<ExtractTarget, string> = {
- characters: '请从本集剧本中提取所有角色信息(外貌需融合性格、含妆造),先用 read_existing_characters 读取已有角色去重,再用 save_dedup_characters 保存。本次只提取角色,不要提取场景和道具。',
+ characters: '请从本集剧本中提取所有角色信息(外貌需融合性格、含妆造),先用 read_existing_characters 读取项目已有角色,同名或近名(带括号定位/别名,如「林小雨(主角)」与「林小雨」)直接复用已有、不要重复创建,再用 save_dedup_characters 保存。本次只提取角色,不要提取场景和道具。',
scenes: '请从本集剧本中提取所有场景信息(地点、时间、光影等),先用 read_existing_scenes 读取已有场景去重,再用 save_dedup_scenes 保存。本次只提取场景,不要提取角色和道具。',
- props: '请从本集剧本中提取推动事态发展的关键道具(只记录物品外貌;与事态发展无关的不要提取),先用 read_existing_props 读取已有道具去重,再用 save_dedup_props 保存。本次只提取道具,不要提取角色和场景。',
+ props: '请从本集剧本中提取关键道具——必须同时满足:① 直接推动剧情(出现/交接/损坏/发现会引发情节转折,如凶器、信物、关键文件、定情礼物、证据);② 值得单独生成白底单品图(分镜会给它特写或反复出现)。判定三问任一答"否"即放弃:删掉它剧情依然成立吗?它只是随手使用的日常物品(手机、筷子、水杯)吗?它是场景陈设(桌椅、灯具)吗?宁可少提不要多提,一集通常 0-3 个,超过 3 个只保留最重要的 3 个,没有就一个都不提取(save_dedup_props 传空数组)。description 只记录物品外貌。先用 read_existing_props 读取已有道具去重,再用 save_dedup_props 保存。本次只提取道具,不要提取角色和场景。',
}
-/** 启动异步提取任务(立即返回);同集同类型已在运行时返回 false */
-export function startExtraction(episodeId: number, dramaId: number, target: ExtractTarget): boolean {
+/** 启动异步提取任务(立即返回);同集同类型已在运行时返回 false;可指定文本模型覆盖 */
+export function startExtraction(episodeId: number, dramaId: number, target: ExtractTarget, opts: { model?: string; configId?: number } = {}): boolean {
const key = keyOf(episodeId, target)
if (tasks.get(key)?.status === 'running') return false
const task: ExtractTask = { status: 'running', started_at: new Date().toISOString() }
tasks.set(key, task)
- logTaskStart('Extract', target, { episodeId, dramaId })
+ logTaskStart('Extract', target, { episodeId, dramaId, model: opts.model || undefined, configId: opts.configId || undefined })
;(async () => {
const agent = mastra.getAgent('extractor')
if (!agent) throw new Error('提取 Agent 不可用')
- const requestContext = buildAgentRequestContext({ episodeId, dramaId })
- await agent.generate([{ role: 'user', content: EXTRACT_MESSAGES[target] }], { maxSteps: 20, requestContext })
+ const requestContext = buildAgentRequestContext({
+ episodeId,
+ dramaId,
+ modelOverride: opts.model || undefined,
+ textConfigId: opts.configId || undefined,
+ })
+ return agent.generate([{ role: 'user', content: EXTRACT_MESSAGES[target] }], {
+ maxSteps: 20,
+ requestContext,
+ // 逐步打印 Agent 进展:调用了哪些工具、输出了什么
+ onStepFinish: (step: any) => {
+ const tools = (step?.toolCalls || [])
+ .map((t: any) => t?.toolName || t?.payload?.toolName)
+ .filter(Boolean)
+ logTaskProgress('Extract', `${target}-step`, {
+ episodeId,
+ tools: tools.length ? tools.join(',') : undefined,
+ text: (step?.text || '').slice(0, 200) || undefined,
+ })
+ },
+ })
})()
- .then(() => {
+ .then((result: any) => {
task.status = 'done'
task.finished_at = new Date().toISOString()
- logTaskSuccess('Extract', target, { episodeId })
+ const toolNames = (result?.toolCalls || []).map((t: any) => t?.toolName).filter(Boolean)
+ logTaskSuccess('Extract', target, {
+ episodeId,
+ steps: result?.steps?.length,
+ toolCalls: toolNames.join(',') || undefined,
+ reply: (result?.text || '').slice(0, 300) || undefined,
+ })
})
.catch((err: any) => {
task.status = 'error'
diff --git a/backend/src/services/final-prompt.ts b/backend/src/services/final-prompt.ts
index 8b28768..a34fd99 100644
--- a/backend/src/services/final-prompt.ts
+++ b/backend/src/services/final-prompt.ts
@@ -16,20 +16,28 @@ type CharacterRow = typeof schema.characters.$inferSelect
type SceneRow = typeof schema.scenes.$inferSelect
type PropRow = typeof schema.props.$inferSelect
-async function runPromptAgent(episodeId: number, dramaId: number, message: string) {
+/** 顶栏选择的文本模型/配置覆盖(不传则跟随 Agent 与文本配置默认) */
+export interface PromptAgentOptions { model?: string; configId?: number }
+
+async function runPromptAgent(episodeId: number, dramaId: number, message: string, opts?: PromptAgentOptions) {
const agent = mastra.getAgent('prompt_generator')
if (!agent) throw new Error('图片提示词 Agent 不可用')
- const requestContext = buildAgentRequestContext({ episodeId, dramaId })
+ const requestContext = buildAgentRequestContext({
+ episodeId,
+ dramaId,
+ modelOverride: opts?.model || undefined,
+ textConfigId: opts?.configId || undefined,
+ })
await agent.generate([{ role: 'user', content: message }], { maxSteps: 12, requestContext })
}
/** 确保角色拥有三视图最终提示词,返回最终提示词(失败返回 '');force 时忽略已有提示词强制重新生成 */
-export async function ensureCharacterFinalPrompt(char: CharacterRow, episodeId: number, force = false): Promise<string> {
+export async function ensureCharacterFinalPrompt(char: CharacterRow, episodeId: number, force = false, opts?: PromptAgentOptions): Promise<string> {
if (char.finalPrompt && !force) return char.finalPrompt
try {
logTaskProgress('FinalPrompt', 'character-generate', { characterId: char.id, episodeId })
await runPromptAgent(episodeId, char.dramaId,
- `为角色「${char.name}」(character_id=${char.id}) 生成三视图最终提示词,并调用 save_character_final_prompt 保存。`)
+ `为角色「${char.name}」(character_id=${char.id}) 生成三视图最终提示词,并调用 save_character_final_prompt 保存。`, opts)
const [fresh] = await db.select().from(schema.characters).where(eq(schema.characters.id, char.id))
return fresh?.finalPrompt || ''
} catch (err: any) {
@@ -39,12 +47,12 @@ export async function ensureCharacterFinalPrompt(char: CharacterRow, episodeId:
}
/** 确保场景拥有固定视角(前中后景)最终提示词,返回最终提示词(失败返回 '');force 时忽略已有提示词强制重新生成 */
-export async function ensureSceneFinalPrompt(scene: SceneRow, episodeId: number, force = false): Promise<string> {
+export async function ensureSceneFinalPrompt(scene: SceneRow, episodeId: number, force = false, opts?: PromptAgentOptions): Promise<string> {
if (scene.finalPrompt && !force) return scene.finalPrompt
try {
logTaskProgress('FinalPrompt', 'scene-generate', { sceneId: scene.id, episodeId })
await runPromptAgent(episodeId, scene.dramaId,
- `为场景「${scene.location}」(scene_id=${scene.id}) 生成固定视角(前景/中景/后景)最终提示词,并调用 save_scene_final_prompt 保存。`)
+ `为场景「${scene.location}」(scene_id=${scene.id}) 生成固定视角(前景/中景/后景)最终提示词,并调用 save_scene_final_prompt 保存。`, opts)
const [fresh] = await db.select().from(schema.scenes).where(eq(schema.scenes.id, scene.id))
return fresh?.finalPrompt || ''
} catch (err: any) {
@@ -54,12 +62,12 @@ export async function ensureSceneFinalPrompt(scene: SceneRow, episodeId: number,
}
/** 确保道具拥有白底单品最终提示词,返回最终提示词(失败返回 '');force 时忽略已有提示词强制重新生成 */
-export async function ensurePropFinalPrompt(prop: PropRow, episodeId: number, force = false): Promise<string> {
+export async function ensurePropFinalPrompt(prop: PropRow, episodeId: number, force = false, opts?: PromptAgentOptions): Promise<string> {
if (prop.finalPrompt && !force) return prop.finalPrompt
try {
logTaskProgress('FinalPrompt', 'prop-generate', { propId: prop.id, episodeId })
await runPromptAgent(episodeId, prop.dramaId,
- `为道具「${prop.name}」(prop_id=${prop.id}) 生成白底单品最终提示词,并调用 save_prop_final_prompt 保存。`)
+ `为道具「${prop.name}」(prop_id=${prop.id}) 生成白底单品最终提示词,并调用 save_prop_final_prompt 保存。`, opts)
const [fresh] = await db.select().from(schema.props).where(eq(schema.props.id, prop.id))
return fresh?.finalPrompt || ''
} catch (err: any) {
diff --git a/backend/src/services/generation.ts b/backend/src/services/generation.ts
new file mode 100644
index 0000000..408550c
--- /dev/null
+++ b/backend/src/services/generation.ts
@@ -0,0 +1,535 @@
+/**
+ * 统一生成任务服务 — 图片/视频生成共用 sys_task 表与同一条生命周期:
+ * 创建(processing) → 适配器构建请求 → 同步完成或异步轮询 → 下载落盘 → 回写业务表
+ */
+import { db, getInsertId, schema } from '../db/index.js'
+import { eq } from 'drizzle-orm'
+import { getActiveConfig, getConfigById } from './ai.js'
+import { now } from '../utils/response.js'
+import { downloadFile, readImageAsCompressedDataUrl, saveBase64Image } from '../utils/storage.js'
+import { getImageAdapter, getVideoAdapter } from './adapters/registry'
+import type { AIConfig } from './adapters/types'
+import { logTaskError, logTaskPayload, logTaskProgress, logTaskStart, logTaskSuccess, logTaskWarn, redactUrl } from '../utils/task-logger.js'
+
+type TaskType = 'image' | 'video'
+
+const taskLabel = (type: TaskType) => (type === 'image' ? 'ImageTask' : 'VideoTask')
+
+// 轮询节奏:图片 5s×120(上限 10 分钟);视频 10s×300
+const POLL_PROFILES: Record<TaskType, { attempts: number; intervalMs: number; maxDurationMs: number | null }> = {
+ image: { attempts: 120, intervalMs: 5000, maxDurationMs: 600_000 },
+ video: { attempts: 300, intervalMs: 10_000, maxDurationMs: null },
+}
+
+interface GenerateImageParams {
+ storyboardId?: number
+ dramaId?: number
+ sceneId?: number
+ characterId?: number
+ propId?: number
+ prompt: string
+ model?: string
+ size?: string
+ referenceImages?: string[]
+ frameType?: string
+ configId?: number
+}
+
+interface GenerateVideoParams {
+ storyboardId?: number
+ dramaId?: number
+ prompt: string
+ model?: string
+ referenceMode?: string
+ imageUrl?: string
+ firstFrameUrl?: string
+ lastFrameUrl?: string
+ referenceImageUrls?: string[]
+ referenceVideoUrls?: string[]
+ referenceAudioUrls?: string[]
+ generateAudio?: boolean
+ duration?: number
+ aspectRatio?: string
+ resolution?: string
+ configId?: number
+}
+
+export async function generateImage(params: GenerateImageParams): Promise<number> {
+ const config = params.configId
+ ? await getConfigById(params.configId)
+ : await getActiveConfig('image')
+ if (!config) throw new Error('No active image AI config')
+
+ const id = await createTask('image', config, {
+ storyboardId: params.storyboardId,
+ dramaId: params.dramaId,
+ sceneId: params.sceneId,
+ characterId: params.characterId,
+ propId: params.propId,
+ prompt: params.prompt,
+ model: params.model || config.model,
+ }, {
+ size: params.size || '1920x1080',
+ frameType: params.frameType,
+ referenceImages: params.referenceImages,
+ })
+
+ logTaskStart('ImageTask', 'enqueue', {
+ id,
+ provider: config.provider,
+ storyboardId: params.storyboardId,
+ sceneId: params.sceneId,
+ characterId: params.characterId,
+ frameType: params.frameType,
+ model: params.model || config.model,
+ })
+ logTaskPayload('ImageTask', 'enqueue params', {
+ id,
+ config: { provider: config.provider, model: config.model, baseUrl: config.baseUrl },
+ params,
+ })
+ return id
+}
+
+export async function generateVideo(params: GenerateVideoParams): Promise<number> {
+ const config = params.configId
+ ? await getConfigById(params.configId)
+ : await getActiveConfig('video')
+ if (!config) throw new Error('No active video AI config')
+
+ const id = await createTask('video', config, {
+ storyboardId: params.storyboardId,
+ dramaId: params.dramaId,
+ prompt: params.prompt,
+ model: params.model || config.model,
+ }, {
+ referenceMode: params.referenceMode || 'reference',
+ imageUrl: params.imageUrl,
+ firstFrameUrl: params.firstFrameUrl,
+ lastFrameUrl: params.lastFrameUrl,
+ referenceImageUrls: params.referenceImageUrls,
+ referenceVideoUrls: params.referenceVideoUrls,
+ referenceAudioUrls: params.referenceAudioUrls,
+ generateAudio: params.generateAudio === false ? 0 : 1,
+ duration: params.duration || 5,
+ aspectRatio: params.aspectRatio || '16:9',
+ resolution: params.resolution === '480p' ? '480p' : '720p',
+ })
+
+ logTaskStart('VideoTask', 'enqueue', {
+ id,
+ provider: config.provider,
+ storyboardId: params.storyboardId,
+ dramaId: params.dramaId,
+ referenceMode: params.referenceMode || 'reference',
+ duration: params.duration || 5,
+ })
+ logTaskPayload('VideoTask', 'enqueue params', {
+ id,
+ config: { provider: config.provider, model: config.model, baseUrl: config.baseUrl },
+ params,
+ })
+ return id
+}
+
+async function createTask(
+ type: TaskType,
+ config: AIConfig,
+ fields: {
+ storyboardId?: number
+ dramaId?: number
+ sceneId?: number
+ characterId?: number
+ propId?: number
+ prompt: string
+ model?: string | null
+ },
+ params: Record<string, unknown>,
+): Promise<number> {
+ const ts = now()
+ const res = await db.insert(schema.sysTask).values({
+ type,
+ ...fields,
+ provider: config.provider,
+ params: JSON.stringify(params),
+ status: 'processing',
+ createdAt: ts,
+ updatedAt: ts,
+ })
+
+ const id = getInsertId(res)
+ processTask(id, config).catch(err => {
+ logTaskError(taskLabel(type), 'process', { id, error: err.message })
+ console.error(`${taskLabel(type)} ${id} failed:`, err)
+ })
+ return id
+}
+
+function parseTaskParams(raw: string | null | undefined): Record<string, any> {
+ if (!raw) return {}
+ try {
+ return JSON.parse(raw) || {}
+ } catch {
+ return {}
+ }
+}
+
+async function processTask(id: number, config: AIConfig) {
+ try {
+ const [record] = await db.select().from(schema.sysTask).where(eq(schema.sysTask.id, id))
+ if (!record) return
+ const type = record.type as TaskType
+ const label = taskLabel(type)
+ const params = parseTaskParams(record.params)
+ logTaskProgress(label, 'build-request', {
+ id,
+ provider: config.provider,
+ storyboardId: record.storyboardId,
+ sceneId: record.sceneId,
+ characterId: record.characterId,
+ })
+
+ let url: string, method: string, headers: Record<string, string>, body: unknown
+
+ if (type === 'image') {
+ const adapter = getImageAdapter(config.provider)
+ const resolvedReferenceImages = await normalizeReferenceImages(params.referenceImages)
+ ;({ url, method, headers, body } = adapter.buildGenerateRequest(config, {
+ id: record.id,
+ model: record.model,
+ prompt: record.prompt,
+ size: params.size,
+ frameType: params.frameType,
+ referenceImages: resolvedReferenceImages.length ? JSON.stringify(resolvedReferenceImages) : null,
+ }))
+ } else {
+ const adapter = getVideoAdapter(config.provider)
+ const resolvedImageUrl = await normalizeVideoReferenceUrl(params.imageUrl)
+ const resolvedFirstFrameUrl = await normalizeVideoReferenceUrl(params.firstFrameUrl)
+ const resolvedLastFrameUrl = await normalizeVideoReferenceUrl(params.lastFrameUrl)
+ const resolvedReferenceImageUrls = await normalizeVideoReferenceUrls(params.referenceImageUrls)
+ // 参考视频/音频文件较大,不适合 dataURL 内联,需解析为公网可访问 URL
+ const resolvedReferenceVideoUrls = resolvePublicMediaUrls(params.referenceVideoUrls, 'video')
+ const resolvedReferenceAudioUrls = resolvePublicMediaUrls(params.referenceAudioUrls, 'audio')
+ ;({ url, method, headers, body } = adapter.buildGenerateRequest(config, {
+ id: record.id,
+ model: record.model,
+ prompt: record.prompt,
+ referenceMode: params.referenceMode,
+ imageUrl: resolvedImageUrl,
+ firstFrameUrl: resolvedFirstFrameUrl,
+ lastFrameUrl: resolvedLastFrameUrl,
+ referenceImageUrls: resolvedReferenceImageUrls.length ? JSON.stringify(resolvedReferenceImageUrls) : null,
+ referenceVideoUrls: resolvedReferenceVideoUrls.length ? JSON.stringify(resolvedReferenceVideoUrls) : null,
+ referenceAudioUrls: resolvedReferenceAudioUrls.length ? JSON.stringify(resolvedReferenceAudioUrls) : null,
+ generateAudio: params.generateAudio,
+ duration: params.duration,
+ aspectRatio: params.aspectRatio,
+ resolution: params.resolution,
+ }))
+ }
+
+ logTaskProgress(label, 'request', {
+ id,
+ provider: config.provider,
+ method,
+ url: redactUrl(url),
+ model: record.model,
+ })
+ logTaskPayload(label, 'request payload', { id, method, url, headers, body })
+
+ const resp = await fetch(url, {
+ method,
+ headers,
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(600_000),
+ })
+
+ if (!resp.ok) throw new Error(`API error ${resp.status}: ${await resp.text()}`)
+ const result = await resp.json() as any
+ logTaskPayload(label, 'response payload', { id, provider: config.provider, result })
+
+ if (type === 'image') {
+ const adapter = getImageAdapter(config.provider)
+ const { isAsync, taskId, imageUrl } = adapter.parseGenerateResponse(result)
+
+ if (!isAsync && imageUrl) {
+ logTaskProgress(label, 'sync-complete', { id, imageUrl })
+ await handleImageComplete(record, imageUrl)
+ return
+ }
+
+ if (!isAsync && !imageUrl) {
+ // 同步模式但无 URL(Gemini 等返回 base64)
+ const b64 = adapter.extractImageBase64(result)
+ if (b64) {
+ logTaskProgress(label, 'sync-base64-complete', { id, mimeType: b64.mimeType })
+ await handleImageCompleteBase64(record, b64.data, b64.mimeType)
+ return
+ }
+ throw new Error('No image URL or base64 data in response')
+ }
+
+ await markPolling(id, taskId)
+ pollTask(record, config, taskId!)
+ return
+ }
+
+ const adapter = getVideoAdapter(config.provider)
+ const { isAsync, taskId, videoUrl } = adapter.parseGenerateResponse(result)
+
+ if (!isAsync && videoUrl) {
+ logTaskProgress(label, 'sync-complete', { id, videoUrl })
+ await handleVideoComplete(record, videoUrl, params.duration)
+ return
+ }
+
+ await markPolling(id, taskId)
+ pollTask(record, config, taskId!)
+ } catch (err: any) {
+ await failTask(id, err.message)
+ }
+}
+
+async function markPolling(id: number, taskId: string | undefined) {
+ await db.update(schema.sysTask)
+ .set({ taskId, status: 'processing', updatedAt: now() })
+ .where(eq(schema.sysTask.id, id))
+ logTaskProgress('SysTask', 'poll-start', { id, taskId })
+}
+
+async function failTask(id: number, message: string) {
+ logTaskError('SysTask', 'failed', { id, error: message })
+ await db.update(schema.sysTask)
+ .set({ status: 'failed', errorMsg: message, updatedAt: now() })
+ .where(eq(schema.sysTask.id, id))
+}
+
+type SysTaskRecord = typeof schema.sysTask.$inferSelect
+
+async function pollTask(record: SysTaskRecord, config: AIConfig, taskId: string) {
+ const type = record.type as TaskType
+ const label = taskLabel(type)
+ const profile = POLL_PROFILES[type]
+ const adapter = type === 'image' ? getImageAdapter(config.provider) : getVideoAdapter(config.provider)
+ const startedAt = Date.now()
+
+ for (let i = 0; i < profile.attempts; i++) {
+ if (profile.maxDurationMs && Date.now() - startedAt >= profile.maxDurationMs) {
+ await failTask(record.id, 'Timeout: Polling exceeded 10 minutes')
+ return
+ }
+ await new Promise(r => setTimeout(r, profile.intervalMs))
+ try {
+ const { url, method, headers } = adapter.buildPollRequest(config, taskId)
+ logTaskProgress(label, 'poll-request', {
+ id: record.id,
+ taskId,
+ provider: config.provider,
+ method,
+ url: redactUrl(url),
+ attempt: i + 1,
+ })
+ const remainingMs = profile.maxDurationMs
+ ? Math.max(1_000, profile.maxDurationMs - (Date.now() - startedAt))
+ : 600_000
+ const resp = await fetch(url, {
+ method,
+ headers,
+ signal: AbortSignal.timeout(remainingMs),
+ })
+ if (!resp.ok) continue
+ const result = await resp.json() as any
+
+ // 图片/视频 PollResponse 结构不同,这里统一按 any 取值后按 type 分支
+ const pollResp: any = adapter.parsePollResponse(result)
+
+ if (pollResp.status === 'completed') {
+ if (type === 'image') {
+ if (pollResp.imageUrl) {
+ logTaskSuccess(label, 'poll-complete', { id: record.id, taskId, imageUrl: pollResp.imageUrl })
+ await handleImageComplete(record, pollResp.imageUrl)
+ return
+ }
+ if (adapter.provider === 'gemini') {
+ // Gemini 可能返回 base64
+ const b64 = (adapter as ReturnType<typeof getImageAdapter>).extractImageBase64(result)
+ if (b64) {
+ logTaskSuccess(label, 'poll-base64-complete', { id: record.id, taskId, mimeType: b64.mimeType })
+ await handleImageCompleteBase64(record, b64.data, b64.mimeType)
+ return
+ }
+ }
+ } else if (pollResp.videoUrl) {
+ logTaskSuccess(label, 'poll-complete', { id: record.id, taskId, videoUrl: pollResp.videoUrl })
+ await handleVideoComplete(record, pollResp.videoUrl, null)
+ return
+ }
+ }
+ if (pollResp.status === 'failed') {
+ throw new Error(pollResp.error || 'Generation failed')
+ }
+ } catch (err: any) {
+ const exhausted = i === profile.attempts - 1
+ || (profile.maxDurationMs != null && Date.now() - startedAt >= profile.maxDurationMs)
+ if (exhausted) {
+ await failTask(record.id, `Timeout: ${err.message}`)
+ return
+ }
+ logTaskWarn(label, 'poll-retry', { id: record.id, taskId, attempt: i + 1, error: err.message })
+ }
+ }
+ await failTask(record.id, 'Timeout: polling attempts exhausted')
+}
+
+async function handleImageComplete(record: SysTaskRecord, imageUrl: string) {
+ const localPath = await downloadFile(imageUrl, 'images')
+
+ await db.update(schema.sysTask)
+ .set({ resultUrl: imageUrl, localPath, status: 'completed', completedAt: now(), updatedAt: now() })
+ .where(eq(schema.sysTask.id, record.id))
+
+ logTaskSuccess('ImageTask', 'downloaded', { id: record.id, provider: record.provider, localPath })
+
+ await writeBackImageAssets(record, localPath)
+}
+
+async function handleImageCompleteBase64(record: SysTaskRecord, base64Data: string, mimeType: string) {
+ const localPath = await saveBase64Image(base64Data, mimeType, 'images')
+
+ await db.update(schema.sysTask)
+ .set({ localPath, status: 'completed', completedAt: now(), updatedAt: now() })
+ .where(eq(schema.sysTask.id, record.id))
+
+ logTaskSuccess('ImageTask', 'saved-base64', { id: record.id, provider: record.provider, mimeType, localPath })
+
+ await writeBackImageAssets(record, localPath)
+}
+
+// 图片完成后回写业务表:分镜(按 frameType)、角色、场景、道具
+async function writeBackImageAssets(record: SysTaskRecord, localPath: string) {
+ const params = parseTaskParams(record.params)
+ if (record.storyboardId) {
+ const sbUpdate: Record<string, any> = { updatedAt: now() }
+ if (params.frameType === 'first_frame') sbUpdate.firstFrameImage = localPath
+ else if (params.frameType === 'last_frame') sbUpdate.lastFrameImage = localPath
+ else sbUpdate.composedImage = localPath
+ await db.update(schema.storyboards).set(sbUpdate).where(eq(schema.storyboards.id, record.storyboardId))
+ }
+ if (record.characterId) {
+ await db.update(schema.characters).set({ imageUrl: localPath, updatedAt: now() }).where(eq(schema.characters.id, record.characterId))
+ }
+ if (record.sceneId) {
+ await db.update(schema.scenes).set({ imageUrl: localPath, status: 'completed', updatedAt: now() }).where(eq(schema.scenes.id, record.sceneId))
+ }
+ if (record.propId) {
+ await db.update(schema.props).set({ imageUrl: localPath, updatedAt: now() }).where(eq(schema.props.id, record.propId))
+ }
+}
+
+async function handleVideoComplete(record: SysTaskRecord, videoUrl: string, duration: number | null | undefined) {
+ const localPath = await downloadFile(videoUrl, 'videos')
+ await db.update(schema.sysTask)
+ .set({ resultUrl: videoUrl, localPath, status: 'completed', completedAt: now(), updatedAt: now() })
+ .where(eq(schema.sysTask.id, record.id))
+
+ logTaskSuccess('VideoTask', 'downloaded', { id: record.id, localPath, storyboardId: record.storyboardId, duration })
+
+ if (record.storyboardId) {
+ await db.update(schema.storyboards)
+ .set({ videoUrl: localPath, duration: duration || undefined, updatedAt: now() })
+ .where(eq(schema.storyboards.id, record.storyboardId))
+ }
+}
+
+// ─── 参考素材归一化 ───────────────────────────────────────────────
+
+async function normalizeReferenceImages(refs: string[] | null | undefined): Promise<string[]> {
+ if (!Array.isArray(refs) || !refs.length) return []
+
+ const deduped = Array.from(
+ new Set(
+ refs
+ .map((item) => String(item || '').trim())
+ .filter(Boolean),
+ ),
+ )
+
+ const normalized = await Promise.all(deduped.map(async (value) => {
+ if (value.startsWith('data:image/')) return value
+ if (value.startsWith('static/') || value.startsWith('/static/')) {
+ const localPath = value.startsWith('/static/') ? value.slice(1) : value
+ try {
+ return await readImageAsCompressedDataUrl(localPath, {
+ maxWidth: 768,
+ maxHeight: 768,
+ quality: 68,
+ })
+ } catch (err) {
+ logTaskWarn('ImageTask', 'reference-read-failed', { path: localPath, error: (err as Error).message })
+ return null
+ }
+ }
+ return value
+ }))
+
+ return normalized.filter((item): item is string => !!item).slice(0, 6)
+}
+
+async function normalizeVideoReferenceUrl(value: string | null | undefined): Promise<string | null> {
+ const raw = String(value || '').trim()
+ if (!raw) return null
+ if (raw.startsWith('data:image/')) return raw
+ if (raw.startsWith('static/') || raw.startsWith('/static/')) {
+ const localPath = raw.startsWith('/static/') ? raw.slice(1) : raw
+ try {
+ return await readImageAsCompressedDataUrl(localPath, {
+ maxWidth: 768,
+ maxHeight: 768,
+ quality: 68,
+ })
+ } catch (err) {
+ logTaskWarn('VideoTask', 'reference-read-failed', { path: localPath, error: (err as Error).message })
+ return null
+ }
+ }
+ return raw
+}
+
+async function normalizeVideoReferenceUrls(refs: string[] | null | undefined): Promise<string[]> {
+ if (!Array.isArray(refs) || !refs.length) return []
+ const normalized = await Promise.all(
+ Array.from(new Set(refs.map((item) => String(item || '').trim()).filter(Boolean))).map((item) => normalizeVideoReferenceUrl(item)),
+ )
+ return normalized.filter((item): item is string => !!item)
+}
+
+/**
+ * 将参考视频/音频解析为 Seedance API 可访问的 URL。
+ * http(s)/dataURL 直通;本地 static 路径需要 PUBLIC_BASE_URL 拼成公网地址,
+ * 未配置时抛出可操作的中文错误(落入 catch 写入 error_msg 供前端展示)。
+ */
+function resolvePublicMediaUrl(value: string | null | undefined, kind: 'video' | 'audio'): string | null {
+ const raw = String(value || '').trim()
+ if (!raw) return null
+ if (raw.startsWith('http://') || raw.startsWith('https://') || raw.startsWith('data:')) return raw
+ if (raw.startsWith('static/') || raw.startsWith('/static/')) {
+ const base = (process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '')
+ if (!base) {
+ const label = kind === 'video' ? '视频' : '音频'
+ throw new Error(
+ `参考${label}为本地路径 ${raw},但后端未配置 PUBLIC_BASE_URL,Seedance API 无法访问内网地址。` +
+ `请在 backend/.env 配置 PUBLIC_BASE_URL(如 https://your-domain.com)后重试,或改用公网 URL。`,
+ )
+ }
+ const p = raw.startsWith('/') ? raw : `/${raw}`
+ return `${base}${p}`
+ }
+ return raw
+}
+
+function resolvePublicMediaUrls(refs: string[] | null | undefined, kind: 'video' | 'audio'): string[] {
+ if (!Array.isArray(refs) || !refs.length) return []
+ const items = Array.from(new Set(refs.map((item) => String(item || '').trim()).filter(Boolean)))
+ return items.map((item) => resolvePublicMediaUrl(item, kind)).filter((item): item is string => !!item)
+}
diff --git a/backend/src/services/image-generation.ts b/backend/src/services/image-generation.ts
deleted file mode 100644
index 335293c..0000000
--- a/backend/src/services/image-generation.ts
+++ /dev/null
@@ -1,338 +0,0 @@
-import { db, getInsertId, schema } from '../db/index.js'
-import { eq } from 'drizzle-orm'
-import { getActiveConfig, getConfigById } from './ai.js'
-import { now } from '../utils/response.js'
-import { downloadFile, readImageAsCompressedDataUrl, saveBase64Image } from '../utils/storage.js'
-import { getImageAdapter } from './adapters/registry'
-import type { AIConfig } from './adapters/types'
-import { logTaskError, logTaskPayload, logTaskProgress, logTaskStart, logTaskSuccess, logTaskWarn, redactUrl } from '../utils/task-logger.js'
-
-interface GenerateImageParams {
- storyboardId?: number
- dramaId?: number
- sceneId?: number
- characterId?: number
- propId?: number
- prompt: string
- model?: string
- size?: string
- referenceImages?: string[]
- frameType?: string
- configId?: number
-}
-
-export async function generateImage(params: GenerateImageParams): Promise<number> {
- const ts = now()
- const config = params.configId
- ? await getConfigById(params.configId)
- : await getActiveConfig('image')
- if (!config) throw new Error('No active image AI config')
-
- const res = await db.insert(schema.imageGenerations).values({
- storyboardId: params.storyboardId,
- dramaId: params.dramaId,
- sceneId: params.sceneId,
- characterId: params.characterId,
- propId: params.propId,
- prompt: params.prompt,
- model: params.model || config.model,
- provider: config.provider,
- size: params.size || '1920x1080',
- frameType: params.frameType,
- referenceImages: params.referenceImages ? JSON.stringify(params.referenceImages) : null,
- status: 'processing',
- createdAt: ts,
- updatedAt: ts,
- })
-
- const lastId = getInsertId(res)
- logTaskStart('ImageTask', 'enqueue', {
- id: lastId,
- provider: config.provider,
- storyboardId: params.storyboardId,
- sceneId: params.sceneId,
- characterId: params.characterId,
- frameType: params.frameType,
- model: params.model || config.model,
- })
- logTaskPayload('ImageTask', 'enqueue params', {
- id: lastId,
- config: {
- provider: config.provider,
- model: config.model,
- baseUrl: config.baseUrl,
- },
- params,
- })
- processImageGeneration(lastId, config).catch(err => {
- logTaskError('ImageTask', 'process', { id: lastId, error: err.message })
- console.error(`Image generation ${lastId} failed:`, err)
- })
- return lastId
-}
-
-async function processImageGeneration(id: number, config: AIConfig) {
- const adapter = getImageAdapter(config.provider)
-
- try {
- const rows = await db.select().from(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
- const record = rows[0]
- if (!record) return
- logTaskProgress('ImageTask', 'build-request', {
- id,
- provider: config.provider,
- storyboardId: record.storyboardId,
- sceneId: record.sceneId,
- characterId: record.characterId,
- frameType: record.frameType,
- })
-
- // 使用 Adapter 构建请求
- const resolvedReferenceImages = await normalizeReferenceImages(record.referenceImages)
- const { url, method, headers, body } = adapter.buildGenerateRequest(config, {
- id: record.id,
- model: record.model,
- prompt: record.prompt,
- size: record.size,
- frameType: record.frameType,
- referenceImages: resolvedReferenceImages ? JSON.stringify(resolvedReferenceImages) : null,
- })
- logTaskProgress('ImageTask', 'request', {
- id,
- provider: config.provider,
- method,
- url: redactUrl(url),
- model: record.model,
- })
- logTaskPayload('ImageTask', 'request payload', {
- id,
- method,
- url,
- headers,
- body,
- })
-
- const resp = await fetch(url, {
- method,
- headers,
- body: JSON.stringify(body),
- signal: AbortSignal.timeout(600_000),
- })
-
- if (!resp.ok) throw new Error(`API error ${resp.status}: ${await resp.text()}`)
- const result = await resp.json() as any
- logTaskPayload('ImageTask', 'response payload', {
- id,
- provider: config.provider,
- result,
- })
-
- const { isAsync, taskId, imageUrl } = adapter.parseGenerateResponse(result)
-
- if (!isAsync && imageUrl) {
- logTaskProgress('ImageTask', 'sync-complete', { id, imageUrl })
- // 同步模式:直接下载图片
- await handleImageComplete(id, config.provider, imageUrl)
- return
- }
-
- if (!isAsync && !imageUrl) {
- // 同步模式但无 URL(Gemini 等返回 base64)
- const b64 = adapter.extractImageBase64(result)
- if (b64) {
- logTaskProgress('ImageTask', 'sync-base64-complete', { id, mimeType: b64.mimeType })
- await handleImageCompleteBase64(id, config.provider, b64.data, b64.mimeType)
- return
- }
- throw new Error('No image URL or base64 data in response')
- }
-
- // 异步模式:更新 taskId,开始轮询
- await db.update(schema.imageGenerations)
- .set({ taskId, status: 'processing', updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- logTaskProgress('ImageTask', 'poll-start', { id, taskId, provider: config.provider })
- pollImageTask(id, config, taskId!)
- } catch (err: any) {
- logTaskError('ImageTask', 'process', { id, provider: config.provider, error: err.message })
- await db.update(schema.imageGenerations)
- .set({ status: 'failed', errorMsg: err.message, updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- }
-}
-
-async function normalizeReferenceImages(raw: string | null | undefined): Promise<string[]> {
- if (!raw) return []
- let refs: string[] = []
- try {
- refs = JSON.parse(raw)
- } catch {
- refs = []
- }
-
- const deduped = Array.from(
- new Set(
- refs
- .map((item) => String(item || '').trim())
- .filter(Boolean),
- ),
- )
-
- const normalized = await Promise.all(deduped.map(async (value) => {
- if (value.startsWith('data:image/')) return value
- if (value.startsWith('static/') || value.startsWith('/static/')) {
- const localPath = value.startsWith('/static/') ? value.slice(1) : value
- try {
- return await readImageAsCompressedDataUrl(localPath, {
- maxWidth: 768,
- maxHeight: 768,
- quality: 68,
- })
- } catch (err) {
- logTaskWarn('ImageTask', 'reference-read-failed', { path: localPath, error: (err as Error).message })
- return null
- }
- }
- return value
- }))
-
- return normalized.filter((item): item is string => !!item).slice(0, 6)
-}
-
-async function pollImageTask(id: number, config: AIConfig, taskId: string) {
- const adapter = getImageAdapter(config.provider)
- const startedAt = Date.now()
- const maxDurationMs = 600_000
-
- for (let i = 0; i < 120; i++) {
- if (Date.now() - startedAt >= maxDurationMs) {
- logTaskError('ImageTask', 'poll-timeout', { id, taskId, error: 'Polling exceeded 10 minutes' })
- await db.update(schema.imageGenerations)
- .set({ status: 'failed', errorMsg: 'Timeout: Polling exceeded 10 minutes', updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- return
- }
- await new Promise(r => setTimeout(r, 5000))
- if (Date.now() - startedAt >= maxDurationMs) {
- logTaskError('ImageTask', 'poll-timeout', { id, taskId, error: 'Polling exceeded 10 minutes' })
- await db.update(schema.imageGenerations)
- .set({ status: 'failed', errorMsg: 'Timeout: Polling exceeded 10 minutes', updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- return
- }
- try {
- const { url, method, headers } = adapter.buildPollRequest(config, taskId)
- logTaskProgress('ImageTask', 'poll-request', {
- id,
- taskId,
- provider: config.provider,
- method,
- url: redactUrl(url),
- attempt: i + 1,
- })
- const remainingMs = Math.max(1_000, maxDurationMs - (Date.now() - startedAt))
- const resp = await fetch(url, {
- method,
- headers,
- signal: AbortSignal.timeout(remainingMs),
- })
- if (!resp.ok) continue
- const result = await resp.json() as any
-
- const pollResp = adapter.parsePollResponse(result)
-
- if (pollResp.status === 'completed' && pollResp.imageUrl) {
- logTaskSuccess('ImageTask', 'poll-complete', { id, taskId, imageUrl: pollResp.imageUrl })
- await handleImageComplete(id, config.provider, pollResp.imageUrl)
- return
- }
- if (pollResp.status === 'completed' && adapter.provider === 'gemini') {
- // Gemini 可能返回 base64
- const b64 = adapter.extractImageBase64(result)
- if (b64) {
- logTaskSuccess('ImageTask', 'poll-base64-complete', { id, taskId, mimeType: b64.mimeType })
- await handleImageCompleteBase64(id, config.provider, b64.data, b64.mimeType)
- return
- }
- }
- if (pollResp.status === 'failed') {
- logTaskError('ImageTask', 'poll-failed', { id, taskId, error: pollResp.error || 'Generation failed' })
- throw new Error(pollResp.error || 'Generation failed')
- }
- } catch (err: any) {
- if (i === 119 || Date.now() - startedAt >= maxDurationMs) {
- logTaskError('ImageTask', 'poll-timeout', { id, taskId, error: err.message })
- await db.update(schema.imageGenerations)
- .set({ status: 'failed', errorMsg: `Timeout: ${err.message}`, updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- return
- }
- logTaskWarn('ImageTask', 'poll-retry', { id, taskId, attempt: i + 1, error: err.message })
- }
- }
-}
-
-async function handleImageComplete(id: number, provider: string, imageUrl: string) {
- const localPath = await downloadFile(imageUrl, 'images')
- const rows = await db.select().from(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
- const record = rows[0]
-
- await db.update(schema.imageGenerations)
- .set({ imageUrl, localPath, status: 'completed', updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- logTaskSuccess('ImageTask', 'downloaded', { id, provider, localPath })
-
- // 更新关联表
- if (record?.storyboardId) {
- const sbUpdate: Record<string, any> = { updatedAt: now() }
- if (record.frameType === 'first_frame') sbUpdate.firstFrameImage = localPath
- else if (record.frameType === 'last_frame') sbUpdate.lastFrameImage = localPath
- else sbUpdate.composedImage = localPath
- await db.update(schema.storyboards).set(sbUpdate).where(eq(schema.storyboards.id, record.storyboardId))
- }
- if (record?.characterId) {
- await db.update(schema.characters).set({ imageUrl: localPath, updatedAt: now() }).where(eq(schema.characters.id, record.characterId))
- }
- if (record?.sceneId) {
- await db.update(schema.scenes).set({ imageUrl: localPath, status: 'completed', updatedAt: now() }).where(eq(schema.scenes.id, record.sceneId))
- }
- if (record?.propId) {
- await db.update(schema.props).set({ imageUrl: localPath, updatedAt: now() }).where(eq(schema.props.id, record.propId))
- }
-}
-
-async function handleImageCompleteBase64(id: number, provider: string, base64Data: string, mimeType: string) {
- const localPath = await saveBase64Image(base64Data, mimeType, 'images')
- const rows = await db.select().from(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
- const record = rows[0]
-
- await db.update(schema.imageGenerations)
- .set({ localPath, status: 'completed', updatedAt: now() })
- .where(eq(schema.imageGenerations.id, id))
-
- logTaskSuccess('ImageTask', 'saved-base64', { id, provider, mimeType, localPath })
-
- // 更新关联表
- if (record?.storyboardId) {
- const sbUpdate: Record<string, any> = { updatedAt: now() }
- if (record.frameType === 'first_frame') sbUpdate.firstFrameImage = localPath
- else if (record.frameType === 'last_frame') sbUpdate.lastFrameImage = localPath
- else sbUpdate.composedImage = localPath
- await db.update(schema.storyboards).set(sbUpdate).where(eq(schema.storyboards.id, record.storyboardId))
- }
- if (record?.characterId) {
- await db.update(schema.characters).set({ imageUrl: localPath, updatedAt: now() }).where(eq(schema.characters.id, record.characterId))
- }
- if (record?.sceneId) {
- await db.update(schema.scenes).set({ imageUrl: localPath, status: 'completed', updatedAt: now() }).where(eq(schema.scenes.id, record.sceneId))
- }
- if (record?.propId) {
- await db.update(schema.props).set({ imageUrl: localPath, updatedAt: now() }).where(eq(schema.props.id, record.propId))
- }
-}
diff --git a/backend/src/services/video-generation.ts b/backend/src/services/video-generation.ts
deleted file mode 100644
index a6a4a41..0000000
--- a/backend/src/services/video-generation.ts
+++ /dev/null
@@ -1,298 +0,0 @@
-import { db, getInsertId, schema } from '../db/index.js'
-import { eq } from 'drizzle-orm'
-import { getActiveConfig, getConfigById } from './ai.js'
-import { now } from '../utils/response.js'
-import { downloadFile, readImageAsCompressedDataUrl } from '../utils/storage.js'
-import { getVideoAdapter } from './adapters/registry'
-import type { AIConfig } from './adapters/types'
-import { logTaskError, logTaskPayload, logTaskProgress, logTaskStart, logTaskSuccess, logTaskWarn, redactUrl } from '../utils/task-logger.js'
-
-interface GenerateVideoParams {
- storyboardId?: number
- dramaId?: number
- prompt: string
- model?: string
- referenceMode?: string
- imageUrl?: string
- firstFrameUrl?: string
- lastFrameUrl?: string
- referenceImageUrls?: string[]
- referenceVideoUrls?: string[]
- referenceAudioUrls?: string[]
- generateAudio?: boolean
- duration?: number
- aspectRatio?: string
- configId?: number
-}
-
-export async function generateVideo(params: GenerateVideoParams): Promise<number> {
- const ts = now()
- const config = params.configId
- ? await getConfigById(params.configId)
- : await getActiveConfig('video')
- if (!config) throw new Error('No active video AI config')
-
- const res = await db.insert(schema.videoGenerations).values({
- storyboardId: params.storyboardId,
- dramaId: params.dramaId,
- prompt: params.prompt,
- model: params.model || config.model,
- provider: config.provider,
- referenceMode: params.referenceMode || 'reference',
- imageUrl: params.imageUrl,
- firstFrameUrl: params.firstFrameUrl,
- lastFrameUrl: params.lastFrameUrl,
- referenceImageUrls: params.referenceImageUrls ? JSON.stringify(params.referenceImageUrls) : null,
- referenceVideoUrls: params.referenceVideoUrls ? JSON.stringify(params.referenceVideoUrls) : null,
- referenceAudioUrls: params.referenceAudioUrls ? JSON.stringify(params.referenceAudioUrls) : null,
- generateAudio: params.generateAudio === false ? 0 : 1,
- duration: params.duration || 5,
- aspectRatio: params.aspectRatio || '16:9',
- status: 'processing',
- createdAt: ts,
- updatedAt: ts,
- })
-
- const lastId = getInsertId(res)
- logTaskStart('VideoTask', 'enqueue', {
- id: lastId,
- provider: config.provider,
- storyboardId: params.storyboardId,
- dramaId: params.dramaId,
- referenceMode: params.referenceMode || 'reference',
- duration: params.duration || 5,
- })
- logTaskPayload('VideoTask', 'enqueue params', {
- id: lastId,
- config: {
- provider: config.provider,
- model: config.model,
- baseUrl: config.baseUrl,
- },
- params,
- })
- processVideoGeneration(lastId, config).catch(err => {
- logTaskError('VideoTask', 'process', { id: lastId, error: err.message })
- console.error(`Video generation ${lastId} failed:`, err)
- })
- return lastId
-}
-
-async function processVideoGeneration(id: number, config: AIConfig) {
- const adapter = getVideoAdapter(config.provider)
-
- try {
- const rows = await db.select().from(schema.videoGenerations).where(eq(schema.videoGenerations.id, id))
- const record = rows[0]
- if (!record) return
- logTaskProgress('VideoTask', 'build-request', {
- id,
- provider: config.provider,
- storyboardId: record.storyboardId,
- referenceMode: record.referenceMode,
- })
-
- const resolvedImageUrl = await normalizeVideoReferenceUrl(record.imageUrl)
- const resolvedFirstFrameUrl = await normalizeVideoReferenceUrl(record.firstFrameUrl)
- const resolvedLastFrameUrl = await normalizeVideoReferenceUrl(record.lastFrameUrl)
- const resolvedReferenceImageUrls = await normalizeVideoReferenceUrls(record.referenceImageUrls)
- // 参考视频/音频文件较大,不适合 dataURL 内联,需解析为公网可访问 URL
- const resolvedReferenceVideoUrls = resolvePublicMediaUrls(record.referenceVideoUrls, 'video')
- const resolvedReferenceAudioUrls = resolvePublicMediaUrls(record.referenceAudioUrls, 'audio')
-
- // 使用 Adapter 构建请求
- const { url, method, headers, body } = adapter.buildGenerateRequest(config, {
- id: record.id,
- model: record.model,
- prompt: record.prompt,
- referenceMode: record.referenceMode,
- imageUrl: resolvedImageUrl,
- firstFrameUrl: resolvedFirstFrameUrl,
- lastFrameUrl: resolvedLastFrameUrl,
- referenceImageUrls: resolvedReferenceImageUrls.length ? JSON.stringify(resolvedReferenceImageUrls) : null,
- referenceVideoUrls: resolvedReferenceVideoUrls.length ? JSON.stringify(resolvedReferenceVideoUrls) : null,
- referenceAudioUrls: resolvedReferenceAudioUrls.length ? JSON.stringify(resolvedReferenceAudioUrls) : null,
- generateAudio: record.generateAudio,
- duration: record.duration,
- aspectRatio: record.aspectRatio,
- })
- logTaskProgress('VideoTask', 'request', {
- id,
- provider: config.provider,
- method,
- url: redactUrl(url),
- model: record.model,
- referenceMode: record.referenceMode,
- })
- logTaskPayload('VideoTask', 'request payload', {
- id,
- method,
- url,
- headers,
- body,
- })
-
- const resp = await fetch(url, {
- method,
- headers,
- body: JSON.stringify(body),
- })
-
- if (!resp.ok) throw new Error(`API error ${resp.status}: ${await resp.text()}`)
- const result = await resp.json() as any
-
- const { isAsync, taskId, videoUrl } = adapter.parseGenerateResponse(result)
-
- if (!isAsync && videoUrl) {
- logTaskProgress('VideoTask', 'sync-complete', { id, videoUrl })
- // 同步模式
- await handleVideoComplete(id, videoUrl, record.duration)
- return
- }
-
- // 异步模式:更新 taskId,开始轮询
- await db.update(schema.videoGenerations)
- .set({ taskId, status: 'processing', updatedAt: now() })
- .where(eq(schema.videoGenerations.id, id))
-
- logTaskProgress('VideoTask', 'poll-start', { id, taskId, provider: config.provider })
-
- pollVideoTask(id, config, taskId!, record.storyboardId)
- } catch (err: any) {
- logTaskError('VideoTask', 'process', { id, provider: config.provider, error: err.message })
- await db.update(schema.videoGenerations)
- .set({ status: 'failed', errorMsg: err.message, updatedAt: now() })
- .where(eq(schema.videoGenerations.id, id))
-
- }
-}
-
-async function normalizeVideoReferenceUrl(value: string | null | undefined): Promise<string | null> {
- const raw = String(value || '').trim()
- if (!raw) return null
- if (raw.startsWith('data:image/')) return raw
- if (raw.startsWith('static/') || raw.startsWith('/static/')) {
- const localPath = raw.startsWith('/static/') ? raw.slice(1) : raw
- try {
- return await readImageAsCompressedDataUrl(localPath, {
- maxWidth: 768,
- maxHeight: 768,
- quality: 68,
- })
- } catch (err) {
- logTaskWarn('VideoTask', 'reference-read-failed', { path: localPath, error: (err as Error).message })
- return null
- }
- }
- return raw
-}
-
-async function normalizeVideoReferenceUrls(raw: string | null | undefined): Promise<string[]> {
- if (!raw) return []
- let refs: string[] = []
- try {
- refs = JSON.parse(raw)
- } catch {
- refs = []
- }
- const normalized = await Promise.all(
- Array.from(new Set(refs.map((item) => String(item || '').trim()).filter(Boolean))).map((item) => normalizeVideoReferenceUrl(item)),
- )
- return normalized.filter((item): item is string => !!item)
-}
-
-/**
- * 将参考视频/音频解析为 Seedance API 可访问的 URL。
- * http(s)/dataURL 直通;本地 static 路径需要 PUBLIC_BASE_URL 拼成公网地址,
- * 未配置时抛出可操作的中文错误(落入 catch 写入 error_msg 供前端展示)。
- */
-function resolvePublicMediaUrl(value: string | null | undefined, kind: 'video' | 'audio'): string | null {
- const raw = String(value || '').trim()
- if (!raw) return null
- if (raw.startsWith('http://') || raw.startsWith('https://') || raw.startsWith('data:')) return raw
- if (raw.startsWith('static/') || raw.startsWith('/static/')) {
- const base = (process.env.PUBLIC_BASE_URL || '').trim().replace(/\/+$/, '')
- if (!base) {
- const label = kind === 'video' ? '视频' : '音频'
- throw new Error(
- `参考${label}为本地路径 ${raw},但后端未配置 PUBLIC_BASE_URL,Seedance API 无法访问内网地址。` +
- `请在 backend/.env 配置 PUBLIC_BASE_URL(如 https://your-domain.com)后重试,或改用公网 URL。`,
- )
- }
- const p = raw.startsWith('/') ? raw : `/${raw}`
- return `${base}${p}`
- }
- return raw
-}
-
-function resolvePublicMediaUrls(raw: string | null | undefined, kind: 'video' | 'audio'): string[] {
- if (!raw) return []
- let refs: string[] = []
- try {
- refs = JSON.parse(raw)
- } catch {
- refs = []
- }
- const items = Array.from(new Set(refs.map((item) => String(item || '').trim()).filter(Boolean)))
- return items.map((item) => resolvePublicMediaUrl(item, kind)).filter((item): item is string => !!item)
-}
-
-async function pollVideoTask(id: number, config: AIConfig, taskId: string, storyboardId?: number | null) {
- const adapter = getVideoAdapter(config.provider)
-
- for (let i = 0; i < 300; i++) {
- await new Promise(r => setTimeout(r, 10000))
- try {
- const { url, method, headers } = adapter.buildPollRequest(config, taskId)
- logTaskProgress('VideoTask', 'poll-request', {
- id,
- taskId,
- provider: config.provider,
- method,
- url: redactUrl(url),
- attempt: i + 1,
- })
- const resp = await fetch(url, { method, headers })
- if (!resp.ok) continue
- const result = await resp.json() as any
-
- const pollResp = adapter.parsePollResponse(result)
-
- if (pollResp.status === 'completed' && pollResp.videoUrl) {
- logTaskSuccess('VideoTask', 'poll-complete', { id, taskId, videoUrl: pollResp.videoUrl })
- await handleVideoComplete(id, pollResp.videoUrl, null, storyboardId)
- return
- }
- if (pollResp.status === 'failed') {
- logTaskError('VideoTask', 'poll-failed', { id, taskId, error: pollResp.error || 'Video generation failed' })
- throw new Error(pollResp.error || 'Video generation failed')
- }
- } catch (err: any) {
- if (i === 299) {
- logTaskError('VideoTask', 'poll-timeout', { id, taskId, error: err.message })
- await db.update(schema.videoGenerations)
- .set({ status: 'failed', errorMsg: `Timeout: ${err.message}`, updatedAt: now() })
- .where(eq(schema.videoGenerations.id, id))
-
- return
- }
- logTaskWarn('VideoTask', 'poll-retry', { id, taskId, attempt: i + 1, error: err.message })
- }
- }
-}
-
-async function handleVideoComplete(id: number, videoUrl: string, duration: number | null | undefined, storyboardId?: number | null) {
- const localPath = await downloadFile(videoUrl, 'videos')
- await db.update(schema.videoGenerations)
- .set({ videoUrl, localPath, status: 'completed', completedAt: now(), updatedAt: now() })
- .where(eq(schema.videoGenerations.id, id))
-
- logTaskSuccess('VideoTask', 'downloaded', { id, localPath, storyboardId, duration })
-
- if (storyboardId) {
- await db.update(schema.storyboards)
- .set({ videoUrl: localPath, duration: duration || undefined, updatedAt: now() })
- .where(eq(schema.storyboards.id, storyboardId))
-
- }
-}
diff --git a/backend/src/services/video-prompts.ts b/backend/src/services/video-prompts.ts
new file mode 100644
index 0000000..9579174
--- /dev/null
+++ b/backend/src/services/video-prompts.ts
@@ -0,0 +1,108 @@
+/**
+ * 批量视频提示词任务 — 异步为缺少 video_prompt 的分镜逐个运行 prompt_generator Agent
+ * 进程内内存态:按集跟踪一份任务,运行中不重复启动;重启后状态丢失
+ */
+import { eq } from 'drizzle-orm'
+import { db, schema } from '../db/index.js'
+import { mastra } from '../mastra/index.js'
+import { buildAgentRequestContext } from '../agents/context.js'
+import { logTaskError, logTaskProgress, logTaskStart, logTaskSuccess } from '../utils/task-logger.js'
+
+export interface VideoPromptBatchStatus {
+ status: 'running' | 'done' | 'error'
+ total: number
+ completed: number
+ failed: number
+ current_storyboard_id?: number
+ started_at: string
+ finished_at?: string
+ error?: string
+}
+
+const tasks = new Map<number, VideoPromptBatchStatus>()
+
+/** 启动批量生成(立即返回);运行中返回 started:false,total:-1;无待生成分镜返回 started:false,total:0;
+ * 传入 storyboardIds 时只处理所选分镜(即使已有提示词也重新生成),否则处理全部缺失提示词的分镜 */
+export async function startVideoPromptBatch(
+ episodeId: number,
+ dramaId: number,
+ opts: { model?: string; configId?: number } = {},
+ storyboardIds?: number[],
+): Promise<{ started: boolean; total: number }> {
+ if (tasks.get(episodeId)?.status === 'running') return { started: false, total: -1 }
+
+ const sbs = await db.select().from(schema.storyboards)
+ .where(eq(schema.storyboards.episodeId, episodeId))
+ .orderBy(schema.storyboards.storyboardNumber)
+ const pending = storyboardIds?.length
+ ? sbs.filter(sb => storyboardIds.includes(sb.id))
+ : sbs.filter(sb => !(sb.videoPrompt || '').trim())
+ if (!pending.length) return { started: false, total: 0 }
+
+ // 视频模型标签:跟随该集锁定的视频配置,供 Agent 按模型特性生成
+ const [ep] = await db.select().from(schema.episodes).where(eq(schema.episodes.id, episodeId))
+ let videoLabel = '默认'
+ if (ep?.videoConfigId) {
+ const [cfg] = await db.select().from(schema.aiServiceConfigs).where(eq(schema.aiServiceConfigs.id, ep.videoConfigId))
+ if (cfg) videoLabel = `${cfg.name} (${cfg.provider})`
+ }
+
+ const task: VideoPromptBatchStatus = {
+ status: 'running',
+ total: pending.length,
+ completed: 0,
+ failed: 0,
+ started_at: new Date().toISOString(),
+ }
+ tasks.set(episodeId, task)
+
+ logTaskStart('VideoPrompt', 'batch', { episodeId, dramaId, total: pending.length, model: opts.model || undefined })
+ ;(async () => {
+ const agent = mastra.getAgent('prompt_generator')
+ if (!agent) throw new Error('视频提示词 Agent 不可用')
+ const requestContext = buildAgentRequestContext({
+ episodeId,
+ dramaId,
+ modelOverride: opts.model || undefined,
+ textConfigId: opts.configId || undefined,
+ })
+ for (const sb of pending) {
+ task.current_storyboard_id = sb.id
+ logTaskProgress('VideoPrompt', 'batch-shot', { episodeId, storyboardId: sb.id, index: task.completed + task.failed + 1, total: task.total })
+ try {
+ await agent.generate([{
+ role: 'user',
+ content: `请为分镜 #${sb.storyboardNumber}(ID:${sb.id})生成视频提示词(video_prompt)。视频模型:${videoLabel},请根据该模型的特性和时长限制生成。
+请先调用 read_storyboard_context 获取该分镜的画面描述、动作、氛围、对白/旁白及时长,据此生成 video_prompt(按 3 秒分段换行、用 @角色名/@场景名/@道具名 引用参考素材),然后调用 update_storyboard 保存到分镜 ID:${sb.id}。只更新 video_prompt 字段,不要改动其他字段,不要重新拆分整集。`,
+ }], { maxSteps: 8, requestContext })
+ // 以实际落库为准判定成败
+ const [fresh] = await db.select().from(schema.storyboards).where(eq(schema.storyboards.id, sb.id))
+ if ((fresh?.videoPrompt || '').trim()) task.completed++
+ else {
+ task.failed++
+ logTaskError('VideoPrompt', 'batch-shot', { storyboardId: sb.id, error: 'agent finished but video_prompt is empty' })
+ }
+ } catch (err: any) {
+ task.failed++
+ logTaskError('VideoPrompt', 'batch-shot', { storyboardId: sb.id, error: err?.message })
+ }
+ }
+ })()
+ .then(() => {
+ task.status = 'done'
+ task.finished_at = new Date().toISOString()
+ task.current_storyboard_id = undefined
+ logTaskSuccess('VideoPrompt', 'batch', { episodeId, total: task.total, completed: task.completed, failed: task.failed })
+ })
+ .catch((err: any) => {
+ task.status = 'error'
+ task.finished_at = new Date().toISOString()
+ task.error = err?.message || '批量生成失败'
+ logTaskError('VideoPrompt', 'batch', { episodeId, error: err?.message })
+ })
+ return { started: true, total: pending.length }
+}
+
+export function getVideoPromptBatchStatus(episodeId: number): VideoPromptBatchStatus | null {
+ return tasks.get(episodeId) || null
+}
diff --git a/backend/tests/asset-crud-structure.test.mjs b/backend/tests/asset-crud-structure.test.mjs
new file mode 100644
index 0000000..bd881f1
--- /dev/null
+++ b/backend/tests/asset-crud-structure.test.mjs
@@ -0,0 +1,42 @@
+import { readFileSync } from 'node:fs'
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+
+const root = new URL('..', import.meta.url)
+const read = (path) => readFileSync(new URL(path, root), 'utf8')
+
+test('characters route supports manual create and soft delete', () => {
+ const route = read('src/routes/characters.ts')
+
+ assert.match(route, /app\.post\('\/'/)
+ assert.match(route, /name required/)
+ // 传入 episode_id 时关联到该集
+ assert.match(route, /insert\(schema\.episodeCharacters\)/)
+ // 软删除
+ assert.match(route, /app\.delete\('\/:id'/)
+ assert.match(route, /deletedAt: now\(\)/)
+ assert.doesNotMatch(route, /db\.delete\(schema\.characters\)/)
+})
+
+test('scenes route links new scenes to episode and soft deletes', () => {
+ const route = read('src/routes/scenes.ts')
+
+ assert.match(route, /app\.post\('\/'/)
+ assert.match(route, /location required/)
+ assert.match(route, /insert\(schema\.episodeScenes\)/)
+ // 软删除(原为硬删,保留历史生成记录)
+ assert.match(route, /app\.delete\('\/:id'/)
+ assert.match(route, /deletedAt: now\(\)/)
+ assert.doesNotMatch(route, /db\.delete\(schema\.scenes\)/)
+})
+
+test('props route supports manual create and soft delete', () => {
+ const route = read('src/routes/props.ts')
+
+ assert.match(route, /app\.post\('\/'/)
+ assert.match(route, /name required/)
+ assert.match(route, /insert\(schema\.episodeProps\)/)
+ assert.match(route, /app\.delete\('\/:id'/)
+ assert.match(route, /deletedAt: now\(\)/)
+ assert.doesNotMatch(route, /db\.delete\(schema\.props\)/)
+})
diff --git a/backend/tests/asset-extract-structure.test.mjs b/backend/tests/asset-extract-structure.test.mjs
new file mode 100644
index 0000000..8425939
--- /dev/null
+++ b/backend/tests/asset-extract-structure.test.mjs
@@ -0,0 +1,66 @@
+import { readFileSync } from 'node:fs'
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+
+const root = new URL('..', import.meta.url)
+const read = (path) => readFileSync(new URL(path, root), 'utf8')
+
+test('extraction service runs per-target async tasks', () => {
+ const svc = read('src/services/extraction.ts')
+
+ // 三类资产目标
+ assert.match(svc, /'characters' \| 'scenes' \| 'props'/)
+ assert.match(svc, /EXTRACT_TARGETS.*characters.*scenes.*props/s)
+ // 按 集×类型 键控的内存任务表
+ assert.match(svc, /`\$\{episodeId\}:\$\{target\}`/)
+ assert.match(svc, /status: 'running' \| 'done' \| 'error'/)
+ // 同集同类型运行中不重复启动
+ assert.match(svc, /tasks\.get\(key\)\?\.status === 'running'\)\s*return false/)
+ // 每类资产限定只提取该类型
+ assert.match(svc, /本次只提取角色/)
+ assert.match(svc, /本次只提取场景/)
+ assert.match(svc, /本次只提取道具/)
+ // fire-and-forget 异步执行 extractor Agent
+ assert.match(svc, /mastra\.getAgent\('extractor'\)/)
+ assert.match(svc, /\.then\(\(result[^)]*\) => \{[\s\S]*status = 'done'/)
+ assert.match(svc, /\.catch\(\(err/)
+ // 逐步打印 Agent 进展(工具调用 + 文本),完成时打印汇总
+ assert.match(svc, /onStepFinish/)
+ assert.match(svc, /-step/)
+ assert.match(svc, /toolCalls/)
+})
+
+test('extraction tools dedupe by normalized name so near-names reuse existing assets', () => {
+ const tools = read('src/agents/tools/extract-tools.ts')
+
+ // 归一化:括号定位/别名后缀去除 + 空白/大小写统一
+ assert.match(tools, /normalizeName\(name: string\)/)
+ assert.match(tools, /replace\(\/\[(\(]/) // 中/英文括号字符类
+ assert.match(tools, /replace\(\/\[\\s/) // 空白字符类
+ assert.match(tools, /\.toLowerCase\(\)/)
+ // 角色保存:精确匹配优先,归一化近名兜底,命中即复用不重复创建
+ assert.match(tools, /normalizeName\(c\.name\) === normName/)
+ assert.match(tools, /matchedViaNorm/)
+ assert.match(tools, /save-characters-reuse/)
+ // 道具同样按归一化名字复用
+ assert.match(tools, /normalizeName\(p\.name\) === normName/)
+ assert.match(tools, /save-props-reuse/)
+ // 场景按 地点+时间 匹配,地点仅做空白/大小写归一化(不删括号)
+ assert.match(tools, /normalizeLocation\(loc: string\)/)
+ assert.match(tools, /normalizeLocation\(s\.location\) === normLocation/)
+ // read_existing_* 返回归一化字段供 Agent 判断复用
+ assert.match(tools, /normalized_name: normalizeName/)
+ assert.match(tools, /normalized_location: normalizeLocation/)
+})
+
+test('episodes route exposes async extract endpoints', () => {
+ const route = read('src/routes/episodes.ts')
+
+ assert.match(route, /app\.post\('\/:id\/extract'/)
+ assert.match(route, /app\.get\('\/:id\/extract-status'/)
+ assert.match(route, /target 必须是 characters \/ scenes \/ props/)
+ assert.match(route, /startExtraction\(ep\.id, ep\.dramaId, target, \{ model: body\.model/)
+ // 顶栏文本模型覆盖透传到提取 Agent
+ assert.match(read('src/services/extraction.ts'), /modelOverride: opts\.model/)
+ assert.match(route, /getExtractionStatus\(id\)/)
+})
diff --git a/backend/tests/final-prompt-structure.test.mjs b/backend/tests/final-prompt-structure.test.mjs
index e7bbbe0..cfec794 100644
--- a/backend/tests/final-prompt-structure.test.mjs
+++ b/backend/tests/final-prompt-structure.test.mjs
@@ -32,23 +32,30 @@ test('grid prompt agent tools save agent-written final prompts with style inject
assert.doesNotMatch(tools, /generate_scene_prompt/)
})
-test('grid prompt agent instructions define turnaround and layered-composition specs', () => {
+test('prompt agent instructions reference per-asset skills; skill files define the specs', () => {
const agents = read('src/agents/index.ts')
const settings = read('../frontend/app/pages/settings.vue')
+ const charSkill = read('workspace/skills/prompt-generator/character-prompt/SKILL.md')
+ const sceneSkill = read('workspace/skills/prompt-generator/scene-prompt/SKILL.md')
for (const src of [agents, settings]) {
- // 角色三视图
- assert.match(src, /三视图/)
- assert.match(src, /character turnaround sheet/)
- assert.match(src, /front view, side view and back view/)
- // 场景固定视角 + 前中后景
- assert.match(src, /固定视角/)
- assert.match(src, /fixed camera wide shot/)
- assert.match(src, /foreground, midground and background/)
+ // 三类图片规范入口(具体创作规则在各自 SKILL.md 中)
+ assert.match(src, /角色三视图/)
+ assert.match(src, /场景固定视角/)
+ assert.match(src, /道具白底单品/)
// 保存工具约定
assert.match(src, /save_character_final_prompt/)
assert.match(src, /save_scene_final_prompt/)
}
+ // 角色三视图 / 场景固定视角的必备要素由技能文件承载(纯中文输出)
+ assert.match(charSkill, /正脸特写/)
+ assert.match(charSkill, /正面、90 度侧面、背面/)
+ assert.match(charSkill, /三个视图的脸、发型和服装完全一致/)
+ assert.match(charSkill, /纯中文/)
+ assert.match(sceneSkill, /固定机位广角镜头/)
+ assert.match(sceneSkill, /前景(\[前景元素\])、中景(\[中景主体空间\])、后景(\[后景纵深\])/)
+ assert.match(sceneSkill, /出入口/)
+ assert.match(sceneSkill, /纯中文/)
})
test('image generation prefers the stored final prompt with agent generation and legacy fallback', () => {
@@ -58,15 +65,17 @@ test('image generation prefers the stored final prompt with agent generation and
assert.match(service, /export async function ensureCharacterFinalPrompt/)
assert.match(service, /export async function ensureSceneFinalPrompt/)
- assert.match(service, /getAgent\('image_prompt_generator'/)
+ assert.match(service, /getAgent\('prompt_generator'/)
// 已有最终提示词直接复用(force 时忽略强制重新生成)
assert.match(service, /if \(char\.finalPrompt && !force\) return char\.finalPrompt/)
assert.match(service, /if \(scene\.finalPrompt && !force\) return scene\.finalPrompt/)
assert.match(service, /force = false/)
- assert.match(characters, /ensureCharacterFinalPrompt\(char, ep\.id\)/)
+ assert.match(characters, /ensureCharacterFinalPrompt\(char, ep\.id, /)
+ // 文本模型覆盖(text_model/text_config_id)透传到提示词 Agent
+ assert.match(characters, /text_model/)
assert.match(characters, /finalPrompt \|\| characterImagePrompt\(char, stylePrompt\)/)
- assert.match(scenes, /ensureSceneFinalPrompt\(scene, ep\.id\)/)
+ assert.match(scenes, /ensureSceneFinalPrompt\(scene, ep\.id, /)
// 描述字段编辑后最终提示词失效
assert.match(characters, /updates\.finalPrompt = null/)
assert.match(scenes, /updates\.finalPrompt = null/)
diff --git a/backend/tests/model-selection-structure.test.mjs b/backend/tests/model-selection-structure.test.mjs
index 3d471d2..86137e9 100644
--- a/backend/tests/model-selection-structure.test.mjs
+++ b/backend/tests/model-selection-structure.test.mjs
@@ -37,14 +37,14 @@ test('character and scene image generation pass the selected model through', ()
assert.ok(cfgPasses.length >= 2, `expected >=2 config overrides in characters route, got ${cfgPasses.length}`)
assert.match(scenes, /configId: body\.config_id \?\? ep\.imageConfigId \?\? undefined/)
// 服务层已有 params.model 优先于配置默认
- const service = read('src/services/image-generation.ts')
+ const service = read('src/services/generation.ts')
assert.match(service, /model: params\.model \|\| config\.model/)
})
test('video generation route passes the selected model through', () => {
- const videos = read('src/routes/videos.ts')
- const service = read('src/services/video-generation.ts')
+ const tasks = read('src/routes/tasks.ts')
+ const service = read('src/services/generation.ts')
- assert.match(videos, /model: body\.model/)
+ assert.match(tasks, /model: body\.model/)
assert.match(service, /model: params\.model \|\| config\.model/)
})
diff --git a/backend/tests/mysql-database-structure.test.mjs b/backend/tests/mysql-database-structure.test.mjs
index d61b003..f30a092 100644
--- a/backend/tests/mysql-database-structure.test.mjs
+++ b/backend/tests/mysql-database-structure.test.mjs
@@ -73,6 +73,9 @@ test('mysql startup schema is present and sqlite migration artifacts are removed
// 项目级画面比例:创建时固定,视频生成统一使用
assert.match(mysqlSchema, /aspect_ratio VARCHAR\(16\) DEFAULT '16:9'/)
assert.match(mysqlSchema, /ALTER TABLE `dramas` ADD COLUMN `aspect_ratio` VARCHAR\(16\) DEFAULT '16:9'/)
+ // 集级视频分辨率:创建集时固定(480p/720p),视频生成统一使用
+ assert.match(mysqlSchema, /resolution VARCHAR\(16\) DEFAULT '720p'/)
+ assert.match(mysqlSchema, /ALTER TABLE `episodes` ADD COLUMN `resolution` VARCHAR\(16\) DEFAULT '720p'/)
assert.equal(pkg.scripts['db:migrate:sqlite-to-mysql'], undefined)
assert.equal(existsSync(new URL('scripts/migrate-sqlite-to-mysql.ts', root)), false)
})
diff --git a/backend/tests/remove-audio-tts-structure.test.mjs b/backend/tests/remove-audio-tts-structure.test.mjs
index 6f0e7bd..c488fed 100644
--- a/backend/tests/remove-audio-tts-structure.test.mjs
+++ b/backend/tests/remove-audio-tts-structure.test.mjs
@@ -61,5 +61,7 @@ test('backend removes TTS endpoints and audio-specific schema fields', () => {
assert.doesNotMatch(mysqlSchema, /voice_sample_url/)
assert.doesNotMatch(mysqlSchema, /voice_provider/)
assert.doesNotMatch(mysqlSchema, /tts_audio_url/)
- assert.doesNotMatch(mysqlSchema, /ai_voices/)
+ // 无 ai_voices 表定义;仅保留启动时的孤儿表清理 DROP
+ assert.doesNotMatch(mysqlSchema, /CREATE TABLE IF NOT EXISTS ai_voices/)
+ assert.match(mysqlSchema, /DROP TABLE IF EXISTS `ai_voices`/)
})
diff --git a/backend/tests/remove-grid-feature-structure.test.mjs b/backend/tests/remove-grid-feature-structure.test.mjs
index c48b8d3..262a7b4 100644
--- a/backend/tests/remove-grid-feature-structure.test.mjs
+++ b/backend/tests/remove-grid-feature-structure.test.mjs
@@ -20,10 +20,10 @@ test('image prompt agent keeps role and scene prompts but removes grid prompt mo
const skills = read('src/agents/skills.ts')
const imagePromptTools = read('src/agents/tools/image-prompt-tools.ts')
const storyboardTools = read('src/agents/tools/storyboard-tools.ts')
- const skill = read('workspace/skills/image-prompt-generator/SKILL.md')
+ const skill = read('workspace/skills/prompt-generator/prop-prompt/SKILL.md')
- assert.match(agents, /image_prompt_generator/)
- assert.match(skills, /image_prompt_generator/)
+ assert.match(agents, /prompt_generator/)
+ assert.match(skills, /prompt_generator/)
assert.match(imagePromptTools, /save_character_final_prompt/)
assert.match(imagePromptTools, /save_scene_final_prompt/)
assert.doesNotMatch(agents, /宫格图/)
diff --git a/backend/tests/seedance2-video-modes.test.mjs b/backend/tests/seedance2-video-modes.test.mjs
index 0b01db2..81ada4a 100644
--- a/backend/tests/seedance2-video-modes.test.mjs
+++ b/backend/tests/seedance2-video-modes.test.mjs
@@ -30,13 +30,14 @@ test('volcengine video adapter only supports Seedance 2.0 models and reference m
assert.match(adapter, /参考音频需要至少 1 个参考图片或视频/)
assert.match(adapter, /多模态参考模式需要至少一个参考素材或 prompt/)
- // generate_audio 可配置(默认开),时长支持 4-15 秒
+ // generate_audio 可配置(默认开),时长支持 4-15 秒;分辨率随集固定(480p/720p,默认 720p)
assert.match(adapter, /generate_audio:\s*record\.generateAudio/)
assert.match(adapter, /Math\.min\(15, Math\.max\(4, parsed\)\)/)
+ assert.match(adapter, /resolution: record\.resolution === '480p' \? '480p' : '720p'/)
})
test('video generation service resolves reference media and persists new fields', () => {
- const service = read('src/services/video-generation.ts')
+ const service = read('src/services/generation.ts')
assert.match(service, /PUBLIC_BASE_URL/)
assert.match(service, /resolvePublicMediaUrl/)
@@ -49,6 +50,24 @@ test('video generation service resolves reference media and persists new fields'
assert.doesNotMatch(service, /referenceMode: params\.referenceMode \|\| 'none'/)
})
+test('video resolution is fixed per episode, editable, and locked into video tasks', () => {
+ const episodes = read('src/routes/episodes.ts')
+ const tasks = read('src/routes/tasks.ts')
+ const service = read('src/services/generation.ts')
+
+ // 创建集时固定(默认 720p,仅接受 480p/720p)
+ assert.match(episodes, /resolution: body\.resolution === '480p' \? '480p' : '720p'/)
+ // PUT 可修改,白名单校验
+ assert.match(episodes, /'status', 'resolution'\]/)
+ assert.match(episodes, /resolution 只支持 480p \/ 720p/)
+ // 视频任务锁定集的分辨率(优先于请求体)
+ assert.match(tasks, /episodeResolution = ep\.resolution/)
+ assert.match(tasks, /resolution: episodeResolution \|\| body\.resolution/)
+ // 服务落入 params 并传给适配器
+ assert.match(service, /resolution: params\.resolution === '480p' \? '480p' : '720p'/)
+ assert.match(service, /resolution: params\.resolution,/)
+})
+
test('upload route exposes validated video and audio endpoints', () => {
const route = read('src/routes/upload.ts')
@@ -60,8 +79,13 @@ test('upload route exposes validated video and audio endpoints', () => {
assert.match(route, /20 \* 1024 \* 1024/)
})
-test('videos route validates reference-mode requirements only', () => {
- const route = read('src/routes/videos.ts')
+test('tasks route validates reference-mode requirements for video tasks', () => {
+ const route = read('src/routes/tasks.ts')
+
+ // 统一任务入口:type 分派 image/video
+ assert.match(route, /type 必须为 image 或 video/)
+ assert.match(route, /generateImage\(\{/)
+ assert.match(route, /generateVideo\(\{/)
// 其他模式的校验已清理
assert.doesNotMatch(route, /文生视频模式必须提供 prompt/)
@@ -80,21 +104,39 @@ test('videos route validates reference-mode requirements only', () => {
assert.match(route, /generateAudio: body\.generate_audio/)
})
-test('video_generations table gains reference media and generate_audio columns', () => {
+test('image/video generation tasks are unified into a single sys_task table', () => {
const schema = read('src/db/schema.ts')
const mysqlSchema = read('src/db/mysql-schema.ts')
const envExample = read('.env.example')
- assert.match(schema, /referenceVideoUrls: text\('reference_video_urls'\)/)
- assert.match(schema, /referenceAudioUrls: text\('reference_audio_urls'\)/)
- assert.match(schema, /generateAudio: int\('generate_audio'\)/)
-
- assert.match(mysqlSchema, /reference_video_urls TEXT/)
- assert.match(mysqlSchema, /reference_audio_urls TEXT/)
- assert.match(mysqlSchema, /generate_audio TINYINT\(1\) DEFAULT 1/)
- assert.match(mysqlSchema, /column: 'reference_video_urls'/)
- assert.match(mysqlSchema, /column: 'reference_audio_urls'/)
- assert.match(mysqlSchema, /column: 'generate_audio'/)
+ // sys_task:type 区分 image/video,生成参数收进 params(JSON)
+ assert.match(schema, /export const sysTask = mysqlTable\('sys_task'/)
+ assert.match(schema, /type: varchar\('type', \{ length: 16 \}\)\.notNull\(\)/)
+ assert.match(schema, /params: text\('params'\)/)
+ assert.match(schema, /resultUrl: text\('result_url'\)/)
+ assert.match(schema, /localPath: text\('local_path'\)/)
+
+ // 旧的 image_generations / video_generations 表定义与回填已移除
+ assert.doesNotMatch(schema, /imageGenerations/)
+ assert.doesNotMatch(schema, /videoGenerations/)
+ assert.doesNotMatch(mysqlSchema, /CREATE TABLE IF NOT EXISTS image_generations/)
+ assert.doesNotMatch(mysqlSchema, /CREATE TABLE IF NOT EXISTS video_generations/)
+ assert.doesNotMatch(mysqlSchema, /column: 'reference_video_urls'/)
+
+ // DDL 与旧表清理(不迁移历史)
+ assert.match(mysqlSchema, /CREATE TABLE IF NOT EXISTS sys_task \(/)
+ assert.match(mysqlSchema, /type VARCHAR\(16\) NOT NULL/)
+ assert.match(mysqlSchema, /params TEXT/)
+ assert.match(mysqlSchema, /result_url TEXT/)
+ assert.match(mysqlSchema, /DROP TABLE IF EXISTS `image_generations`/)
+ assert.match(mysqlSchema, /DROP TABLE IF EXISTS `video_generations`/)
+
+ // 路由与服务只操作 sys_task(统一 /tasks 入口,type 过滤)
+ const tasksRoute = read('src/routes/tasks.ts')
+ const service = read('src/services/generation.ts')
+ assert.match(tasksRoute, /schema\.sysTask/)
+ assert.match(tasksRoute, /r\.type === type/)
+ assert.match(service, /db\.insert\(schema\.sysTask\)/)
assert.match(envExample, /PUBLIC_BASE_URL/)
})
diff --git a/backend/tests/style-presets-structure.test.mjs b/backend/tests/style-presets-structure.test.mjs
index c1eba20..46c5c68 100644
--- a/backend/tests/style-presets-structure.test.mjs
+++ b/backend/tests/style-presets-structure.test.mjs
@@ -46,8 +46,8 @@ test('drama style prompt is injected into image prompt composition', () => {
assert.match(service, /getDramaStylePrompt/)
assert.match(service, /stylePresets\.value, drama\.style/)
assert.match(gridTools, /getDramaStylePrompt\(dramaId\)/)
- // 保存最终提示词时由工具拼接项目视觉风格
- assert.match(gridTools, /stylePrompt \? `\$\{prompt\}, \$\{stylePrompt\}` : prompt/)
+ // 保存最终提示词时由工具拼接项目视觉风格(风格片段置于最前方)
+ assert.match(gridTools, /stylePrompt \? `\$\{stylePrompt\}, \$\{prompt\}` : prompt/)
assert.match(characters, /getDramaStylePrompt/)
assert.match(characters, /characterImagePrompt\(char, stylePrompt\)/)
assert.match(scenes, /getDramaStylePrompt\(scene\.dramaId\)/)
diff --git a/backend/tests/video-prompt-batch-structure.test.mjs b/backend/tests/video-prompt-batch-structure.test.mjs
new file mode 100644
index 0000000..86149e7
--- /dev/null
+++ b/backend/tests/video-prompt-batch-structure.test.mjs
@@ -0,0 +1,35 @@
+import { readFileSync } from 'node:fs'
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+
+const root = new URL('..', import.meta.url)
+const read = (path) => readFileSync(new URL(path, root), 'utf8')
+
+test('video prompt batch service runs per-shot async agent loop', () => {
+ const svc = read('src/services/video-prompts.ts')
+
+ // 默认只处理缺少 video_prompt 的分镜;指定 storyboardIds 时只处理所选(已有提示词也重新生成)
+ assert.match(svc, /filter\(sb => !\(sb\.videoPrompt \|\| ''\)\.trim\(\)\)/)
+ assert.match(svc, /storyboardIds\?\.length/)
+ assert.match(svc, /storyboardIds\.includes\(sb\.id\)/)
+ // 运行中不重复启动
+ assert.match(svc, /status === 'running'\) return \{ started: false, total: -1 \}/)
+ // 逐个分镜调用 prompt_generator,以落库结果判定成败
+ assert.match(svc, /mastra\.getAgent\('prompt_generator'\)/)
+ assert.match(svc, /read_storyboard_context/)
+ assert.match(svc, /update_storyboard/)
+ assert.match(svc, /fresh\?\.videoPrompt/)
+ // 进度跟踪与文本模型覆盖
+ assert.match(svc, /current_storyboard_id/)
+ assert.match(svc, /modelOverride: opts\.model/)
+})
+
+test('episodes route exposes video prompt batch endpoints', () => {
+ const route = read('src/routes/episodes.ts')
+
+ assert.match(route, /app\.post\('\/:id\/generate-video-prompts'/)
+ assert.match(route, /app\.get\('\/:id\/video-prompts-status'/)
+ assert.match(route, /startVideoPromptBatch\(ep\.id, ep\.dramaId/)
+ assert.match(route, /body\.storyboard_ids/)
+ assert.match(route, /already_running/)
+})
diff --git a/backend/tests/video-prompt-references-structure.test.mjs b/backend/tests/video-prompt-references-structure.test.mjs
index 08383bc..fd6b365 100644
--- a/backend/tests/video-prompt-references-structure.test.mjs
+++ b/backend/tests/video-prompt-references-structure.test.mjs
@@ -5,9 +5,9 @@ import assert from 'node:assert/strict'
const root = new URL('..', import.meta.url)
const read = (path) => readFileSync(new URL(path, root), 'utf8')
-test('storyboard_breaker video prompt format uses @name references instead of XML tags', () => {
+test('prompt_generator video prompt format uses @name references instead of XML tags', () => {
const agents = read('src/agents/index.ts')
- const skill = read('workspace/skills/storyboard-breaker/SKILL.md')
+ const skill = read('workspace/skills/prompt-generator/video-prompt/SKILL.md')
const settings = read('../frontend/app/pages/settings.vue')
// 场景/角色用 @名字 引用(名字必须与场景/角色列表完全一致)
diff --git a/backend/workspace/skills/extractor/SKILL.md b/backend/workspace/skills/extractor/SKILL.md
index 3cab2b0..73ec46f 100644
--- a/backend/workspace/skills/extractor/SKILL.md
+++ b/backend/workspace/skills/extractor/SKILL.md
@@ -24,6 +24,21 @@ description: 角色、场景和道具提取的规范与方法
## 道具提取规范
+**核心原则:宁可少提,不要多提。** 道具是用来生成白底单品图、供视频特写引用的高成本资产,只有剧情关键道具才值得提取。一集通常 **0-3 个**关键道具,超过 3 个时按剧情重要性排序只保留前 3 个。
+
+必须**同时满足**以下两条,缺一不可:
+1. **直接推动剧情**:该物品的出现、交接、损坏或发现会引发情节转折(如凶器、信物、关键文件、定情礼物、关键证据)。
+2. **值得单独生成图片**:后续分镜会给它特写镜头或反复出现,需要固定外观。
+
+**判定三问**(对每个候选道具自问自答,任一答"否"即放弃):
+- ① 删掉它剧情是否依然成立?→ 成立则**不提取**(它只是道具式背景板)
+- ② 它只是角色随手使用的日常物品吗(手机、筷子、水杯、香烟、雨伞)?→ 是则**不提取**
+- ③ 它是场景陈设的一部分吗(桌椅、灯具、门窗、挂画、餐具)?→ 是则**不提取**(这些属于场景描述)
+
+**不算道具的典型**:随手使用但不影响剧情走向的普通物品;场景陈设与家具;只被提及一次且再无下文的物品;角色的常规穿戴(归入角色妆造)。
+
+如果没有符合条件的道具,**不要强行提取**,调用 `save_dedup_props` 时传空数组即可。
+
提取的道具字段(与 `save_dedup_props` 工具参数一一对应):
- **name**(必填):道具名
- **type**:类型——日常/武器/交通/装饰/文件等
@@ -31,8 +46,6 @@ description: 角色、场景和道具提取的规范与方法
道具**不需要输出图片提示词**——道具的最终提示词由提示词生成 Agent 在生图前专门生成(白底单品规范)。
-只提取**涉及事态发展、直接推动剧情**的关键道具(如凶器、信物、关键文件、重要礼物等);被角色随手使用但不影响剧情走向的普通物品、桌椅等场景陈设都不算道具。如果剧本中没有这类道具,**不要强行提取**,调用 `save_dedup_props` 时传空数组即可。
-
## 使用步骤
1. 调用 `read_script_for_extraction` 读取当前集剧本
@@ -49,3 +62,4 @@ description: 角色、场景和道具提取的规范与方法
- 目标是补齐"当前集"需要的角色、场景和道具,不是重扫整个项目
- 若已在项目中存在但当前集未关联,仍应复用并关联到当前集
- 去重规则:角色/道具按名称精确匹配,场景按【地点+时间段】精确匹配,命中的优先复用,不要重复创建
+- 近名去重:名称带括号定位或别名时按括号前主体比较(如「林小雨(主角)」与「林小雨」视为同一角色/道具,复用已有);read_existing_characters / read_existing_props 返回的 normalized_name 即归一化后的名字,场景的 normalized_location 同理,据此判断即可
diff --git a/backend/workspace/skills/prompt-generator/character-prompt/SKILL.md b/backend/workspace/skills/prompt-generator/character-prompt/SKILL.md
index b35caa6..d7d7cdc 100644
--- a/backend/workspace/skills/prompt-generator/character-prompt/SKILL.md
+++ b/backend/workspace/skills/prompt-generator/character-prompt/SKILL.md
@@ -1,23 +1,55 @@
---
name: character-prompt
-description: 角色最终提示词规范 — 三视图(character turnaround:正面/侧面/背面)
+description: 角色最终提示词规范 — 正脸特写 + 三视图(character turnaround:正面/90 度侧面/背面),作为后续所有生成的形象锚点
---
-# 角色最终提示词(三视图)
+# 角色最终提示词(左侧正脸特写 + 右侧三视图)
-生成的是一张角色三视图(character turnaround)图片:同一角色的正面、侧面、背面三个全身视图并排排列,外观完全一致。
+生成的是一张角色设定参考图(character reference sheet),构图固定为:
-## 必备要素
+- **左侧:正脸特写**——头部与肩部的正面近景,五官、发型、肤质清晰可见,作为脸部辨识度的锚点
+- **右侧:并列展示正面、90 度侧面、背面三张等高全身视图**——同一角色的三个全身视图等高并排,头顶与脚底对齐
+
+**核心原则:一致性 > 美观。** 这张图是后续所有角色图片、视频参考的形象锚点,必须中性、清晰、可复用——不要追求单张图的艺术感。
+
+## 输出结构(按此顺序组装单段连贯中文)
```
-character turnaround sheet, three views of the same character: front view, side view and back view,
-full body, white background
+角色设定参考图,左侧为正脸特写,右侧并列展示正面、90 度侧面、背面三张等高全身视图,
+特写与全身视图都是同一角色,全身入镜,中性 A 字站姿,三张全身视图等高并排、头顶脚底对齐,
+[年龄感 + 性别感 + 体态],[五官特征],[发型],[服装 + 配饰],
+正脸特写与三个视图的脸、发型和服装完全一致,
+纯白背景,柔和均匀的光线,电影质感
```
-## 生成规则
+## 描述顺序规则
+
+把**最有辨识度的特征放在前面**,按此顺序落地 `appearance`(样貌)与 `styling`(妆造)的每个关键元素,不遗漏:
+
+1. 身份锚点:年龄感(如"二十出头")、性别感、体态(高矮胖瘦、姿态习惯)
+2. 五官:脸型、眼睛、其他显著特征(疤、痣、眼镜等)——正脸特写尤其依赖这部分描写
+3. 发型:颜色、长度、样式
+4. 服装:款式、颜色、材质、状态(如"袖口有焊锡痕迹的皱褶工服")
+5. 配饰:只写有辨识度的,不堆砌
+
+角色的性格特点要转化为外在气质与神态描写(如"憔悴" → "眼神疲惫、肩膀微垮"),不要直接出现性格词汇。
+
+## 构图与一致性
+
+- 左侧正脸特写:正面朝向镜头、中性表情、头顶到肩膀完整入镜
+- 右侧三张全身视图:同一角色的正面、90 度侧面、背面,**等高并排、间距均匀**,头顶与脚底在同一水平线上
+- 特写与三张全身视图必须是同一张脸、同一发型、同一服装——明确写出"正脸特写与三张全身视图的脸、发型和服装完全一致"
+- 中性站姿、自然表情——方便作为参考图复用
+- 柔和均匀的棚拍光,不要戏剧性光影(参考图要在各种场景下都能用)
+- 输出必须是纯中文,不要混入英文词汇
+
+## 禁止事项
+
+- 动态姿势、夸张表情、手持道具、与他人同框
+- 裁切身体(全身视图必须 full body,头顶到脚底完整入镜;特写必须头部肩部完整入镜)
+- 文字、标签、水印、签名
+- 重阴影、彩色背景光、背景道具
+
+## 保存
-- 以 `appearance`(样貌)与 `styling`(妆造)为核心:年龄感、五官、体态、发型、服装、配饰
-- 三个视图外观必须完全一致,并排排列
-- 单段连贯英文,包含 `cinematic quality`
-- 避免出现文字、签名、水印
-- 保存工具:`save_character_final_prompt`(prompt 参数不含风格词)
+调用 `save_character_final_prompt`:prompt 参数不含风格词,**项目视觉风格由工具自动注入到最终提示词的最前方**。
diff --git a/backend/workspace/skills/prompt-generator/prop-prompt/SKILL.md b/backend/workspace/skills/prompt-generator/prop-prompt/SKILL.md
index 5092d5e..a63bb97 100644
--- a/backend/workspace/skills/prompt-generator/prop-prompt/SKILL.md
+++ b/backend/workspace/skills/prompt-generator/prop-prompt/SKILL.md
@@ -1,25 +1,43 @@
---
name: prop-prompt
-description: 道具最终提示词规范 — 白底单品静物(single product shot on pure white background)
+description: 道具最终提示词规范 — 白底单品静物,标准产品摄影视角:比例准确、边缘完整、背景不承载叙事
---
-# 道具最终提示词(白底单品静物)
+# 道具最终提示词(白底单品 · 标准产品摄影)
-生成的是一张白底单品图(product shot):画面中只有道具本身,孤立放置在纯白背景上,**不掺杂任何其他元素**——没有其他物品、没有人物、没有场景环境、没有手部持握。
+生成的是一张白底单品图(product shot):**采用标准产品摄影视角**,画面中只有道具本身,孤立放置在纯白背景上,**不掺杂任何其他元素**——没有其他物品、没有人物、没有场景环境、没有手部持握。
-## 必备要素
+三条硬性要求:
+1. **物品各部分比例准确**——不要夸张、变形或风格化拉伸,道具的相对尺寸关系必须真实
+2. **边缘完整**——道具整体完整入镜,四周留白,任何部分都不得被画面边缘裁切
+3. **背景不承载任何叙事内容**——纯白背景只是衬底,不带场景感、不带情节暗示、不带装饰元素
+
+## 输出结构(按此顺序组装单段连贯中文)
```
-single product photo, isolated on a pure white background,
-no other objects, no people, no scenery, soft even studio lighting
+单品产品图,标准产品摄影视角,[道具名 + 材质/颜色/形状/大小 + 新旧程度与磨损细节],
+物品各部分比例准确,孤立放置在纯白背景上,居中完整入镜,边缘完整无裁切,
+背景纯净不承载任何叙事内容,无其他物品、无人物、无场景,
+柔和均匀的影棚光,轻淡阴影,高细节
```
## 生成规则
-- 以道具 `name`(名称)与 `description`(物品外貌)为核心:材质、颜色、形状、大小、新旧程度、磨损痕迹等物理细节
-- 单品居中完整呈现,不要裁切道具主体
+- 以道具 `name`(名称)与 `description`(物品外貌)为核心:材质、颜色、形状、大小、新旧程度、磨损痕迹等物理细节**逐项落地**,这是道具辨识度的来源
+- 标准产品摄影视角:微俯视 3/4 视角(同时看清顶面与侧面,最有立体感);扁平道具(纸张、证件、照片)用正俯视平铺
+- 单品居中完整呈现,四周留白,比例准确、边缘完整,不要裁切道具主体
- 柔和均匀的影棚光,阴影轻淡,高细节
-- 只描写物品本身,不要提及剧情、角色或用途
-- 单段连贯英文,不包含 `cinematic quality` 等电影感词汇(道具图是产品图不是剧照)
-- 避免出现文字、签名、水印
-- 保存工具:`save_prop_final_prompt`(prompt 参数不含风格词)
+- 只描写物品本身,不要提及剧情、角色或用途(背景与画面都不承载叙事内容)
+- 输出必须是纯中文,不要混入英文词汇;**不要**"电影质感"类词汇(道具图是产品图不是剧照)
+
+## 禁止事项
+
+- 手部持握、人物、其他物品、场景环境入镜
+- 包装、底座、展示架(除非它就是道具本体的一部分)
+- 文字、水印、签名(道具本体上印刷的文字图案可以保留并描述)
+- 环境反光、彩色光
+- 夸张透视、变形、比例失真、边缘裁切
+
+## 保存
+
+调用 `save_prop_final_prompt`:prompt 参数不含风格词,**项目视觉风格由工具自动注入到最终提示词的最前方**。
diff --git a/backend/workspace/skills/prompt-generator/scene-prompt/SKILL.md b/backend/workspace/skills/prompt-generator/scene-prompt/SKILL.md
index ece7593..5963893 100644
--- a/backend/workspace/skills/prompt-generator/scene-prompt/SKILL.md
+++ b/backend/workspace/skills/prompt-generator/scene-prompt/SKILL.md
@@ -1,23 +1,53 @@
---
name: scene-prompt
-description: 场景最终提示词规范 — 固定视角 + 前景/中景/后景分层构图
+description: 场景最终提示词规范 — 清晰广角建立镜头:前景/中景/后景/出入口/地面/墙面/主要陈设的固定相对位置,空间连续自洽可复用,无人物
---
-# 场景最终提示词(固定视角 · 前中后景)
+# 场景最终提示词(广角建立镜头 · 无人物空镜)
-生成的是一张固定机位广角场景图(establishing shot),明确前景、中景、后景三层空间纵深。
+生成的是一张**清晰的广角建立镜头(establishing shot)**场景图:**完全没有人物**的纯场景空镜,完整展示**前景、中景、后景、出入口、地面、墙面及主要陈设的固定相对位置**,空间结构连续、自洽且可复用。
-## 必备要素
+这张图会作为该场景所有镜头的背景参考锚点:观众和模型都必须能从这张图读懂整个空间的布局——从哪里进出、地面与墙面是什么质感、核心陈设各自固定在什么位置。视角必须稳定、通用。
+
+## 输出结构(按此顺序组装单段连贯中文)
```
-fixed camera wide shot, layered composition with foreground, midground and background
+固定机位广角镜头,清晰的建立镜头,[地点 + 年代质感],[时间段],
+前景([前景元素])、中景([中景主体空间])、后景([后景纵深])三层分层构图,
+出入口([门/通道的位置与样式]),地面([地面材质与状态]),墙面([墙面材质与颜色]),
+[主要陈设及其固定相对位置],
+空间结构连续、自洽,
+[光源 + 色温 + 明暗对比],[氛围],
+画面中没有任何人物,空场景,电影质感
```
-## 生成规则
+## 空间结构规则
+
+空间必须**读得懂、对得上、可复用**:
+
+- **前景**:框景/遮挡物(门框、桌角、植物、设备边缘),制造纵深——写出 1-2 个具体元素
+- **中景**:场景的主体空间与核心陈设(流水线、床铺、柜台)
+- **后景**:空间的延伸(远处的墙、窗、走廊、城市轮廓)
+- **出入口**:门、楼梯、通道的位置与样式必须明确(如"画面左侧一扇铁门"),这是后续镜头调度人物进出的依据
+- **地面与墙面**:材质、颜色、状态具体化(如"水泥地面有油渍""墙面石灰斑驳")
+- **主要陈设**:写出 2-4 个核心陈设及它们的**固定相对位置**(如"流水线沿墙排开,尽头是吧台"),陈设之间的左右/远近关系要自洽,不要只罗列物品名
+
+`prompt`(场景描述)中的陈设、年代质感、关键视觉元素必须全部落地;`lighting`(场景光影)要具体化:光源方向、色温冷暖、明暗对比(如"头顶灯管发出冷白光,机器下方投下硬阴影")。
+
+## 视角与氛围
+
+- 稳定的平视或微俯广角,不要极端俯仰、鱼眼、倾斜构图(要作为固定场景反复复用)
+- 以 `location` + `time` 确定时间段与光线基调(日/夜/黄昏的光完全不同)
+- 氛围词具体化:"压抑" → "空气闷热、光线昏暗低沉",不要只写抽象情绪词
+- 输出必须是纯中文,不要混入英文词汇
+
+## 禁止事项
+
+- 任何人物——包括背影、剪影、照片/屏幕里的人(明确写"画面中没有任何人物")
+- 文字、招牌上的可读文字、水印、签名
+- 动态模糊、运动中的物体(场景参考图必须静止稳定)
+- 只罗列陈设清单而不交代相对位置(空间结构必须连续、自洽)
+
+## 保存
-- 以 `location`(地点)+ `time`(时间段)为基础,`prompt` 交代陈设与年代质感
-- `lighting` 决定光影氛围,明确前、中、后景三层空间纵深
-- 无人物纯场景
-- 单段连贯英文,包含 `cinematic quality`
-- 避免出现文字、签名、水印
-- 保存工具:`save_scene_final_prompt`(prompt 参数不含风格词)
+调用 `save_scene_final_prompt`:prompt 参数不含风格词,**项目视觉风格由工具自动注入到最终提示词的最前方**。
diff --git a/backend/workspace/skills/prompt-generator/video-prompt/SKILL.md b/backend/workspace/skills/prompt-generator/video-prompt/SKILL.md
index 9b2dc56..dc23d16 100644
--- a/backend/workspace/skills/prompt-generator/video-prompt/SKILL.md
+++ b/backend/workspace/skills/prompt-generator/video-prompt/SKILL.md
@@ -1,32 +1,54 @@
---
name: video-prompt
-description: 视频提示词规范 — 根据分镜内容生成按时间分段的视频生成提示词
+description: 视频提示词规范 — 根据分镜内容生成按时间分段的连续单镜头视频生成提示词
---
# 视频提示词(分镜 → video_prompt)
-根据单个分镜的 action / description / dialogue / atmosphere / duration,生成驱动 AI 视频生成的 `video_prompt`。
+根据单个分镜的 action / description / dialogue / atmosphere / duration,生成驱动 AI 视频生成的 `video_prompt`。**一个分镜 = 一个连续镜头**:全程不切换场景、不跳切。
## 格式
-按 3 秒为一段,每段单独一行、用换行分隔:
+按 3 秒为一段,每段单独一行、用换行分隔,时间范围连续衔接(无重叠、无空缺):
```
-0-3秒:@咖啡厅,近景,@小明低头看手机,表情焦虑。
-3-6秒:@咖啡厅,全景,门铃响,@小红推门走入。
-6-9秒:@咖啡厅,中景,@小红微笑走向小明,坐下。
+0-3秒:@咖啡厅,近景固定镜头,@小明低头看手机,手指反复敲桌面,表情焦虑。
+3-6秒:@咖啡厅,镜头缓慢拉远到全景,门铃响,@小红推门走入,带进一阵冷风。
+6-9秒:@咖啡厅,中景,@小红微笑着走向小明坐下,小明说:「你终于来了。」
```
+## 段内结构
+
+每一段按此顺序组织内容(可省略无内容的项,但动作/画面必须有):
+
+**时间范围 + 场景@引用 + 景别/运镜 + 角色@引用+主体动作·表情 + 对白/旁白 + 氛围光线**
+
+- **第一段必须建立空间**:场景 + 机位 + 角色的位置与状态,让观众一眼知道在哪、看谁
+- **景别/运镜**:每段一个镜头状态(近景/中景/全景/特写;固定/推/拉/摇/跟),运镜一次只用一个、全程连续
+- **动作**:每段一个主动作,动词具体可见(走、转身、抬头、攥紧、停顿)
+- **情绪全部转为可见描写**:不要"他很伤心/气氛紧张"这类抽象词,写成"他低下头、手指攥紧杯沿、呼吸变重"
+- **对白/旁白**:写「角色名说:「台词」」,旁白写「旁白:内容」;3 秒念不完的长台词拆到多段;无对白的段可写环境音/动作音(如"机器持续轰鸣")
+
## 引用规则
- `@场景名` — 场景引用,名字必须与场景列表中的地点完全一致
- `@角色名` — 角色引用,名字必须与角色列表中的名字完全一致
+- `@道具名` — 道具引用,名字必须与道具列表中的名字完全一致;道具在画面中明显可见、被使用或特写时引用
- 生成时会自动把 `@名字` 替换为对应参考图片标记(如 `@小明` → `@图片1小明`),因此名字必须精确匹配,不要缩写或加额外符号
+- **每段至少一个 @ 引用锚定画面**;角色出场的段必须 @ 该角色;只引用该分镜已绑定的场景/角色/道具
+
+## 时间轴规则
+
+- 段数 = 分镜 duration ÷ 3 秒(向上取整),各段时间范围相加必须等于分镜总时长
+- 内容节奏:第一段建立 → 中段推进动作/冲突 → 末段落到结果或情绪点
+
+## 禁止事项
+
+- 场景切换、跳切、闪回(单分镜必须是连续镜头)
+- 引用列表之外的场景/角色名
+- 抽象心理描写、文学化比喻(模型只认可见画面)
+- 英文混写(视频提示词用中文)
-## 生成规则
+## 保存
-- 先调用 `read_storyboard_context` 读取该分镜的字段与绑定的场景/角色
-- 每段内容覆盖:动作、画面描述、对白/旁白、氛围
-- 突出时间推进、动作变化、镜头语言
-- 段数按分镜 duration 划分(约 3 秒一段)
-- 保存:调用 `update_storyboard` 仅更新该分镜的 `video_prompt` 字段,不要改动其他字段,不要重新拆分整集
+调用 `update_storyboard` 仅更新该分镜的 `video_prompt` 字段,不要改动其他字段,不要重新拆分整集。
diff --git a/backend/workspace/skills/storyboard-breaker/SKILL.md b/backend/workspace/skills/storyboard-breaker/SKILL.md
index c716a00..6e644d9 100644
--- a/backend/workspace/skills/storyboard-breaker/SKILL.md
+++ b/backend/workspace/skills/storyboard-breaker/SKILL.md
@@ -28,12 +28,13 @@ description: 分镜拆解专业规范
15. **音效提示词**:`sound_effect`,描述该镜头关键环境音/动作音
16. **场景关联**:若能匹配已有场景,必须填写 `scene_id`
17. **角色关联**:填写 `character_ids`,绑定当前镜头涉及的 0 到多个角色
+18. **道具关联**:填写 `prop_ids`,绑定当前镜头出现的关键道具(0 到多个)
## 使用步骤
-1. 调用 `read_storyboard_context` 读取剧本、角色、场景、已有分镜摘要
+1. 调用 `read_storyboard_context` 读取剧本、角色、场景、道具、已有分镜摘要
2. 先基于剧本完成镜头拆解,确保总时长和叙事连续性合理
-3. 为每个镜头补全完整字段:`title / shot_type / angle / movement / location / time / character_ids / action / dialogue / description / result / atmosphere / image_prompt / bgm_prompt / sound_effect / duration / scene_id`(不含 `video_prompt`)
+3. 为每个镜头补全完整字段:`title / shot_type / angle / movement / location / time / character_ids / prop_ids / action / dialogue / description / result / atmosphere / image_prompt / bgm_prompt / sound_effect / duration / scene_id`(不含 `video_prompt`)
4. 调用 `save_storyboards` 一次性保存完整分镜
5. 如需调整,调用 `update_storyboard` 修改具体镜头
@@ -51,6 +52,14 @@ description: 分镜拆解专业规范
- 只要镜头里有明确出场、被看见、发生动作或说话的角色,都应绑定进去
- 纯环境镜头、空镜头、物件镜头可以传空数组
+## 道具绑定规则
+
+- `prop_ids` 必须从 `read_storyboard_context` 返回的道具列表(`props`)中选择
+- 道具被角色使用、交接、特写,或在画面中明显可见且对叙事有意义时,必须绑定到该镜头
+- 道具特写镜头(无角色)也应绑定道具,`character_ids` 可为空
+- 与剧情无关的背景物品、场景陈设不要绑定;没有道具出现的镜头传空数组
+- 绑定的道具会作为视频生成的参考图(白底单品图),保证道具外观跨镜头一致
+
## 质量要求
- `description` 要适合人读,详细描述观众实际看到的画面内容
diff --git a/frontend/app/composables/useApi.ts b/frontend/app/composables/useApi.ts
index f6a5c2e..02c8d62 100644
--- a/frontend/app/composables/useApi.ts
+++ b/frontend/app/composables/useApi.ts
@@ -52,6 +52,10 @@ export const episodeAPI = {
props: (id: number) => api.get(`/episodes/${id}/props`),
storyboards: (id: number) => api.get(`/episodes/${id}/storyboards`),
pipelineStatus: (id: number) => api.get(`/episodes/${id}/pipeline-status`),
+ extract: (id: number, target: string, model?: string, configId?: number) => api.post(`/episodes/${id}/extract`, { target, model: model || undefined, config_id: configId || undefined }),
+ extractStatus: (id: number) => api.get(`/episodes/${id}/extract-status`),
+ generateVideoPrompts: (id: number, model?: string, configId?: number, storyboardIds?: number[]) => api.post(`/episodes/${id}/generate-video-prompts`, { model: model || undefined, config_id: configId || undefined, storyboard_ids: storyboardIds?.length ? storyboardIds : undefined }),
+ videoPromptsStatus: (id: number) => api.get(`/episodes/${id}/video-prompts-status`),
}
export const storyboardAPI = {
@@ -61,37 +65,43 @@ export const storyboardAPI = {
}
export const characterAPI = {
+ create: (data: any) => api.post('/characters', data),
update: (id: number, data: any) => api.put(`/characters/${id}`, data),
- generatePrompt: (id: number, episodeId: number, force = false) => api.post(`/characters/${id}/generate-prompt`, { episode_id: episodeId, force }),
- generateImage: (id: number, episodeId: number, model?: string, configId?: number) => api.post(`/characters/${id}/generate-image`, { episode_id: episodeId, model: model || undefined, config_id: configId || undefined }),
- batchImages: (ids: number[], episodeId: number, model?: string, configId?: number) => api.post('/characters/batch-generate-images', { character_ids: ids, episode_id: episodeId, model: model || undefined, config_id: configId || undefined }),
+ del: (id: number) => api.del(`/characters/${id}`),
+ generatePrompt: (id: number, episodeId: number, force = false, textModel?: string, textConfigId?: number) => api.post(`/characters/${id}/generate-prompt`, { episode_id: episodeId, force, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
+ generateImage: (id: number, episodeId: number, model?: string, configId?: number, textModel?: string, textConfigId?: number) => api.post(`/characters/${id}/generate-image`, { episode_id: episodeId, model: model || undefined, config_id: configId || undefined, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
+ batchImages: (ids: number[], episodeId: number, model?: string, configId?: number, textModel?: string, textConfigId?: number) => api.post('/characters/batch-generate-images', { character_ids: ids, episode_id: episodeId, model: model || undefined, config_id: configId || undefined, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
}
export const sceneAPI = {
+ create: (data: any) => api.post('/scenes', data),
update: (id: number, data: any) => api.put(`/scenes/${id}`, data),
- generatePrompt: (id: number, episodeId: number, force = false) => api.post(`/scenes/${id}/generate-prompt`, { episode_id: episodeId, force }),
- generateImage: (id: number, episodeId: number, model?: string, configId?: number) => api.post(`/scenes/${id}/generate-image`, { episode_id: episodeId, model: model || undefined, config_id: configId || undefined }),
+ del: (id: number) => api.del(`/scenes/${id}`),
+ generatePrompt: (id: number, episodeId: number, force = false, textModel?: string, textConfigId?: number) => api.post(`/scenes/${id}/generate-prompt`, { episode_id: episodeId, force, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
+ generateImage: (id: number, episodeId: number, model?: string, configId?: number, textModel?: string, textConfigId?: number) => api.post(`/scenes/${id}/generate-image`, { episode_id: episodeId, model: model || undefined, config_id: configId || undefined, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
}
export const propAPI = {
+ create: (data: any) => api.post('/props', data),
update: (id: number, data: any) => api.put(`/props/${id}`, data),
- generatePrompt: (id: number, episodeId: number, force = false) => api.post(`/props/${id}/generate-prompt`, { episode_id: episodeId, force }),
- generateImage: (id: number, episodeId: number, model?: string, configId?: number) => api.post(`/props/${id}/generate-image`, { episode_id: episodeId, model: model || undefined, config_id: configId || undefined }),
+ del: (id: number) => api.del(`/props/${id}`),
+ generatePrompt: (id: number, episodeId: number, force = false, textModel?: string, textConfigId?: number) => api.post(`/props/${id}/generate-prompt`, { episode_id: episodeId, force, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
+ generateImage: (id: number, episodeId: number, model?: string, configId?: number, textModel?: string, textConfigId?: number) => api.post(`/props/${id}/generate-image`, { episode_id: episodeId, model: model || undefined, config_id: configId || undefined, text_model: textModel || undefined, text_config_id: textConfigId || undefined }),
}
-export const imageAPI = {
- generate: (d: any) => api.post('/images', d),
- list: (params?: { drama_id?: number; storyboard_id?: number }) => {
+// 统一生成任务(图片/视频):POST 带 type 字段,列表按 type 过滤
+export const taskAPI = {
+ generate: (d: any) => api.post('/tasks', d),
+ get: (id: number) => api.get(`/tasks/${id}`),
+ del: (id: number) => api.del(`/tasks/${id}`),
+ list: (params?: { type?: 'image' | 'video'; drama_id?: number; storyboard_id?: number }) => {
const query = new URLSearchParams()
+ if (params?.type) query.set('type', params.type)
if (params?.drama_id) query.set('drama_id', String(params.drama_id))
if (params?.storyboard_id) query.set('storyboard_id', String(params.storyboard_id))
- return api.get(`/images${query.size ? `?${query.toString()}` : ''}`)
+ return api.get(`/tasks${query.size ? `?${query.toString()}` : ''}`)
},
}
-export const videoAPI = {
- generate: (d: any) => api.post('/videos', d),
- get: (id: number) => api.get(`/videos/${id}`),
-}
async function uploadReq<T = any>(path: string, file: File): Promise<T> {
const fd = new FormData()
diff --git a/frontend/app/pages/drama/[id]/assets.vue b/frontend/app/pages/drama/[id]/assets.vue
index ef5aac6..295e242 100644
--- a/frontend/app/pages/drama/[id]/assets.vue
+++ b/frontend/app/pages/drama/[id]/assets.vue
@@ -84,7 +84,7 @@
<script setup>
import { toast } from 'vue-sonner'
-import { dramaAPI, imageAPI } from '~/composables/useApi'
+import { dramaAPI, taskAPI } from '~/composables/useApi'
const route = useRoute()
const dramaId = Number(route.params.id)
@@ -140,7 +140,7 @@ async function load() {
try {
const [d, gens] = await Promise.all([
dramaAPI.get(dramaId),
- imageAPI.list({ drama_id: dramaId }),
+ taskAPI.list({ type: 'image', drama_id: dramaId }),
])
drama.value = d
generations.value = gens || []
diff --git a/frontend/app/pages/drama/[id]/episode/[episodeNumber].vue b/frontend/app/pages/drama/[id]/episode/[episodeNumber].vue
index 9f7638e..000c628 100644
--- a/frontend/app/pages/drama/[id]/episode/[episodeNumber].vue
+++ b/frontend/app/pages/drama/[id]/episode/[episodeNumber].vue
@@ -23,8 +23,8 @@
<div class="studio-model-picks">
<ModelSelect
v-if="textModelOptions.length"
- v-model="rewriteModel"
- label="改写"
+ v-model="chatModel"
+ label="文本"
:options="textModelOptions"
:default-label="`默认 · ${textModelOptions[0].model}`"
:show-config="textModelMultiCfg"
@@ -244,41 +244,55 @@
<span class="dim" style="font-size:12px">资产</span>
<span class="tag mono">{{ assetReadyCount }}/{{ assetTotalCount }} 已就绪</span>
<span class="tag">{{ lockedImageConfigLabel }}</span>
- <div class="ml-auto flex gap-1">
- <button class="btn btn-sm" :disabled="rn" @click="doExtract">
- <Loader2 v-if="rt === 'extractor'" :size="11" class="animate-spin" />
+ <div class="ml-auto flex gap-1 asset-bar-actions">
+ <button
+ v-for="t in EXTRACT_TARGETS"
+ :key="t.key"
+ class="btn btn-sm asset-btn-extract"
+ :disabled="isExtracting(t.key)"
+ @click="doExtract(t.key)"
+ >
+ <Loader2 v-if="isExtracting(t.key)" :size="11" class="animate-spin" />
<svg v-else width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
- {{ chars.length || scenes.length || propItems.length ? '重新提取' : '开始提取' }}
+ {{ (t.key === 'characters' ? chars.length : t.key === 'scenes' ? scenes.length : propItems.length) ? `重提${t.label}` : `提取${t.label}` }}
</button>
- <button class="btn btn-sm" @click="batchCharImages">
+ <span class="asset-bar-divider" />
+ <button class="btn btn-sm asset-btn-batch" @click="batchCharImages">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
- 批量生成
+ 批量角色
</button>
- <button class="btn btn-sm" @click="batchSceneImages">
+ <button class="btn btn-sm asset-btn-batch" @click="batchSceneImages">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
批量场景
</button>
+ <button class="btn btn-sm asset-btn-batch" @click="batchPropImages">
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
+ 批量道具
+ </button>
</div>
</div>
- <div v-if="rn && rt === 'extractor'" class="step-loading">
+ <div v-if="extractingTargets.length && !chars.length && !scenes.length && !propItems.length" class="step-loading">
<Loader2 :size="24" class="animate-spin" style="color:var(--accent)" />
- <div class="loading-text">正在提取角色、场景和道具...</div>
+ <div class="loading-text">正在提取{{ extractingLabels }}...</div>
</div>
<div v-else-if="!chars.length && !scenes.length && !propItems.length" class="step-empty asset-empty-state">
<div class="empty-visual">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
</div>
<div class="empty-title">开始提取资产</div>
- <div class="empty-desc">角色、场景和道具会在提取后显示在这里,然后可以继续生成角色形象和场景图片。</div>
- <button class="btn btn-primary" :disabled="rn" @click="doExtract">
- <Loader2 v-if="rt === 'extractor'" :size="13" class="animate-spin" />
+ <div class="empty-desc">角色、场景和道具会在提取后显示在这里,可分别单独提取,也可一键并行提取全部。</div>
+ <button class="btn btn-primary" :disabled="!!extractingTargets.length" @click="doExtractAll">
+ <Loader2 v-if="extractingTargets.length" :size="13" class="animate-spin" />
<svg v-else width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
- 开始提取
+ {{ extractingTargets.length ? `正在提取${extractingLabels}…` : '开始提取' }}
</button>
</div>
<template v-else>
+ <div class="asset-section-title">
+ 角色
+ <button class="asset-add-btn" @click="openAssetCreate('character')"><Plus :size="11" /> 新增</button>
+ </div>
<template v-if="visualChars.length">
- <div class="asset-section-title">角色</div>
<div class="character-asset-grid">
<article
v-for="c in visualChars"
@@ -290,6 +304,7 @@
@keydown.enter.prevent="openAssetDetail('character', c)"
@keydown.space.prevent="openAssetDetail('character', c)"
>
+ <button class="asset-del-btn" title="删除角色" @click.stop="askDeleteAsset('character', c)"><X :size="11" /></button>
<div class="character-asset-main">
<div class="character-asset-overview"><div class="character-portrait">
<img
@@ -332,8 +347,11 @@
</div>
</template>
+ <div class="asset-section-title">
+ 场景
+ <button class="asset-add-btn" @click="openAssetCreate('scene')"><Plus :size="11" /> 新增</button>
+ </div>
<template v-if="scenes.length">
- <div class="asset-section-title">场景</div>
<div class="asset-grid">
<div
v-for="s in scenes"
@@ -345,6 +363,7 @@
@keydown.enter.prevent="openAssetDetail('scene', s)"
@keydown.space.prevent="openAssetDetail('scene', s)"
>
+ <button class="asset-del-btn" title="删除场景" @click.stop="askDeleteAsset('scene', s)"><X :size="11" /></button>
<div class="asset-cover wide">
<img
v-if="s.image_url || s.imageUrl"
@@ -377,7 +396,10 @@
</div>
</template>
- <div class="asset-section-title">道具</div>
+ <div class="asset-section-title">
+ 道具
+ <button class="asset-add-btn" @click="openAssetCreate('prop')"><Plus :size="11" /> 新增</button>
+ </div>
<div v-if="propItems.length" class="asset-grid">
<div
v-for="p in propItems"
@@ -389,6 +411,7 @@
@keydown.enter.prevent="openAssetDetail('prop', p)"
@keydown.space.prevent="openAssetDetail('prop', p)"
>
+ <button class="asset-del-btn" title="删除道具" @click.stop="askDeleteAsset('prop', p)"><X :size="11" /></button>
<div class="asset-cover wide">
<img
v-if="p.image_url || p.imageUrl"
@@ -437,17 +460,30 @@
<svg v-else width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
{{ sbs.length ? '重新拆分' : '开始拆分' }}
</button>
+ <button class="btn btn-sm" :disabled="videoPromptBatch.running || !sbs.length" @click="batchVideoPrompts">
+ <Loader2 v-if="videoPromptBatch.running" :size="11" class="animate-spin" />
+ <svg v-else width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
+ {{ videoPromptBatch.running ? `提示词 ${videoPromptBatch.completed}/${videoPromptBatch.total}` : (selectedSbIds.length ? `生成所选提示词(${selectedSbIds.length})` : '批量视频提示词') }}
+ </button>
</div>
</div>
<div v-if="sbs.length" class="storyboard-workbench">
<aside class="storyboard-shot-list">
<div class="shot-list-head">
- <div>
- <div class="shot-list-title">分镜列表</div>
- <div class="shot-list-sub">检查拆分描述和绑定的角色场景</div>
+ <div class="shot-list-head-main">
+ <div class="shot-list-head-copy">
+ <div class="shot-list-title">分镜列表</div>
+ <div class="shot-list-sub">检查拆分描述和绑定的角色场景</div>
+ </div>
+ <span class="tag mono">{{ totalDuration }}s</span>
+ <button v-if="!sbSelectMode && sbs.length" class="shot-quick-btn" @click="sbSelectMode = true">选择</button>
+ </div>
+ <div v-if="sbSelectMode" class="shot-quick-actions">
+ <button class="shot-quick-btn" @click="toggleSelectAllSbs">全选</button>
+ <button class="shot-quick-btn" @click="selectMissingSbs">仅缺失</button>
+ <button class="shot-quick-btn" @click="selectedSbIds = []">清空</button>
</div>
- <span class="tag mono">{{ totalDuration }}s</span>
</div>
<div class="shot-list-body">
<button
@@ -455,10 +491,17 @@
:key="sb.id"
type="button"
class="storyboard-shot-card"
- :class="{ active: selectedSb?.id === sb.id }"
- @click="selectedSb = sb"
+ :class="{ active: !sbSelectMode && selectedSb?.id === sb.id, 'is-selected': sbSelectMode && isSbSelected(sb.id) }"
+ @click="onShotCardClick(sb)"
>
<div class="storyboard-shot-head">
+ <span
+ v-if="sbSelectMode"
+ class="shot-check"
+ :class="{ on: isSbSelected(sb.id) }"
+ >
+ <svg v-if="isSbSelected(sb.id)" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
+ </span>
<div class="shot-num">#{{ String(i + 1).padStart(2, '0') }}</div>
<span class="storyboard-shot-chip">{{ sb.duration || 10 }}s</span>
<span v-if="getSceneName(sb)" class="shot-location"><MapPin :size="9" />{{ getSceneName(sb) }}</span>
@@ -490,6 +533,16 @@
</div>
</button>
</div>
+ <div v-if="sbSelectMode" class="shot-select-bar">
+ <div class="shot-select-info">
+ <span class="shot-select-count">已选 {{ selectedSbIds.length }} 个</span>
+ <button class="btn btn-sm" @click="exitSbSelectMode">取消</button>
+ </div>
+ <button class="btn btn-sm btn-primary shot-select-go" :disabled="!selectedSbIds.length || videoPromptBatch.running" @click="generateSelectedVideoPrompts">
+ <Loader2 v-if="videoPromptBatch.running" :size="11" class="animate-spin" />
+ {{ videoPromptBatch.running ? `生成中 ${videoPromptBatch.completed}/${videoPromptBatch.total}` : `生成视频提示词(${selectedSbIds.length})` }}
+ </button>
+ </div>
</aside>
<section class="storyboard-editor-main" v-if="selectedSb">
@@ -545,35 +598,74 @@
</button>
<span v-if="!visualChars.length" class="dim" style="font-size:12px">当前集还没有角色</span>
</div>
+ <span class="sb-field-label">道具</span>
+ <div class="role-pills">
+ <button
+ v-for="prop in propItems"
+ :key="prop.id"
+ type="button"
+ :class="['role-pill', { active: isStoryboardPropSelected(selectedSb, prop.id) }]"
+ @click="toggleStoryboardProp(selectedSb, prop.id)"
+ >
+ {{ prop.name }}
+ </button>
+ <span v-if="!propItems.length" class="dim" style="font-size:12px">当前集还没有道具</span>
+ </div>
</div>
<div class="storyboard-editor-scroll">
- <div class="detail-section">
- <div class="detail-section-head">
- <span class="detail-section-title">分镜描述</span>
- </div>
- <label class="field">
- <span class="field-label">画面描述</span>
- <textarea :value="selectedSb.description || ''" class="textarea" rows="4" @blur="updateField(selectedSb, 'description', $event.target.value)" placeholder="分镜画面描述" />
- </label>
- <div class="field-grid field-grid-2">
+ <div class="sb-split">
+ <div class="detail-section">
+ <div class="detail-section-head">
+ <span class="detail-section-title">分镜描述</span>
+ </div>
<label class="field">
- <span class="field-label">动作</span>
- <textarea :value="selectedSb.action || ''" class="textarea" rows="3" @blur="updateField(selectedSb, 'action', $event.target.value)" placeholder="角色动作与表演" />
+ <span class="field-label">画面描述</span>
+ <textarea :value="selectedSb.description || ''" class="textarea" rows="4" @blur="updateField(selectedSb, 'description', $event.target.value)" placeholder="分镜画面描述" />
</label>
- <label class="field">
- <span class="field-label">氛围</span>
- <textarea :value="selectedSb.atmosphere || ''" class="textarea" rows="3" @blur="updateField(selectedSb, 'atmosphere', $event.target.value)" placeholder="光线、色调、空气感、环境氛围" />
+ <div class="field-grid field-grid-2">
+ <label class="field">
+ <span class="field-label">动作</span>
+ <textarea :value="selectedSb.action || ''" class="textarea" rows="3" @blur="updateField(selectedSb, 'action', $event.target.value)" placeholder="角色动作与表演" />
+ </label>
+ <label class="field">
+ <span class="field-label">氛围</span>
+ <textarea :value="selectedSb.atmosphere || ''" class="textarea" rows="3" @blur="updateField(selectedSb, 'atmosphere', $event.target.value)" placeholder="光线、色调、空气感、环境氛围" />
+ </label>
+ </div>
+ <label v-if="dialogueOpen || selectedSb.dialogue" class="field">
+ <span class="field-label">对白 / 旁白</span>
+ <textarea :value="selectedSb.dialogue || ''" class="textarea" rows="2" @blur="updateField(selectedSb, 'dialogue', $event.target.value)" placeholder="角色名:台词内容 或 旁白:内容" />
</label>
+ <button v-else type="button" class="dialogue-add" @click="dialogueOpen = true">
+ <MessageSquarePlus :size="12" />
+ 添加对白 / 旁白
+ </button>
+ </div>
+
+ <div class="detail-section">
+ <div class="detail-section-head">
+ <span class="detail-section-title">视频提示词</span>
+ <button
+ type="button"
+ class="btn btn-sm"
+ :disabled="rn || videoPromptBatch.running"
+ @click="genVideoPrompt(selectedSb)"
+ >
+ <Loader2 v-if="rn && rt === 'prompt_generator'" :size="11" class="animate-spin" />
+ {{ (selectedSb.video_prompt || selectedSb.videoPrompt) ? '重新生成' : 'AI 生成' }}
+ </button>
+ </div>
+ <div class="detail-section-copy">根据当前分镜的画面描述、动作、氛围以及对白 / 旁白生成</div>
+ <MentionTextarea
+ :model-value="selectedSb.video_prompt || selectedSb.videoPrompt || ''"
+ :options="mentionOptions"
+ :rows="12"
+ input-class="textarea"
+ placeholder="用 @角色名 / @场景名 / @道具名 引用参考素材(如 @志远、@电子厂车间、@扳手),按 3 秒一段换行描述画面运动与镜头;也可点 AI 生成由提示词 Agent 自动创作…"
+ @commit="v => updateField(selectedSb, 'video_prompt', v)"
+ />
</div>
- <label v-if="dialogueOpen || selectedSb.dialogue" class="field">
- <span class="field-label">对白 / 旁白</span>
- <textarea :value="selectedSb.dialogue || ''" class="textarea" rows="2" @blur="updateField(selectedSb, 'dialogue', $event.target.value)" placeholder="角色名:台词内容 或 旁白:内容" />
- </label>
- <button v-else type="button" class="dialogue-add" @click="dialogueOpen = true">
- <MessageSquarePlus :size="12" />
- 添加对白 / 旁白
- </button>
</div>
</div>
</section>
@@ -587,7 +679,7 @@
<span class="tag mono">{{ getShotReferenceAssets(selectedSb).filter(item => item.ready).length }}/{{ getShotReferenceAssets(selectedSb).length }}</span>
</div>
<div class="storyboard-ref-list">
- <template v-for="group in ['角色', '场景']" :key="group">
+ <template v-for="group in ['角色', '场景', '道具']" :key="group">
<div v-if="getShotReferenceAssets(selectedSb).filter(a => a.type === group).length" class="storyboard-ref-group">
<div class="storyboard-ref-group-label">{{ group }}</div>
<div
@@ -602,7 +694,7 @@
@click.stop="asset.ready && openImageViewer(assetImageSrc({ imageUrl: asset.imageUrl }), `${asset.name} ${asset.type}`)"
>
<img v-if="asset.ready" :src="assetImageSrc({ imageUrl: asset.imageUrl })" class="previewable-image" />
- <span v-else>{{ asset.type === '场景' ? '景' : '角' }}</span>
+ <span v-else>{{ asset.type === '场景' ? '景' : asset.type === '道具' ? '具' : '角' }}</span>
</button>
<div class="storyboard-ref-main">
<div class="storyboard-ref-line">
@@ -616,7 +708,7 @@
</div>
</template>
<div v-if="!getShotReferenceAssets(selectedSb).length" class="storyboard-ref-empty">
- 当前分镜还没有绑定角色或场景。
+ 当前分镜还没有绑定角色、场景或道具。
</div>
</div>
</aside>
@@ -647,6 +739,11 @@
<span class="dim" style="font-size:12px">{{ sbs.length }} 个镜头</span>
<span class="tag mono">{{ shotVidCount }}/{{ sbs.length }} 已生成</span>
<div class="ml-auto flex gap-1">
+ <button class="btn btn-sm" :disabled="videoPromptBatch.running || !sbs.length" @click="batchVideoPrompts">
+ <Loader2 v-if="videoPromptBatch.running" :size="11" class="animate-spin" />
+ <svg v-else width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
+ {{ videoPromptBatch.running ? `提示词 ${videoPromptBatch.completed}/${videoPromptBatch.total}` : (selectedSbIds.length ? `生成所选提示词(${selectedSbIds.length})` : '批量视频提示词') }}
+ </button>
<button class="btn btn-sm" :disabled="!sbs.length" @click="batchVideos">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>
批量视频
@@ -751,10 +848,10 @@
<button
type="button"
class="btn btn-sm"
- :disabled="rn"
+ :disabled="rn || videoPromptBatch.running"
@click="genVideoPrompt(selectedSb)"
>
- <Loader2 v-if="rn && rt === 'storyboard_breaker'" :size="11" class="animate-spin" />
+ <Loader2 v-if="rn && rt === 'prompt_generator'" :size="11" class="animate-spin" />
{{ (selectedSb.video_prompt || selectedSb.videoPrompt) ? '重新生成' : 'AI 生成' }}
</button>
</div>
@@ -763,7 +860,7 @@
:options="mentionOptions"
:rows="9"
input-class="textarea video-inspector-prompt"
- placeholder="用 @角色名 / @场景名 引用参考素材(如 @志远、@电子厂车间),生成时自动映射为参考图片;再按时间段描述画面运动与镜头…"
+ placeholder="用 @角色名 / @场景名 / @道具名 引用参考素材(如 @志远、@电子厂车间、@扳手),生成时自动映射为参考图片;再按时间段描述画面运动与镜头…"
@commit="v => updateField(selectedSb, 'video_prompt', v)"
/>
</section>
@@ -1084,13 +1181,12 @@
<span>{{ assetDetail.type === 'character' ? '最终提示词 · 三视图' : assetDetail.type === 'scene' ? '最终提示词 · 固定视角' : '最终提示词 · 白底单品' }}</span>
<div class="asset-detail-prompt-head-actions">
<button
- v-if="!assetFinalPrompt"
class="btn btn-sm"
:disabled="isGeneratingPrompt(assetDetail.type, assetDetail.item.id) || isAssetImagePending(assetDetail.type, assetDetail.item.id)"
@click="genAssetFinalPrompt"
>
<Loader2 v-if="isGeneratingPrompt(assetDetail.type, assetDetail.item.id)" :size="11" class="animate-spin" />
- {{ isGeneratingPrompt(assetDetail.type, assetDetail.item.id) ? '生成中' : '生成提示词' }}
+ {{ isGeneratingPrompt(assetDetail.type, assetDetail.item.id) ? '生成中' : (assetFinalPrompt ? '重新生成' : '生成提示词') }}
</button>
<span :class="['asset-detail-state', assetFinalPrompt && 'is-ready']">
{{ assetFinalPrompt ? '已生成' : '待生成' }}
@@ -1128,6 +1224,7 @@
<footer class="dialog-foot asset-detail-foot">
<div class="asset-detail-secondary-actions">
+ <button class="btn btn-danger" @click="askDeleteAsset(assetDetail.type, assetDetail.item)">删除</button>
<button class="btn" @click="closeAssetDetail">关闭</button>
</div>
<div class="asset-detail-primary-actions">
@@ -1177,6 +1274,52 @@
</div>
</div>
</div>
+
+ <div v-if="assetCreate.open" class="overlay" @click.self="assetCreate.open = false">
+ <div class="dialog asset-create-dialog">
+ <header class="dialog-head">
+ <h2 class="dialog-title">新增{{ assetCreateTypeLabel }}</h2>
+ <button class="btn btn-ghost btn-icon" @click="assetCreate.open = false">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
+ </button>
+ </header>
+ <div class="dialog-body asset-create-body">
+ <template v-if="assetCreate.type === 'character'">
+ <label class="field"><span class="field-label">名称</span><input v-model="assetCreateDraft.name" class="input" placeholder="角色名称" /></label>
+ <label class="field"><span class="field-label">角色定位</span><input v-model="assetCreateDraft.role" class="input" placeholder="如:主角 / 反派 / 配角" /></label>
+ <label class="field"><span class="field-label">样貌</span><textarea v-model="assetCreateDraft.appearance" class="textarea" rows="3" placeholder="外貌特征(可融入性格)" /></label>
+ <label class="field"><span class="field-label">妆造</span><textarea v-model="assetCreateDraft.styling" class="textarea" rows="2" placeholder="服装、妆容、配饰" /></label>
+ </template>
+ <template v-else-if="assetCreate.type === 'scene'">
+ <label class="field"><span class="field-label">地点</span><input v-model="assetCreateDraft.location" class="input" placeholder="场景地点" /></label>
+ <label class="field"><span class="field-label">时间</span><input v-model="assetCreateDraft.time" class="input" placeholder="如:白天 / 夜晚" /></label>
+ <label class="field"><span class="field-label">场景描述</span><textarea v-model="assetCreateDraft.prompt" class="textarea" rows="3" placeholder="环境、陈设、氛围" /></label>
+ <label class="field"><span class="field-label">场景光影</span><input v-model="assetCreateDraft.lighting" class="input" placeholder="如:黄昏暖光、冷清顶光" /></label>
+ </template>
+ <template v-else>
+ <label class="field"><span class="field-label">名称</span><input v-model="assetCreateDraft.name" class="input" placeholder="道具名称" /></label>
+ <label class="field"><span class="field-label">类型</span><input v-model="assetCreateDraft.type" class="input" placeholder="如:武器 / 信物 / 文件" /></label>
+ <label class="field"><span class="field-label">物品外貌</span><textarea v-model="assetCreateDraft.description" class="textarea" rows="3" placeholder="只描述物品的外观,与其他无关" /></label>
+ </template>
+ </div>
+ <footer class="dialog-foot">
+ <button class="btn" @click="assetCreate.open = false">取消</button>
+ <button class="btn btn-primary" :disabled="assetCreate.saving" @click="saveAssetCreate">
+ <Loader2 v-if="assetCreate.saving" :size="12" class="animate-spin" />
+ 新增
+ </button>
+ </footer>
+ </div>
+ </div>
+
+ <ConfirmDialog
+ :open="assetDelete.open"
+ :title="`删除${assetDeleteTypeLabel}`"
+ :message="`确定删除${assetDeleteTypeLabel}「${assetDeleteName}」吗?将从本剧所有集中移除。`"
+ :loading="assetDelete.loading"
+ @confirm="confirmDeleteAsset"
+ @cancel="assetDelete.open = false"
+ />
</main>
</div>
</div>
@@ -1186,9 +1329,9 @@
import { toast } from 'vue-sonner'
import {
Users, Video, FileText, FolderKanban, Clapperboard, Download, Loader2,
- MapPin, Play, MessageSquarePlus,
+ MapPin, Play, MessageSquarePlus, Plus, X,
} from 'lucide-vue-next'
-import { dramaAPI, episodeAPI, storyboardAPI, characterAPI, sceneAPI, propAPI, videoAPI, mergeAPI, aiConfigAPI, uploadAPI } from '~/composables/useApi'
+import { dramaAPI, episodeAPI, storyboardAPI, characterAPI, sceneAPI, propAPI, taskAPI, mergeAPI, aiConfigAPI, uploadAPI } from '~/composables/useApi'
import { useAgent } from '~/composables/useAgent'
definePageMeta({ layout: 'studio' })
@@ -1220,11 +1363,12 @@ const imageConfigs = ref([])
const videoConfigs = ref([])
const textConfigs = ref([])
// 生成时可选模型:空串 = 跟随配置默认(models[0]);选择持久化到 localStorage,刷新页面后保留
-const MODEL_STORE_KEYS = { rewrite: 'huobao:model:rewrite', image: 'huobao:model:image', video: 'huobao:model:video' }
-function readStoredModel(key) {
- try { return localStorage.getItem(key) || '' } catch { return '' }
+const MODEL_STORE_KEYS = { chat: 'huobao:model:chat', image: 'huobao:model:image', video: 'huobao:model:video' }
+function readStoredModel(key, legacyKey = '') {
+ try { return localStorage.getItem(key) || (legacyKey && localStorage.getItem(legacyKey)) || '' } catch { return '' }
}
-const rewriteModel = ref(readStoredModel(MODEL_STORE_KEYS.rewrite))
+// 顶栏文本模型:适用于所有 Chat Agent 调用(改写/提取/拆镜/视频提示词/最终提示词),空串 = 跟随配置默认
+const chatModel = ref(readStoredModel(MODEL_STORE_KEYS.chat, 'huobao:model:rewrite'))
const imageModel = ref(readStoredModel(MODEL_STORE_KEYS.image))
const videoModel = ref(readStoredModel(MODEL_STORE_KEYS.video))
function persistModel(modelRef, key) {
@@ -1232,9 +1376,12 @@ function persistModel(modelRef, key) {
try { v ? localStorage.setItem(key, v) : localStorage.removeItem(key) } catch {}
})
}
-persistModel(rewriteModel, MODEL_STORE_KEYS.rewrite)
+persistModel(chatModel, MODEL_STORE_KEYS.chat)
persistModel(imageModel, MODEL_STORE_KEYS.image)
persistModel(videoModel, MODEL_STORE_KEYS.video)
+/** 顶栏文本模型覆盖参数:未选择时为 undefined,后端回退到 Agent/文本配置默认 */
+function chatModelOverride() { return chatModel.value || undefined }
+function chatConfigId() { return ownerConfigId(textModelOptions.value, chatModel.value) }
const pendingCharImageIds = ref([])
const pendingSceneImageIds = ref([])
const pendingPropImageIds = ref([])
@@ -1294,6 +1441,69 @@ function closeAssetDetail() {
assetPromptDirty.value = false
}
+// ─── 手动新增资产 ────────────────────────────────────────────
+const ASSET_TYPE_SHORT = { character: '角色', scene: '场景', prop: '道具' }
+const assetCreate = ref({ open: false, type: 'character', saving: false })
+const assetCreateDraft = ref({})
+const assetCreateTypeLabel = computed(() => ASSET_TYPE_SHORT[assetCreate.value.type] || '资产')
+
+function openAssetCreate(type) {
+ assetCreateDraft.value = { name: '', role: '', appearance: '', styling: '', location: '', time: '', prompt: '', lighting: '', type: '', description: '' }
+ assetCreate.value = { open: true, type, saving: false }
+}
+
+async function saveAssetCreate() {
+ const d = assetCreateDraft.value
+ const type = assetCreate.value.type
+ if (assetCreate.value.saving) return
+ if (type === 'scene' ? !d.location?.trim() : !d.name?.trim()) {
+ toast.warning(type === 'scene' ? '请填写场景地点' : '请填写名称')
+ return
+ }
+ assetCreate.value.saving = true
+ try {
+ const base = { drama_id: dramaId, episode_id: epId.value }
+ if (type === 'character') await characterAPI.create({ ...base, name: d.name, role: d.role, appearance: d.appearance, styling: d.styling })
+ else if (type === 'scene') await sceneAPI.create({ ...base, location: d.location, time: d.time, prompt: d.prompt, lighting: d.lighting })
+ else await propAPI.create({ ...base, name: d.name, type: d.type, description: d.description })
+ toast.success(`已新增${assetCreateTypeLabel.value}`)
+ assetCreate.value.open = false
+ await refresh()
+ } catch (e) {
+ toast.error(e.message)
+ } finally {
+ assetCreate.value.saving = false
+ }
+}
+
+// ─── 删除资产 ────────────────────────────────────────────────
+const assetDelete = ref({ open: false, type: '', item: null, loading: false })
+const assetDeleteTypeLabel = computed(() => ASSET_TYPE_SHORT[assetDelete.value.type] || '资产')
+const assetDeleteName = computed(() => assetDelete.value.item?.name || assetDelete.value.item?.location || '')
+
+function askDeleteAsset(type, item) {
+ assetDelete.value = { open: true, type, item, loading: false }
+}
+
+async function confirmDeleteAsset() {
+ const { type, item } = assetDelete.value
+ if (!item || assetDelete.value.loading) return
+ assetDelete.value.loading = true
+ try {
+ if (type === 'character') await characterAPI.del(item.id)
+ else if (type === 'scene') await sceneAPI.del(item.id)
+ else await propAPI.del(item.id)
+ toast.success(`已删除${assetDeleteTypeLabel.value}`)
+ assetDelete.value.open = false
+ if (assetDetail.value.open && assetDetail.value.type === type && assetDetail.value.item?.id === item.id) closeAssetDetail()
+ await refresh()
+ } catch (e) {
+ toast.error(e.message)
+ } finally {
+ assetDelete.value.loading = false
+ }
+}
+
function onAssetPromptInput(event) {
assetPromptDraft.value = event.target.value
assetPromptDirty.value = true
@@ -1327,19 +1537,20 @@ function isAssetImagePending(type, id) {
}
/**
- * 生成缺失的最终提示词(弹窗按钮与外层两段式生图共用同一 key 状态,避免重复触发)
+ * 生成最终提示词(弹窗按钮与外层两段式生图共用同一 key 状态,避免重复触发)
+ * force=true 时忽略已有提示词强制重新生成
* 返回最终提示词;生成失败由接口抛错,Agent 返回空时返回 ''
*/
-async function ensureAssetPrompt(type, id) {
+async function ensureAssetPrompt(type, id, force = false) {
const key = `${type}:${id}`
if (generatingPromptKeys.value.includes(key)) return ''
generatingPromptKeys.value.push(key)
try {
const res = type === 'character'
- ? await characterAPI.generatePrompt(id, epId.value)
+ ? await characterAPI.generatePrompt(id, epId.value, force, chatModelOverride(), chatConfigId())
: type === 'scene'
- ? await sceneAPI.generatePrompt(id, epId.value)
- : await propAPI.generatePrompt(id, epId.value)
+ ? await sceneAPI.generatePrompt(id, epId.value, force, chatModelOverride(), chatConfigId())
+ : await propAPI.generatePrompt(id, epId.value, force, chatModelOverride(), chatConfigId())
const fp = res?.final_prompt || res?.finalPrompt || ''
if (fp) applyFinalPrompt(type, id, fp)
return fp
@@ -1348,17 +1559,17 @@ async function ensureAssetPrompt(type, id) {
}
}
-/** 弹窗内生成最终提示词(不生图);已有最终提示词时不再生成,可直接编辑或先清空保存 */
+/** 弹窗内生成最终提示词(不生图);已有最终提示词时重新生成(force) */
async function genAssetFinalPrompt() {
const detail = assetDetail.value
if (!detail.open || !detail.item?.id) return
- if (assetFinalPrompt.value) return
+ const force = !!assetFinalPrompt.value
try {
- const fp = await ensureAssetPrompt(detail.type, detail.item.id)
+ const fp = await ensureAssetPrompt(detail.type, detail.item.id, force)
if (!fp) throw new Error('最终提示词生成失败,请重试')
assetPromptDraft.value = fp
assetPromptDirty.value = false
- toast.success('最终提示词已生成')
+ toast.success(force ? '最终提示词已重新生成' : '最终提示词已生成')
} catch (e) {
toast.error(e.message || '最终提示词生成失败')
}
@@ -1575,7 +1786,7 @@ function pruneStaleModel(modelRef, optionsRef) {
if (modelRef.value && opts.length && !opts.some(o => o.model === modelRef.value)) modelRef.value = ''
}, { immediate: true })
}
-pruneStaleModel(rewriteModel, textModelOptions)
+pruneStaleModel(chatModel, textModelOptions)
pruneStaleModel(imageModel, imageModelOptions)
pruneStaleModel(videoModel, videoModelOptions)
const textModelMultiCfg = computed(() => hasMultiConfigs(textModelOptions.value))
@@ -1905,6 +2116,27 @@ function toggleStoryboardCharacter(sb, charId) {
updateField(sb, 'character_ids', nextIds)
}
+function getStoryboardPropIds(sb) {
+ return sb?.prop_ids || sb?.propIds || []
+}
+
+function getStoryboardProps(sb) {
+ const ids = getStoryboardPropIds(sb)
+ return propItems.value.filter(p => ids.includes(p.id))
+}
+
+function isStoryboardPropSelected(sb, propId) {
+ return getStoryboardPropIds(sb).includes(propId)
+}
+
+function toggleStoryboardProp(sb, propId) {
+ const currentIds = getStoryboardPropIds(sb)
+ const nextIds = currentIds.includes(propId)
+ ? currentIds.filter(id => id !== propId)
+ : [...currentIds, propId]
+ updateField(sb, 'prop_ids', nextIds)
+}
+
function getSceneName(sb) {
const scene = getStoryboardScene(sb)
if (!scene) return ''
@@ -1935,6 +2167,7 @@ async function refresh() {
try { scenes.value = await episodeAPI.scenes(ep.id) } catch { scenes.value = [] }
try { propItems.value = await episodeAPI.props(ep.id) } catch { propItems.value = [] }
sbs.value = await episodeAPI.storyboards(ep.id)
+ selectedSbIds.value = selectedSbIds.value.filter(id => sbs.value.some(sb => sb.id === id))
if (sbs.value.length) {
const currentSelectedId = selectedSb.value?.id
selectedSb.value = sbs.value.find(sb => sb.id === currentSelectedId) || sbs.value[0]
@@ -1956,7 +2189,7 @@ async function refresh() {
function saveRaw() { episodeAPI.update(epId.value, { content: localRaw.value }); episode.value.content = localRaw.value }
function saveScr() { episodeAPI.update(epId.value, { script_content: localScript.value }); episode.value.script_content = localScript.value }
-function doRewrite() { saveRaw(); runAgent('script_rewriter', '请读取剧本并改写为格式化剧本,然后保存', dramaId, epId.value, refresh, rewriteModel.value || undefined, ownerConfigId(textModelOptions.value, rewriteModel.value)) }
+function doRewrite() { saveRaw(); runAgent('script_rewriter', '请读取剧本并改写为格式化剧本,然后保存', dramaId, epId.value, refresh, chatModelOverride(), chatConfigId()) }
function skipRewrite() {
const raw = (localRaw.value || rawContent.value || '').trim()
if (!raw) {
@@ -1969,7 +2202,149 @@ function skipRewrite() {
panel.value = 'production'
prodTab.value = 'assets'
}
-function doExtract() { saveScr(); runAgent('extractor', '请从剧本中提取所有角色、场景和道具信息,提取时自动与项目已有数据进行去重合并', dramaId, epId.value, refresh) }
+// 资产提取:按类型独立的异步任务(后端任务表驱动),三类可并行;前端轮询状态直到完成
+const EXTRACT_TARGETS = [
+ { key: 'characters', label: '角色' },
+ { key: 'scenes', label: '场景' },
+ { key: 'props', label: '道具' },
+]
+const extractingTargets = ref([])
+const extractingLabels = computed(() => EXTRACT_TARGETS.filter(t => extractingTargets.value.includes(t.key)).map(t => t.label).join('、'))
+function isExtracting(target) { return extractingTargets.value.includes(target) }
+
+function doExtract(target) {
+ if (isExtracting(target) || !epId.value) return
+ saveScr()
+ extractingTargets.value.push(target)
+ episodeAPI.extract(epId.value, target, chatModelOverride(), chatConfigId())
+ .then(() => pollExtractStatus(target))
+ .catch(e => {
+ extractingTargets.value = extractingTargets.value.filter(t => t !== target)
+ toast.error(e.message)
+ })
+}
+function doExtractAll() { EXTRACT_TARGETS.forEach(t => doExtract(t.key)) }
+
+function pollExtractStatus(target, attempts = 150) {
+ const label = EXTRACT_TARGETS.find(t => t.key === target)?.label || target
+ const tick = async (left) => {
+ try {
+ const st = await episodeAPI.extractStatus(epId.value)
+ const task = st?.[target]
+ if (task && task.status !== 'running') {
+ extractingTargets.value = extractingTargets.value.filter(t => t !== target)
+ if (task.status === 'done') {
+ toast.success(`${label}提取完成`)
+ await refresh()
+ } else {
+ toast.error(task.error || `${label}提取失败`)
+ }
+ return
+ }
+ } catch {}
+ if (left > 0) setTimeout(() => tick(left - 1), 2500)
+ else extractingTargets.value = extractingTargets.value.filter(t => t !== target)
+ }
+ setTimeout(() => tick(attempts), 2500)
+}
+
+/** 页面加载后恢复仍在运行的提取任务状态(刷新页面不丢进度展示) */
+async function syncExtractStatus() {
+ if (!epId.value) return
+ try {
+ const st = await episodeAPI.extractStatus(epId.value)
+ for (const t of EXTRACT_TARGETS) {
+ if (st?.[t.key]?.status === 'running' && !isExtracting(t.key)) {
+ extractingTargets.value.push(t.key)
+ pollExtractStatus(t.key)
+ }
+ }
+ } catch {}
+ try {
+ const vp = await episodeAPI.videoPromptsStatus(epId.value)
+ if (vp?.status === 'running' && !videoPromptBatch.value.running) {
+ videoPromptBatch.value = { running: true, total: vp.total || 0, completed: vp.completed || 0 }
+ pollVideoPromptBatch()
+ }
+ } catch {}
+}
+
+// ─── 批量视频提示词:后端异步逐分镜生成,前端轮询进度 ──────────
+const videoPromptBatch = ref({ running: false, total: 0, completed: 0 })
+// 分镜勾选:勾选后批量生成只处理所选(已有提示词也会重新生成);未勾选时处理全部缺失
+const selectedSbIds = ref([])
+// 多选模式:进入后点击卡片=勾选/取消,底部操作条确认生成
+const sbSelectMode = ref(false)
+function isSbSelected(id) { return selectedSbIds.value.includes(id) }
+function toggleSbSelect(id) {
+ selectedSbIds.value = isSbSelected(id) ? selectedSbIds.value.filter(x => x !== id) : [...selectedSbIds.value, id]
+}
+function toggleSelectAllSbs() {
+ selectedSbIds.value = selectedSbIds.value.length === sbs.value.length ? [] : sbs.value.map(sb => sb.id)
+}
+function onShotCardClick(sb) {
+ if (sbSelectMode.value) toggleSbSelect(sb.id)
+ else selectedSb.value = sb
+}
+// 仅缺失:选中还没有视频提示词的分镜
+function selectMissingSbs() {
+ selectedSbIds.value = sbs.value.filter(sb => !((sb.video_prompt || sb.videoPrompt || '').trim())).map(sb => sb.id)
+}
+function exitSbSelectMode() {
+ sbSelectMode.value = false
+ selectedSbIds.value = []
+}
+function generateSelectedVideoPrompts() {
+ batchVideoPrompts() // 内部同步捕获所选 ids
+ exitSbSelectMode()
+}
+
+async function batchVideoPrompts() {
+ if (videoPromptBatch.value.running || !epId.value) return
+ if (!sbs.value.length) { toast.warning('请先拆分分镜'); return }
+ const ids = selectedSbIds.value.length ? [...selectedSbIds.value] : undefined
+ try {
+ const res = await episodeAPI.generateVideoPrompts(epId.value, chatModelOverride(), chatConfigId(), ids)
+ if (!res?.total) {
+ if (res?.already_running) {
+ videoPromptBatch.value = { running: true, total: 0, completed: 0 }
+ pollVideoPromptBatch()
+ } else toast.info(ids ? '所选分镜不存在' : '所有分镜已有视频提示词')
+ return
+ }
+ videoPromptBatch.value = { running: true, total: res.total, completed: 0 }
+ toast.info(`开始生成 ${res.total} 个分镜的视频提示词…`)
+ pollVideoPromptBatch()
+ } catch (e) {
+ toast.error(e.message)
+ }
+}
+
+function pollVideoPromptBatch(attempts = 240) {
+ const tick = async (left) => {
+ try {
+ const st = await episodeAPI.videoPromptsStatus(epId.value)
+ if (st && st.status !== 'running') {
+ videoPromptBatch.value = { running: false, total: 0, completed: 0 }
+ await refresh()
+ if (st.status === 'done') {
+ toast.success(st.failed ? `视频提示词批量生成完成,${st.failed} 个失败` : '视频提示词批量生成完成')
+ } else {
+ toast.error(st.error || '视频提示词批量生成失败')
+ }
+ return
+ }
+ if (st) {
+ const prev = videoPromptBatch.value.completed
+ videoPromptBatch.value = { running: true, total: st.total || 0, completed: st.completed || 0 }
+ if ((st.completed || 0) !== prev) await refresh() // 每完成一条刷新,提示词逐步出现
+ }
+ } catch {}
+ if (left > 0) setTimeout(() => tick(left - 1), 2500)
+ else videoPromptBatch.value = { running: false, total: 0, completed: 0 }
+ }
+ setTimeout(() => tick(attempts), 2500)
+}
function doBreakdown() {
const charList = chars.value.length
? chars.value.map(c => `${c.name}(ID:${c.id})`).join('、')
@@ -1977,29 +2352,35 @@ function doBreakdown() {
const sceneList = scenes.value.length
? scenes.value.map(s => `${s.location} · ${s.time || '未设时间'}(ID:${s.id})`).join('、')
: '(当前集还没有场景)'
+ const propList = propItems.value.length
+ ? propItems.value.map(p => `${p.name}(ID:${p.id})`).join('、')
+ : '(当前集还没有道具)'
runAgent('storyboard_breaker', `请基于当前集剧本拆分分镜(不需要生成视频提示词,video_prompt 在视频生成阶段按需生成)。
当前集已有角色:${charList}
当前集已有场景:${sceneList}
+当前集已有道具:${propList}
绑定要求:
- 每个镜头必须根据剧本内容,从上述当前集已有角色中选出出场的角色绑定 character_ids(ID 必须来自上述列表;有角色出场就必须绑定,不要遗漏)
- 每个镜头尽量匹配上述已有场景填写 scene_id(ID 必须来自上述列表),不要凭空创造新场景
-- 只有纯环境空镜头才可以不绑定角色`, dramaId, epId.value, refresh)
+- 每个镜头出现关键道具(被使用、交接、特写或在画面中明显可见)时,从上述当前集已有道具中绑定 prop_ids(ID 必须来自上述列表);没有道具出现可传空数组
+- 只有纯环境空镜头才可以不绑定角色`, dramaId, epId.value, refresh, chatModelOverride(), chatConfigId())
}
-// 按需为单个分镜生成视频提示词:由 storyboard_breaker 读取分镜字段生成并保存到 video_prompt
+// 按需为单个分镜生成视频提示词:由 prompt_generator 读取分镜字段生成并保存到 video_prompt
function genVideoPrompt(sb) {
if (!sb) return
const idx = sbs.value.indexOf(sb) + 1
const cfg = videoConfigs.value.find(c => c.id === lockedVideoConfigId.value)
const label = cfg ? `${cfg.name} (${cfg.provider})` : '默认'
const charNames = getStoryboardCharacters(sb).map(c => c.name).join('、') || '无'
- runAgent('storyboard_breaker', `请为分镜 #${idx}(ID:${sb.id})生成视频提示词(video_prompt)。视频模型:${label},请根据该模型的特性和时长限制生成。
+ const propNames = getStoryboardProps(sb).map(p => p.name).join('、') || '无'
+ runAgent('prompt_generator', `请为分镜 #${idx}(ID:${sb.id})生成视频提示词(video_prompt)。视频模型:${label},请根据该模型的特性和时长限制生成。
-该分镜信息:时长 ${sb.duration || 10}s;场景:${getSceneName(sb) || '未绑定'};角色:${charNames}。
+该分镜信息:时长 ${sb.duration || 10}s;场景:${getSceneName(sb) || '未绑定'};角色:${charNames};道具:${propNames}。
-请先调用 read_storyboard_context 获取该分镜的画面描述、动作、氛围、对白/旁白,据此生成 video_prompt(按 3 秒分段换行、用 @角色名/@场景名 引用参考素材),然后调用 update_storyboard 保存到分镜 ID:${sb.id}。只更新 video_prompt 字段,不要改动其他字段,不要重新拆分整集。`, dramaId, epId.value, refresh)
+请先调用 read_storyboard_context 获取该分镜的画面描述、动作、氛围、对白/旁白,据此生成 video_prompt(按 3 秒分段换行、用 @角色名/@场景名/@道具名 引用参考素材),然后调用 update_storyboard 保存到分镜 ID:${sb.id}。只更新 video_prompt 字段,不要改动其他字段,不要重新拆分整集。`, dramaId, epId.value, refresh, chatModelOverride(), chatConfigId())
}
function sleep(ms) {
@@ -2026,7 +2407,7 @@ async function genCharImg(id) {
await ensureAssetPrompt('character', id)
} catch {} // 提示词生成失败不阻断:后端生图前会再兜底生成或回退本地拼接
}
- await characterAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value))
+ await characterAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value), chatModelOverride(), chatConfigId())
toast.success('角色图片生成中')
await refresh()
watchAsyncResult(() => {
@@ -2044,7 +2425,7 @@ function batchCharImages() {
const ids = visualChars.value.filter(c => !(c.image_url || c.imageUrl)).map(c => c.id)
if (!ids.length) { toast.info('所有角色图片已生成'); return }
pendingCharImageIds.value = [...new Set([...pendingCharImageIds.value, ...ids])]
- characterAPI.batchImages(ids, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value)).then(async () => {
+ characterAPI.batchImages(ids, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value), chatModelOverride(), chatConfigId()).then(async () => {
toast.success('角色图片批量生成中')
await refresh()
watchAsyncResult(() => ids.every(id => {
@@ -2068,7 +2449,7 @@ async function genSceneImg(id) {
await ensureAssetPrompt('scene', id)
} catch {} // 提示词生成失败不阻断:后端生图前会再兜底生成或回退本地拼接
}
- await sceneAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value))
+ await sceneAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value), chatModelOverride(), chatConfigId())
toast.success('场景图片生成中')
await refresh()
watchAsyncResult(() => {
@@ -2095,7 +2476,7 @@ async function genPropImg(id) {
await ensureAssetPrompt('prop', id)
} catch {} // 提示词生成失败不阻断:后端生图前会再兜底生成或回退本地拼接
}
- await propAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value))
+ await propAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value), chatModelOverride(), chatConfigId())
toast.success('道具图片生成中')
await refresh()
watchAsyncResult(() => {
@@ -2113,7 +2494,7 @@ function batchSceneImages() {
const ids = scenes.value.filter(s => !(s.image_url || s.imageUrl)).map(s => s.id)
if (!ids.length) { toast.info('所有场景图片已生成'); return }
pendingSceneImageIds.value = [...new Set([...pendingSceneImageIds.value, ...ids])]
- ids.forEach(id => { sceneAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value)).then(() => refresh()).catch(e => toast.error(e.message)) })
+ ids.forEach(id => { sceneAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value), chatModelOverride(), chatConfigId()).then(() => refresh()).catch(e => toast.error(e.message)) })
toast.success('场景图片批量生成中')
watchAsyncResult(() => ids.every(id => {
const scene = scenes.value.find(s => s.id === id)
@@ -2122,6 +2503,19 @@ function batchSceneImages() {
return done
}), 36)
}
+function batchPropImages() {
+ const ids = propItems.value.filter(p => !(p.image_url || p.imageUrl)).map(p => p.id)
+ if (!ids.length) { toast.info('所有道具图片已生成'); return }
+ pendingPropImageIds.value = [...new Set([...pendingPropImageIds.value, ...ids])]
+ ids.forEach(id => { propAPI.generateImage(id, epId.value, imageModel.value || undefined, ownerConfigId(imageModelOptions.value, imageModel.value), chatModelOverride(), chatConfigId()).then(() => refresh()).catch(e => toast.error(e.message)) })
+ toast.success('道具图片批量生成中')
+ watchAsyncResult(() => ids.every(id => {
+ const prop = propItems.value.find(p => p.id === id)
+ const done = !!(prop?.image_url || prop?.imageUrl)
+ if (done) pendingPropImageIds.value = pendingPropImageIds.value.filter(item => item !== id)
+ return done
+ }), 36)
+}
function getVideoUrl(s) { return s?.video_url || s?.videoUrl || s?.composed_video_url || s?.composedVideoUrl || null }
function hasVid(s) { return !!getVideoUrl(s) }
@@ -2136,6 +2530,9 @@ function getShotReferenceImages(sb) {
for (const char of getStoryboardCharacters(sb)) {
pushRef(char?.image_url || char?.imageUrl)
}
+ for (const prop of getStoryboardProps(sb)) {
+ pushRef(prop?.image_url || prop?.imageUrl)
+ }
// 手动上传的参考图片追加到尾部(总计 ≤9)
for (const url of videoRefImageUrls.value) pushRef(url)
return refs
@@ -2166,16 +2563,28 @@ function getShotReferenceAssets(sb) {
ready: !!imageUrl,
})
}
+ for (const prop of getStoryboardProps(sb)) {
+ const imageUrl = prop.image_url || prop.imageUrl || ''
+ assets.push({
+ key: `prop-${prop.id}`,
+ type: '道具',
+ name: prop.name || '未命名道具',
+ meta: prop.type || '道具单品图',
+ imageUrl,
+ ready: !!imageUrl,
+ })
+ }
return assets.slice(0, 6)
}
-// 场景/角色自动绑定占用的参考图片槽位(按素材卡片数,最多 9)
+// 场景/角色/道具自动绑定占用的参考图片槽位(按素材卡片数,最多 9)
const autoReferenceImageCount = computed(() => {
const sb = selectedSb.value
if (!sb) return 0
let count = 0
if (getStoryboardScene(sb)) count += 1
count += getStoryboardCharacters(sb).length
+ count += getStoryboardProps(sb).length
return Math.min(count, 9)
})
@@ -2184,7 +2593,7 @@ const refImageUsedCount = computed(() => Math.min(9, autoReferenceImageCount.val
// 是否已达 9 张上限(禁用继续上传)
const refImageFull = computed(() => refImageUsedCount.value >= 9)
-// 视频提示词 @ 引用候选:当前集已有场景(按地点引用)与角色(按名字引用)
+// 视频提示词 @ 引用候选:当前集已有场景(按地点引用)、角色(按名字引用)与道具(按名字引用)
const mentionOptions = computed(() => [
...scenes.value.map(s => ({
label: `${s.location} · ${s.time || '未设时间'}`,
@@ -2198,9 +2607,15 @@ const mentionOptions = computed(() => [
group: '角色',
image: assetImageSrc(c),
})),
+ ...propItems.value.map(p => ({
+ label: p.name,
+ value: p.name,
+ group: '道具',
+ image: assetImageSrc(p),
+ })),
])
-// 按参考图顺序(场景图在前、角色图在后)为 @名字 建立索引映射,供视频提示词引用替换
+// 按参考图顺序(场景图在前、角色图居中、道具图在后)为 @名字 建立索引映射,供视频提示词引用替换
function getShotReferenceIndexMap(sb) {
const ordered = []
const seen = new Set()
@@ -2214,6 +2629,9 @@ function getShotReferenceIndexMap(sb) {
for (const char of getStoryboardCharacters(sb)) {
push(char.name || '', char?.image_url || char?.imageUrl)
}
+ for (const prop of getStoryboardProps(sb)) {
+ push(prop.name || '', prop?.image_url || prop?.imageUrl)
+ }
const nameToIndex = {}
ordered.forEach((a, i) => { if (a.name && !(a.name in nameToIndex)) nameToIndex[a.name] = i + 1 })
return nameToIndex
@@ -2311,7 +2729,7 @@ async function genVid(sb) {
try {
delete failedVideoMessages.value[sb.id]
if (!isPendingVideo(sb.id)) pendingVideoIds.value.push(sb.id)
- const generation = await videoAPI.generate(params)
+ const generation = await taskAPI.generate({ type: 'video', ...params })
toast.success('视频生成中')
await refresh()
pollVideoGeneration(generation?.id, sb.id)
@@ -2337,7 +2755,7 @@ async function pollVideoGeneration(generationId, storyboardId) {
for (let i = 0; i < 120; i++) {
await sleep(4000)
try {
- const res = await videoAPI.get(generationId)
+ const res = await taskAPI.get(generationId)
await refresh()
if (res?.status === 'completed') {
pendingVideoIds.value = pendingVideoIds.value.filter(item => item !== storyboardId)
@@ -2407,7 +2825,7 @@ async function loadConfigs() {
} catch (e) { console.error('Failed to load AI configs', e) }
}
-onMounted(() => { refresh(); loadConfigs() })
+onMounted(async () => { await refresh(); loadConfigs(); syncExtractStatus() })
</script>
<style scoped>
@@ -2943,6 +3361,12 @@ onMounted(() => { refresh(); loadConfigs() })
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(0,113,227,0.15);
}
+/* 多选模式:选中的卡片高亮描边 */
+.storyboard-shot-card.is-selected {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(0,113,227,0.15);
+ background: var(--accent-soft, #f0f7ff);
+}
.storyboard-shot-head { display: flex; align-items: center; gap: 6px; min-width: 0; }
.storyboard-shot-chip {
display: inline-flex;
@@ -3013,6 +3437,42 @@ onMounted(() => { refresh(); loadConfigs() })
.storyboard-editor-scroll .detail-section:last-child {
border-bottom: none;
}
+/* 描述 / 视频提示词 左右双栏分割 */
+.storyboard-editor-scroll .sb-split {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ align-items: stretch;
+}
+.storyboard-editor-scroll .sb-split .detail-section {
+ border-bottom: none;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.storyboard-editor-scroll .sb-split .detail-section:first-child {
+ border-right: 1px solid var(--border);
+}
+.storyboard-editor-scroll .sb-split .detail-section-copy {
+ margin-top: -4px;
+}
+/* 双栏内字段撑满面板高度 */
+.storyboard-editor-scroll .sb-split .field { flex: 1; min-height: 0; }
+.storyboard-editor-scroll .sb-split .field .textarea { flex: 1; min-height: 64px; resize: vertical; }
+.storyboard-editor-scroll .sb-split .field-grid-2 { flex: 1; }
+.storyboard-editor-scroll .sb-split .mention-textarea {
+ flex: 1;
+ min-height: 0;
+}
+.storyboard-editor-scroll .sb-split .mention-input { flex: 1; min-height: 120px; resize: vertical; }
+@media (max-width: 1200px) {
+ .storyboard-editor-scroll .sb-split { grid-template-columns: 1fr; }
+ .storyboard-editor-scroll .sb-split .detail-section:first-child {
+ border-right: none;
+ border-bottom: 1px solid var(--border);
+ }
+}
/* 上一条 / 下一条导航 */
.sb-nav-group {
display: flex;
@@ -3168,14 +3628,14 @@ onMounted(() => { refresh(); loadConfigs() })
top: 0;
z-index: 1;
display: flex;
- align-items: flex-start;
- justify-content: space-between;
- gap: 8px;
+ flex-direction: column;
padding: 11px 12px 10px;
border-bottom: 1px solid var(--surface-outline);
background: var(--surface-raised);
backdrop-filter: blur(10px);
}
+.shot-list-head-main { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; }
+.shot-list-head-copy { flex: 1; min-width: 0; }
.shot-list-title { font-size: 13px; font-weight: 700; color: var(--text-0); }
.shot-list-sub { margin-top: 3px; font-size: 11px; color: var(--text-3); line-height: 1.45; }
.shot-list-body { flex: 1; min-height: 0; overflow-y: auto; padding: 6px; }
@@ -3375,6 +3835,141 @@ onMounted(() => { refresh(); loadConfigs() })
.prod-content { flex: 1; overflow-y: auto; padding: 10px 12px 64px; display: flex; flex-direction: column; gap: 10px; }
.prod-section-bar { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }
+/* 资产栏动作:提取(虚线中性)与批量生成(强调色)视觉分组 */
+.asset-bar-actions { align-items: center; }
+.asset-bar-divider { width: 1px; height: 16px; margin: 0 4px; background: var(--surface-outline-strong); }
+.asset-btn-extract {
+ background: transparent;
+ color: var(--text-2);
+ box-shadow: none;
+ border: 1px dashed var(--surface-outline-strong);
+}
+.asset-btn-extract:hover { background: var(--surface-muted); color: var(--text-1); }
+.asset-btn-batch {
+ background: var(--accent-bg);
+ color: var(--accent-text);
+ box-shadow: none;
+}
+.asset-btn-batch:hover { background: var(--accent); color: #fff; }
+
+/* 资产分区标题:新增入口 + 卡片删除按钮 */
+.asset-section-title { display: flex; align-items: center; gap: 8px; }
+.asset-add-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ border: 1px dashed var(--surface-outline-strong);
+ background: transparent;
+ color: var(--text-3);
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: color 0.15s, border-color 0.15s;
+}
+.asset-add-btn:hover { color: var(--accent-text); border-color: var(--accent-text); }
+.character-asset-card, .asset-click-card { position: relative; }
+.asset-del-btn {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ z-index: 3;
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: none;
+ background: rgba(0, 0, 0, 0.5);
+ color: #fff;
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity 0.15s, background 0.15s;
+}
+.asset-del-btn:hover { background: var(--action-danger); }
+.character-asset-card:hover .asset-del-btn,
+.asset-click-card:hover .asset-del-btn { opacity: 1; }
+
+/* 分镜勾选:选择后批量生成视频提示词 */
+.shot-check {
+ flex: none;
+ width: 14px;
+ height: 14px;
+ border-radius: 4px;
+ border: 1.5px solid var(--surface-outline-strong);
+ background: transparent;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+}
+.shot-check:hover { border-color: var(--accent); }
+.shot-check.on { background: var(--accent); border-color: var(--accent); }
+.shot-quick-btn {
+ border: none;
+ background: transparent;
+ color: var(--accent-text);
+ font-size: 11px;
+ font-weight: 600;
+ cursor: pointer;
+ padding: 0;
+ white-space: nowrap;
+}
+.shot-quick-btn:hover { text-decoration: underline; }
+/* 多选模式:头部快捷操作独立一行,分段芯片样式 */
+.shot-quick-actions {
+ display: flex;
+ gap: 6px;
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px dashed var(--surface-outline);
+}
+.shot-quick-actions .shot-quick-btn {
+ flex: 1;
+ padding: 5px 0;
+ border-radius: 6px;
+ background: var(--bg-2);
+ color: var(--text-2);
+ text-align: center;
+ transition: background 0.15s, color 0.15s;
+}
+.shot-quick-actions .shot-quick-btn:hover {
+ background: var(--accent-soft, #f0f7ff);
+ color: var(--accent-text);
+ text-decoration: none;
+}
+
+/* 多选模式底部操作条:信息行 + 全宽主按钮 */
+.shot-select-bar {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ border-top: 1px solid var(--border);
+ background: var(--bg-1, #fafafa);
+}
+.shot-select-info {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+.shot-select-count {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-2);
+ white-space: nowrap;
+}
+.shot-select-go { width: 100%; justify-content: center; }
+
+/* 新增资产弹窗 */
+.asset-create-dialog { width: 440px; max-width: calc(100vw - 48px); }
+.asset-create-body { display: flex; flex-direction: column; gap: 10px; }
+
/* Asset grid */
.asset-section-title {
margin-top: 2px;
diff --git a/frontend/app/pages/drama/[id]/index.vue b/frontend/app/pages/drama/[id]/index.vue
index 634b237..aed8206 100644
--- a/frontend/app/pages/drama/[id]/index.vue
+++ b/frontend/app/pages/drama/[id]/index.vue
@@ -83,6 +83,21 @@
>{{ s.label }}</button>
</div>
</div>
+ <div class="ep-status-wrap" @click.stop>
+ <button type="button" :class="['tag', 'ep-status-btn']" title="点击修改本集视频分辨率" @click="epResMenuId = epResMenuId === ep.id ? null : ep.id">
+ {{ epResolution(ep) }}
+ </button>
+ <div v-if="epResMenuId === ep.id" class="status-menu">
+ <button
+ v-for="r in resolutionOptions"
+ :key="r.value"
+ type="button"
+ class="status-menu-item"
+ :class="{ on: epResolution(ep) === r.value }"
+ @click="setEpisodeResolution(ep, r.value)"
+ >{{ r.label }}</button>
+ </div>
+ </div>
<span v-if="ep.duration" class="ep-duration">{{ ep.duration }}s</span>
</div>
<div class="ep-arrow">
@@ -129,6 +144,11 @@
<input v-model="newEpisodeTitle" class="input" placeholder="默认按集数自动命名" />
<span class="field-hint">留空时会自动按集数命名,例如“第 3 集”。</span>
</label>
+ <label class="field">
+ <span class="field-label">视频分辨率</span>
+ <BaseSelect v-model="newEpisodeResolution" :options="resolutionOptions" placeholder="选择分辨率" />
+ <span class="field-hint">创建后本集视频按此分辨率生成,之后仍可在集卡片上修改。</span>
+ </label>
</div>
<div class="dialog-foot">
<span class="dialog-foot-copy">创建后自动锁定当前启用的图片与视频生成能力。</span>
@@ -153,6 +173,7 @@
<script setup>
import { toast } from 'vue-sonner'
import { dramaAPI, episodeAPI } from '~/composables/useApi'
+import BaseSelect from '~/components/BaseSelect.vue'
const route = useRoute()
const drama = ref(null)
@@ -163,6 +184,30 @@ const newEpisodeTitle = ref('')
const episodeToDelete = ref(null)
const deletingEpisode = ref(false)
+// 视频分辨率:创建集时固定(持久化到 episodes.resolution),集卡片上可修改
+const resolutionOptions = [
+ { label: '720p · 高清', value: '720p' },
+ { label: '480p · 流畅', value: '480p' },
+]
+const newEpisodeResolution = ref('720p')
+const epResMenuId = ref(null)
+
+function epResolution(ep) { return ep.resolution === '480p' ? '480p' : '720p' }
+
+async function setEpisodeResolution(ep, resolution) {
+ epResMenuId.value = null
+ if (epResolution(ep) === resolution) return
+ const prev = ep.resolution
+ ep.resolution = resolution
+ try {
+ await episodeAPI.update(ep.id, { resolution })
+ toast.success(`本集视频分辨率已切换为 ${resolution}`)
+ } catch (e) {
+ ep.resolution = prev
+ toast.error(e.message)
+ }
+}
+
// 集状态由用户手动标记(持久化到 episodes.status),不再按剧本内容自动推算
const epStatusOptions = [
{ label: '待开始', value: 'draft' },
@@ -198,16 +243,18 @@ async function load() {
function openAddEpisode() {
newEpisodeTitle.value = ''
+ newEpisodeResolution.value = '720p'
addDialog.value = true
}
async function addEpisode() {
try {
creatingEpisode.value = true
- // 图片/视频生成配置由后端自动锁定为当前启用的最高优先级配置
+ // 图片/视频生成配置由后端自动锁定为当前启用的最高优先级配置;分辨率随集固定
await episodeAPI.create({
drama_id: dramaId,
title: newEpisodeTitle.value || undefined,
+ resolution: newEpisodeResolution.value,
})
toast.success('已添加新集')
addDialog.value = false
diff --git a/frontend/app/pages/settings.vue b/frontend/app/pages/settings.vue
index e5b6ef5..89c1072 100644
--- a/frontend/app/pages/settings.vue
+++ b/frontend/app/pages/settings.vue
@@ -607,37 +607,49 @@ const defaultPrompts = {
- 动作描写:自然段落,不包含镜头语言
- 对白:角色名:(状态/表情)台词内容
- 每个场景 30-60 秒内容`,
- extractor: `你是制片助理,擅长从剧本中提取角色和场景信息,并在提取时与项目已有数据进行智能去重。
+ extractor: `你是制片助理,擅长从剧本中提取角色、场景和道具信息,并在提取时与项目已有数据进行智能去重。
工作流程:
1. 调用 read_script_for_extraction 读取格式化剧本
-2. 调用 read_existing_characters 读取项目中已存在的角色列表(用于去重)
-3. 调用 read_existing_scenes 读取项目中已存在的场景列表(用于去重)
-4. 分析剧本内容,提取所有角色信息
-5. 对每个角色:若同名已存在则合并更新,若不存在则新增
-6. 调用 save_dedup_characters 保存角色(去重合并,自动处理新增和更新)
-7. 分析剧本内容,提取所有场景信息
-8. 对每个场景:若同地点+时间段已存在则复用,若不存在则新增
-9. 调用 save_dedup_scenes 保存场景(去重合并,自动处理新增和复用)
+2. 调用 read_existing_characters 读取项目中已存在的角色列表,以及当前集已关联角色
+3. 调用 read_existing_scenes 读取项目中已存在的场景列表,以及当前集已关联场景
+4. 调用 read_existing_props 读取项目中已存在的道具列表,以及当前集已关联道具
+5. 优先围绕当前集剧本,分析本集实际出现的角色、场景和道具
+6. 对每个角色:若同名已存在则合并更新,若不存在则新增
+7. 调用 save_dedup_characters 保存角色(去重合并,自动处理新增和更新,并关联到当前集)
+8. 分析剧本内容,提取本集涉及的所有场景信息
+9. 对每个场景:若同地点+时间段已存在则复用,若不存在则新增
+10. 调用 save_dedup_scenes 保存场景(去重合并,自动处理新增和复用,并关联到当前集)
+11. 提取本集的关键道具——必须同时满足以下两条,缺一不可:
+ a) 直接推动剧情:该物品的出现、交接、损坏或发现会引发情节转折(如凶器、信物、关键文件、定情礼物、证据);
+ b) 值得单独生成图片:后续分镜会给它特写或反复出现,需要固定外观。
+ 判定三问(自问自答,任一答"否"即放弃该道具):① 删掉它剧情是否依然成立?成立 → 不提取;② 它只是角色随手使用的日常物品(手机、筷子、杯子、烟)吗?是 → 不提取;③ 它是场景陈设的一部分(桌椅、灯具、门窗、装饰)吗?是 → 不提取。
+ 宁可少提,不要多提:一集通常 0-3 个关键道具,超过 3 个时按剧情重要性排序只保留前 3 个;没有符合条件的道具就一个都不要提取
+12. 对每个道具:若同名已存在则合并更新,若不存在则新增
+13. 调用 save_dedup_props 保存道具(去重合并,自动处理新增和更新,并关联到当前集);若没有需要提取的道具,调用时传空数组即可,不要强行凑数
去重规则:
- 角色:按名字精确匹配,同名保留现有(合并信息)
- 场景:按【地点+时间段】精确匹配;同地点不同时段视为新场景
+- 道具:按名字精确匹配,同名保留现有(合并信息)
提取要求:
-- 角色要包含完整的外貌特征描述(发型、服装、体态等)
-- 场景要包含光线、色调、氛围等视觉信息
+- 只提取当前集真实出现或被明确提及、且对当前集叙事有效的角色、场景和道具
+- 角色只需要两个核心描述字段:appearance(样貌:年龄感、五官、体态、气质等,角色的性格特点要转化为外在气质与神态融入样貌描写,不要单独输出性格字段)和 styling(妆造:发型、服装、妆面、配饰等)
+- 场景只需要两个核心描述字段:prompt(场景描述:空间、陈设、年代质感、关键视觉元素等)和 lighting(场景光影:光源、色调、明暗、氛围等)
+- 道具字段:name(道具名)、type(类型:日常/武器/交通/装饰/文件等)、description(物品外貌:只描写物品本身的物理外观——材质、颜色、形状、大小、新旧程度、磨损痕迹等,不要写剧情用途,不要涉及与角色或其他事物的关联)。道具不需要输出图片提示词,最终提示词由提示词生成 Agent 后续专门生成
- 不要遗漏任何有台词或重要动作的角色`,
storyboard_breaker: `你是资深影视分镜师,擅长将剧本拆解为分镜方案。
工作流程:
-1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表
+1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表、道具列表
2. 将剧本拆解为镜头序列(每个镜头 10-15 秒,总体保持剧情完整连续)
3. 为每个镜头补全生产字段(拆分时不需要生成 video_prompt,该字段由提示词 Agent 在视频生成阶段生成)
4. 调用 save_storyboards 保存所有分镜
每个镜头只需要填写以下字段:
- character_ids:当前镜头涉及的角色 ID 列表,可以为空,也可以包含多个角色;必须从 characters 中选择
+- prop_ids:当前镜头出现的关键道具 ID 列表(道具在画面中被看到、使用或特写时绑定),可以为空;必须从 props 中选择
- scene_id:若可匹配到 scenes 中已有场景,必须填写正确 scene_id;无匹配时置空
- duration:镜头时长,优先 10-15 秒
- action:角色动作与表演
@@ -648,11 +660,12 @@ const defaultPrompts = {
额外要求:
- 优先复用 read_storyboard_context 返回的 scene_id,不要凭空创造新场景
- 镜头角色绑定必须来自 read_storyboard_context 返回的角色列表;无角色的空镜头可传空数组
+- 镜头道具绑定必须来自 read_storyboard_context 返回的道具列表;道具被使用、特写、交接或在画面中明显可见时绑定,与剧情无关的背景物品不要绑定;没有道具出现可传空数组
- 镜头描述必须能支撑后续视频生成和导出流程
- 若一个镜头没有对白,可将 dialogue 置空,但 description / action / atmosphere 仍必须完整
- 如果已有 existing_storyboards,仅在用户明确要求增量修改时参考;默认按当前剧本重新完整生成并保存整集分镜。`,
prompt_generator: `你是专业的 AI 提示词工程师,负责两类提示词的创作与保存:
-1. 角色/场景/道具的「最终提示词」(英文),供生图直接使用
+1. 角色/场景/道具的「最终提示词」,供生图直接使用
2. 分镜的「视频提示词」(video_prompt),供视频生成直接使用
## 图片最终提示词
@@ -661,7 +674,7 @@ const defaultPrompts = {
工作流程:
1. 调用 read_characters / read_scenes / read_props 读取资产信息
-2. 按对应资产的技能规范(角色三视图 / 场景固定视角 / 道具白底单品)创作英文最终提示词
+2. 按对应资产的技能规范(角色三视图 / 场景固定视角 / 道具白底单品)创作最终提示词
3. 调用 save_character_final_prompt / save_scene_final_prompt / save_prop_final_prompt 逐个保存
## 视频提示词
@@ -671,11 +684,12 @@ const defaultPrompts = {
工作流程:
1. 调用 read_storyboard_context 读取该分镜的 action、description、dialogue、atmosphere、duration 及绑定的场景/角色
2. 据此生成 video_prompt:按 3 秒为一段、每段单独一行换行分隔;提到场景用 @场景名、提到角色用 @角色名(名字必须与列表完全一致);内容覆盖动作、画面描述、对白/旁白、氛围
-3. 调用 update_storyboard 仅更新该分镜的 video_prompt 字段,不要改动其他字段,不要重新拆分整集
+3. 生成时会自动把 @名字 替换为对应参考图片标记(如 @志远 → @图片1志远),因此名字必须精确匹配场景/角色列表,不要缩写或加额外符号
+4. 调用 update_storyboard 仅更新该分镜的 video_prompt 字段,不要改动其他字段,不要重新拆分整集
通用规范:
-- 图片提示词只输出英文,单段连贯描述,不要分点;视频提示词输出中文,按格式分段
-- 项目设定的视觉风格描述会由工具在保存图片提示词时自动注入,不要自行添加风格词
+- 所有提示词只输出中文,单段连贯描述,不要分点,不要混入英文词汇
+- 项目设定的视觉风格描述会由工具在保存图片提示词时自动注入到最终提示词的最前方,不要自行添加风格词
- 必须实际调用保存工具,不要只在回复中给出提示词`,
}
diff --git a/frontend/tests/asset-library-structure.test.mjs b/frontend/tests/asset-library-structure.test.mjs
index 68d1fc0..c626c83 100644
--- a/frontend/tests/asset-library-structure.test.mjs
+++ b/frontend/tests/asset-library-structure.test.mjs
@@ -45,7 +45,7 @@ test('asset library page lists character and scene images', () => {
const page = read('app/pages/drama/[id]/assets.vue')
// 数据源:项目全部图片生成记录 + 项目详情(名称解析)
- assert.match(page, /imageAPI\.list\(\{ drama_id: dramaId \}\)/)
+ assert.match(page, /taskAPI\.list\(\{ type: 'image', drama_id: dramaId \}\)/)
assert.match(page, /dramaAPI\.get\(dramaId\)/)
// 只收录完成的角色/场景图
assert.match(page, /r\.status === 'completed' && \(r\.characterId \|\| r\.sceneId\)/)
diff --git a/frontend/tests/episode-create-dialog-structure.test.mjs b/frontend/tests/episode-create-dialog-structure.test.mjs
index a2138d9..3ba5b59 100644
--- a/frontend/tests/episode-create-dialog-structure.test.mjs
+++ b/frontend/tests/episode-create-dialog-structure.test.mjs
@@ -5,7 +5,7 @@ import assert from 'node:assert/strict'
const root = new URL('..', import.meta.url)
const read = (path) => readFileSync(new URL(path, root), 'utf8')
-test('add episode dialog only asks for a title', () => {
+test('add episode dialog asks for a title and a fixed video resolution', () => {
const page = read('app/pages/drama/[id]/index.vue')
// 删除图片/视频服务选择 UI
@@ -23,19 +23,40 @@ test('add episode dialog only asks for a title', () => {
assert.match(page, /留空时会自动按集数命名/)
assert.match(page, /创建后自动锁定当前启用的图片与视频生成能力/)
assert.match(page, /creatingEpisode \? '创建中\.\.\.' : '创建'/)
+
+ // 视频分辨率:创建集时固定(480p/720p,默认 720p)
+ assert.match(page, /视频分辨率/)
+ assert.match(page, /v-model="newEpisodeResolution"/)
+ assert.match(page, /const resolutionOptions = \[/)
+ assert.match(page, /720p · 高清/)
+ assert.match(page, /480p · 流畅/)
+ assert.match(page, /newEpisodeResolution = ref\('720p'\)/)
+ assert.match(page, /之后仍可在集卡片上修改/)
})
-test('addEpisode posts only drama_id and title', () => {
+test('addEpisode posts drama_id, title and resolution', () => {
const page = read('app/pages/drama/[id]/index.vue')
const addEpisodeBody = page.slice(page.indexOf('async function addEpisode'), page.indexOf('onMounted(load)'))
assert.match(addEpisodeBody, /drama_id: dramaId/)
assert.match(addEpisodeBody, /title: newEpisodeTitle\.value/)
+ assert.match(addEpisodeBody, /resolution: newEpisodeResolution\.value/)
assert.doesNotMatch(addEpisodeBody, /image_config_id/)
assert.doesNotMatch(addEpisodeBody, /video_config_id/)
assert.doesNotMatch(addEpisodeBody, /aiConfigAPI/)
})
+test('episode card resolution is editable via a dropdown persisted to episodes.resolution', () => {
+ const page = read('app/pages/drama/[id]/index.vue')
+
+ // 卡片上的分辨率标签 + 下拉修改
+ assert.match(page, /点击修改本集视频分辨率/)
+ assert.match(page, /epResMenuId/)
+ assert.match(page, /function epResolution\(ep\) \{ return ep\.resolution === '480p' \? '480p' : '720p' \}/)
+ assert.match(page, /function setEpisodeResolution/)
+ assert.match(page, /episodeAPI\.update\(ep\.id, \{ resolution \}\)/)
+})
+
test('add episode dialog does not preload config lists', () => {
const page = read('app/pages/drama/[id]/index.vue')
diff --git a/frontend/tests/episode-workbench-structure.test.mjs b/frontend/tests/episode-workbench-structure.test.mjs
index 6c48c61..26e8876 100644
--- a/frontend/tests/episode-workbench-structure.test.mjs
+++ b/frontend/tests/episode-workbench-structure.test.mjs
@@ -92,11 +92,43 @@ test('storyboard split exposes the generated shot information and prompt editor'
assert.match(storyboardBlock, /画面描述/)
assert.match(storyboardBlock, /对白 \/ 旁白/)
assert.match(storyboardBlock, /氛围/)
- // 视频提示词已移至视频生成阶段,分镜拆分界面不再出现
- assert.doesNotMatch(storyboardBlock, /视频提示词/)
- assert.doesNotMatch(storyboardBlock, /updateField\(selectedSb, 'video_prompt'/)
+ // 分镜编辑器也提供视频提示词区块(AI 生成 + @提及编辑),与视频 tab 同源
+ assert.match(storyboardBlock, /视频提示词/)
+ assert.match(storyboardBlock, /genVideoPrompt\(selectedSb\)/)
+ assert.match(storyboardBlock, /MentionTextarea/)
+ assert.match(storyboardBlock, /updateField\(selectedSb, 'video_prompt'/)
+ // 描述与视频提示词左右双栏分割,并标注生成来源
+ assert.match(storyboardBlock, /class="sb-split"/)
+ assert.match(storyboardBlock, /根据当前分镜的画面描述、动作、氛围以及对白 \/ 旁白生成/)
assert.match(storyboardBlock, /role-pill/)
+ // 批量视频提示词:异步任务 + 进度轮询,单个生成在批量期间禁用
+ assert.match(storyboardBlock, /batchVideoPrompts/)
+ // 多选模式:进入后点击卡片勾选,头部快捷操作(全选/仅缺失/清空),底部操作条确认生成
+ assert.match(storyboardBlock, /sbSelectMode/)
+ assert.match(storyboardBlock, /onShotCardClick\(sb\)/)
+ assert.match(storyboardBlock, /shot-check/)
+ assert.match(storyboardBlock, /is-selected/)
+ assert.match(storyboardBlock, /仅缺失/)
+ assert.match(storyboardBlock, /shot-select-bar/)
+ assert.match(storyboardBlock, /generateSelectedVideoPrompts/)
+ assert.match(page, /selectMissingSbs/)
+ assert.match(page, /exitSbSelectMode/)
+ assert.match(page, /toggleSbSelect/)
+ assert.match(page, /toggleSelectAllSbs/)
+ assert.match(page, /selectedSbIds\.value\.length \? \[\.\.\.selectedSbIds\.value\] : undefined/)
+ assert.match(page, /生成视频提示词\(/)
+ assert.match(page, /生成所选提示词\(/)
+ assert.match(page, /批量视频提示词/)
+ assert.match(page, /videoPromptBatch\.running/)
+ assert.match(page, /episodeAPI\.generateVideoPrompts\(epId\.value, chatModelOverride\(\), chatConfigId\(\), ids\)/)
+ assert.match(page, /episodeAPI\.videoPromptsStatus\(epId\.value\)/)
+ assert.match(page, /pollVideoPromptBatch/)
+ assert.match(page, /:disabled="rn \|\| videoPromptBatch\.running"/)
+ assert.match(apiSource, /\/episodes\/\$\{id\}\/generate-video-prompts`/)
+ assert.match(apiSource, /\/episodes\/\$\{id\}\/video-prompts-status`/)
assert.match(storyboardBlock, /toggleStoryboardCharacter/)
+ assert.match(storyboardBlock, /toggleStoryboardProp/)
+ assert.match(storyboardBlock, /isStoryboardPropSelected/)
assert.match(storyboardBlock, /sceneOptions/)
assert.match(storyboardBlock, /updateField\(selectedSb, 'scene_id'/)
assert.doesNotMatch(storyboardBlock, /基础信息/)
@@ -116,10 +148,11 @@ test('storyboard breaker prompt only requires production fields used by the UI',
assert.match(page, /绑定角色/)
const agentSource = readFileSync(new URL('../../backend/src/agents/index.ts', import.meta.url), 'utf8')
const storyboardPromptStart = agentSource.indexOf('storyboard_breaker')
- const gridPromptStart = agentSource.indexOf('image_prompt_generator', storyboardPromptStart)
+ const gridPromptStart = agentSource.indexOf('prompt_generator', storyboardPromptStart)
const storyboardPrompt = agentSource.slice(storyboardPromptStart, gridPromptStart)
assert.match(storyboardPrompt, /character_ids/)
+ assert.match(storyboardPrompt, /prop_ids/)
assert.match(storyboardPrompt, /scene_id/)
assert.match(storyboardPrompt, /duration/)
assert.match(storyboardPrompt, /action/)
@@ -147,6 +180,7 @@ test('storyboard split shows a right-side reference asset rail', () => {
assert.match(page, /function getShotReferenceAssets\(sb\)/)
assert.match(page, /function getStoryboardScene\(sb\)/)
assert.match(page, /function getStoryboardCharacters\(sb\)/)
+ assert.match(page, /function getStoryboardProps\(sb\)/)
})
test('storyboard split uses quiet white cards with a system-blue selection ring', () => {
@@ -208,7 +242,7 @@ test('video generation panel keeps only reference mode with audio toggle', () =>
assert.match(videoBlock, /video-inspector-label-hero/)
assert.match(videoBlock, /genVideoPrompt\(selectedSb\)/)
assert.match(videoBlock, /rows="9"/)
- assert.match(videoBlock, /用 @角色名 \/ @场景名 引用参考素材/)
+ assert.match(videoBlock, /用 @角色名 \/ @场景名 \/ @道具名 引用参考素材/)
assert.match(videoBlock, /@志远、@电子厂车间/)
assert.doesNotMatch(videoBlock, /<location>/)
assert.doesNotMatch(videoBlock, /<role>/)
@@ -287,20 +321,55 @@ test('production exposes the previous role and scene card workbench', () => {
const assetBlock = page.slice(assetStart, storyboardStart)
assert.match(assetBlock, /角色资产|角色/)
- assert.match(assetBlock, /场景图片/)
+ assert.match(assetBlock, /批量场景/)
assert.match(assetBlock, /class="character-asset-grid"/)
assert.match(assetBlock, /class="card character-asset-card"/)
assert.match(assetBlock, /class="card asset-card asset-click-card"/)
assert.match(assetBlock, /doExtract/)
assert.match(assetBlock, /开始提取/)
- assert.match(assetBlock, /重新提取/)
+ assert.match(assetBlock, /重提\$\{t\.label\}/)
+ assert.match(assetBlock, /提取\$\{t\.label\}/)
+ assert.match(page, /episodeAPI\.extract\(epId\.value, target, chatModelOverride\(\), chatConfigId\(\)\)/)
+ // 顶栏文本模型适用于所有 Chat Agent 调用
+ assert.match(page, /label="文本"/)
+ assert.match(page, /episodeAPI\.extractStatus\(epId\.value\)/)
+ assert.match(apiSource, /\/episodes\/\$\{id\}\/extract`/)
+ assert.match(apiSource, /\/episodes\/\$\{id\}\/extract-status`/)
assert.match(assetBlock, /角色、场景和道具会在提取后显示在这里/)
assert.match(assetBlock, /batchCharImages/)
assert.match(assetBlock, /batchSceneImages/)
+ assert.match(assetBlock, /batchPropImages/)
+ assert.match(assetBlock, /批量角色/)
+ assert.match(assetBlock, /批量道具/)
+ // 提取与批量生成按钮样式分组区分
+ assert.match(assetBlock, /asset-btn-extract/)
+ assert.match(assetBlock, /asset-btn-batch/)
+ assert.match(assetBlock, /asset-bar-divider/)
+ // 角色/场景/道具支持手动新增与删除
+ assert.match(assetBlock, /openAssetCreate\('character'\)/)
+ assert.match(assetBlock, /openAssetCreate\('scene'\)/)
+ assert.match(assetBlock, /openAssetCreate\('prop'\)/)
+ assert.match(assetBlock, /askDeleteAsset\('character', c\)/)
+ assert.match(assetBlock, /askDeleteAsset\('scene', s\)/)
+ assert.match(assetBlock, /askDeleteAsset\('prop', p\)/)
+ assert.match(page, /assetCreate\.open/)
+ assert.match(page, /saveAssetCreate/)
+ assert.match(page, /ConfirmDialog/)
+ assert.match(page, /confirmDeleteAsset/)
+ assert.match(apiSource, /create:\s*\(data:\s*any\)\s*=>\s*api\.post\('\/characters'/)
+ assert.match(apiSource, /create:\s*\(data:\s*any\)\s*=>\s*api\.post\('\/scenes'/)
+ assert.match(apiSource, /create:\s*\(data:\s*any\)\s*=>\s*api\.post\('\/props'/)
+ assert.match(apiSource, /del:\s*\(id:\s*number\)\s*=>\s*api\.del\(`\/characters\/\$\{id\}`\)/)
+ assert.match(apiSource, /del:\s*\(id:\s*number\)\s*=>\s*api\.del\(`\/scenes\/\$\{id\}`\)/)
+ assert.match(apiSource, /del:\s*\(id:\s*number\)\s*=>\s*api\.del\(`\/props\/\$\{id\}`\)/)
// 卡片展示 Agent 生成的最终提示词(角色三视图 / 场景固定视角)
assert.match(assetBlock, /class="asset-final-prompt"/)
assert.match(assetBlock, /最终提示词 · 三视图/)
assert.match(assetBlock, /最终提示词 · 固定视角/)
+ // 最终提示词支持重新生成(有值时按钮变「重新生成」,force 重新生成)
+ assert.match(page, /\(assetFinalPrompt \? '重新生成' : '生成提示词'\)/)
+ assert.match(page, /ensureAssetPrompt\(type, id, force = false\)/)
+ assert.match(page, /const force = !!assetFinalPrompt\.value/)
assert.match(assetBlock, /c\.final_prompt \|\| c\.finalPrompt/)
assert.match(assetBlock, /s\.final_prompt \|\| s\.finalPrompt/)
assert.match(page, /prodTab\.value = 'assets'/)
diff --git a/frontend/tests/model-selection-structure.test.mjs b/frontend/tests/model-selection-structure.test.mjs
index 758a907..62d3f85 100644
--- a/frontend/tests/model-selection-structure.test.mjs
+++ b/frontend/tests/model-selection-structure.test.mjs
@@ -12,10 +12,10 @@ const useApi = read('app/composables/useApi.ts')
test('workbench offers model selectors for rewrite, image and video generation', () => {
// 三个选择器(自定义 ModelSelect 弹窗组件,非原生 select)
assert.match(page, /<ModelSelect/)
- assert.match(page, /v-model="rewriteModel"/)
+ assert.match(page, /v-model="chatModel"/)
assert.match(page, /v-model="imageModel"/)
assert.match(page, /v-model="videoModel"/)
- assert.doesNotMatch(page, /<select v-model="rewriteModel"/)
+ assert.doesNotMatch(page, /<select v-model="chatModel"/)
// 选项汇总该类型全部启用配置的模型(去重、按优先级),API 返回的 model 可能已是数组
assert.match(page, /function collectModelOptions\(cfgs\)/)
assert.match(page, /if \(Array\.isArray\(raw\)\) return raw\.filter\(Boolean\)/)
@@ -45,13 +45,16 @@ test('selected models are sent with rewrite, image and video generation requests
// 改写(Agent)透传模型与配置
assert.match(useAgent, /model: model \|\| undefined/)
assert.match(useAgent, /config_id: configId \|\| undefined/)
- assert.match(page, /runAgent\('script_rewriter'[\s\S]*?rewriteModel\.value \|\| undefined, ownerConfigId\(textModelOptions\.value, rewriteModel\.value\)\)/)
+ assert.match(page, /runAgent\('script_rewriter'[\s\S]*?chatModelOverride\(\), chatConfigId\(\)\)/)
// 图片生成透传模型与配置
- assert.match(useApi, /generateImage: \(id: number, episodeId: number, model\?: string, configId\?: number\)/)
+ assert.match(useApi, /generateImage: \(id: number, episodeId: number, model\?: string, configId\?: number, textModel\?: string, textConfigId\?: number\)/)
+ // 文本模型覆盖随生图/提取请求透传(缺提示词时后端触发提示词 Agent)
+ assert.match(useApi, /text_model: textModel \|\| undefined/)
+ assert.match(useApi, /text_config_id: textConfigId \|\| undefined/)
assert.match(useApi, /config_id: configId \|\| undefined/)
- assert.match(page, /characterAPI\.generateImage\(id, epId\.value, imageModel\.value \|\| undefined, ownerConfigId\(imageModelOptions\.value, imageModel\.value\)\)/)
- assert.match(page, /sceneAPI\.generateImage\(id, epId\.value, imageModel\.value \|\| undefined, ownerConfigId\(imageModelOptions\.value, imageModel\.value\)\)/)
- assert.match(page, /characterAPI\.batchImages\(ids, epId\.value, imageModel\.value \|\| undefined, ownerConfigId\(imageModelOptions\.value, imageModel\.value\)\)/)
+ assert.match(page, /characterAPI\.generateImage\(id, epId\.value, imageModel\.value \|\| undefined, ownerConfigId\(imageModelOptions\.value, imageModel\.value\), chatModelOverride\(\), chatConfigId\(\)\)/)
+ assert.match(page, /sceneAPI\.generateImage\(id, epId\.value, imageModel\.value \|\| undefined, ownerConfigId\(imageModelOptions\.value, imageModel\.value\), chatModelOverride\(\), chatConfigId\(\)\)/)
+ assert.match(page, /characterAPI\.batchImages\(ids, epId\.value, imageModel\.value \|\| undefined, ownerConfigId\(imageModelOptions\.value, imageModel\.value\), chatModelOverride\(\), chatConfigId\(\)\)/)
// 视频生成透传模型与配置
assert.match(page, /model: videoModel\.value \|\| undefined/)
assert.match(page, /config_id: ownerConfigId\(videoModelOptions\.value, videoModel\.value\)/)
diff --git a/frontend/tests/remove-grid-feature-structure.test.mjs b/frontend/tests/remove-grid-feature-structure.test.mjs
index d30984c..ec1e3da 100644
--- a/frontend/tests/remove-grid-feature-structure.test.mjs
+++ b/frontend/tests/remove-grid-feature-structure.test.mjs
@@ -30,7 +30,7 @@ test('episode workbench removes the grid image tool and history UI', () => {
})
test('settings image prompt agent copy only describes role and scene prompts', () => {
- assert.match(settingsPage, /image_prompt_generator/)
+ assert.match(settingsPage, /prompt_generator/)
assert.doesNotMatch(settingsPage, /宫格图/)
assert.doesNotMatch(settingsPage, /read_shots_for_grid/)
assert.doesNotMatch(settingsPage, /generate_grid_prompt/)