From f03ab0d2d3f315ea9949ecb47769ba637d8e9edb Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Sat, 30 May 2026 23:20:33 +0800
Subject: [PATCH] Optimized prompts

---
 video-claw/video-claw/backend/core/agents/script_agent.py |  142 ++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 133 insertions(+), 9 deletions(-)

diff --git a/video-claw/video-claw/backend/core/agents/script_agent.py b/video-claw/video-claw/backend/core/agents/script_agent.py
index fc08c37..3f25c03 100644
--- a/video-claw/video-claw/backend/core/agents/script_agent.py
+++ b/video-claw/video-claw/backend/core/agents/script_agent.py
@@ -10,7 +10,7 @@
 import logging
 from functools import partial
 from datetime import datetime, timezone
-from typing import Any, Optional, Dict
+from typing import Any, Optional, Dict, List
 
 from prompts.loader import load_prompt_with_fallback
 from .base_agent import AgentInterface
@@ -21,6 +21,9 @@
     return load_prompt_with_fallback("script", name, lang, "zh")
 
 class ScriptWriterAgent(AgentInterface):
+    MIN_EPISODE_LINES = 25
+    MAX_EPISODE_LINES = 30
+
     def __init__(self):
         super().__init__(name="ScriptWriter")
 
@@ -68,6 +71,65 @@
 
     def _save_progress(self, sid: str, phase: str, data: dict):
         pass
+
+    @classmethod
+    def _split_episode_blocks(cls, script_text: str) -> List[dict]:
+        episode_re = re.compile(
+            r"^\s*(?:#{1,6}\s*)?(?:\*\*)?\s*(?:第\s*(\d+)\s*集(?![--])|Episode\s+(\d+)\b)",
+            re.IGNORECASE,
+        )
+        blocks: List[dict] = []
+        current = {"episode_number": 1, "lines": []}
+        seen_header = False
+
+        for line in script_text.splitlines():
+            match = episode_re.match(line.strip())
+            if match:
+                if seen_header and current["lines"]:
+                    blocks.append(current)
+                ep_no = int(match.group(1) or match.group(2) or len(blocks) + 1)
+                current = {"episode_number": ep_no, "lines": [line]}
+                seen_header = True
+            else:
+                current["lines"].append(line)
+
+        if current["lines"]:
+            blocks.append(current)
+        return blocks
+
+    @staticmethod
+    def _is_counted_script_line(line: str) -> bool:
+        text = line.strip()
+        if not text:
+            return False
+        if re.match(r"^\s*(?:#{1,6}\s*)?(?:\*\*)?\s*(?:第\s*\d+\s*集(?![--])|Episode\s+\d+\b)", text, re.IGNORECASE):
+            return False
+        if re.match(r"^\s*(?:\*\*)?\s*(?:第\s*\d+\s*集[--]第\s*\d+\s*场|\d+\s*[--]\s*\d+\b)", text, re.IGNORECASE):
+            return False
+        if text.startswith("**") and text.endswith("**"):
+            return False
+        if re.match(r"^(人物|角色|Characters)\s*[::]", text, re.IGNORECASE):
+            return False
+        return True
+
+    @classmethod
+    def _script_length_stats(cls, script_text: str) -> List[dict]:
+        stats: List[dict] = []
+        for block in cls._split_episode_blocks(script_text):
+            counted = [line for line in block["lines"] if cls._is_counted_script_line(line)]
+            stats.append({
+                "episode_number": block["episode_number"],
+                "line_count": len(counted),
+                "too_long": len(counted) > cls.MAX_EPISODE_LINES,
+            })
+        return stats
+
+    @classmethod
+    def _length_feedback(cls, stats: List[dict]) -> str:
+        return "\n".join(
+            f"- 第{item['episode_number']}集:{item['line_count']}行"
+            for item in stats
+        )
 
     async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
         if intervention and "modified_script" in intervention:
@@ -153,7 +215,25 @@
                 sequel_idea=sequel_idea,
                 start_episode_num=last_episode_num + 1
             )
+            
+            _log_progress(45, "正在生成续写初稿...")
             sequel_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, True, sid, web_search)
+
+            _log_progress(50, "正在进行台词评估...")
+            eval_dialogue_prompt = _get_script_prompt("eval_dialogue", "zh" if is_zh else "en").format(script_text=sequel_script_text)
+            dialogue_critique = await loop.run_in_executor(None, self._cancellable_query, llm, eval_dialogue_prompt, [], llm_model, True, sid, web_search)
+            
+            _log_progress(55, "正在进行情节评估...")
+            eval_plot_prompt = _get_script_prompt("eval_plot", "zh" if is_zh else "en").format(script_text=sequel_script_text)
+            plot_critique = await loop.run_in_executor(None, self._cancellable_query, llm, eval_plot_prompt, [], llm_model, True, sid, web_search)
+            
+            _log_progress(58, "正在根据评估意见优化续写内容...")
+            revise_prompt = _get_script_prompt("revise_script", "zh" if is_zh else "en").format(
+                script_text=sequel_script_text, 
+                dialogue_critique=dialogue_critique, 
+                plot_critique=plot_critique
+            )
+            sequel_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, revise_prompt, [], llm_model, True, sid, web_search)
 
             _log_progress(60, "提取新增人物/场景...")
             meta_prompt = _get_script_prompt("meta_extract_sequel", "zh").format(
@@ -262,15 +342,59 @@
                 self._report_progress("剧本生成", msg, pct)
                 logger.info(f"[{pct}%] {msg}")
 
-            # 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)
-
             loop = asyncio.get_running_loop()
+
+            async def _trim_script_if_needed(script_text: str, phase: str) -> str:
+                trimmed = script_text
+                for attempt in range(2):
+                    stats = self._script_length_stats(trimmed)
+                    overlong = [item for item in stats if item.get("too_long")]
+                    if not overlong:
+                        return trimmed
+                    logger.warning(
+                        "[ScriptWriter] %s script is too long; trimming attempt=%d stats=%s",
+                        phase,
+                        attempt + 1,
+                        stats,
+                    )
+                    _log_progress(12 if phase == "初稿" else 45, f"{phase}篇幅超限,正在删减到每集{self.MAX_EPISODE_LINES}行以内...")
+                    trim_prompt = _get_script_prompt("trim_script", "zh" if is_zh else "en").format(
+                        script_text=trimmed,
+                        min_lines=self.MIN_EPISODE_LINES,
+                        max_lines=self.MAX_EPISODE_LINES,
+                        line_report=self._length_feedback(stats),
+                    )
+                    trimmed = await loop.run_in_executor(None, self._cancellable_query, llm, trim_prompt, [], llm_model, True, sid, web_search)
+                    logger.info("[ScriptWriter] Trimmed %s script generated (%d chars)", phase, len(trimmed))
+                return trimmed
+
+            # 1. Generate full script
+            _log_progress(10, "正在生成完整剧本文本初稿...")
+            prompt = _get_script_prompt("generate_script", "zh" if is_zh else "en").format(idea=idea, style=style, episodes=episodes)
+
             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, "原稿生成完成,正在提取人物/场景信息...")
+            logger.info(f"[ScriptWriter] Initial script generated ({len(full_script_text)} chars)")
+            full_script_text = await _trim_script_if_needed(full_script_text, "初稿")
+            
+            _log_progress(20, "正在进行台词评估...")
+            eval_dialogue_prompt = _get_script_prompt("eval_dialogue", "zh" if is_zh else "en").format(script_text=full_script_text)
+            dialogue_critique = await loop.run_in_executor(None, self._cancellable_query, llm, eval_dialogue_prompt, [], llm_model, True, sid, web_search)
+            
+            _log_progress(30, "正在进行情节评估...")
+            eval_plot_prompt = _get_script_prompt("eval_plot", "zh" if is_zh else "en").format(script_text=full_script_text)
+            plot_critique = await loop.run_in_executor(None, self._cancellable_query, llm, eval_plot_prompt, [], llm_model, True, sid, web_search)
+            
+            _log_progress(40, "正在根据评估意见优化剧本...")
+            revise_prompt = _get_script_prompt("revise_script", "zh" if is_zh else "en").format(
+                script_text=full_script_text, 
+                dialogue_critique=dialogue_critique, 
+                plot_critique=plot_critique
+            )
+            full_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, revise_prompt, [], llm_model, True, sid, web_search)
+            logger.info(f"[ScriptWriter] Final script generated ({len(full_script_text)} chars)")
+            full_script_text = await _trim_script_if_needed(full_script_text, "优化后")
+
+            _log_progress(60, "最终剧本生成完成,正在提取人物/场景信息...")
 
             # 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)
@@ -289,7 +413,7 @@
             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, "开始结构化全集数据...")
+            _log_progress(80, "开始结构化全集数据...")
             
             extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
                 script_text=full_script_text

--
Gitblit v1.8.0