| | |
| | | self._check_cancel() |
| | | |
| | | style_prompt = self._get_style_prompt(style) |
| | | full_prompt = ( |
| | | f"{style_prompt}, masterpiece, cinematic composition, " |
| | | f"best quality, high resolution, " |
| | | f"{first_frame_prompt}" |
| | | ) |
| | | full_prompt = f"{style_prompt}, {first_frame_prompt}" |
| | | |
| | | save_path = self._next_version_path(sid, segment_id) |
| | | save_dir = os.path.dirname(save_path) |
| | |
| | | |
| | | # ─── 构建最终 payload ─── |
| | | |
| | | def _build_payload(self, sid: str, segments: list, session_data: dict = None) -> dict: |
| | | def _build_payload(self, sid: str, segments: list, session_data: dict = None, prompts_map: dict = None, selected_images: dict = None) -> dict: |
| | | """构建最终 payload""" |
| | | scenes = [] |
| | | if prompts_map is None: |
| | | prompts_map = {} |
| | | if selected_images is None: |
| | | selected_images = {} |
| | | |
| | | # 建立 scene_id 到 selected 路径的映射 |
| | | selected_map = {} |
| | | existing_prompts = {} |
| | | if session_data and "artifacts" in session_data: |
| | | ref_gen = session_data["artifacts"].get("reference_generation", {}) |
| | | for scene in ref_gen.get("scenes", []): |
| | | sid_in_json = scene.get("id") |
| | | if sid_in_json: |
| | | selected_map[sid_in_json] = scene.get("selected", "") |
| | | existing_prompts[sid_in_json] = scene.get("visual_prompt", "") |
| | | |
| | | for idx, seg in enumerate(segments, 1): |
| | | segment_id = seg.get('segment_id', f'seg_unk_{idx}') |
| | | versions = self._list_versions(sid, segment_id) |
| | | |
| | | # 优先从 artifacts 中读取 selected 字段 |
| | | selected_path = selected_map.get(segment_id) |
| | | # 优先从本轮生成的 selected_images 中读取,如果找不到,再从 session 的 artifacts 中读取 selected 字段 |
| | | selected_path = selected_images.get(segment_id) |
| | | if not selected_path: |
| | | selected_path = selected_map.get(segment_id) |
| | | if not selected_path: |
| | | selected_path = versions[-1] if versions else "" |
| | | |
| | | # 获取该段下第一个镜头的 content 作为片段描述 |
| | | shots_summary = seg.get('shots', [])[0].get('content', '') if seg.get('shots') else "" |
| | | |
| | | # 取提示词 |
| | | visual_prompt = prompts_map.get(segment_id) or existing_prompts.get(segment_id) or "" |
| | | |
| | | # status: 有图片=done, 无图片=pending(待生成) |
| | | status = "done" if versions else "pending" |
| | |
| | | "name": f"第{seg.get('episode_number', 1)}集-片段{seg.get('segment_number', idx)}", |
| | | "index": idx, |
| | | "description": shots_summary, |
| | | "visual_prompt": visual_prompt, |
| | | "selected": selected_path, |
| | | "versions": versions, |
| | | "status": status, |
| | |
| | | session_data = json.load(f) |
| | | |
| | | artifacts = session_data.get("artifacts", {}) |
| | | |
| | | # 提取已经存在于 session 中的 visual_prompts |
| | | session_visual_prompts = {} |
| | | ref_gen = artifacts.get("reference_generation", {}) |
| | | for scene in ref_gen.get("scenes", []): |
| | | sid_in_json = scene.get("id") |
| | | vp = scene.get("visual_prompt") |
| | | if sid_in_json and vp: |
| | | session_visual_prompts[sid_in_json] = vp |
| | | |
| | | img_client = ImageClient( |
| | | dashscope_api_key=settings.DASHSCOPE_API_KEY, |
| | |
| | | plot = first_shot.get('content', '') |
| | | char_desc, set_desc = self._get_descriptions(seg, char_id_map, setting_id_map, character_json) |
| | | |
| | | ff_prompt_tpl = load_prompt('reference', 'first_frame', 'zh' if is_zh else 'en') |
| | | ff_prompt_resp = self._cancellable_query( |
| | | llm, |
| | | prompt=ff_prompt_tpl.format( |
| | | original_text=script_json.get("original_text", ""), |
| | | plot=plot, |
| | | character_description=char_desc, |
| | | setting_description=set_desc |
| | | ), |
| | | model=llm_model |
| | | ) |
| | | if hasattr(ff_prompt_resp, 'content'): |
| | | ff_prompt = ff_prompt_resp.content.strip() |
| | | existing_vp = session_visual_prompts.get(segment_id) |
| | | if existing_vp: |
| | | ff_prompt = existing_vp |
| | | logger.info(f"[{segment_id}] 重新生成时命中已有提示词,复用原提示词...") |
| | | else: |
| | | ff_prompt = str(ff_prompt_resp).strip() |
| | | ff_prompt_tpl = load_prompt('reference', 'first_frame', 'zh' if is_zh else 'en') |
| | | ff_prompt_resp = self._cancellable_query( |
| | | llm, |
| | | prompt=ff_prompt_tpl.format( |
| | | original_text=script_json.get("original_text", ""), |
| | | plot=plot, |
| | | character_description=char_desc, |
| | | setting_description=set_desc |
| | | ), |
| | | model=llm_model |
| | | ) |
| | | if hasattr(ff_prompt_resp, 'content'): |
| | | ff_prompt = ff_prompt_resp.content.strip() |
| | | else: |
| | | ff_prompt = str(ff_prompt_resp).strip() |
| | | |
| | | prompt_map[segment_id] = ff_prompt |
| | | |
| | | logger.info(f"[{segment_id}] first-frame prompt: {ff_prompt}...") |
| | |
| | | await loop.run_in_executor(None, regen_run) |
| | | |
| | | self._report_progress("参考图", "完成", 100) |
| | | return self._build_payload(sid, fresh_segments, session_data) |
| | | return self._build_payload(sid, fresh_segments, session_data, prompt_map, selected_images) |
| | | |
| | | # ═══ 正常流程:全量生成 ═══ |
| | | self._report_progress("参考图", "加载分镜数据...", 5) |
| | |
| | | self._report_progress("参考图", "加载分镜列表", 8, data={"assets_preview": {"scenes": preview}}) |
| | | |
| | | llm = LLM() |
| | | first_frame_prompts = {} # 提升作用域,用于最后写回结果文件 |
| | | selected_images_map = {} # 提升作用域,记录本轮新生成且 VLM 挑选出来的图片路径 |
| | | |
| | | def run(): |
| | | nonlocal first_frame_prompts |
| | | nonlocal selected_images_map |
| | | # 筛选需要生成的(跳过已有图的) |
| | | pending_segments = [] |
| | | selected_images = {} |
| | | for seg in segments: |
| | | segment_id = seg['segment_id'] |
| | | existing = self._list_versions(sid, segment_id) |
| | |
| | | # 步骤2-6(每片段):流式生成提示词并立即开始图像生成 |
| | | self._report_progress("参考图", "开始生成...", calc_pct(0)) |
| | | |
| | | first_frame_prompts = {} # 用于最后写回结果文件 |
| | | |
| | | with ThreadPoolExecutor(max_workers=concurrency) as executor: |
| | | futs = {} |
| | | done = 0 |
| | |
| | | first_shot = seg.get('shots', [])[0] if seg.get('shots') else {} |
| | | plot = first_shot.get('content', '') |
| | | char_desc, set_desc = self._get_descriptions(seg, char_id_map, setting_id_map, character_json) |
| | | ff_prompt_tpl = load_prompt('reference', "first_frame", 'zh' if is_zh else 'en') |
| | | |
| | | try: |
| | | ff_prompt_resp = self._cancellable_query( |
| | | llm, |
| | | prompt=ff_prompt_tpl.format( |
| | | original_text=script_json.get("original_text", ""), |
| | | plot=plot, |
| | | character_description=char_desc, |
| | | setting_description=set_desc |
| | | ), |
| | | model=llm_model |
| | | ) |
| | | if hasattr(ff_prompt_resp, 'content'): |
| | | ff_prompt = ff_prompt_resp.content.strip() |
| | | else: |
| | | ff_prompt = str(ff_prompt_resp).strip() |
| | | except Exception as e: |
| | | logger.error(f"Error generating first-frame prompt for {segment_id}: {e}") |
| | | ff_prompt = plot[:200] |
| | | existing_vp = session_visual_prompts.get(segment_id) |
| | | if existing_vp: |
| | | ff_prompt = existing_vp |
| | | logger.info(f"[{segment_id}] 命中已有提示词,复用原提示词...") |
| | | else: |
| | | ff_prompt_tpl = load_prompt('reference', "first_frame", 'zh' if is_zh else 'en') |
| | | try: |
| | | ff_prompt_resp = self._cancellable_query( |
| | | llm, |
| | | prompt=ff_prompt_tpl.format( |
| | | original_text=script_json.get("original_text", ""), |
| | | plot=plot, |
| | | character_description=char_desc, |
| | | setting_description=set_desc |
| | | ), |
| | | model=llm_model |
| | | ) |
| | | if hasattr(ff_prompt_resp, 'content'): |
| | | ff_prompt = ff_prompt_resp.content.strip() |
| | | else: |
| | | ff_prompt = str(ff_prompt_resp).strip() |
| | | except Exception as e: |
| | | logger.error(f"Error generating first-frame prompt for {segment_id}: {e}") |
| | | ff_prompt = plot[:200] |
| | | |
| | | first_frame_prompts[segment_id] = ff_prompt |
| | | logger.info(f"[{segment_id}] Prompt ready, starting image generation...") |
| | |
| | | pct = calc_pct(step) |
| | | |
| | | if result_path: |
| | | selected_images[segment_id_done] = result_path |
| | | selected_images_map[segment_id_done] = result_path |
| | | versions = self._list_versions(sid, segment_id_done) |
| | | self._report_progress("参考图", f"完成: {segment_id_done}", pct, data={ |
| | | "asset_complete": { |
| | |
| | | if "cancel" in str(e).lower(): |
| | | logger.info("ReferenceGeneratorAgent: 用户取消,返回已完成部分结果") |
| | | self._report_progress("参考图", "已取消(保留已完成图片)", 100) |
| | | return self._build_payload(sid, segments, session_data) |
| | | return self._build_payload(sid, segments, session_data, first_frame_prompts, selected_images_map) |
| | | raise |
| | | |
| | | self._report_progress("参考图", "完成", 100) |
| | | return self._build_payload(sid, segments, session_data) |
| | | return self._build_payload(sid, segments, session_data, first_frame_prompts, selected_images_map) |
| | |
| | | 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( |
| | |
| | | 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) |
| | | _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] Full script generated ({len(full_script_text)} chars)") |
| | | _log_progress(40, "原稿生成完成,正在提取人物/场景信息...") |
| | | logger.info(f"[ScriptWriter] Initial script generated ({len(full_script_text)} chars)") |
| | | |
| | | _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 |
| | | ) + 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)") |
| | | |
| | | _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) |
| | |
| | | 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 |
| | |
| | | |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | # ─── 幕名 ─── |
| | | ACT_NAMES = {1: "激励事件", 2: "进入新世界", 3: "灵魂黑夜", 4: "高潮决战"} |
| | | |
| | | def _get_shot_prompt(lang: str = "zh") -> str: |
| | | from prompts.loader import load_prompt_with_fallback |
| | | return load_prompt_with_fallback("storyboard", "shot", lang, "zh") |
| | |
| | | |
| | | # ─── 提示词组装 ─── |
| | | |
| | | def _assemble_prompt(self, segment: dict, style_prompt: str) -> str: |
| | | def _assemble_prompt(self, segment: dict, style_prompt: str, video_data: Optional[dict]=None) -> str: |
| | | """组装视频提示词 |
| | | 格式: |
| | | 风格控制:用户选择的风格提示词, 电影质感 |
| | | 分镜列表:分镜1:[时长] content... 分镜2:[时长] content... |
| | | """ |
| | | # 如果 video_data 中有 description,则优先使用 |
| | | # 前端修改后的提示词会存入 artifacts.video_generation.clips.description |
| | | if video_data and "description" in video_data: |
| | | return video_data["description"] |
| | | |
| | | # 否则从 segment 中组装 |
| | | prompt = f"风格控制:{style_prompt}\n" |
| | | prompt += "分镜列表:" |
| | | |
| | |
| | | dur = shot.get("duration", 5) |
| | | content = shot.get("content", "").strip() |
| | | prompt += f"\n分镜{i}:[{dur}秒] {content}" |
| | | |
| | | |
| | | prompt += "\n不要生成字幕或水印" |
| | | |
| | | return prompt |
| | | |
| | | def _get_style_keywords(self, session_data: dict) -> str: |
| | |
| | | segments = [] |
| | | for ep in episodes: |
| | | segments.extend(ep.get("segments", [])) |
| | | |
| | | if not segments: |
| | | raise Exception("未找到分镜片段数据,请先完成阶段3") |
| | | |
| | | video_clips = artifacts.get('video_generation', {}).get('clips', []) |
| | | |
| | | # 2. 获取参考图路径映射 (从 Reference Generation) |
| | | ref_art = artifacts.get('reference_generation', {}) |
| | |
| | | if regen_ids: |
| | | self._report_progress("视频生成", "重新生成中...", 5) |
| | | segment_map = {s['segment_id']: s for s in segments} |
| | | clip_map = {c['id']: c for c in video_clips} |
| | | |
| | | def regen_run(): |
| | | done = 0 |
| | |
| | | futs = {} |
| | | for seg_id in regen_ids: |
| | | seg = segment_map.get(seg_id) |
| | | clip = clip_map.get(seg_id) if clip_map.get(seg_id) else None |
| | | if not seg: continue |
| | | prompt = self._assemble_prompt(seg, style_prompt) |
| | | prompt = self._assemble_prompt(seg, style_prompt, video_data=clip) |
| | | |
| | | print("#"*100) |
| | | print(clip) |
| | | print(prompt) |
| | | return |
| | | |
| | | img_path = self._get_reference_image(sid, seg_id, scene_map) |
| | | duration = seg.get("total_duration", 10) |
| | | fut = executor.submit( |
| | |
| | | if not model: |
| | | model = "wan2.7-i2v" |
| | | |
| | | # 确保 duration 是整数,视频模型通常要求整数秒 |
| | | duration = int(duration) |
| | | |
| | | if Config.PRINT_MODEL_INPUT: |
| | | lines = [ |
| | | "---- VIDEO GENERATION REQUEST ----", |