From 2f3fb5e5d22fbc321e6940c5daafd38dfb1f0d04 Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Wed, 08 Apr 2026 16:13:54 +0800
Subject: [PATCH] 续写提示词
---
aigc-director/aigc-claw/backend/core/agents/script_agent.py | 1087 +++++---------------------------------------------------
1 files changed, 107 insertions(+), 980 deletions(-)
diff --git a/aigc-director/aigc-claw/backend/core/agents/script_agent.py b/aigc-director/aigc-claw/backend/core/agents/script_agent.py
index ec1fc72..6ac13d7 100644
--- a/aigc-director/aigc-claw/backend/core/agents/script_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/script_agent.py
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
"""
-阶段1: 编剧智能体 - 多轮LLM交互生成结构化剧本JSON
-流程: Logline → 节拍表(4幕) → 分场大纲(逐幕) → JSON结构化提取(带校验重试)
+阶段1: 编剧智能体 (直出一遍过版本)
"""
import os
@@ -9,49 +8,45 @@
import json
import asyncio
import logging
-import string
-import random
+from functools import partial
from datetime import datetime, timezone
from typing import Any, Optional, Dict
from prompts.loader import load_prompt_with_fallback
+from .base_agent import AgentInterface
+
+logger = logging.getLogger(__name__)
def _get_script_prompt(name: str, lang: str = "zh") -> str:
return load_prompt_with_fallback("script", name, lang, "zh")
-from .base_agent import AgentInterface
-
-# 导入提示词加载器
-from prompts.loader import load_prompt
-
-logger = logging.getLogger(__name__)
-
-ACT_NAMES_ZH = {1: "激励事件", 2: "进入新世界", 3: "灵魂黑夜", 4: "高潮决战"}
-ACT_NAMES_EN = {1: "Inciting Incident", 2: "Break into Two", 3: "Dark Night of the Soul", 4: "Finale"}
-
class ScriptWriterAgent(AgentInterface):
- """编剧智能体:多轮LLM交互 → 结构化剧本JSON"""
-
def __init__(self):
super().__init__(name="ScriptWriter")
- # ─── JSON 提取 ───
-
@staticmethod
- def _extract_json_from_text(text: str) -> Optional[dict]:
- """从LLM输出中提取JSON对象"""
+ def _extract_json_from_text(text: str) -> Optional[Any]:
text = text.strip()
text = re.sub(r'^```(?:json)?\s*', '', text)
text = re.sub(r'\s*```$', '', text)
text = text.strip()
-
try:
return json.loads(text)
except json.JSONDecodeError:
pass
- start = text.find('{')
- end = text.rfind('}')
+ # 尝试匹配第一个 { 或 [ 到底部对应的 } 或 ]
+ start_obj = text.find('{')
+ start_arr = text.find('[')
+
+ # 确定起始位置
+ if start_obj == -1 and start_arr == -1:
+ return None
+
+ start = start_obj if (start_obj != -1 and (start_arr == -1 or start_obj < start_arr)) else start_arr
+ end_char = '}' if start == start_obj else ']'
+ end = text.rfind(end_char)
+
if start != -1 and end != -1 and end > start:
try:
return json.loads(text[start:end + 1])
@@ -59,150 +54,22 @@
pass
return None
- @staticmethod
- def _extract_json_array_from_text(text: str) -> Optional[list]:
- """从LLM输出中提取JSON数组"""
- text = text.strip()
- # 去除 markdown 代码块标记(支持多行)
- text = re.sub(r'```(?:json)?\s*\n?', '', text)
- text = text.strip()
-
- try:
- result = json.loads(text)
- if isinstance(result, list):
- return result
- # LLM 有时返回对象而非数组,尝试包装
- if isinstance(result, dict):
- return [result]
- except json.JSONDecodeError:
- pass
-
- start = text.find('[')
- end = text.rfind(']')
- if start != -1 and end != -1 and end > start:
- try:
- result = json.loads(text[start:end + 1])
- if isinstance(result, list):
- return result
- except json.JSONDecodeError:
- pass
-
- # 尝试匹配多个独立 JSON 对象
- objects = []
- for m in re.finditer(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', text):
- try:
- obj = json.loads(m.group())
- if isinstance(obj, dict) and 'logline' in obj:
- objects.append(obj)
- except json.JSONDecodeError:
- continue
- if objects:
- return objects
-
- return None
-
- @staticmethod
- def _gen_id(prefix: str = "char") -> str:
- return f"{prefix}_{''.join(random.choices(string.ascii_lowercase + string.digits, k=8))}"
-
- # ─── 保存结果 ───
+ def _gen_id(self, prefix: str = "char") -> str:
+ import uuid
+ return f"{prefix}_{uuid.uuid4().hex[:6]}"
def _save_result(self, json_data: dict, sid: str, is_zh: bool):
- """保存结构化剧本JSON到结果文件"""
- from config import settings
- script_dir = os.path.join(settings.RESULT_DIR, 'script')
- os.makedirs(script_dir, exist_ok=True)
-
- result_file = os.path.join(script_dir, f'script_{sid}.json')
- results = {}
- if os.path.exists(result_file) and os.path.getsize(result_file) > 0:
- with open(result_file, 'r', encoding='utf-8') as f:
- results = json.load(f)
-
- results.setdefault(str(sid), {})['script_json'] = json_data
- with open(result_file, 'w', encoding='utf-8') as f:
- json.dump(results, f, indent=4, ensure_ascii=False)
+ from config import settings as app_settings
+ os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
+ out_path = os.path.join(app_settings.RESULT_DIR, 'script', f'{sid}.json')
+ with open(out_path, 'w', encoding='utf-8') as f:
+ json.dump(json_data, f, ensure_ascii=False, indent=2)
+ logger.info(f"[ScriptWriter] script saved to {out_path}")
def _save_progress(self, sid: str, phase: str, data: dict):
- """保存剧本生成的中间进度状态到结果文件"""
- from config import settings
- script_dir = os.path.join(settings.RESULT_DIR, 'script')
- os.makedirs(script_dir, exist_ok=True)
-
- result_file = os.path.join(script_dir, f'script_{sid}.json')
- results = {}
- if os.path.exists(result_file) and os.path.getsize(result_file) > 0:
- with open(result_file, 'r', encoding='utf-8') as f:
- results = json.load(f)
-
- # 初始化 progress 字段
- results.setdefault(str(sid), {}).setdefault('progress', {})
-
- # 保存当前阶段信息
- results[str(sid)]['progress']['current_phase'] = phase
- results[str(sid)]['progress']['updated_at'] = datetime.now(timezone.utc).isoformat()
-
- # 根据阶段保存对应的数据
- if phase == 'logline_check':
- # 创意检查结果
- results[str(sid)]['progress']['idea_analyzed'] = data.get('idea_analyzed', False)
- results[str(sid)]['progress']['logline_extracted'] = data.get('logline_summary')
- elif phase == 'logline_generation':
- # 生成的候选 logline
- results[str(sid)]['progress']['logline_options'] = data.get('logline_options', [])
- elif phase == 'logline_confirmed':
- # 用户选择的 logline
- results[str(sid)]['progress']['selected_logline'] = data.get('selected_logline')
- elif phase == 'mode_selection':
- # 用户选择的模式
- results[str(sid)]['progress']['selected_mode'] = data.get('selected_mode')
- elif phase == 'script_generation':
- # 完整剧本已生成
- results[str(sid)]['progress']['script_generated'] = True
- results[str(sid)]['progress']['title'] = data.get('title')
-
- with open(result_file, 'w', encoding='utf-8') as f:
- json.dump(results, f, indent=4, ensure_ascii=False)
-
- # ─── 核心流程 ───
+ pass
async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
-
- # 检查当前阶段,避免重复生成 logline
- current_phase = input_data.get("phase", "")
- selected_logline = input_data.get("selected_logline")
- selected_mode = input_data.get("selected_mode")
-
- # 如果已选择模式,直接生成剧本
- if selected_mode:
- # 如果 selected_logline 是索引(数字),需要转换为 logline 对象
- if isinstance(selected_logline, int):
- logline_options = input_data.get("logline_options", [])
- if 0 <= selected_logline < len(logline_options):
- logline_data = logline_options[selected_logline]
- else:
- logline_data = {}
- else:
- logline_data = selected_logline if isinstance(selected_logline, dict) else {}
-
- if selected_mode == "micro":
- return await self._phase_micro_script_gen(input_data, logline_data)
- else:
- return await self._phase_script_gen(input_data, logline_data)
-
- # 如果已选择 logline 但未选择模式,返回模式选择
- if selected_logline and current_phase == "mode_selection":
- return {
- "payload": {
- "phase": "mode_selection",
- "selected_logline": selected_logline,
- "session_id": input_data.get("session_id", ""),
- },
- "requires_intervention": True,
- "openclaw_hint": "用户已选择情节,需要选择拍摄模式(电影模式4幕/微电影模式1幕)。请展示给用户并等待用户选择。",
- }
-
- # (A) 用户介入修改最终剧本
if intervention and "modified_script" in intervention:
modified = intervention["modified_script"]
sid = input_data.get("session_id", "")
@@ -213,835 +80,95 @@
self._save_result(modified, sid, is_zh)
return {"payload": modified, "requires_intervention": False, "stage_completed": True}
- # (B1) 用户选择了创作模式 → 根据模式生成剧本
- if intervention and "selected_mode" in intervention:
- selected = input_data.get("selected_logline", {})
- mode = intervention["selected_mode"]
+ async def run_logic():
+ idea = input_data.get("idea", "")
sid = input_data.get("session_id", "")
+ style = input_data.get("style", "anime")
+ llm_model = input_data.get("llm_model", "qwen3.5-plus")
+ web_search = input_data.get("web_search", False)
+ episodes = input_data.get("episodes", 4)
+ is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
- # 如果 selected_logline 是索引(数字),转换为对应的 logline 对象
- if isinstance(selected, int):
- logline_options = input_data.get("logline_options", [])
- if 0 <= selected < len(logline_options):
- logline_data = logline_options[selected]
- else:
- logline_data = {}
- else:
- logline_data = selected if isinstance(selected, dict) else {}
-
- # 保存进度状态
- self._save_progress(sid, "mode_selection", {
- "selected_mode": mode
- })
-
- if mode == "micro":
- return await self._phase_micro_script_gen(input_data, logline_data)
- else:
- return await self._phase_script_gen(input_data, logline_data)
-
- # (B2) 用户选择了一个 Logline → 显示模式选择
- if intervention and "selected_logline" in intervention:
- selected = intervention["selected_logline"]
- sid = input_data.get("session_id", "")
-
- # 如果 selected_logline 是索引(数字),转换为对应的 logline 对象
- if isinstance(selected, int):
- logline_options = input_data.get("logline_options", [])
- if 0 <= selected < len(logline_options):
- logline_data = logline_options[selected]
- else:
- logline_data = {}
- else:
- logline_data = selected if isinstance(selected, dict) else {}
-
- # 保存进度状态
- self._save_progress(sid, "logline_confirmed", {
- "selected_logline": logline_data
- })
-
- return {
- "payload": {
- "phase": "mode_selection",
- "selected_logline": logline_data,
- "session_id": sid,
- },
- "requires_intervention": True,
- "openclaw_hint": "用户已选择情节,需要选择拍摄模式(电影模式4幕/微电影模式1幕)。请展示给用户并等待用户选择。",
- }
-
- # 首次运行:自动判断是直接提取 logline 还是进入扩写
- auto_mode = input_data.get("auto_mode", False)
-
- # 代理(自动)模式:跳过 Logline 选择,直接生成剧本
- if auto_mode:
- return await self._phase_direct(input_data)
-
- # 自动判断:创意足够则提取 logline,否则自动扩写生成 3 个选项
- return await self._phase_logline_check(input_data)
-
- # ─── Phase 1A: 生成 3 个 Logline 方案 ───
-
- async def _phase_logline_gen(self, input_data: Dict) -> Dict:
- idea = input_data.get("idea", "")
- sid = input_data.get("session_id", "")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
- web_search = input_data.get("web_search", False)
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
- def run():
+ from config import settings as app_settings
from tool.llm_client import LLM
+ os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
llm = LLM()
- self._report_progress("剧本生成", "正在生成 Logline 方案...", 5)
- prompt = _get_script_prompt("logline_generate", "zh" if is_zh else "en").format(idea=idea)
- for attempt in range(3):
- self._check_cancel()
- raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter] Logline gen attempt {attempt + 1}, raw output ({len(raw)} chars): {raw[:500]}")
- options = self._extract_json_array_from_text(raw)
- if options and len(options) > 0:
- # 确保每个选项包含必要字段
- required = {"logline", "who", "goal", "conflict", "twist", "theme"}
- valid = [o for o in options if isinstance(o, dict) and required.issubset(o.keys())]
- if valid:
- self._report_progress("剧本生成", "Logline 方案已生成", 20)
- return valid[:3]
+ def _log_progress(pct, msg):
+ self._report_progress("剧本生成", msg, pct)
+ logger.info(f"[{pct}%] {msg}")
- logger.warning(f"[ScriptWriter] Logline gen attempt {attempt + 1}: parse failed")
- if is_zh:
- prompt = (
- "上次输出格式不正确,请严格按要求重新输出。"
- "必须输出纯JSON数组,不要用```包裹,不要有任何多余文字。\n\n"
- + (_get_script_prompt("logline_generate", "zh")).format(idea=idea)
- )
- else:
- prompt = (
- "Previous output format was incorrect. Please try again. "
- "Output ONLY a raw JSON array, no code blocks, no extra text.\n\n"
- + (_get_script_prompt("logline_generate", "en")).format(idea=idea)
- )
+ # 1. Generate full script
+ _log_progress(10, "正在生成完整剧本文本...")
+ prompt_name = "generate_script"
+ prompt = _get_script_prompt(prompt_name, "zh" if is_zh else "en").format(idea=idea, style=style, episodes=episodes)
- raise Exception("Logline 生成失败:多次尝试均无法解析输出")
+ loop = asyncio.get_running_loop()
+ full_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, True, sid, web_search)
+ logger.info(f"[ScriptWriter] Full script generated ({len(full_script_text)} chars)")
+ _log_progress(40, "原稿生成完成,正在提取人物/场景信息...")
- loop = asyncio.get_running_loop()
- options = await loop.run_in_executor(None, run)
+ # 2. Extract meta data -> total_episodes, characters, settings
+ meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(script_text=full_script_text, outline=full_script_text)
+ meta_raw = await loop.run_in_executor(None, self._cancellable_query, llm, meta_prompt, [], llm_model, True, sid, web_search)
+ meta_res = self._extract_json_from_text(meta_raw)
+ meta_data = meta_res if isinstance(meta_res, dict) else {}
- # 保存进度状态
- self._save_progress(sid, "logline_generation", {
- "logline_options": options
- })
+ all_characters = meta_data.get("characters", [])
+ all_settings = meta_data.get("settings", [])
+ for c in all_characters:
+ c["character_id"] = c.get("character_id") or self._gen_id("char")
+ for s in all_settings:
+ s["setting_id"] = s.get("setting_id") or self._gen_id("set")
- return {
- "payload": {
- "phase": "logline_selection",
- "logline_options": options,
+ asset_chars_str = json.dumps([{"name": c.get("name"), "description": c.get("description"), "role": c.get("role")} for c in all_characters], ensure_ascii=False)
+ asset_sets_str = json.dumps([{"name": s.get("name"), "description": s.get("description")} for s in all_settings], ensure_ascii=False)
+
+ # 3. 解析各集数据 - 针对新版数组输出格式进行优化
+ _log_progress(70, "开始结构化全集数据...")
+
+ extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
+ script_text=full_script_text
+ )
+
+ raw_acts = await loop.run_in_executor(None, self._cancellable_query, llm, extract_prompt, [], llm_model, True, sid, web_search)
+ parsed_acts = self._extract_json_from_text(raw_acts)
+
+ all_episodes = []
+ if isinstance(parsed_acts, list):
+ for act in parsed_acts:
+ if isinstance(act, dict):
+ all_episodes.append({
+ "episode_number": act.get("episode_number"),
+ "act_title": act.get("act_title") or f"第{act.get('episode_number')}集",
+ "content": act.get("content", "")
+ })
+
+ if not all_episodes:
+ logger.error(f"[ScriptWriter] Failed to parse episodes from LLM output. Raw: {raw_acts[:200]}...")
+
+ final_json = {
+ "project_id": f"proj_{sid}",
"session_id": sid,
- },
- "requires_intervention": True,
- "openclaw_hint": "生成了多个情节候选(logline),需要用户选择。请展示给用户并等待用户选择。",
- }
-
- # ─── Phase 1B: 检测输入是否可提取 Logline ───
-
- async def _phase_logline_check(self, input_data: Dict) -> Dict:
- idea = input_data.get("idea", "")
- sid = input_data.get("session_id", "")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
- web_search = input_data.get("web_search", False)
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
- def run():
- from tool.llm_client import LLM
- llm = LLM()
- self._report_progress("剧本生成", "分析创意文本...", 5)
- check_prompt = _get_script_prompt("logline_check", "zh" if is_zh else "en").format(idea=idea)
- answer = self._cancellable_query(llm, check_prompt, model=llm_model, task_id=sid, web_search=web_search).strip()
-
- if answer.lower().startswith("yes"):
- self._report_progress("剧本生成", "提取 Logline...", 10)
- extract_prompt = _get_script_prompt("logline_extract", "zh" if is_zh else "en").format(idea=idea)
- raw = self._cancellable_query(llm, extract_prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter] Logline extract raw ({len(raw)} chars): {raw[:500]}")
- logline_data = self._extract_json_from_text(raw)
- if logline_data and isinstance(logline_data, dict) and 'logline' in logline_data:
- self._report_progress("剧本生成", "Logline 提取完成", 20)
- return {"phase": "logline_confirm", "logline_summary": logline_data}
-
- return {"phase": "suggest_expand"}
-
- loop = asyncio.get_running_loop()
- result = await loop.run_in_executor(None, run)
- result["session_id"] = sid
-
- # 如果创意不够,自动进入扩写阶段,生成 3 个 logline 供选择
- if result.get("phase") == "suggest_expand":
- return await self._phase_logline_gen(input_data)
-
- # 保存进度状态
- phase = result.get("phase", "logline_check")
- self._save_progress(sid, "logline_check", {
- "idea_analyzed": phase == "logline_confirm",
- "logline_summary": result.get("logline_summary")
- })
-
- return {
- "payload": result,
- "requires_intervention": True,
- "openclaw_hint": "已提取情节概要,需要用户确认。请展示给用户并等待用户确认。",
- }
-
- # ─── Phase 2: 根据选定 Logline 生成完整剧本 ───
-
- async def _phase_script_gen(self, input_data: Dict, logline_data: Dict) -> Dict:
- idea = input_data.get("idea", "")
- sid = input_data.get("session_id", "")
- style = input_data.get("style", "anime")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
- web_search = input_data.get("web_search", False)
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
- # 用 Logline 六要素构建丰富的故事概要
- if is_zh:
- draft = (
- f"故事核心 Logline:{logline_data.get('logline', '')}\n"
- f"主角:{logline_data.get('who', '')}\n"
- f"目标:{logline_data.get('goal', '')}\n"
- f"核心障碍:{logline_data.get('conflict', '')}\n"
- f"反转:{logline_data.get('twist', '')}\n"
- f"主题:{logline_data.get('theme', '')}\n\n"
- f"原始灵感:{idea}"
- )
- else:
- draft = (
- f"Story Logline: {logline_data.get('logline', '')}\n"
- f"Protagonist: {logline_data.get('who', '')}\n"
- f"Goal: {logline_data.get('goal', '')}\n"
- f"Core Conflict: {logline_data.get('conflict', '')}\n"
- f"Twist: {logline_data.get('twist', '')}\n"
- f"Theme: {logline_data.get('theme', '')}\n\n"
- f"Original idea: {idea}"
- )
-
- def run():
- from config import settings as app_settings
- from tool.llm_client import LLM
-
- os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
- os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
-
- llm = LLM()
-
- # 逐幕生成节拍表 + 分场大纲 + 结构化提取
- json_data = self._generate_script_incremental(
- llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
- )
-
- # 补充元数据
- json_data.setdefault("project_id", f"proj_{sid}")
- json_data.setdefault("version", 1)
- json_data["created_at"] = datetime.now(timezone.utc).isoformat()
- json_data["metadata"] = {
- "generation_model": llm_model,
- "generation_prompt": idea,
+ "version": 1,
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ "metadata": {
+ "generation_model": llm_model,
+ "generation_prompt": idea,
+ "original_text": full_script_text
+ },
+ "title": meta_data.get("title", "Generated Script"),
+ "logline": meta_data.get("logline", ""),
+ "genre": meta_data.get("genre", []),
+ "mood": meta_data.get("mood", ""),
+ "characters": all_characters,
+ "settings": all_settings,
+ "episodes": all_episodes
}
- json_data["session_id"] = sid
- json_data["logline_data"] = logline_data
+
+ self._save_result(final_json, sid, is_zh)
+ _log_progress(100, "剧本结构化解析完成!")
+ return final_json
- self._save_result(json_data, sid, is_zh)
- # 保存进度状态
- self._save_progress(sid, "script_generation", {
- "title": json_data.get("title")
- })
- self._report_progress("剧本生成", "完成", 100)
- return json_data
-
- loop = asyncio.get_running_loop()
- script_json = await loop.run_in_executor(None, run)
-
- # 保存进度状态
- self._save_progress(sid, "script_generation", {
- "title": script_json.get("title")
- })
-
- return {
- "payload": script_json,
- "requires_intervention": False,
- "stage_completed": True, # 明确标记阶段完成
- "openclaw_hint": "剧本生成完成。",
- }
-
- # ─── Phase 2-Micro: 微电影模式 - 根据选定 Logline 生成紧凑单幕剧本 ───
-
- async def _phase_micro_script_gen(self, input_data: Dict, logline_data: Dict) -> Dict:
- idea = input_data.get("idea", "")
- sid = input_data.get("session_id", "")
- style = input_data.get("style", "anime")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
- web_search = input_data.get("web_search", False)
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
- # 用 Logline 六要素构建故事概要
- if is_zh:
- draft = (
- f"故事核心 Logline:{logline_data.get('logline', '')}\n"
- f"主角:{logline_data.get('who', '')}\n"
- f"目标:{logline_data.get('goal', '')}\n"
- f"核心障碍:{logline_data.get('conflict', '')}\n"
- f"反转:{logline_data.get('twist', '')}\n"
- f"主题:{logline_data.get('theme', '')}\n\n"
- f"原始灵感:{idea}"
- )
- else:
- draft = (
- f"Story Logline: {logline_data.get('logline', '')}\n"
- f"Protagonist: {logline_data.get('who', '')}\n"
- f"Goal: {logline_data.get('goal', '')}\n"
- f"Core Conflict: {logline_data.get('conflict', '')}\n"
- f"Twist: {logline_data.get('twist', '')}\n"
- f"Theme: {logline_data.get('theme', '')}\n\n"
- f"Original idea: {idea}"
- )
-
- def run():
- from config import settings as app_settings
- from tool.llm_client import LLM
-
- os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
- os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
-
- llm = LLM()
-
- # 微电影模式: 单幕生成
- json_data = self._generate_micro_script_incremental(
- llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
- )
-
- # 补充元数据
- json_data.setdefault("project_id", f"proj_{sid}")
- json_data.setdefault("version", 1)
- json_data["created_at"] = datetime.now(timezone.utc).isoformat()
- json_data["metadata"] = {
- "generation_model": llm_model,
- "generation_prompt": idea,
- "mode": "micro",
- }
- json_data["session_id"] = sid
- json_data["logline_data"] = logline_data
-
- self._save_result(json_data, sid, is_zh)
- # 保存进度状态
- self._save_progress(sid, "script_generation", {
- "title": json_data.get("title")
- })
- self._report_progress("剧本生成", "完成", 100)
- return json_data
-
- loop = asyncio.get_running_loop()
- script_json = await loop.run_in_executor(None, run)
-
- # 保存进度状态
- self._save_progress(sid, "script_generation", {
- "title": script_json.get("title")
- })
-
- return {
- "payload": script_json,
- "requires_intervention": False,
- "stage_completed": True, # 明确标记阶段完成
- "openclaw_hint": "剧本生成完成。",
- }
-
- # ─── 代理模式(自动生成 Logline 并选择第一个) ───
-
- async def _phase_direct(self, input_data: Dict) -> Dict:
- """代理模式:生成 3 个 Logline → 自动选择第一个 → 生成完整剧本"""
- idea = input_data.get("idea", "")
- sid = input_data.get("session_id", "")
- style = input_data.get("style", "anime")
- llm_model = input_data.get("llm_model", "qwen3.5-plus")
- web_search = input_data.get("web_search", False)
- is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
- def run():
- from config import settings as app_settings
- from tool.llm_client import LLM
-
- os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
- os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
-
- llm = LLM()
-
- # Step 1: 生成 Logline 方案
- self._report_progress("剧本生成", "正在生成 Logline 方案...", 5)
- prompt = _get_script_prompt("logline_generate", "zh" if is_zh else "en").format(idea=idea)
-
- logline_data = None
- for attempt in range(3):
- self._check_cancel()
- raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter][auto] Logline gen attempt {attempt + 1}, raw ({len(raw)} chars): {raw[:500]}")
- options = self._extract_json_array_from_text(raw)
- if options and len(options) > 0:
- required = {"logline", "who", "goal", "conflict", "twist", "theme"}
- valid = [o for o in options if isinstance(o, dict) and required.issubset(o.keys())]
- if valid:
- logline_data = valid[0] # 自动选择第一个
- logger.info(f"[ScriptWriter][auto] Auto-selected logline: {logline_data.get('logline', '')[:80]}")
- break
-
- logger.warning(f"[ScriptWriter][auto] Logline gen attempt {attempt + 1}: parse failed")
- if is_zh:
- prompt = (
- "上次输出格式不正确,请严格按要求重新输出。"
- "必须输出纯JSON数组,不要用```包裹,不要有任何多余文字。\n\n"
- + _get_script_prompt("logline_generate", "zh").format(idea=idea)
- )
- else:
- prompt = (
- "Previous output format was incorrect. Please try again. "
- "Output ONLY a raw JSON array, no code blocks, no extra text.\n\n"
- + _get_script_prompt("logline_generate", "en").format(idea=idea)
- )
-
- if logline_data is None:
- raise Exception("Logline 生成失败:多次尝试均无法解析输出")
-
- self._report_progress("剧本生成", "已自动选择 Logline,开始创作情节...", 15)
-
- # Step 2: 用 Logline 六要素构建故事概要
- if is_zh:
- draft = (
- f"故事核心 Logline:{logline_data.get('logline', '')}\n"
- f"主角:{logline_data.get('who', '')}\n"
- f"目标:{logline_data.get('goal', '')}\n"
- f"核心障碍:{logline_data.get('conflict', '')}\n"
- f"反转:{logline_data.get('twist', '')}\n"
- f"主题:{logline_data.get('theme', '')}\n\n"
- f"原始灵感:{idea}"
- )
- else:
- draft = (
- f"Story Logline: {logline_data.get('logline', '')}\n"
- f"Protagonist: {logline_data.get('who', '')}\n"
- f"Goal: {logline_data.get('goal', '')}\n"
- f"Core Conflict: {logline_data.get('conflict', '')}\n"
- f"Twist: {logline_data.get('twist', '')}\n"
- f"Theme: {logline_data.get('theme', '')}\n\n"
- f"Original idea: {idea}"
- )
-
- # Step 3: 逐幕生成节拍表 + 分场大纲 + 结构化提取
- json_data = self._generate_script_incremental(
- llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
- )
-
- # 补充元数据
- json_data.setdefault("project_id", f"proj_{sid}")
- json_data.setdefault("version", 1)
- json_data["created_at"] = datetime.now(timezone.utc).isoformat()
- json_data["metadata"] = {
- "generation_model": llm_model,
- "generation_prompt": idea,
- }
- json_data["session_id"] = sid
- json_data["logline_data"] = logline_data
-
- self._save_result(json_data, sid, is_zh)
- # 保存进度状态
- self._save_progress(sid, "script_generation", {
- "title": json_data.get("title")
- })
- self._report_progress("剧本生成", "完成", 100)
- return json_data
-
- loop = asyncio.get_running_loop()
- script_json = await loop.run_in_executor(None, run)
-
- # 保存进度状态
- self._save_progress(sid, "script_generation", {
- "title": script_json.get("title")
- })
-
- return {
- "payload": script_json,
- "requires_intervention": False,
- "stage_completed": True, # 明确标记阶段完成
- "openclaw_hint": "剧本生成完成。",
- }
-
- # ─── 公共: 逐幕生成节拍表 + 分场大纲 + 结构化提取 ───
-
- def _generate_script_incremental(self, llm, draft: str, idea: str, style: str,
- llm_model: str, sid: str, is_zh: bool,
- web_search: bool = False,
- pct_start: int = 20) -> dict:
- """生成 Save the Cat! 节拍表 → 逐幕生成分场大纲 + 结构化提取,返回合并的 JSON"""
-
- # Step 1: 生成四幕节拍表
- self._report_progress("剧本生成", "生成节拍表...", pct_start)
- prompt = _get_script_prompt("beat_sheet", "zh" if is_zh else "en").format(draft=draft, idea=idea, style=style)
- beat_sheet = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter] Beat sheet generated ({len(beat_sheet)} chars)")
-
- # 发送节拍表到前端
- self._report_progress("剧本生成", "节拍表生成完成", pct_start + 5,
- data={"beat_sheet": beat_sheet})
-
- # Step 2: 提取顶层元数据 (title, logline, genre, synopsis, mood)
- self._report_progress("剧本生成", "提取故事元信息...", pct_start + 7)
- meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(beat_sheet=beat_sheet)
- meta_raw = self._cancellable_query(llm, meta_prompt, model=llm_model, task_id=sid, web_search=web_search)
- meta_data = self._extract_json_from_text(meta_raw) or {}
- logger.info(f"[ScriptWriter] Meta extracted: {list(meta_data.keys())}")
-
- # Step 3: 逐幕生成分场大纲 + 结构化提取
- act_names = ACT_NAMES_ZH if is_zh else ACT_NAMES_EN
- all_characters = [] # 累积角色
- all_settings = [] # 累积场景
- all_scenes = [] # 累积分场
- seen_char_names = set()
- seen_setting_names = set()
- scene_start = 1
-
- for act_num in range(1, 5):
- self._check_cancel()
- act_name = act_names[act_num]
-
- # --- 生成分场大纲 ---
- pct_outline = pct_start + 8 + (act_num - 1) * 15 # 28, 43, 58, 73
- progress_msg = (f"生成第{act_num}幕分场大纲({act_name})..."
- if is_zh else f"Generating Act {act_num} outline ({act_name})...")
- self._report_progress("剧本生成", progress_msg, pct_outline)
-
- outline_prompt = _get_script_prompt("step_outline", "zh" if is_zh else "en").format(
- beat_sheet=beat_sheet,
- act_number=act_num,
- act_name=act_name,
- scene_start=scene_start,
- style=style,
- )
- outline = self._cancellable_query(llm, outline_prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter] Act {act_num} outline generated ({len(outline)} chars)")
-
- # --- 结构化提取本幕 JSON ---
- pct_extract = pct_outline + 8
- progress_msg = (f"提取第{act_num}幕结构化数据..."
- if is_zh else f"Extracting Act {act_num} structured data...")
- self._report_progress("剧本生成", progress_msg, pct_extract)
-
- act_json = self._extract_act_json(
- llm, outline, act_num, scene_start, style, llm_model, sid, is_zh, web_search
- )
-
- # 累积角色(去重)
- for c in act_json.get("characters", []):
- if c.get("name") and c["name"] not in seen_char_names:
- if not c.get("character_id"):
- c["character_id"] = self._gen_id("char")
- all_characters.append(c)
- seen_char_names.add(c["name"])
-
- # 累积场景(去重)
- for s in act_json.get("settings", []):
- if s.get("name") and s["name"] not in seen_setting_names:
- if not s.get("setting_id"):
- s["setting_id"] = self._gen_id("set")
- all_settings.append(s)
- seen_setting_names.add(s["name"])
-
- # 累积分场
- act_scenes = act_json.get("scenes", [])
- all_scenes.extend(act_scenes)
-
- # 计算下一幕场次起始
- if act_scenes:
- scene_start = max(s.get("scene_number", scene_start) for s in act_scenes) + 1
-
- # 发送本幕结果到前端
- act_label = f"第{act_num}幕 - {act_name}" if is_zh else f"Act {act_num} - {act_name}"
- self._report_progress("剧本生成",
- f"{act_label} 完成" if is_zh else f"{act_label} done",
- pct_extract + 2,
- data={"act_complete": {
- "act": act_num,
- "act_name": act_name,
- "characters": act_json.get("characters", []),
- "settings": act_json.get("settings", []),
- "scenes": act_scenes,
- }})
-
- # Step 4: 合并最终 JSON
- # 重新编号 scene_number
- for i, sc in enumerate(all_scenes):
- sc["scene_number"] = i + 1
-
- json_data = {
- "title": meta_data.get("title", ""),
- "logline": meta_data.get("logline", ""),
- "genre": meta_data.get("genre", []),
- "target_duration": 1800,
- "synopsis": meta_data.get("synopsis", ""),
- "characters": all_characters,
- "settings": all_settings,
- "scenes": all_scenes,
- "overall_style": style,
- "mood": meta_data.get("mood", ""),
- }
-
- # Step 5: 合并相似场景和角色
- self._report_progress("剧本生成",
- "审查并合并相似场景..." if is_zh else "Consolidating similar settings...",
- 96)
- json_data = self._consolidate_script(llm, json_data, llm_model, sid, is_zh, web_search=web_search)
-
- return json_data
-
- # ─── 微电影模式: 单幕紧凑生成 ───
-
- def _generate_micro_script_incremental(self, llm, draft: str, idea: str, style: str,
- llm_model: str, sid: str, is_zh: bool,
- web_search: bool = False,
- pct_start: int = 20) -> dict:
- """微电影模式:生成紧凑单幕剧情概要 → 分场大纲 → 结构化提取,返回合并的 JSON"""
-
- # Step 1: 生成单幕剧情概要
- self._report_progress("剧本生成", "生成微电影剧情概要...", pct_start)
- prompt = _get_script_prompt("micro_beat_sheet", "zh" if is_zh else "en").format(
- draft=draft, idea=idea, style=style
- )
- beat_sheet = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter][micro] Beat sheet generated ({len(beat_sheet)} chars)")
-
- # 发送概要到前端
- self._report_progress("剧本生成", "剧情概要生成完成", pct_start + 10,
- data={"beat_sheet": beat_sheet})
-
- # Step 2: 提取顶层元数据
- self._report_progress("剧本生成", "提取故事元信息...", pct_start + 15)
- meta_prompt = _get_script_prompt("micro_meta_extract", "zh" if is_zh else "en").format(
- beat_sheet=beat_sheet
- )
- meta_raw = self._cancellable_query(llm, meta_prompt, model=llm_model, task_id=sid, web_search=web_search)
- meta_data = self._extract_json_from_text(meta_raw) or {}
- logger.info(f"[ScriptWriter][micro] Meta extracted: {list(meta_data.keys())}")
-
- # Step 3: 生成分场大纲
- self._check_cancel()
- self._report_progress("剧本生成",
- "生成微电影分场大纲..." if is_zh else "Generating micro-film step outline...",
- pct_start + 25)
-
- outline_prompt = _get_script_prompt("micro_step_outline", "zh" if is_zh else "en").format(
- beat_sheet=beat_sheet, style=style
- )
- outline = self._cancellable_query(llm, outline_prompt, model=llm_model, task_id=sid, web_search=web_search)
- logger.info(f"[ScriptWriter][micro] Outline generated ({len(outline)} chars)")
-
- # Step 4: 结构化 JSON 提取
- self._report_progress("剧本生成",
- "提取结构化数据..." if is_zh else "Extracting structured data...",
- pct_start + 45)
-
- act_json = self._extract_act_json(
- llm, outline, act_number=1, scene_start=1,
- style=style, llm_model=llm_model, sid=sid, is_zh=is_zh,
- web_search=web_search
- )
-
- characters = act_json.get("characters", [])
- settings = act_json.get("settings", [])
- scenes = act_json.get("scenes", [])
-
- # 补全 ID
- for c in characters:
- if not c.get("character_id"):
- c["character_id"] = self._gen_id("char")
- for s in settings:
- if not s.get("setting_id"):
- s["setting_id"] = self._gen_id("set")
-
- # 重新编号并去掉 act 字段(微电影不分幕)
- for i, sc in enumerate(scenes):
- sc["scene_number"] = i + 1
- sc.pop("act", None)
-
- # 发送到前端
- act_label = "微电影" if is_zh else "Micro-film"
- self._report_progress("剧本生成",
- f"{act_label} 分场完成" if is_zh else f"{act_label} scenes done",
- pct_start + 60,
- data={"act_complete": {
- "act": 1,
- "act_name": act_label,
- "characters": characters,
- "settings": settings,
- "scenes": scenes,
- }})
-
- # Step 5: 合并最终 JSON
- json_data = {
- "title": meta_data.get("title", ""),
- "logline": meta_data.get("logline", ""),
- "genre": meta_data.get("genre", []),
- "target_duration": 180, # 微电影默认 3 分钟
- "synopsis": meta_data.get("synopsis", ""),
- "characters": characters,
- "settings": settings,
- "scenes": scenes,
- "overall_style": style,
- "mood": meta_data.get("mood", ""),
- }
-
- # Step 6: 合并相似场景和角色
- self._report_progress("剧本生成",
- "审查并合并相似场景..." if is_zh else "Consolidating similar settings...",
- pct_start + 70)
- json_data = self._consolidate_script(llm, json_data, llm_model, sid, is_zh, web_search=web_search)
-
- return json_data
-
- # ─── 公共: 单幕结构化提取 (带校验重试) ───
-
- def _extract_act_json(self, llm, outline: str, act_number: int,
- scene_start: int, style: str,
- llm_model: str, sid: str, is_zh: bool,
- web_search: bool = False) -> dict:
- """从单幕分场大纲提取结构化JSON,带校验重试"""
- extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
- act_number=act_number, scene_start=scene_start, outline=outline
- )
-
- last_error = ""
-
- for attempt in range(3):
- self._check_cancel()
- raw = self._cancellable_query(llm, extract_prompt, model=llm_model, task_id=sid, web_search=web_search)
- parsed = self._extract_json_from_text(raw)
-
- if parsed is None:
- last_error = "LLM输出无法解析为JSON"
- logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: JSON parse failed")
- extract_prompt = (
- ("上次输出不是合法JSON,请重新输出。" if is_zh
- else "Previous output was not valid JSON. Please try again. ")
- + extract_prompt
- )
- continue
-
- # 基本校验: 必须有 scenes 列表
- scenes = parsed.get("scenes")
- if not isinstance(scenes, list) or len(scenes) == 0:
- last_error = "scenes 必须是非空列表"
- logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: no scenes")
- extract_prompt = (
- (f"上次输出的JSON缺少scenes。请确保scenes是非空列表。" if is_zh
- else "Previous JSON had no scenes. Ensure scenes is a non-empty array. ")
- + extract_prompt
- )
- continue
-
- # 校验每个 scene 的必要字段
- valid = True
- for i, sc in enumerate(scenes):
- for key in ["scene_number", "act", "location", "characters", "plot"]:
- if key not in sc:
- last_error = f"scenes[{i}] 缺少字段: {key}"
- valid = False
- break
- if not valid:
- break
-
- if not valid:
- logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: {last_error}")
- extract_prompt = (
- (f"上次输出的JSON存在问题: {last_error}。请修正后重新输出。" if is_zh
- else f"Previous JSON issue: {last_error}. Please fix and retry. ")
- + extract_prompt
- )
- continue
-
- return parsed
-
- raise Exception(f"第{act_number}幕JSON提取失败 (已重试3次): {last_error}")
-
- # ─── 公共: 场景 & 角色合并 ───
-
- def _consolidate_script(self, llm, json_data: dict,
- llm_model: str, sid: str, is_zh: bool,
- web_search: bool = False) -> dict:
- """审查并合并重复/相似的场景和角色"""
- characters = json_data.get("characters", [])
- settings = json_data.get("settings", [])
- scenes = json_data.get("scenes", [])
-
- if len(settings) <= 1 and len(characters) <= 1:
- return json_data
-
- # 构建简洁的列表供 LLM 审查
- settings_summary = [{"name": s["name"], "description": s.get("description", "")}
- for s in settings]
- chars_summary = [{"name": c["name"], "description": c.get("description", "")}
- for c in characters]
-
- prompt = _get_script_prompt("consolidate", "zh" if is_zh else "en").format(
- settings_json=json.dumps(settings_summary, ensure_ascii=False, indent=2),
- characters_json=json.dumps(chars_summary, ensure_ascii=False, indent=2),
- )
-
- self._check_cancel()
- raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
- result = self._extract_json_from_text(raw)
-
- if not result or not isinstance(result, dict):
- logger.warning("[ScriptWriter] Consolidation: failed to parse LLM response, skipping")
- return json_data
-
- setting_merges = result.get("setting_merges", {})
- char_merges = result.get("character_merges", {})
-
- if not setting_merges and not char_merges:
- logger.info("[ScriptWriter] Consolidation: nothing to merge")
- return json_data
-
- # --- 合并场景 ---
- if setting_merges:
- logger.info(f"[ScriptWriter] Merging settings: {setting_merges}")
- # 移除被合并的 settings
- merged_names = set(setting_merges.keys())
- json_data["settings"] = [s for s in settings if s["name"] not in merged_names]
-
- # 更新 scenes 中的 location 引用
- for sc in scenes:
- loc = sc.get("location", "")
- if loc in setting_merges:
- sc["location"] = setting_merges[loc]
-
- # --- 合并角色 ---
- if char_merges:
- logger.info(f"[ScriptWriter] Merging characters: {char_merges}")
- merged_char_names = set(char_merges.keys())
- json_data["characters"] = [c for c in characters if c["name"] not in merged_char_names]
-
- # 更新 scenes 中的 characters 引用
- for sc in scenes:
- new_chars = []
- seen = set()
- for cn in sc.get("characters", []):
- target = char_merges.get(cn, cn)
- if target not in seen:
- new_chars.append(target)
- seen.add(target)
- sc["characters"] = new_chars
-
- logger.info(f"[ScriptWriter] After consolidation: "
- f"{len(json_data['settings'])} settings, "
- f"{len(json_data['characters'])} characters")
-
- # 验证 scenes 的 location 是否都在 settings 中
- settings_names = {s["name"] for s in json_data.get("settings", [])}
- for sc in json_data.get("scenes", []):
- loc = sc.get("location", "")
- if loc and loc not in settings_names:
- logger.error(f"[ScriptWriter] ERROR: Scene location '{loc}' not found in settings! available: {settings_names}")
-
- return json_data
+ result = await run_logic()
+ return {"payload": result, "requires_intervention": False, "stage_completed": True}
--
Gitblit v1.8.0