| | |
| | | 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 |
| | |
| | | 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") |
| | | |
| | |
| | | |
| | | 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 |
| | | ) |
| | | |
| | | @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: |
| | |
| | | self._report_progress("剧本生成", msg, pct) |
| | | logger.info(f"[{pct}%] {msg}") |
| | | |
| | | 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 |
| | | |
| | | 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) |
| | | |
| | | 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] 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) |
| | |
| | | script_text=full_script_text, |
| | | dialogue_critique=dialogue_critique, |
| | | plot_critique=plot_critique |
| | | ) + prompt # 将原始生成提示词追加到优化提示词末尾,提供更多上下文信息帮助优化 |
| | | ) |
| | | 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, "最终剧本生成完成,正在提取人物/场景信息...") |
| | | |
| | |
| | | _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) |
| | |
| | | |
| | | 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}", |