hit-cxf
2026-06-03 3d3d16ac0371a8e42c59ee8284a662914f275722
Add a mechanism for detecting and repairing the number of plot episodes
2 files added
7 files modified
161 ■■■■■ changed files
video-claw/video-claw/backend/core/agents/script_agent.py 99 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/script/act_extract_en.txt 8 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/script/act_extract_zh.txt 8 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/script/generate_script_en.txt 4 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/script/generate_script_zh.txt 4 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/script/repair_episode_count_en.txt 18 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/script/repair_episode_count_zh.txt 18 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/setting/eval_setting_zh.txt 1 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/prompts/setting/setting_zh.txt 1 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/agents/script_agent.py
@@ -131,6 +131,54 @@
            for item in stats
        )
    @staticmethod
    def _expected_episode_numbers(episodes: int) -> List[int]:
        return list(range(1, max(1, int(episodes)) + 1))
    @classmethod
    def _episode_numbers_from_script(cls, script_text: str) -> List[int]:
        return [
            int(block["episode_number"])
            for block in cls._split_episode_blocks(script_text)
            if block.get("lines")
        ]
    @classmethod
    def _episode_count_feedback(cls, script_text: str, episodes: int) -> str:
        expected = cls._expected_episode_numbers(episodes)
        found = cls._episode_numbers_from_script(script_text)
        missing = [num for num in expected if num not in found]
        extra = [num for num in found if num not in expected]
        return (
            f"目标集数:{episodes};应包含集号:{expected};"
            f"当前识别到集号:{found or '无'};缺失:{missing or '无'};多余:{extra or '无'}。"
        )
    @classmethod
    def _episode_count_matches(cls, script_text: str, episodes: int) -> bool:
        found = sorted(set(cls._episode_numbers_from_script(script_text)))
        return found == cls._expected_episode_numbers(episodes)
    @classmethod
    def _build_episodes_from_script_text(cls, script_text: str, expected_episodes: int) -> List[dict]:
        episodes: List[dict] = []
        for block in cls._split_episode_blocks(script_text):
            ep_no = int(block.get("episode_number") or len(episodes) + 1)
            if ep_no < 1 or ep_no > expected_episodes:
                continue
            content = "\n".join(block.get("lines") or []).strip()
            if not content:
                continue
            episodes.append({
                "episode_number": ep_no,
                "act_title": f"第{ep_no}集",
                "content": content,
            })
        deduped: Dict[int, dict] = {}
        for ep in episodes:
            deduped[ep["episode_number"]] = ep
        return [deduped[num] for num in cls._expected_episode_numbers(expected_episodes) if num in deduped]
    async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
        if intervention and "modified_script" in intervention:
            modified = intervention["modified_script"]
@@ -368,6 +416,30 @@
                    logger.info("[ScriptWriter] Trimmed %s script generated (%d chars)", phase, len(trimmed))
                return trimmed
            async def _repair_episode_count_if_needed(script_text: str, phase: str) -> str:
                repaired = script_text
                for attempt in range(2):
                    if self._episode_count_matches(repaired, episodes):
                        return repaired
                    feedback = self._episode_count_feedback(repaired, episodes)
                    logger.warning(
                        "[ScriptWriter] %s script episode count mismatch; repair attempt=%d %s",
                        phase,
                        attempt + 1,
                        feedback,
                    )
                    _log_progress(14 if phase == "初稿" else 48, f"{phase}集数不一致,正在修正为{episodes}集...")
                    repair_prompt = _get_script_prompt("repair_episode_count", "zh" if is_zh else "en").format(
                        script_text=repaired,
                        episodes=episodes,
                        episode_report=feedback,
                        min_lines=self.MIN_EPISODE_LINES,
                        max_lines=self.MAX_EPISODE_LINES,
                    )
                    repaired = await loop.run_in_executor(None, self._cancellable_query, llm, repair_prompt, [], llm_model, True, sid, web_search)
                    repaired = await _trim_script_if_needed(repaired, f"{phase}集数修复后")
                return repaired
            # 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)
@@ -375,6 +447,7 @@
            full_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, True, sid, web_search)
            logger.info(f"[ScriptWriter] Initial script generated ({len(full_script_text)} chars)")
            full_script_text = await _trim_script_if_needed(full_script_text, "初稿")
            full_script_text = await _repair_episode_count_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)
@@ -393,6 +466,7 @@
            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, "优化后")
            full_script_text = await _repair_episode_count_if_needed(full_script_text, "优化后")
            _log_progress(60, "最终剧本生成完成,正在提取人物/场景信息...")
@@ -416,7 +490,8 @@
            _log_progress(80, "开始结构化全集数据...")
            
            extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
                script_text=full_script_text
                script_text=full_script_text,
                episodes=episodes,
            )
            
            raw_acts = await loop.run_in_executor(None, self._cancellable_query, llm, extract_prompt, [], llm_model, True, sid, web_search)
@@ -434,6 +509,28 @@
            if not all_episodes:
                logger.error(f"[ScriptWriter] Failed to parse episodes from LLM output. Raw: {raw_acts[:200]}...")
            expected_numbers = self._expected_episode_numbers(episodes)
            parsed_numbers = sorted({
                int(ep.get("episode_number"))
                for ep in all_episodes
                if isinstance(ep.get("episode_number"), int) or str(ep.get("episode_number", "")).isdigit()
            })
            if parsed_numbers != expected_numbers:
                logger.warning(
                    "[ScriptWriter] Structured episodes mismatch; expected=%s parsed=%s. Falling back to regex split.",
                    expected_numbers,
                    parsed_numbers,
                )
                fallback_episodes = self._build_episodes_from_script_text(full_script_text, episodes)
                fallback_numbers = [ep["episode_number"] for ep in fallback_episodes]
                if fallback_numbers == expected_numbers:
                    all_episodes = fallback_episodes
                else:
                    logger.error(
                        "[ScriptWriter] Regex split still mismatched; expected=%s fallback=%s. Keeping parsed output.",
                        expected_numbers,
                        fallback_numbers,
                    )
            
            final_json = {
                "project_id": f"proj_{sid}",
video-claw/video-claw/backend/prompts/script/act_extract_en.txt
@@ -8,9 +8,17 @@
---
[Target Episode Count]
{episodes}
---
[Splitting Requirements]
1. Group the script content into the corresponding `episode_number`.
   - You must return exactly {episodes} array elements.
   - `episode_number` must be consecutive from 1 to {episodes}; do not omit episodes and do not merge multiple episodes.
2. For `act_title`, summarize a concise and engaging title of no more than 10 words based on the story of the episode.
3. For `content`, preserve the full script text of the episode (including scene descriptions, action directions, and character dialogue).
video-claw/video-claw/backend/prompts/script/act_extract_zh.txt
@@ -8,9 +8,17 @@
---
【目标集数】
{episodes}
---
【拆分要求】
1. 请将输入的剧本内容按集数归纳到对应的 `episode_number` 下。
   - 必须返回正好 {episodes} 个数组元素。
   - `episode_number` 必须从 1 到 {episodes} 连续,不能缺集,不能合并多集。
2. `act_title` 请根据该集的剧情,总结一个精炼、引人注意的标题,10个字以内。
3. `content` 请保留该集的完整剧本正文(包含场景描述、动作说明和角色台词)。
video-claw/video-claw/backend/prompts/script/generate_script_en.txt
@@ -1,7 +1,7 @@
You are an expert micro-drama screenwriter. Based on the user's "core inspiration" and "story style," directly create a complete micro-drama script.
[Script Format]:
1. **Episodic Structure and Length**: The script must be divided into episodes (e.g., "## Episode 1", "## Episode 2"...). Each episode must contain 25-30 action/dialogue lines, recommended 26-29 lines, and must NEVER exceed 30 action/dialogue lines. Episode headings, scene headings, and character-list lines do not count toward this limit. Do not output character bios, outlines, or prefaces. Directly output the script text starting from "## Episode 1".
1. **Episodic Structure and Length**: You MUST output exactly the requested number of episodes. Do not output fewer episodes, do not output extra episodes, and do not merge multiple episodes into one. If the requested count is N, output consecutive headings from "## Episode 1" through "## Episode N", and every episode must contain complete script content. Each episode must contain 25-30 action/dialogue lines, recommended 26-29 lines, and must NEVER exceed 30 action/dialogue lines. Episode headings, scene headings, and character-list lines do not count toward this limit. Do not output character bios, outlines, or prefaces. Directly output the script text starting from "## Episode 1".
2. **Scene and Industrial Layout**:
   - Each scene must begin with a bold, centered scene heading format: `**a-b Day/Night Int/Ext Scene Name**` ('a' is the episode number, 'b' is the scene sequence).
   - Below the heading, exactly one line should specify: `Characters: xxx, xxx`, followed by one blank line.
@@ -37,4 +37,4 @@
---
Now, begin your creation. Based on the [User Core Inspiration/Story Setting], output the complete script text containing {episodes} episodes. Before outputting, self-check the action/dialogue line count of every episode. If any episode exceeds 30 action/dialogue lines, delete side beats, repeated reactions, or optional scenes instead of turning dialogue into unnatural short fragments. Only output the complete script; no additional commentary or preface is required.
Now, begin your creation. Based on the [User Core Inspiration/Story Setting], output the complete script text containing exactly {episodes} episodes, with consecutive headings from "## Episode 1" through "## Episode {episodes}". Before outputting, self-check: 1) the episode count is exactly {episodes}; 2) episode numbers are consecutive from 1 to {episodes}; 3) every episode has 25-30 action/dialogue lines. If any episode exceeds 30 action/dialogue lines, delete side beats, repeated reactions, or optional scenes instead of turning dialogue into unnatural short fragments. Only output the complete script; no additional commentary or preface is required.
video-claw/video-claw/backend/prompts/script/generate_script_zh.txt
@@ -9,7 +9,7 @@
- **信息全口述**:严禁通过画面传递信息。所有身份证明、反转契机、手机消息、合同内容,必须由角色“亲口说出来”。
### 剧本格式规范
1. **分集结构**:严格按集划分,每集剧本正文只能有 25-30 行动作或台词,推荐 26-29 行,绝对不能超过 30 行。
1. **分集结构**:必须严格输出【总集数】指定的集数,不能少集、不能多集、不能把多集内容合并成一集。若【总集数】为 N,必须连续输出“## 第1集”到“## 第N集”,且每集都必须有完整正文。每集剧本正文只能有 25-30 行动作或台词,推荐 26-29 行,绝对不能超过 30 行。
2. **场志格式(居中加粗)**:`**第x集-第y场 日/夜 内/外 场景名称**`
   - 下行紧跟:`人物:xxx, xxx`
3. **动作描写**:必须以 `<action>` 开头,独立成行。
@@ -38,4 +38,4 @@
---
### 开始创作
请直接从“## 第1集”开始输出。输出前先自检每集动作/台词行数,任何一集超过 30 行都必须删除支线、删除重复反应、减少场次,而不是把台词改成不完整的短句。
请直接从“## 第1集”开始输出,连续输出到“## 第{episodes}集”。输出前先自检:1)集数必须正好是 {episodes} 集;2)集号必须从 1 到 {episodes} 连续;3)每集动作/台词行数必须是 25-30 行。任何一集超过 30 行都必须删除支线、删除重复反应、减少场次,而不是把台词改成不完整的短句。
video-claw/video-claw/backend/prompts/script/repair_episode_count_en.txt
New file
@@ -0,0 +1,18 @@
You are a micro-drama script repair editor. The script below does not match the target episode count. Repair it into a complete script that strictly satisfies the target count.
[Episode Count Report]
{episode_report}
[Hard Requirements]
1. Output exactly {episodes} episodes, with consecutive headings from "## Episode 1" through "## Episode {episodes}".
2. Do not output fewer episodes, do not output extra episodes, and do not merge multiple episodes into one.
3. Each episode must keep {min_lines}-{max_lines} action/dialogue lines. Episode headings, scene headings, and character-list lines do not count.
4. Preserve the existing main plot, main characters, main settings, and key reversals.
5. If an episode is missing, write a complete episode that logically fits the surrounding story. If extra invalid content exists, delete it or place it into the correct episode.
6. Do not explain. Do not use Markdown code fences. Do not output any commentary outside the script.
7. Action lines must start with `<action>`. Dialogue must keep the format "Character: dialogue" or "Character (tone): dialogue".
[Script To Repair]
{script_text}
Output only the repaired complete script text.
video-claw/video-claw/backend/prompts/script/repair_episode_count_zh.txt
New file
@@ -0,0 +1,18 @@
你是微短剧剧本修复编辑。下面的剧本集数与目标不一致,请修复为严格符合目标集数的完整剧本文本。
【集数检查结果】
{episode_report}
【硬性要求】
1. 必须输出正好 {episodes} 集,集号必须从“## 第1集”连续到“## 第{episodes}集”。
2. 不得少集,不得多集,不得把多集内容合并成一集。
3. 每集必须保留 {min_lines}-{max_lines} 行动作或台词;集标题、场志、人物行不计入行数。
4. 保持已有主线、主要人物、主要场景和已写出的关键反转。
5. 如果缺少某一集,请根据前后剧情补写完整一集;如果多出无效内容,请删除或合并到正确集内。
6. 不要解释,不要 Markdown 代码块,不要输出标题以外的说明文字。
7. 动作必须以 `<action>` 开头,台词格式保持“角色:台词”或“角色(情绪):台词”。
【待修复剧本】
{script_text}
请只输出修复后的完整剧本文本。
video-claw/video-claw/backend/prompts/setting/eval_setting_zh.txt
@@ -12,7 +12,6 @@
4. 出现无关主角或大量无关人物,导致场景资产不可复用;如果描述明确需要空场景,则人物出现属于硬性失败。
5. 出现文字、水印、标签、标注线、说明文字或明显UI元素。
6. 图片严重模糊、过曝、过暗、透视严重崩坏或低清,无法看清场景结构。
7. 出现国旗、国徽、政治标语、政治人物画像、政党或政府宣传海报、竞选/游行标识等政治敏感元素。
若没有硬性失败项,再评估【软性维度】并给出1-10分。软性问题可以扣分,但不应单独导致不合格。
video-claw/video-claw/backend/prompts/setting/setting_zh.txt
@@ -1,5 +1,4 @@
全景远景,平视广角镜头,{style},电影级构图,杰作,高画质。
场景描述: {name} — {desc}
画面主体区域绝对禁止出现人物、动物或其他活体。
画面中禁止出现国旗、国徽、政治标语、政治人物画像、政党或政府宣传海报、竞选/游行标识等政治敏感元素。
环境必须保持干净、整洁、朴素或华丽皆可,但绝对禁止任何肮脏、混乱、恶心、血腥或破败的凌乱元素,确保环境布景完整、构图平衡。