Optimized VLM Judge-Refine Cycle
1 files deleted
4 files added
40 files modified
| | |
| | | "CRITICAL": "X", |
| | | } |
| | | |
| | | LEVEL_COLORS = { |
| | | "DEBUG": "\033[90m", |
| | | "INFO": "\033[36m", |
| | | "WARNING": "\033[33m", |
| | | "ERROR": "\033[31m", |
| | | "CRITICAL": "\033[1;37;41m", |
| | | } |
| | | RESET = "\033[0m" |
| | | |
| | | def __init__(self, *args, use_color=False, **kwargs): |
| | | super().__init__(*args, **kwargs) |
| | | self.use_color = use_color |
| | | |
| | | def format(self, record: logging.LogRecord) -> str: |
| | | record.level_icon = self.LEVEL_ICONS.get(record.levelname, record.levelname[:1]) |
| | | if self.use_color: |
| | | color = self.LEVEL_COLORS.get(record.levelname) |
| | | if color: |
| | | record.level_icon = f"{color}{record.level_icon}{self.RESET}" |
| | | record.levelname = f"{color}{record.levelname}{self.RESET}" |
| | | return super().format(record) |
| | | |
| | | |
| | |
| | | console_handler.setFormatter(AIGCFormatter( |
| | | "%(asctime)s | %(level_icon)s %(levelname)-7s | %(name)s:%(lineno)d | %(message)s", |
| | | datefmt="%H:%M:%S", |
| | | use_color=sys.stdout.isatty(), |
| | | )) |
| | | |
| | | listener = QueueListener(log_queue, console_handler, respect_handler_level=True) |
| | |
| | | root_logger.handlers.clear() |
| | | root_logger.addHandler(queue_handler) |
| | | |
| | | for name in ("uvicorn", "uvicorn.error", "uvicorn.access", "httpx"): |
| | | for name in ("uvicorn", "uvicorn.error", "uvicorn.access", "httpx", "httpcore"): |
| | | logger = logging.getLogger(name) |
| | | logger.handlers.clear() |
| | | logger.propagate = True |
| | | logger.setLevel(logging.WARNING if name == "httpx" else level) |
| | | logger.setLevel(logging.WARNING if name in {"httpx", "httpcore"} else level) |
| | | apply_access_log_setting() |
| | | |
| | | _listener = listener |
| | |
| | | meta = { |
| | | "idea": final_idea, |
| | | "user_textbox_input": req.idea, |
| | | "style": req.style or "realistic", |
| | | "style": req.style or getattr(settings, "STYLE", None) or "realistic", |
| | | "video_ratio": req.video_ratio or "9:16", |
| | | "video_resolution": req.video_resolution or "720P", |
| | | "expand_idea": req.expand_idea if req.expand_idea is not None else True, |
| | | "llm_model": req.llm_model, |
| | | "vlm_model": req.vlm_model, |
| | |
| | | "image_it2i_model": meta["image_it2i_model"], |
| | | "video_model": meta["video_model"], |
| | | "episodes": meta["episodes"], |
| | | "video_ratio": req.video_ratio, |
| | | "video_ratio": meta["video_ratio"], |
| | | "video_resolution": meta["video_resolution"], |
| | | } |
| | | } |
| | | |
| | |
| | | if not state: |
| | | raise HTTPException(404, "Session not found") |
| | | body = await request.json() |
| | | allowed_keys = ("llm_model", "vlm_model", "image_t2i_model", "image_it2i_model", "video_model", "video_ratio", "enable_concurrency") |
| | | allowed_keys = ("llm_model", "vlm_model", "image_t2i_model", "image_it2i_model", "video_model", "video_ratio", "video_resolution", "style", "enable_concurrency") |
| | | if not state.meta: |
| | | state.meta = {} |
| | | for k in allowed_keys: |
| | |
| | | video_model: str |
| | | duration: int = 5 |
| | | video_ratio: str = "9:16" |
| | | video_resolution: Optional[str] = None |
| | | resolution: Optional[str] = None |
| | | negative_prompt: Optional[str] = None |
| | | watermark: Optional[bool] = None |
| | |
| | | video_model: str |
| | | duration: int = 5 |
| | | video_ratio: str = "9:16" |
| | | video_resolution: Optional[str] = None |
| | | resolution: Optional[str] = None |
| | | tts_voice: str = "zh-CN-YunjianNeural" |
| | | tts_speed: float = 1.2 |
| | |
| | | class ProjectStartRequest(BaseModel): |
| | | idea: str |
| | | file_path: Optional[str] = None |
| | | style: Optional[str] = "realistic" |
| | | style: Optional[str] = None |
| | | video_ratio: Optional[str] = "9:16" |
| | | video_resolution: Optional[str] = "720P" |
| | | expand_idea: Optional[bool] = True |
| | | llm_model: Optional[str] = None |
| | | vlm_model: Optional[str] = None |
| | |
| | | "image_it2i": "doubao-seedream-5-0-260128", |
| | | "image_t2i": "doubao-seedream-5-0-260128", |
| | | "video": "wan2.7-i2v", |
| | | "video_ratio": "16:9", |
| | | "eval": "qwen3.5-plus", |
| | | }, |
| | | "generation": { |
| | | "style": "realistic", |
| | | "video_ratio": "16:9", |
| | | "video_resolution": "720P", |
| | | }, |
| | | } |
| | | |
| | |
| | | clean = _deep_merge(DEFAULT_CONFIG, data) |
| | | clean.pop("llm", None) |
| | | |
| | | legacy_models = data.get("models", {}) if isinstance(data, dict) else {} |
| | | if isinstance(legacy_models, dict): |
| | | for legacy_key in ("style", "video_ratio", "video_resolution"): |
| | | if legacy_key in legacy_models and not _get(data, f"generation.{legacy_key}"): |
| | | clean.setdefault("generation", {})[legacy_key] = legacy_models[legacy_key] |
| | | clean["models"].pop(legacy_key, None) |
| | | |
| | | server = clean["server"] |
| | | server["host"] = str(server.get("host") or DEFAULT_CONFIG["server"]["host"]) |
| | | try: |
| | |
| | | value[sub_key] = "" if sub_value is None else str(sub_value) |
| | | else: |
| | | clean["models"][key] = "" if value is None else str(value) |
| | | |
| | | for key, value in clean["generation"].items(): |
| | | clean["generation"][key] = "" if value is None else str(value) |
| | | |
| | | for provider, values in clean["api_providers"].items(): |
| | | if provider == "common": |
| | |
| | | IMAGE_IT2I_MODEL = _get(CONFIG, "models.image_it2i") |
| | | IMAGE_T2I_MODEL = _get(CONFIG, "models.image_t2i") |
| | | VIDEO_MODEL = _get(CONFIG, "models.video") |
| | | VIDEO_RATIO = _get(CONFIG, "models.video_ratio") |
| | | VIDEO_RATIO = _get(CONFIG, "generation.video_ratio") |
| | | VIDEO_RESOLUTION = _get(CONFIG, "generation.video_resolution") |
| | | STYLE = _get(CONFIG, "generation.style") |
| | | EVAL_MODEL = _get(CONFIG, "models.eval") |
| | | |
| | | BASE_DIR = str(BASE_DIR) |
| | |
| | | cls.IMAGE_IT2I_MODEL = _get(clean, "models.image_it2i") |
| | | cls.IMAGE_T2I_MODEL = _get(clean, "models.image_t2i") |
| | | cls.VIDEO_MODEL = _get(clean, "models.video") |
| | | cls.VIDEO_RATIO = _get(clean, "models.video_ratio") |
| | | cls.VIDEO_RATIO = _get(clean, "generation.video_ratio") |
| | | cls.VIDEO_RESOLUTION = _get(clean, "generation.video_resolution") |
| | | cls.STYLE = _get(clean, "generation.style") |
| | | cls.EVAL_MODEL = _get(clean, "models.eval") |
| | | return cls.as_dict() |
| | | |
| | |
| | | image_it2i: doubao-seedream-5-0-260128 |
| | | image_t2i: doubao-seedream-5-0-260128 |
| | | video: wan2.7-i2v |
| | | video_ratio: '16:9' |
| | | eval: qwen3.5-plus |
| | | generation: |
| | | style: realistic |
| | | video_ratio: '16:9' |
| | | video_resolution: 720P |
| | |
| | | with open(session_file, 'r', encoding='utf-8') as f: |
| | | session_data = json.load(f) |
| | | |
| | | session_meta = session_data.get("meta") |
| | | if not isinstance(session_meta, dict): |
| | | session_meta = {} |
| | | |
| | | # 基础参数列表 |
| | | keys_to_merge = [ |
| | | "style", "video_ratio", "llm_model", "vlm_model", |
| | | "idea", "user_textbox_input", "style", "video_ratio", "video_resolution", |
| | | "llm_model", "vlm_model", |
| | | "image_t2i_model", "image_it2i_model", "video_model", |
| | | "video_style", "expand_idea", "enable_concurrency" |
| | | "video_style", "expand_idea", "enable_concurrency", "web_search", "episodes" |
| | | ] |
| | | |
| | | merged_data = input_data.copy() |
| | | for key in keys_to_merge: |
| | | # 只有当 input_data 中缺失该参数时,才从 session 中补齐 |
| | | if key not in merged_data or not merged_data[key]: |
| | | if key in session_data: |
| | | if key in session_meta and session_meta[key] is not None: |
| | | merged_data[key] = session_meta[key] |
| | | elif key in session_data and session_data[key] is not None: |
| | | # 兼容旧会话:旧版本把生成参数保存在根字段。 |
| | | merged_data[key] = session_data[key] |
| | | |
| | | return merged_data |
| | |
| | | # 替换场景信息 |
| | | return template.format(name=name, desc=desc, style=style) |
| | | |
| | | @staticmethod |
| | | def _apply_eval_feedback_to_prompt(base_prompt: str, eval_result: dict, iteration: int) -> str: |
| | | suggested_prompt = (eval_result.get('suggested_prompt') or '').strip() |
| | | if suggested_prompt: |
| | | return suggested_prompt |
| | | |
| | | hard_failures = eval_result.get('hard_failures') or [] |
| | | soft_issues = eval_result.get('soft_issues') or [] |
| | | issues = eval_result.get('issues') or [] |
| | | suggestion = (eval_result.get('suggestion') or '').strip() |
| | | |
| | | feedback_lines = [] |
| | | if hard_failures: |
| | | feedback_lines.append("硬性失败项:" + ";".join(map(str, hard_failures))) |
| | | if issues: |
| | | feedback_lines.append("主要问题:" + ";".join(map(str, issues))) |
| | | if soft_issues: |
| | | feedback_lines.append("软性问题:" + ";".join(map(str, soft_issues))) |
| | | if suggestion: |
| | | feedback_lines.append("修改建议:" + suggestion) |
| | | if not feedback_lines: |
| | | return base_prompt |
| | | |
| | | return ( |
| | | f"{base_prompt}\n\n" |
| | | f"【第{iteration + 1}轮VLM评估反馈】\n" |
| | | f"上一轮生成未通过评估,请在下一轮生成时优先修正以下问题,同时保持原始角色/场景设定不变:\n" |
| | | + "\n".join(f"- {line}" for line in feedback_lines) |
| | | ) |
| | | |
| | | # ─── 文件管理(基于唯一ID) ─── |
| | | |
| | | @staticmethod |
| | |
| | | # VLM 评估 |
| | | eval_result = self._evaluate_with_vlm(save_path, desc, asset_type, vlm_model) |
| | | |
| | | # 使用固定阈值判断是否接受(8分及以上通过) |
| | | score = eval_result.get('score', 0) |
| | | issues = eval_result.get('issues', []) |
| | | suggestion = eval_result.get('suggestion', '') |
| | | is_acceptable = score >= 8 |
| | | hard_failures = eval_result.get('hard_failures') or [] |
| | | if 'is_acceptable' in eval_result: |
| | | is_acceptable = bool(eval_result.get('is_acceptable')) and not hard_failures |
| | | else: |
| | | is_acceptable = not hard_failures and score >= 7 |
| | | |
| | | if is_acceptable: |
| | | logger.info(f"[{asset_type}] {name} ✓ VLM评估通过 - 评分: {score}/10") |
| | | else: |
| | | logger.warning(f"[{asset_type}] {name} ✗ VLM评估不通过 - 评分: {score}/10") |
| | | logger.warning(f"[{asset_type}] 问题: {issues}") |
| | | if hard_failures: |
| | | logger.warning(f"[{asset_type}] 硬性失败项: {hard_failures}") |
| | | if suggestion: |
| | | logger.warning(f"[{asset_type}] 建议: {suggestion}") |
| | | |
| | |
| | | return asset_id, save_path, eval_result |
| | | else: |
| | | # 评估不通过,记录问题并继续循环 |
| | | current_prompt = self._apply_eval_feedback_to_prompt(base_prompt, eval_result, iteration) |
| | | logger.info(f"[{asset_type}] {name} 下一轮将使用VLM反馈优化提示词") |
| | | # 报告进度 |
| | | self._report_progress("角色设计", f"重新生成中 ({iteration + 2}/{max_iterations}): {name}", 0) |
| | | |
| | |
| | | |
| | | # ─── 单张生成 ─── |
| | | |
| | | @staticmethod |
| | | def _apply_eval_feedback_to_visual_prompt(current_prompt: str, eval_result: dict, version: int) -> str: |
| | | suggested_prompt = (eval_result.get('suggested_prompt') or '').strip() |
| | | if suggested_prompt: |
| | | return suggested_prompt |
| | | |
| | | hard_failures = eval_result.get('hard_failures') or [] |
| | | soft_issues = eval_result.get('soft_issues') or [] |
| | | issues = eval_result.get('issues') or [] |
| | | suggestion = (eval_result.get('suggestion') or '').strip() |
| | | |
| | | feedback_lines = [] |
| | | if hard_failures: |
| | | feedback_lines.append("硬性失败项:" + ";".join(map(str, hard_failures))) |
| | | if issues: |
| | | feedback_lines.append("主要问题:" + ";".join(map(str, issues))) |
| | | if soft_issues: |
| | | feedback_lines.append("软性问题:" + ";".join(map(str, soft_issues))) |
| | | if suggestion: |
| | | feedback_lines.append("修改建议:" + suggestion) |
| | | if not feedback_lines: |
| | | return current_prompt |
| | | |
| | | return ( |
| | | f"{current_prompt}\n\n" |
| | | f"【第{version + 1}轮VLM评估反馈】\n" |
| | | f"上一轮参考图未通过评估,请在下一轮生成时优先修正以下问题;不要改变角色核心外貌和场景核心设定:\n" |
| | | + "\n".join(f"- {line}" for line in feedback_lines) |
| | | ) |
| | | |
| | | def _generate_one(self, img_client, sid: str, segment: dict, |
| | | first_frame_prompt: str, refs: List[str], |
| | | style: str, it2i_model: str, t2i_model: str, |
| | |
| | | max_versions: int = 3) -> tuple: |
| | | """生成单个片段参考图,返回 (segment_id, path_or_None, eval_result) |
| | | |
| | | 最多生成 max_versions 个版本,如果所有版本都没有达到8分, |
| | | 最多生成 max_versions 个版本,如果所有版本都没有达到硬性合格标准, |
| | | 使用 VLM 选择最好的一张作为最终参考图。 |
| | | """ |
| | | segment_id = segment.get('segment_id', '') |
| | | |
| | | # 仅提取第一个镜头的描述作为当前 Plot |
| | | plot = segment.get('shots', [])[0].get('content', '') if segment.get('shots') else "" |
| | | visual_prompt = first_frame_prompt |
| | | current_visual_prompt = first_frame_prompt |
| | | |
| | | # 取消时直接跳过,不抛异常,以保留已生成的部分结果 |
| | | if self.cancellation_check and self.cancellation_check(): |
| | |
| | | self._check_cancel() |
| | | |
| | | style_prompt = self._get_style_prompt(style) |
| | | full_prompt = f"{style_prompt}, {first_frame_prompt}" |
| | | full_prompt = f"{style_prompt}, {current_visual_prompt}" |
| | | |
| | | save_path = self._next_version_path(sid, segment_id) |
| | | save_dir = os.path.dirname(save_path) |
| | |
| | | os.rename(gen, save_path) |
| | | |
| | | # VLM 评估 |
| | | eval_result = self._evaluate_with_vlm(save_path, segment, plot, visual_prompt, |
| | | eval_result = self._evaluate_with_vlm(save_path, segment, plot, current_visual_prompt, |
| | | character_description=character_description, |
| | | setting_description=setting_description, |
| | | vlm_model=vlm_model) |
| | | |
| | | score = eval_result.get('score', 0) |
| | | is_acceptable = score >= 8 |
| | | hard_failures = eval_result.get('hard_failures') or [] |
| | | if 'is_acceptable' in eval_result: |
| | | is_acceptable = bool(eval_result.get('is_acceptable')) and not hard_failures |
| | | else: |
| | | is_acceptable = not hard_failures and score >= 7 |
| | | |
| | | logger.info(f"[{segment_id}] 版本{version + 1}: 评分 {score}/10, {'✓通过' if is_acceptable else '✗不通过'}") |
| | | if hard_failures: |
| | | logger.warning(f"[{segment_id}] 硬性失败项: {hard_failures}") |
| | | |
| | | # 记录版本信息 |
| | | eval_result["final_visual_prompt"] = current_visual_prompt |
| | | all_versions.append(save_path) |
| | | all_eval_results.append(eval_result) |
| | | |
| | | # 如果达到8分,立即返回 |
| | | # 如果 VLM 判定达到硬性标准,立即返回 |
| | | if is_acceptable: |
| | | return segment_id, save_path, eval_result |
| | | |
| | | # 报告进度 |
| | | if version < max_versions - 1: |
| | | current_visual_prompt = self._apply_eval_feedback_to_visual_prompt(current_visual_prompt, eval_result, version) |
| | | logger.info(f"[{segment_id}] 下一轮将使用VLM反馈优化首帧提示词") |
| | | self._report_progress("参考图", f"重新生成中 ({version + 2}/{max_versions}): {segment_id}", 0) |
| | | |
| | | except Exception as e: |
| | | logger.error(f"Segment {segment_id} image generation failed: {e}") |
| | | |
| | | # 所有版本都没有达到8分,使用 VLM 选择最好的 |
| | | # 所有版本都没有达到硬性标准,使用 VLM 选择最好的 |
| | | if all_versions: |
| | | logger.warning(f"[{segment_id}] 所有版本都未达到8分,使用VLM选择最佳...") |
| | | logger.warning(f"[{segment_id}] 所有版本都未达到硬性合格标准,使用VLM选择最佳...") |
| | | best_path, best_eval = self._select_best_with_vlm( |
| | | all_versions, segment, plot, visual_prompt, |
| | | all_versions, segment, plot, current_visual_prompt, |
| | | character_description=character_description, |
| | | setting_description=setting_description, |
| | | vlm_model=vlm_model |
| | | ) |
| | | if best_path: |
| | | if best_path and isinstance(best_eval, dict): |
| | | best_eval["final_visual_prompt"] = current_visual_prompt |
| | | hard_failures = best_eval.get("hard_failures") or [] |
| | | is_acceptable = bool(best_eval.get("is_acceptable")) and not hard_failures |
| | | if is_acceptable: |
| | | return segment_id, best_path, best_eval |
| | | logger.warning( |
| | | "[%s] VLM选择的最佳图仍有硬性失败项,不作为最终参考图: %s", |
| | | segment_id, |
| | | hard_failures or best_eval.get("issues", []), |
| | | ) |
| | | return segment_id, None, best_eval |
| | | |
| | | # 如果没有任何生成成功 |
| | | logger.warning(f"[{segment_id}] 没有成功生成任何图片") |
| | | if all_eval_results and isinstance(all_eval_results[-1], dict): |
| | | all_eval_results[-1]["final_visual_prompt"] = current_visual_prompt |
| | | return segment_id, None, None |
| | | |
| | | def _select_best_with_vlm(self, image_paths: List[str], segment: dict, plot: str, visual_prompt: str, |
| | |
| | | if 0 <= selected_idx < len(image_paths): |
| | | best_path = image_paths[selected_idx] |
| | | logger.info(f"[{segment_id}] VLM选择第{selected_idx + 1}张作为最佳图片") |
| | | hard_failures = selected.get('hard_failures') or [] |
| | | score = selected.get('score', 5) |
| | | # 构建评估结果 |
| | | best_eval = { |
| | | "score": selected.get('score', 5), |
| | | "score": score, |
| | | "hard_failures": hard_failures, |
| | | "soft_issues": selected.get('soft_issues', []), |
| | | "issues": selected.get('issues', []), |
| | | "is_acceptable": True, |
| | | "is_acceptable": not hard_failures and score >= 7, |
| | | "selected_by_vlm": True, |
| | | "reason": selected.get('reason', '') |
| | | } |
| | |
| | | except Exception as e: |
| | | logger.error(f"[{segment_id}] VLM选择最佳图片失败: {e}") |
| | | |
| | | # 如果失败,返回第一个版本 |
| | | return image_paths[0], {"score": 5, "issues": [], "selected_by_vlm": False} |
| | | # 如果失败,不要把未通过硬性校验的图片静默标记为可用。 |
| | | return image_paths[0], { |
| | | "score": 0, |
| | | "hard_failures": ["VLM选择最佳图片失败,无法确认硬性标准"], |
| | | "issues": ["VLM选择最佳图片失败"], |
| | | "is_acceptable": False, |
| | | "selected_by_vlm": False, |
| | | } |
| | | |
| | | def _evaluate_with_vlm(self, image_path: str, segment: dict, plot: str, visual_prompt: str, |
| | | character_description: str = "", setting_description: str = "", |
| | |
| | | except: |
| | | pass |
| | | |
| | | return {"score": 5, "issues": ["评估解析失败"], "is_acceptable": True} |
| | | return { |
| | | "score": 0, |
| | | "hard_failures": ["VLM评估解析失败,无法确认硬性标准"], |
| | | "issues": ["评估解析失败"], |
| | | "is_acceptable": False, |
| | | } |
| | | |
| | | except Exception as e: |
| | | logger.warning(f"VLM evaluation failed: {e}") |
| | | return {"score": 5, "issues": [str(e)], "is_acceptable": True} |
| | | return { |
| | | "score": 0, |
| | | "hard_failures": ["VLM评估失败,无法确认硬性标准"], |
| | | "issues": [str(e)], |
| | | "is_acceptable": False, |
| | | } |
| | | |
| | | # ─── 构建最终 payload ─── |
| | | |
| | |
| | | |
| | | fresh_segment_map = {s['segment_id']: s for s in fresh_segments} |
| | | |
| | | llm = LLM() |
| | | |
| | | selected_images = {} |
| | | prompt_map = {} # segment_id → first_frame_prompt |
| | | |
| | |
| | | def calc_pct_regen(step: int) -> int: |
| | | return min(2 + int(98 * step / total_steps), 100) |
| | | |
| | | # 根据最新的 Segment 生成对应的 visual_prompt |
| | | for i, segment_id in enumerate(regen_scenes): |
| | | def regen_segment_run(segment_id: str, index: int): |
| | | seg = fresh_segment_map.get(segment_id, {}) |
| | | |
| | | # 提取第一个分镜的剧情供首帧提示词使用(视频首帧应基于片段起点) |
| | | 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) |
| | |
| | | logger.info(f"[{segment_id}] 重新生成时命中已有提示词,复用原提示词...") |
| | | else: |
| | | ff_prompt_tpl = load_prompt('reference', 'first_frame', 'zh' if is_zh else 'en') |
| | | try: |
| | | local_llm = LLM() |
| | | ff_prompt_resp = self._cancellable_query( |
| | | llm, |
| | | local_llm, |
| | | prompt=ff_prompt_tpl.format( |
| | | original_text=script_json.get("original_text", ""), |
| | | plot=plot, |
| | |
| | | ff_prompt = ff_prompt_resp.content.strip() |
| | | else: |
| | | ff_prompt = str(ff_prompt_resp).strip() |
| | | |
| | | prompt_map[segment_id] = ff_prompt |
| | | except Exception as e: |
| | | logger.error(f"Error generating first-frame prompt for {segment_id}: {e}") |
| | | ff_prompt = plot[:200] |
| | | |
| | | logger.info(f"[{segment_id}] first-frame prompt: {ff_prompt}...") |
| | | self._report_progress("参考图", f"准备提示词: {segment_id}", calc_pct_regen(i * steps_per_segment + 1)) |
| | | self._report_progress("参考图", f"准备提示词: {segment_id}", calc_pct_regen(index * steps_per_segment + 1)) |
| | | |
| | | # 并发生成图像 |
| | | self._report_progress("参考图", "生成参考图...", calc_pct_regen(total * 2)) |
| | | with ThreadPoolExecutor(max_workers=concurrency) as executor: |
| | | futs = {} |
| | | for segment_id in regen_scenes: |
| | | seg = fresh_segment_map.get(segment_id, {}) |
| | | refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map) |
| | | char_desc, set_desc = self._get_descriptions( |
| | | seg, char_id_map, setting_id_map, character_json |
| | | ) |
| | | fut = executor.submit( |
| | | self._generate_one, img_client, sid, |
| | | seg, prompt_map[segment_id], refs, |
| | | result_segment_id, result_path, eval_result = self._generate_one( |
| | | img_client, sid, |
| | | seg, ff_prompt, refs, |
| | | style, it2i, t2i, video_ratio, resolution, vlm_model, |
| | | character_description=char_desc, setting_description=set_desc |
| | | ) |
| | | final_prompt = ff_prompt |
| | | if isinstance(eval_result, dict): |
| | | final_prompt = eval_result.get("final_visual_prompt") or ff_prompt |
| | | return result_segment_id, result_path, eval_result, final_prompt |
| | | |
| | | # 并发生成提示词与图像 |
| | | self._report_progress("参考图", "生成参考图...", calc_pct_regen(total * 2)) |
| | | with ThreadPoolExecutor(max_workers=concurrency) as executor: |
| | | futs = {} |
| | | for i, segment_id in enumerate(regen_scenes): |
| | | fut = executor.submit(regen_segment_run, segment_id, i) |
| | | futs[fut] = segment_id |
| | | for fut in as_completed(futs): |
| | | segment_id_done = futs[fut] |
| | | try: |
| | | _, result_path, eval_result = fut.result() |
| | | _, result_path, eval_result, ff_prompt = fut.result() |
| | | prompt_map[segment_id_done] = ff_prompt |
| | | except Exception as e: |
| | | logger.error(f"Regen future error for {segment_id_done}: {e}") |
| | | result_path = None |
| | |
| | | preview = self._build_preview(sid, segments, session_data) |
| | | self._report_progress("参考图", "加载分镜列表", 8, data={"assets_preview": {"scenes": preview}}) |
| | | |
| | | llm = LLM() |
| | | first_frame_prompts = {} # 提升作用域,用于最后写回结果文件 |
| | | selected_images_map = {} # 提升作用域,记录本轮新生成且 VLM 挑选出来的图片路径 |
| | | |
| | |
| | | futs = {} |
| | | done = 0 |
| | | |
| | | for i, seg in enumerate(pending_segments): |
| | | def segment_run(seg: dict, index: int): |
| | | segment_id = seg['segment_id'] |
| | | |
| | | # 1. 准备该片段的视觉提示词(基于片段的第一个分镜) |
| | | self._report_progress("参考图", f"正在启动: {segment_id}", calc_pct(index * steps_per_segment), data={ |
| | | "asset_complete": { |
| | | "type": "scenes", "id": segment_id, |
| | | "status": "running" |
| | | } |
| | | }) |
| | | |
| | | 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) |
| | |
| | | else: |
| | | ff_prompt_tpl = load_prompt('reference', "first_frame", 'zh' if is_zh else 'en') |
| | | try: |
| | | local_llm = LLM() |
| | | ff_prompt_resp = self._cancellable_query( |
| | | llm, |
| | | local_llm, |
| | | prompt=ff_prompt_tpl.format( |
| | | original_text=script_json.get("original_text", ""), |
| | | plot=plot, |
| | |
| | | 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...") |
| | | |
| | | # 2. 发送任务开始状态 (Running),以便前端 UI 立即显示加载状态 |
| | | self._report_progress("参考图", f"正在启动: {segment_id}", calc_pct(i * steps_per_segment), data={ |
| | | "asset_complete": { |
| | | "type": "scenes", "id": segment_id, |
| | | "status": "running" |
| | | } |
| | | }) |
| | | |
| | | # 3. 立即提交图像生成任务,不再等待其他片段的提示词 |
| | | refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map) |
| | | char_desc, set_desc = self._get_descriptions(seg, char_id_map, setting_id_map, character_json) |
| | | fut = executor.submit( |
| | | self._generate_one, img_client, sid, |
| | | result_segment_id, result_path, eval_result = self._generate_one( |
| | | img_client, sid, |
| | | seg, ff_prompt, refs, |
| | | style, it2i, t2i, video_ratio, resolution, vlm_model, |
| | | character_description=char_desc, setting_description=set_desc |
| | | ) |
| | | futs[fut] = segment_id |
| | | final_prompt = ff_prompt |
| | | if isinstance(eval_result, dict): |
| | | final_prompt = eval_result.get("final_visual_prompt") or ff_prompt |
| | | return result_segment_id, result_path, eval_result, final_prompt |
| | | |
| | | # 报告进度(提交任务也算一点进度) |
| | | for i, seg in enumerate(pending_segments): |
| | | segment_id = seg['segment_id'] |
| | | fut = executor.submit(segment_run, seg, i) |
| | | futs[fut] = segment_id |
| | | self._report_progress("参考图", f"等待生成: {segment_id}", calc_pct(i * steps_per_segment)) |
| | | |
| | | # 4. 等待所有任务完成 |
| | |
| | | for fut in as_completed(futs): |
| | | segment_id_done = futs[fut] |
| | | try: |
| | | _, result_path, eval_result = fut.result() |
| | | _, result_path, eval_result, ff_prompt = fut.result() |
| | | first_frame_prompts[segment_id_done] = ff_prompt |
| | | except Exception as e: |
| | | logger.error(f"Image future error for {segment_id_done}: {e}") |
| | | result_path = None |
| | |
| | | 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 |
| | | ) |
| | | |
| | | 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 |
| | | |
| | | # 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, "初稿") |
| | | |
| | | _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, "优化后") |
| | | |
| | | _log_progress(60, "最终剧本生成完成,正在提取人物/场景信息...") |
| | | |
| | |
| | | |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | def _get_shot_prompt(lang: str = "zh") -> str: |
| | | def _get_storyboard_prompt(name: str, lang: str = "zh") -> str: |
| | | from prompts.loader import load_prompt_with_fallback |
| | | return load_prompt_with_fallback("storyboard", "shot", lang, "zh") |
| | | return load_prompt_with_fallback("storyboard", name, lang, "zh") |
| | | |
| | | class StoryboardAgent(AgentInterface): |
| | | def __init__(self): |
| | | super().__init__(name="Storyboard") |
| | | |
| | | MIN_SHOT_DURATION = 3 |
| | | MIN_SHOT_DURATION = 2 |
| | | MIN_SEGMENT_DURATION = 5 |
| | | MAX_SEGMENT_DURATION = 15 |
| | | OPENING_SHOT_TYPES = {"中景", "全景"} |
| | |
| | | result = json.loads(m.group()) |
| | | if isinstance(result, list): return result |
| | | except json.JSONDecodeError: pass |
| | | return None |
| | | |
| | | @staticmethod |
| | | def _extract_json_object(text: str) -> Optional[dict]: |
| | | text = text.strip() |
| | | text = re.sub(r"^```(?:json)?\s*", "", text) |
| | | text = re.sub(r"\s*```$", "", text) |
| | | try: |
| | | result = json.loads(text) |
| | | if isinstance(result, dict): |
| | | return result |
| | | except json.JSONDecodeError: |
| | | pass |
| | | start = text.find("{") |
| | | end = text.rfind("}") |
| | | if start >= 0 and end > start: |
| | | try: |
| | | result = json.loads(text[start:end + 1]) |
| | | if isinstance(result, dict): |
| | | return result |
| | | except json.JSONDecodeError: |
| | | pass |
| | | return None |
| | | |
| | | @staticmethod |
| | |
| | | return speaker, tone, dialogue |
| | | |
| | | @classmethod |
| | | def _duration_for_script_unit(cls, text: str, is_dialogue: bool) -> int: |
| | | if not is_dialogue: |
| | | return 2 |
| | | dialogue = cls._dialogue_parts(text) |
| | | dialogue_text = dialogue[2] if dialogue else text |
| | | visible_text = re.sub(r"\s+", "", dialogue_text) |
| | | duration = (len(visible_text) + 4) // 5 |
| | | return max(2, min(15, duration)) |
| | | |
| | | @classmethod |
| | | def _is_entry_action(cls, text: str, character_names: List[str]) -> bool: |
| | | if cls._dialogue_parts(text): |
| | | return False |
| | | if character_names and not cls._match_characters(text, character_names): |
| | | return False |
| | | return bool(re.search( |
| | | r"(走进|走入|进入|进来|推门而入|推门进|冲进|闯进|踏进|来到|回到|走向(?:教室|办公室|会议室|厕所|房间|门口))", |
| | | text, |
| | | )) |
| | | |
| | | @classmethod |
| | | def _annotate_episode_script( |
| | | cls, |
| | | script_text: str, |
| | | characters: List[dict], |
| | | settings: List[dict], |
| | | ) -> Tuple[str, List[dict]]: |
| | | character_names = cls._character_names(characters) |
| | | setting_names = cls._setting_names(settings) |
| | | raw_lines = script_text.replace("\r\n", "\n").split("\n") |
| | | |
| | | annotated_lines: List[str] = [] |
| | | units: List[dict] = [] |
| | | current_location = setting_names[0] if setting_names else "" |
| | | scene_characters: List[str] = [] |
| | | scene_key = 0 |
| | | |
| | | for line_number, raw_line in enumerate(raw_lines, 1): |
| | | stripped = raw_line.strip() |
| | | line = cls._clean_script_line(cls._strip_markup(stripped)) |
| | | if not line: |
| | | continue |
| | | if cls._is_metadata_line(line) or cls._is_end_marker(line): |
| | | annotated_lines.append(line) |
| | | continue |
| | | |
| | | header_location = cls._parse_scene_header(stripped, setting_names) |
| | | if header_location: |
| | | scene_key += 1 |
| | | current_location = header_location |
| | | scene_characters = cls._match_characters(line, character_names) |
| | | annotated_lines.append(cls._strip_markup(stripped)) |
| | | continue |
| | | |
| | | if re.match(r"^人物[::]", line): |
| | | scene_characters = cls._match_characters(line, character_names) |
| | | annotated_lines.append(line) |
| | | continue |
| | | |
| | | dialogue = cls._dialogue_parts(line) |
| | | is_action = bool(re.match(r"^<action>", stripped, flags=re.I)) or bool(re.search(r"</action>$", stripped, flags=re.I)) |
| | | if not dialogue and not is_action: |
| | | annotated_lines.append(line) |
| | | continue |
| | | |
| | | unit_id = f"U{len(units) + 1:03d}" |
| | | is_dialogue = dialogue is not None |
| | | duration = cls._duration_for_script_unit(line, is_dialogue) |
| | | matched_chars = cls._match_characters(line, character_names) |
| | | unit_chars = matched_chars[:] |
| | | speaker = "" |
| | | tone = "" |
| | | if dialogue: |
| | | speaker, tone, _ = dialogue |
| | | speaker_matches = cls._match_characters(speaker, character_names) |
| | | if speaker_matches: |
| | | unit_chars = list(dict.fromkeys(speaker_matches + unit_chars)) |
| | | |
| | | units.append({ |
| | | "unit_id": unit_id, |
| | | "line_number": line_number, |
| | | "text": line, |
| | | "duration": duration, |
| | | "is_dialogue": is_dialogue, |
| | | "speaker": speaker, |
| | | "tone": tone, |
| | | "characters": unit_chars, |
| | | "scene_characters": scene_characters[:], |
| | | "scene_key": scene_key, |
| | | "location": cls._resolve_location(line, current_location, setting_names), |
| | | "is_entry": cls._is_entry_action(line, character_names), |
| | | }) |
| | | annotated_lines.append(f"[{duration}秒][{unit_id}] {line}") |
| | | |
| | | return "\n".join(annotated_lines), units |
| | | |
| | | @classmethod |
| | | def _segment_plan_from_units(cls, ep_n: int, segment_number: int, items: List[dict]) -> dict: |
| | | characters: List[str] = [] |
| | | for item in items: |
| | | for name in item.get("characters") or item.get("scene_characters") or []: |
| | | if name not in characters: |
| | | characters.append(name) |
| | | return { |
| | | "episode_number": ep_n, |
| | | "segment_number": segment_number, |
| | | "location": items[0].get("location", "") if items else "", |
| | | "characters": characters, |
| | | "total_duration": sum(int(item.get("duration") or 0) for item in items), |
| | | "items": items, |
| | | } |
| | | |
| | | @classmethod |
| | | def _extract_plan_unit_ids(cls, seg: dict) -> List[str]: |
| | | ids: List[str] = [] |
| | | for value in seg.get("unit_ids") or []: |
| | | if isinstance(value, str) and re.match(r"^U\d{3,}$", value): |
| | | ids.append(value) |
| | | for item in seg.get("items") or []: |
| | | if isinstance(item, dict): |
| | | unit_id = item.get("unit_id") |
| | | if isinstance(unit_id, str) and re.match(r"^U\d{3,}$", unit_id): |
| | | ids.append(unit_id) |
| | | if not ids: |
| | | raw = json.dumps(seg, ensure_ascii=False) |
| | | ids = re.findall(r"\bU\d{3,}\b", raw) |
| | | return list(dict.fromkeys(ids)) |
| | | |
| | | @classmethod |
| | | def _validate_segment_plan(cls, ep_n: int, raw_plan: List[dict], units: List[dict]) -> List[dict]: |
| | | unit_by_id = {item["unit_id"]: item for item in units} |
| | | source_ids = [item["unit_id"] for item in units] |
| | | flat_ids: List[str] = [] |
| | | plans: List[dict] = [] |
| | | |
| | | for seg in raw_plan: |
| | | if not isinstance(seg, dict): |
| | | raise ValueError("片段规划包含非对象元素") |
| | | ids = cls._extract_plan_unit_ids(seg) |
| | | if not ids: |
| | | raise ValueError("片段缺少 unit_ids") |
| | | for unit_id in ids: |
| | | if unit_id not in unit_by_id: |
| | | raise ValueError(f"片段包含未知 unit_id: {unit_id}") |
| | | if unit_id in flat_ids: |
| | | raise ValueError(f"片段重复引用 unit_id: {unit_id}") |
| | | |
| | | items = [unit_by_id[unit_id] for unit_id in ids] |
| | | scene_keys = {item.get("scene_key") for item in items} |
| | | if len(scene_keys) > 1: |
| | | raise ValueError("片段跨场景,场景切换必须分片段") |
| | | for idx, item in enumerate(items): |
| | | if item.get("is_entry") and idx != 0: |
| | | raise ValueError(f"{item['unit_id']} 是入场动作,必须作为片段开头") |
| | | |
| | | duration = sum(int(item.get("duration") or 0) for item in items) |
| | | if duration > cls.MAX_SEGMENT_DURATION: |
| | | raise ValueError(f"片段时长 {duration}s 超出上限 {cls.MAX_SEGMENT_DURATION}s") |
| | | |
| | | flat_ids.extend(ids) |
| | | plans.append(cls._segment_plan_from_units(ep_n, len(plans) + 1, items)) |
| | | |
| | | if flat_ids != source_ids: |
| | | missing = [unit_id for unit_id in source_ids if unit_id not in flat_ids] |
| | | extra = [unit_id for unit_id in flat_ids if unit_id not in source_ids] |
| | | raise ValueError(f"片段规划动作/台词缺漏或乱序,missing={missing}, extra={extra}") |
| | | return plans |
| | | |
| | | @classmethod |
| | | def _fallback_segment_plan(cls, ep_n: int, units: List[dict]) -> List[dict]: |
| | | plans: List[dict] = [] |
| | | current: List[dict] = [] |
| | | |
| | | def flush_current(): |
| | | nonlocal current |
| | | if not current: |
| | | return |
| | | plans.append(cls._segment_plan_from_units(ep_n, len(plans) + 1, current)) |
| | | current = [] |
| | | |
| | | for unit in units: |
| | | current_duration = sum(int(item.get("duration") or 0) for item in current) |
| | | scene_changed = current and unit.get("scene_key") != current[-1].get("scene_key") |
| | | entry_boundary = current and unit.get("is_entry") |
| | | would_overflow = current and current_duration + int(unit.get("duration") or 0) > cls.MAX_SEGMENT_DURATION |
| | | |
| | | if scene_changed or entry_boundary or would_overflow: |
| | | flush_current() |
| | | current.append(unit) |
| | | |
| | | flush_current() |
| | | return plans |
| | | |
| | | @staticmethod |
| | | def _scene_item_payload(items: List[dict]) -> List[dict]: |
| | | return [ |
| | | { |
| | | "unit_id": item["unit_id"], |
| | | "duration": item["duration"], |
| | | "text": item["text"], |
| | | "characters": item.get("characters", []), |
| | | "is_entry": item.get("is_entry", False), |
| | | } |
| | | for item in items |
| | | ] |
| | | |
| | | @classmethod |
| | | def _build_segmentation_prompt( |
| | | cls, |
| | | ep_n: int, |
| | | ep_t: str, |
| | | annotated_script: str, |
| | | characters: List[dict], |
| | | settings: List[dict], |
| | | retry_error: str = "", |
| | | ) -> str: |
| | | template = _get_storyboard_prompt("segment_plan", "zh") |
| | | retry_feedback = "" |
| | | if retry_error: |
| | | retry_feedback = f"上一次输出未通过校验,错误原因:{retry_error}\n请根据这个错误修正输出。" |
| | | from prompts.loader import format_prompt |
| | | return format_prompt( |
| | | template, |
| | | episode_number=ep_n, |
| | | episode_title=ep_t, |
| | | annotated_script=annotated_script, |
| | | asset_characters=json.dumps(characters, ensure_ascii=False), |
| | | asset_settings=json.dumps(settings, ensure_ascii=False), |
| | | retry_feedback=retry_feedback, |
| | | ) |
| | | |
| | | @classmethod |
| | | def _build_segment_design_prompt( |
| | | cls, |
| | | ep_n: int, |
| | | ep_t: str, |
| | | plan: dict, |
| | | style: str, |
| | | retry_error: str = "", |
| | | ) -> str: |
| | | items_payload = cls._scene_item_payload(plan.get("items", [])) |
| | | segment_total = sum(int(item.get("duration") or 0) for item in plan.get("items", [])) |
| | | output_total = max(cls.MIN_SEGMENT_DURATION, segment_total) |
| | | template = _get_storyboard_prompt("segment_design", "zh") |
| | | retry_feedback = "" |
| | | if retry_error: |
| | | retry_feedback = f"上一次输出未通过校验,错误原因:{retry_error}\n请根据这个错误修正输出。" |
| | | from prompts.loader import format_prompt |
| | | return format_prompt( |
| | | template, |
| | | episode_number=ep_n, |
| | | episode_title=ep_t, |
| | | segment_number=plan.get("segment_number"), |
| | | location=plan.get("location", ""), |
| | | characters=json.dumps(plan.get("characters", []), ensure_ascii=False), |
| | | total_duration=output_total, |
| | | items=json.dumps(items_payload, ensure_ascii=False), |
| | | style=style, |
| | | retry_feedback=retry_feedback, |
| | | ) |
| | | |
| | | async def _query_json_array_with_retries( |
| | | self, |
| | | prompt: str, |
| | | llm_model: str, |
| | | sid: str, |
| | | *, |
| | | label: str, |
| | | max_retries: int = 3, |
| | | ) -> List[dict]: |
| | | from models.llm_client import LLM |
| | | |
| | | loop = asyncio.get_running_loop() |
| | | last_error: Optional[Exception] = None |
| | | raw = "" |
| | | for attempt in range(max_retries): |
| | | try: |
| | | llm = LLM() |
| | | raw = await loop.run_in_executor( |
| | | None, |
| | | self._cancellable_query, |
| | | llm, |
| | | prompt, |
| | | [], |
| | | llm_model, |
| | | False, |
| | | sid, |
| | | False, |
| | | ) |
| | | extracted = self._extract_json_array(raw) |
| | | if extracted is not None: |
| | | return extracted |
| | | raise ValueError("模型输出不是 JSON 数组") |
| | | except Exception as exc: |
| | | last_error = exc |
| | | logger.warning("[Storyboard] %s attempt %d failed: %s", label, attempt + 1, exc) |
| | | logger.error("[Storyboard] %s failed after retries. Last raw: %s", label, raw[:2000]) |
| | | raise last_error or ValueError(f"{label} 失败") |
| | | |
| | | async def _query_json_object_with_retries( |
| | | self, |
| | | prompt: str, |
| | | llm_model: str, |
| | | sid: str, |
| | | *, |
| | | label: str, |
| | | max_retries: int = 3, |
| | | ) -> dict: |
| | | from models.llm_client import LLM |
| | | |
| | | loop = asyncio.get_running_loop() |
| | | last_error: Optional[Exception] = None |
| | | raw = "" |
| | | for attempt in range(max_retries): |
| | | try: |
| | | llm = LLM() |
| | | raw = await loop.run_in_executor( |
| | | None, |
| | | self._cancellable_query, |
| | | llm, |
| | | prompt, |
| | | [], |
| | | llm_model, |
| | | False, |
| | | sid, |
| | | False, |
| | | ) |
| | | extracted = self._extract_json_object(raw) |
| | | if extracted is not None: |
| | | return extracted |
| | | raise ValueError("模型输出不是 JSON 对象") |
| | | except Exception as exc: |
| | | last_error = exc |
| | | logger.warning("[Storyboard] %s attempt %d failed: %s", label, attempt + 1, exc) |
| | | logger.error("[Storyboard] %s failed after retries. Last raw: %s", label, raw[:2000]) |
| | | raise last_error or ValueError(f"{label} 失败") |
| | | |
| | | @classmethod |
| | | def _normalize_shot_type(cls, value: Any, *, first: bool = False) -> str: |
| | | text = str(value or "") |
| | | if "全景" in text: |
| | | shot_type = "全景" |
| | | elif "中景" in text: |
| | | shot_type = "中景" |
| | | elif "近景" in text or "特写" in text: |
| | | shot_type = "近景" |
| | | else: |
| | | shot_type = "中景" |
| | | if first and shot_type not in cls.OPENING_SHOT_TYPES: |
| | | return "中景" |
| | | return shot_type |
| | | |
| | | @classmethod |
| | | def _shot_durations_for_plan(cls, plan: dict) -> List[int]: |
| | | durations = [int(item.get("duration") or cls.MIN_SHOT_DURATION) for item in plan.get("items", [])] |
| | | total = sum(durations) |
| | | if durations and total < cls.MIN_SEGMENT_DURATION: |
| | | durations[-1] += cls.MIN_SEGMENT_DURATION - total |
| | | return durations |
| | | |
| | | @classmethod |
| | | def _opening_camera_prefix(cls, shot_type: str, characters: List[str]) -> str: |
| | | subject = "、".join(characters) if characters else "片段中的所有人物" |
| | | return f"{shot_type},平视机位,镜头同时拍到{subject},站位:主要人物面向镜头或彼此成自然对话关系分布。" |
| | | |
| | | @classmethod |
| | | def _normalize_segment_design(cls, ep_n: int, plan: dict, raw_design: dict) -> dict: |
| | | items = plan.get("items", []) |
| | | raw_shots = raw_design.get("shots") if isinstance(raw_design, dict) else None |
| | | if not isinstance(raw_shots, list) or not raw_shots: |
| | | raise ValueError("片段设计缺少 shots") |
| | | |
| | | by_id = { |
| | | shot.get("unit_id"): shot |
| | | for shot in raw_shots |
| | | if isinstance(shot, dict) and isinstance(shot.get("unit_id"), str) |
| | | } |
| | | if by_id: |
| | | missing = [item["unit_id"] for item in items if item["unit_id"] not in by_id] |
| | | extra = [unit_id for unit_id in by_id if unit_id not in {item["unit_id"] for item in items}] |
| | | if missing or extra: |
| | | raise ValueError(f"片段设计 unit_id 不匹配,missing={missing}, extra={extra}") |
| | | ordered_raw = [by_id[item["unit_id"]] for item in items] |
| | | else: |
| | | if len(raw_shots) != len(items): |
| | | raise ValueError("片段设计 shots 数量与 items 不一致") |
| | | ordered_raw = raw_shots |
| | | |
| | | durations = cls._shot_durations_for_plan(plan) |
| | | shots: List[dict] = [] |
| | | characters = plan.get("characters", []) |
| | | for idx, (item, raw_shot) in enumerate(zip(items, ordered_raw)): |
| | | shot_type = cls._normalize_shot_type(raw_shot.get("shot_type"), first=(idx == 0)) |
| | | content = str(raw_shot.get("content") or "").strip() |
| | | shots.append({ |
| | | "shot_number": idx + 1, |
| | | "shot_type": shot_type, |
| | | "duration": durations[idx], |
| | | "content": content, |
| | | }) |
| | | |
| | | return cls._segment_from_shots( |
| | | ep_n, |
| | | int(plan.get("segment_number") or 1), |
| | | plan.get("location", ""), |
| | | shots, |
| | | characters, |
| | | ) |
| | | |
| | | @classmethod |
| | | def _fallback_design_segment(cls, ep_n: int, plan: dict) -> dict: |
| | | characters = plan.get("characters", []) |
| | | durations = cls._shot_durations_for_plan(plan) |
| | | shots: List[dict] = [] |
| | | for idx, item in enumerate(plan.get("items", [])): |
| | | is_dialogue = bool(item.get("is_dialogue")) |
| | | speaker = item.get("speaker") or "角色" |
| | | shot_type = "中景" if idx == 0 or is_dialogue else "全景" |
| | | if idx == 0: |
| | | prefix = cls._opening_camera_prefix(shot_type, characters) |
| | | content = f"{prefix}人物朝向彼此或镜头侧前方。{item['text']}" |
| | | elif is_dialogue: |
| | | content = f"{shot_type},平视略侧机位拍摄{speaker},人物面向对话对象。{item['text']}" |
| | | else: |
| | | subject = "、".join(item.get("characters") or characters) or "场景主体" |
| | | content = f"{shot_type},平视跟拍{subject},人物沿动作方向移动。{item['text']}" |
| | | shots.append({ |
| | | "shot_number": idx + 1, |
| | | "shot_type": shot_type, |
| | | "duration": durations[idx], |
| | | "content": content, |
| | | }) |
| | | return cls._segment_from_shots( |
| | | ep_n, |
| | | int(plan.get("segment_number") or 1), |
| | | plan.get("location", ""), |
| | | shots, |
| | | characters, |
| | | ) |
| | | |
| | | async def _plan_episode_segments( |
| | | self, |
| | | ep_n: int, |
| | | ep_t: str, |
| | | annotated_script: str, |
| | | units: List[dict], |
| | | characters: List[dict], |
| | | settings: List[dict], |
| | | llm_model: str, |
| | | sid: str, |
| | | ) -> List[dict]: |
| | | last_error: Optional[Exception] = None |
| | | for attempt in range(3): |
| | | try: |
| | | prompt = self._build_segmentation_prompt( |
| | | ep_n, |
| | | ep_t, |
| | | annotated_script, |
| | | characters, |
| | | settings, |
| | | retry_error=str(last_error) if last_error else "", |
| | | ) |
| | | raw_plan = await self._query_json_array_with_retries( |
| | | prompt, |
| | | llm_model, |
| | | sid, |
| | | label=f"第 {ep_n} 集片段规划", |
| | | max_retries=1, |
| | | ) |
| | | return self._validate_segment_plan(ep_n, raw_plan, units) |
| | | except Exception as exc: |
| | | last_error = exc |
| | | logger.warning("[Storyboard] Episode %s segment plan validation attempt %d failed: %s", ep_n, attempt + 1, exc) |
| | | |
| | | logger.warning("[Storyboard] Episode %s falling back to deterministic segment plan: %s", ep_n, last_error) |
| | | return self._fallback_segment_plan(ep_n, units) |
| | | |
| | | async def _design_one_segment( |
| | | self, |
| | | ep_n: int, |
| | | ep_t: str, |
| | | plan: dict, |
| | | style: str, |
| | | llm_model: str, |
| | | sid: str, |
| | | ) -> dict: |
| | | last_error: Optional[Exception] = None |
| | | for attempt in range(3): |
| | | try: |
| | | prompt = self._build_segment_design_prompt( |
| | | ep_n, |
| | | ep_t, |
| | | plan, |
| | | style, |
| | | retry_error=str(last_error) if last_error else "", |
| | | ) |
| | | raw_design = await self._query_json_object_with_retries( |
| | | prompt, |
| | | llm_model, |
| | | sid, |
| | | label=f"第 {ep_n} 集片段 {plan.get('segment_number')} 分镜设计", |
| | | max_retries=1, |
| | | ) |
| | | return self._normalize_segment_design(ep_n, plan, raw_design) |
| | | except Exception as exc: |
| | | last_error = exc |
| | | logger.warning( |
| | | "[Storyboard] Episode %s segment %s design attempt %d failed: %s", |
| | | ep_n, |
| | | plan.get("segment_number"), |
| | | attempt + 1, |
| | | exc, |
| | | ) |
| | | |
| | | logger.warning( |
| | | "[Storyboard] Episode %s segment %s falling back to deterministic design: %s", |
| | | ep_n, |
| | | plan.get("segment_number"), |
| | | last_error, |
| | | ) |
| | | return self._fallback_design_segment(ep_n, plan) |
| | | |
| | | async def _design_episode_storyboard( |
| | | self, |
| | | ep_n: int, |
| | | ep_t: str, |
| | | ep_c: str, |
| | | characters: List[dict], |
| | | settings: List[dict], |
| | | style: str, |
| | | llm_model: str, |
| | | sid: str, |
| | | ) -> List[dict]: |
| | | annotated_script, units = self._annotate_episode_script(ep_c, characters, settings) |
| | | if not units: |
| | | raise Exception(f"第 {ep_n} 集未能识别出动作或台词") |
| | | |
| | | self._report_progress("分镜", f"第 {ep_n} 集已完成动作/台词时长标注,共 {len(units)} 项", 20) |
| | | plans = await self._plan_episode_segments(ep_n, ep_t, annotated_script, units, characters, settings, llm_model, sid) |
| | | if not plans: |
| | | raise Exception(f"第 {ep_n} 集片段规划失败") |
| | | |
| | | self._report_progress("分镜", f"第 {ep_n} 集已规划 {len(plans)} 个片段,开始并行设计分镜", 35) |
| | | tasks = [ |
| | | self._design_one_segment(ep_n, ep_t, plan, style, llm_model, sid) |
| | | for plan in plans |
| | | ] |
| | | segments = await asyncio.gather(*tasks) |
| | | segments.sort(key=lambda item: int(item.get("segment_number") or 0)) |
| | | return segments |
| | | |
| | | @classmethod |
| | | def _estimate_duration(cls, text: str, is_dialogue: bool) -> int: |
| | | """Heuristic duration in seconds; every shot is at least 3s.""" |
| | | """Legacy heuristic duration in seconds.""" |
| | | visible_text = re.sub(r"[“”\"',。!?、,.!?;;::\s]", "", text) |
| | | if is_dialogue: |
| | | duration = 3 + len(visible_text) // 18 |
| | |
| | | return valid_episodes |
| | | |
| | | async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict: |
| | | from models.llm_client import LLM |
| | | input_data = self._merge_session_params(input_data) |
| | | sid = input_data.get("session_id") |
| | | if not sid: raise Exception("Missing session_id") |
| | |
| | | session_file = os.path.join("code/data/sessions", f"{sid}.json") |
| | | with open(session_file, "r", encoding="utf-8") as f: |
| | | session_data = json.load(f) |
| | | session_meta = session_data.get("meta") if isinstance(session_data.get("meta"), dict) else {} |
| | | |
| | | llm_model = input_data.get("llm_model") or session_data.get("llm_model") |
| | | llm_model = input_data.get("llm_model") or session_meta.get("llm_model") |
| | | if not llm_model: |
| | | raise ValueError("Missing required model configuration: llm_model") |
| | | style = input_data.get("style") or session_data.get("style") or "anime" |
| | | style = input_data.get("style") or session_meta.get("style") or "anime" |
| | | |
| | | # 处理人工干预/修改 |
| | | if intervention and "modified_storyboard" in intervention: |
| | |
| | | |
| | | chars = script_data.get("characters", []) |
| | | sets = script_data.get("settings", []) |
| | | is_zh = any("\u4e00" <= c <= "\u9fff" for c in script_data.get("title", "")) |
| | | shot_prompt_tpl = _get_shot_prompt("zh" if is_zh else "en") |
| | | |
| | | self._report_progress("分镜", f"开始生成 {len(episodes_to_proc)} 集缺失的分镜...", 5) |
| | | |
| | | async def proc_ep(ep): |
| | | # ... (保持原本处理逻辑不变) |
| | | ep_n = ep.get("episode_number", 1) |
| | | # ... (以下为原本 proc_ep 逻辑) |
| | | ep_t = ep.get("act_title", f"第{ep_n}集") |
| | | ep_c = ep.get("content", "") |
| | | |
| | | regex_segments = self._build_segments_by_regex(ep_n, ep_c, chars, sets) |
| | | if regex_segments: |
| | | logger.info("[Storyboard] Episode %s parsed by regex into %d segments.", ep_n, len(regex_segments)) |
| | | self._report_progress("分镜", f"集数 {ep_n} 已通过规则解析生成分镜", 35) |
| | | return { |
| | | "episode_number": ep_n, |
| | | "episode_title": ep_t, |
| | | "segments": regex_segments |
| | | } |
| | | |
| | | logger.warning("[Storyboard] Episode %s regex parsing produced no segments; falling back to LLM.", ep_n) |
| | | |
| | | # 清洗剧本内容:按行拆分,用于提示说明“一行一分镜” |
| | | lines = [line.strip() for line in ep_c.split('\n') if line.strip()] |
| | | script_text_with_lines = "\n".join([f"L{idx+1}: {line}" for idx, line in enumerate(lines)]) |
| | | |
| | | prompt = shot_prompt_tpl.format( |
| | | act_number=ep_n, |
| | | act_title=ep_t, |
| | | script_text=script_text_with_lines, |
| | | asset_characters=json.dumps(chars, ensure_ascii=False), |
| | | asset_settings=json.dumps(sets, ensure_ascii=False), |
| | | style=style |
| | | segments = await self._design_episode_storyboard( |
| | | ep_n, |
| | | ep_t, |
| | | ep_c, |
| | | chars, |
| | | sets, |
| | | style, |
| | | llm_model, |
| | | sid, |
| | | ) |
| | | |
| | | llm = LLM() |
| | | loop = asyncio.get_running_loop() |
| | | |
| | | # 增加重试机制 (Max 3 retries) |
| | | max_retries = 3 |
| | | extracted = None |
| | | raw = "" |
| | | |
| | | for attempt in range(max_retries): |
| | | try: |
| | | self._report_progress("分镜", f"生成集数 {ep_n} (第 {attempt + 1} 次尝试)...", 5 + attempt * 2) |
| | | raw = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, False, sid, False) |
| | | extracted = self._extract_json_array(raw) |
| | | if extracted: |
| | | break |
| | | logger.warning(f"Episode {ep_n} Attempt {attempt + 1}: Failed to extract JSON array. Retrying...") |
| | | except Exception as e: |
| | | logger.error(f"Episode {ep_n} Attempt {attempt + 1}: LLM query error: {str(e)}") |
| | | if attempt == max_retries - 1: raise e |
| | | |
| | | if not extracted: |
| | | logger.error(f"LLM output failed to parse as JSON for Episode {ep_n} after {max_retries} attempts. Raw: {raw}") |
| | | # 抛出异常以触发 orchestrator 的错误状态处理逻辑 |
| | | raise Exception(f"第 {ep_n} 集分镜生成失败:模型输出无法解析") |
| | | |
| | | valid_segments = self._normalize_llm_segments(ep_n, extracted) |
| | | if not valid_segments: |
| | | raise Exception(f"第 {ep_n} 集分镜生成失败:无法从模型输出构造有效片段") |
| | | |
| | | return { |
| | | "episode_number": ep_n, |
| | | "episode_title": ep_t, |
| | | "segments": valid_segments |
| | | "segments": segments |
| | | } |
| | | |
| | | # 核心:支持流式保存增量产物,让前端能看到实时进度 |
| | |
| | | # 报告一次进度,带上 asset_complete 强制前端从磁盘刷新一次初步数据 |
| | | self._report_progress("分镜设计", "准备生成分镜...", 10, {"asset_complete": True}) |
| | | |
| | | results_queue = [proc_ep(ep) for ep in episodes_to_proc] |
| | | results_queue = [asyncio.create_task(proc_ep(ep)) for ep in episodes_to_proc] |
| | | |
| | | for coro in asyncio.as_completed(results_queue): |
| | | res = await coro |
| | |
| | | img_path: str, video_model: str, |
| | | duration: int = 10, sound: str = "", |
| | | shot_type: str = "multi", |
| | | video_ratio: str = "16:9") -> tuple: |
| | | video_ratio: str = "16:9", |
| | | video_resolution: str = "720P") -> tuple: |
| | | """生成单个视频片段,返回 (segment_id, path_or_None)""" |
| | | if self.cancellation_check and self.cancellation_check(): |
| | | logger.info(f"VideoDirectorAgent: {segment_id} 跳过(用户取消)") |
| | |
| | | sound=sound, |
| | | shot_type=shot_type, |
| | | video_ratio=video_ratio, |
| | | resolution=video_resolution, |
| | | ) |
| | | return segment_id, save_path |
| | | except Exception as e: |
| | |
| | | concurrency = get_max_concurrency(video_model, enable_concurrency) |
| | | |
| | | video_ratio = input_data.get("video_ratio", "16:9") |
| | | video_resolution = input_data.get("video_resolution", "720P") |
| | | video_shot_type = input_data.get("video_shot_type", "multi") |
| | | |
| | | # 加载会话数据 |
| | |
| | | fut = executor.submit( |
| | | self._generate_one, sid, seg_id, prompt, |
| | | img_path, video_model, duration, |
| | | "", video_shot_type, video_ratio |
| | | "", video_shot_type, video_ratio, video_resolution |
| | | ) |
| | | futs[fut] = seg_id |
| | | for fut in as_completed(futs): |
| | |
| | | fut = executor.submit( |
| | | self._generate_one, sid, seg_id, prompt, |
| | | img_path, video_model, dur, |
| | | "", video_shot_type, video_ratio |
| | | "", video_shot_type, video_ratio, video_resolution |
| | | ) |
| | | futs[fut] = seg_id |
| | | for fut in as_completed(futs): |
| | |
| | | "user_textbox_input", |
| | | "style", |
| | | "video_ratio", |
| | | "video_resolution", |
| | | "expand_idea", |
| | | "llm_model", |
| | | "vlm_model", |
| | | "image_t2i_model", |
| | | "image_it2i_model", |
| | | "video_model", |
| | | "video_style", |
| | | "enable_concurrency", |
| | | "web_search", |
| | | "episodes", |
| | |
| | | if isinstance(nested_meta, dict): |
| | | meta.update({k: _normalize_meta_value(v) for k, v in nested_meta.items() if v is not None}) |
| | | for key in SESSION_META_KEYS: |
| | | if key in data and data[key] is not None: |
| | | if key not in meta and key in data and data[key] is not None: |
| | | meta[key] = _normalize_meta_value(data[key]) |
| | | return meta |
| | | |
| | |
| | | normalized_meta = {k: _normalize_meta_value(v) for k, v in meta.items() if v is not None} |
| | | if state: |
| | | state.meta.update(normalized_meta) |
| | | for k, v in normalized_meta.items(): |
| | | data[k] = v |
| | | if "created_at" not in data: |
| | | data["created_at"] = time.time() |
| | | |
| | | # 会话级生成参数统一保存在 meta 中;清理旧版本遗留的根字段。 |
| | | for key in SESSION_META_KEYS: |
| | | data.pop(key, None) |
| | | |
| | | # 2. 将内存中的最新 state 合并到 data 中 |
| | | if state: |
| | |
| | | data["error"] = state.error |
| | | data["updated_at"] = state.updated_at.timestamp() if isinstance(state.updated_at, datetime) else time.time() |
| | | |
| | | # 保存元数据:nested meta 是主结构;根字段保留给旧会话文件和外部读写兼容。 |
| | | # 保存元数据:meta 是唯一的会话级生成参数存储位置。 |
| | | if state.meta: |
| | | data["meta"] = copy.deepcopy(state.meta) |
| | | for k, v in state.meta.items(): |
| | | if v is not None: |
| | | data[k] = _normalize_meta_value(v) |
| | | else: |
| | | data.pop("meta", None) |
| | | else: |
| | | data["updated_at"] = time.time() |
| | | |
| | |
| | | fpath = os.path.join(self._session_dir, filename) |
| | | with open(fpath, 'r', encoding='utf-8') as f: |
| | | data = json.load(f) |
| | | meta = _extract_session_meta(data) |
| | | script_artifact = data.get("artifacts", {}).get("script_generation", {}) |
| | | title = ( |
| | | script_artifact.get("title") |
| | | or meta.get("idea") |
| | | or meta.get("user_textbox_input") |
| | | or data.get("idea", "") |
| | | ) |
| | | sessions.append({ |
| | | "id": data["session_id"], |
| | | "idea": data.get("idea", ""), |
| | | "style": data.get("style", ""), |
| | | "title": title, |
| | | "idea": meta.get("idea") or meta.get("user_textbox_input") or data.get("idea", ""), |
| | | "style": meta.get("style") or data.get("style", ""), |
| | | "date": data.get("updated_at", 0), |
| | | "status": data.get("status", {}), |
| | | }) |
| | |
| | | deepseek-v4-flash: DeepSeek-V4 Flash |
| | | deepseek-v4-pro: DeepSeek-V4 Pro |
| | | """ |
| | | def __init__(self, base_url="", api_key=""): |
| | | def __init__(self, base_url="", api_key="", timeout=120): |
| | | import httpx |
| | | self.base_url = base_url or Config.DEEPSEEK_BASE_URL or "https://api.deepseek.com/v1" |
| | | self.api_key = api_key or Config.DEEPSEEK_API_KEY |
| | | self.timeout = timeout |
| | | |
| | | if not self.api_key: |
| | | logger.warning("DEEPSEEK_API_KEY is not set") |
| | | |
| | | kwargs = {"api_key": self.api_key, "base_url": self.base_url} |
| | | kwargs = {"api_key": self.api_key, "base_url": self.base_url, "timeout": self.timeout} |
| | | proxy = Config.provider_proxy("deepseek") |
| | | if proxy: |
| | | kwargs["http_client"] = httpx.Client(proxy=proxy) |
| | | kwargs["http_client"] = httpx.Client(proxy=proxy, timeout=self.timeout) |
| | | self.client = OpenAI(**kwargs) |
| | | self.max_attempts = 3 |
| | | self.max_attempts = 2 |
| | | self.max_tokens = 8000 |
| | | |
| | | def query(self, prompt, image_urls=[], model="deepseek-chat", web_search=False): |
| | |
| | | if response.choices and response.choices[0].message.content: |
| | | return response.choices[0].message.content |
| | | else: |
| | | logger.warning("DeepSeek returned an empty response; retrying") |
| | | choice = response.choices[0] if response.choices else None |
| | | message = getattr(choice, "message", None) if choice else None |
| | | try: |
| | | message_payload = message.model_dump(exclude_none=True) if message else None |
| | | except Exception: |
| | | message_payload = str(message) if message else None |
| | | logger.warning( |
| | | "DeepSeek returned an empty response; retrying. model=%s finish_reason=%s usage=%s message=%s", |
| | | model, |
| | | getattr(choice, "finish_reason", None) if choice else None, |
| | | getattr(response, "usage", None), |
| | | message_payload, |
| | | ) |
| | | time.sleep(2) |
| | | except Exception as e: |
| | | logger.warning("DeepSeek request failed; retrying: %s", e) |
| | | logger.warning("DeepSeek request failed; retrying. model=%s timeout=%ss error=%s", model, self.timeout, e) |
| | | time.sleep(5) |
| | | attempts += 1 |
| | | |
| | |
| | | model, |
| | | duration, |
| | | sound, |
| | | video_ratio, |
| | | resolution, |
| | | mode, |
| | | cfg_scale, |
| | | negative_prompt or "", |
| | |
| | | ) |
| | | else: |
| | | raise ValueError(f"未知的视频生成模型: {model}") |
| | | |
| | | @staticmethod |
| | | def _normalize_seedance_resolution(resolution: Optional[str]) -> str: |
| | | value = (resolution or "720p").strip().lower() |
| | | return value if value in {"720p", "1080p"} else "720p" |
| | | |
| | | def _generate_wan( |
| | | self, |
| | |
| | | model: str, |
| | | duration: int = 5, |
| | | sound: str = "", |
| | | video_ratio: str = "16:9", |
| | | resolution: Optional[str] = None, |
| | | mode: str = "pro", |
| | | cfg_scale: float = 0.5, |
| | | negative_prompt: str = "", |
| | |
| | | model=model, |
| | | duration=duration, |
| | | sound=sound, |
| | | video_ratio=video_ratio, |
| | | resolution=resolution, |
| | | mode=mode, |
| | | cfg_scale=cfg_scale, |
| | | negative_prompt=negative_prompt, |
| | |
| | | model=model, |
| | | duration=duration, |
| | | ratio=video_ratio, |
| | | resolution=resolution or "720p", |
| | | resolution=self._normalize_seedance_resolution(resolution), |
| | | seed=seed, |
| | | watermark=watermark, |
| | | generate_audio=generate_audio, |
| | |
| | | # 使用强制 TLS 1.2 + 自动重试的 Session |
| | | self._session = _build_session(proxy=Config.provider_proxy("kling")) |
| | | |
| | | @staticmethod |
| | | def _resolve_mode(mode: str = "pro", resolution: Optional[str] = None) -> str: |
| | | """Map UI resolution to Kling's quality mode while preserving explicit mode as fallback.""" |
| | | value = (resolution or "").strip().lower() |
| | | if value == "1080p": |
| | | return "pro" |
| | | if value == "720p": |
| | | return "std" |
| | | return mode if mode in {"std", "pro"} else "pro" |
| | | |
| | | # ─── JWT 鉴权 ─── |
| | | |
| | | def _generate_token(self) -> str: |
| | |
| | | duration: str = "5", |
| | | cfg_scale: float = 0.5, |
| | | sound: str = "", |
| | | video_ratio: str = "16:9", |
| | | resolution: Optional[str] = None, |
| | | ) -> str: |
| | | """ |
| | | 提交图生视频任务 |
| | |
| | | duration: 视频时长,v3: "3"~"15", v2: "5"或"10" |
| | | cfg_scale: 自由度 [0,1],越大越贴合提示词 |
| | | sound: 是否生成声音 "on"/"off" |
| | | video_ratio: 输出画幅比例,按可灵 API 的 aspect_ratio 字段传递 |
| | | resolution: UI 分辨率,720P 映射为 std,1080P 映射为 pro |
| | | |
| | | Returns: |
| | | task_id: 任务 ID |
| | |
| | | # v2 系列仅支持 5 或 10 |
| | | clamped = str(min(max(int(duration), 5), 10)) |
| | | |
| | | mode = self._resolve_mode(mode, resolution) |
| | | image_b64 = self._encode_image(image_path) |
| | | |
| | | body = { |
| | |
| | | "mode": mode, |
| | | "duration": clamped, |
| | | } |
| | | if video_ratio: |
| | | body["aspect_ratio"] = video_ratio |
| | | |
| | | # sound 参数处理 |
| | | # v3 / v2-6: 默认开启声音,除非显式 sound="off" |
| | |
| | | url = f"{self.base_url}/v1/videos/image2video" |
| | | headers = self._auth_headers() |
| | | |
| | | logger.info(f"KlingVideoClient: 提交任务 model={model_name}, mode={mode}, duration={clamped}s, sound={body.get('sound', 'off')}") |
| | | logger.info(f"KlingVideoClient: 提交任务 model={model_name}, mode={mode}, duration={clamped}s, aspect_ratio={body.get('aspect_ratio')}, sound={body.get('sound', 'off')}") |
| | | |
| | | resp = self._session.post(url, json=body, headers=headers, timeout=300) |
| | | if not resp.ok: |
| | |
| | | cfg_scale: float = 0.5, |
| | | negative_prompt: str = "", |
| | | sound: str = "", |
| | | video_ratio: str = "16:9", |
| | | resolution: Optional[str] = None, |
| | | ) -> str: |
| | | """ |
| | | 图生视频完整流程:提交任务 → 轮询等待 → 下载视频 |
| | |
| | | cfg_scale: 自由度 [0,1] |
| | | negative_prompt: 负向提示词 |
| | | sound: 是否生成声音 "on"/"off" |
| | | video_ratio: 输出画幅比例,按可灵 API 的 aspect_ratio 字段传递 |
| | | resolution: UI 分辨率,720P 映射为 std,1080P 映射为 pro |
| | | |
| | | Returns: |
| | | video_url: 远端视频 URL |
| | |
| | | duration=str(duration), |
| | | cfg_scale=cfg_scale, |
| | | sound=sound, |
| | | video_ratio=video_ratio, |
| | | resolution=resolution, |
| | | ) |
| | | |
| | | # 2. 轮询等待 |
| | |
| | | first_clip_path=video_path, |
| | | reference_image_path=image_path, |
| | | negative_prompt=params.get("negative_prompt"), |
| | | resolution=params.get("resolution"), |
| | | video_resolution=params.get("video_resolution") or params.get("resolution"), |
| | | watermark=params.get("watermark"), |
| | | prompt_extend=params.get("prompt_extend"), |
| | | ) |
| | |
| | | image_path: Optional[str] = None, |
| | | duration: int = 5, |
| | | video_ratio: str = "9:16", |
| | | video_resolution: Optional[str] = None, |
| | | **params, |
| | | ) -> str: |
| | | provider, resolved_model = parse_api_workflow(model, "video") |
| | |
| | | model=resolved_model, |
| | | duration=safe_duration, |
| | | video_ratio=video_ratio, |
| | | resolution=video_resolution or params.pop("resolution", None), |
| | | **params, |
| | | ) |
| | | return output_path |
| | |
| | | reference_audio_path=segment_audio_path, |
| | | audio=True, |
| | | negative_prompt=params.get("negative_prompt"), |
| | | resolution=params.get("resolution"), |
| | | video_resolution=params.get("video_resolution") or params.get("resolution"), |
| | | watermark=params.get("watermark"), |
| | | prompt_extend=params.get("prompt_extend"), |
| | | ) |
| | |
| | | video_mode = params.get("video_mode") or "image_concat" |
| | | dynamic_video = video_mode == "dynamic_video" or bool(params.get("generate_videos", False)) |
| | | video_model = params.get("video_model") |
| | | video_resolution = params.get("video_resolution") or params.get("resolution") or "720P" |
| | | if (dynamic_video or template_video_mode) and not video_model: |
| | | raise ValueError("standard pipeline video generation requires video_model") |
| | | video_duration = clamp_segment_count(params.get("video_duration") or params.get("duration") or 5, default=5) |
| | |
| | | image_path=image_path, |
| | | duration=max(video_duration, int(duration + 0.999)), |
| | | video_ratio=media_video_ratio, |
| | | video_resolution=video_resolution, |
| | | ) |
| | | storyboard["frames"][idx - 1]["template_media_video_path"] = media_video_path |
| | | |
| | |
| | | image_path=clip_image_path, |
| | | duration=max(video_duration, int(duration + 0.999)), |
| | | video_ratio=video_ratio, |
| | | video_resolution=video_resolution, |
| | | ) |
| | | motion_artifact = artifact(video_only_segment_path, "video", f"video_{idx:02d}_motion") |
| | | artifacts.append(motion_artifact) |
| | |
| | | 你是一个专业的AI图像质量评估师。请根据以下信息评估生成的4视图角色参考图。 |
| | | 你是一个专业的AI角色资产图评估师。请评估生成的4视图角色参考图是否可作为后续视频生成的稳定角色资产。 |
| | | |
| | | 角色描述: |
| | | {character_description} |
| | | |
| | | 注意:这是一张4视图角色参考图,包含: |
| | | 这张图应包含4个角色视图: |
| | | 1. 正面特写(头部及上半身) |
| | | 2. 正面全身照 |
| | | 3. 侧面全身照 |
| | | 4. 背面全身照 |
| | | |
| | | 请严格按照以下标准评估并给出1-10分: |
| | | 请先判断【硬性失败项】。只要命中任意硬性失败项,is_acceptable 必须为 false,即使图片美观也不能通过。 |
| | | |
| | | 【评分标准】 |
| | | 满分10分,每个检查项符合得1分,不符合扣1分,最高10分: |
| | | 【硬性失败项】 |
| | | 1. 四视图缺失或明显不完整:缺少正面特写、正面全身、侧面全身、背面全身中的任意一种。 |
| | | 2. 四视图不是同一角色:脸型、发型、体型、服装在不同视图中明显变成不同人物。 |
| | | 3. 关键角色设定错误:性别、年龄段、职业气质、核心服装、核心发型与角色描述明显不符。 |
| | | 4. 角色主体不可用:脸部严重崩坏、身体严重畸形、主要部位被遮挡或裁切,无法作为角色参考。 |
| | | 5. 出现文字、水印、标签、标注线、说明文字或明显UI元素。 |
| | | 6. 图片严重模糊、过曝、过暗或低清,无法看清角色外观。 |
| | | |
| | | 1. 四视图一致性(+1/-1):四个视图是否为同一角色(面貌、服装、体型是否一致) |
| | | 2. 面貌还原(+1/-1):面孔是否与描述一致 |
| | | 3. 发型还原(+1/-1):发型是否与描述一致 |
| | | 4. 服装还原(+1/-1):服装颜色、款式是否与描述一致 |
| | | 5. 体型还原(+1/-1):体型是否与描述一致 |
| | | 6. 完整性(+1/-1):四个视图是否都存在且完整 |
| | | 7. 光线质量(+1/-1):光线是否自然、合理 |
| | | 8. 构图质量(+1/-1):构图是否合理、均衡 |
| | | 9. 图片质量(+1/-1):清晰度良好,无模糊、无畸变 |
| | | 10. 无无关元素(+1/-1):无文字、标签、注释、水印等 |
| | | 若没有硬性失败项,再评估【软性维度】并给出1-10分。软性问题可以扣分,但不应单独导致不合格。 |
| | | |
| | | 【扣分项】(发现以下问题必须扣分并在issues中列出): |
| | | - 四个视图角色面貌不一致:-1分 |
| | | - 服装颜色与描述不符:-1分 |
| | | - 发型与描述不符:-1分 |
| | | - 面孔与描述不符:-1分 |
| | | - 缺少某个视图:-1分 |
| | | - 出现文字/水印:-1分 |
| | | 【软性维度】 |
| | | 1. 面貌还原:脸型、五官、年龄感是否贴合描述。 |
| | | 2. 发型还原:发型、发色、长度是否贴合描述。 |
| | | 3. 服装还原:颜色、款式、材质和职业属性是否贴合描述。 |
| | | 4. 体型还原:身高感、体态、胖瘦是否贴合描述。 |
| | | 5. 视图角度清晰:正面、侧面、背面角度是否明确。 |
| | | 6. 构图可用:角色居中、无遮挡、全身比例清楚。 |
| | | 7. 风格一致:画面风格与项目整体风格一致。 |
| | | 8. 细节稳定:四视图中的配饰、服装细节保持稳定。 |
| | | |
| | | 【最终评分规则】 |
| | | - 8分及以上:可接受(is_acceptable: true) |
| | | - 7分及以下:需要重新生成(is_acceptable: false) |
| | | 【合格标准】 |
| | | - 如果 hard_failures 非空:is_acceptable=false,score 最高不得超过6。 |
| | | - 如果 hard_failures 为空且 score >= 7:is_acceptable=true。 |
| | | - 如果 hard_failures 为空但 score < 7:is_acceptable=false。 |
| | | - 小瑕疵如手指略不完美、光线一般、背景简单,不应列入 hard_failures,只能作为 soft_issues。 |
| | | |
| | | 请输出纯JSON格式(不要用```包裹): |
| | | {{ |
| | | "score": 1-10, |
| | | "issues": ["问题1", "问题2", ...], |
| | | "hard_failures": ["硬性失败项1", "硬性失败项2"], |
| | | "soft_issues": ["软性问题1", "软性问题2"], |
| | | "issues": ["合并后的主要问题列表"], |
| | | "is_acceptable": true/false, |
| | | "suggestion": "修改建议(如果有问题)" |
| | | "suggestion": "如果需要重新生成,说明最应该修正什么;如果可接受则为空字符串" |
| | | }} |
| | | |
| | | 如果图片可接受,issues 返回空数组 []。 |
| | |
| | | 你是一个专业的AI图像质量评估师。请根据以下信息评估生成的视频首帧参考图。 |
| | | 你是一个专业的视频首帧参考图评估师。请评估生成的参考图是否适合作为视频模型的首帧输入。 |
| | | |
| | | 分镜剧情: |
| | | {plot} |
| | |
| | | 场景描述: |
| | | {setting_description} |
| | | |
| | | 请严格按照以下标准评估并给出1-10分: |
| | | 请先判断【硬性失败项】。只要命中任意硬性失败项,is_acceptable 必须为 false,即使图片美观也不能通过。 |
| | | |
| | | 【评分标准】 |
| | | 满分10分,每个检查项符合得1分,不符合扣1分,最高10分: |
| | | 【硬性失败项】 |
| | | 1. 核心角色数量错误:分镜需要出现的主要人物明显多了或少了。 |
| | | 2. 核心角色不可辨认:主要人物脸部/身体严重崩坏、被遮挡、被裁切,或无法看清是谁。 |
| | | 3. 角色资产明显不一致:主要人物的性别、年龄段、核心服装、核心发型与角色描述明显不符。 |
| | | 4. 场景地点错误:图片环境明显不是分镜要求的地点。 |
| | | 5. 人物状态/人物关系完全错误:图片没有体现片段开始前的人物状态、位置关系、视线方向或核心情绪,且无法作为该片段的视频起点。 |
| | | 6. 景别/构图不可用:主体严重偏出画面、构图严重倾斜、人物关系看不清,或不适合做视频首帧。 |
| | | 7. 人物与场景互动错误:人物不能与桌子、椅子、门、墙、车辆、道具等发生明显穿模、嵌入、悬浮、错位接触或不合理遮挡。必须专门检查人物身体、手臂、腿脚、衣服边缘与桌面、桌腿、椅背、门框、墙面、车辆和道具的接触边界;只要身体像是穿过/嵌入这些物体,必须列入 hard_failures。 |
| | | 8. 出现文字、水印、标签、标注线、说明文字或明显UI元素。 |
| | | 9. 图片严重模糊、过曝、过暗、低清或畸变,无法作为视频首帧。 |
| | | |
| | | 1. 角色外观一致性(+1/-1):角色发型、服装、面孔是否与角色描述一致 |
| | | 2. 场景一致性(+1/-1):场景地点、布局是否与场景描述一致 |
| | | 3. 剧情相关性(+1/-1):图片是否体现分镜剧情的核心内容和情感 |
| | | 4. 姿态合理性(+1/-1):角色姿态是否体现动作的起始瞬间 |
| | | 5. 光线质量(+1/-1):光线是否自然、合理、有层次 |
| | | 6. 色调氛围(+1/-1):色调是否符合分镜设定的氛围(日/夜、暖/冷等) |
| | | 7. 构图美感(+1/-1):构图是否平衡、美观、符合影视镜头语言 |
| | | 8. 图片质量(+1/-1):无模糊、无畸变、无明显瑕疵 |
| | | 9. 细节完整(+1/-1):画面细节丰富,无缺失或残缺 |
| | | 10. 无无关元素(+1/-1):无文字、水印、标签等无关内容 |
| | | 若没有硬性失败项,再评估【软性维度】并给出1-10分。软性问题可以扣分,但不应单独导致不合格。 |
| | | |
| | | 【扣分项】(发现以下问题必须扣分并在issues中列出): |
| | | - 角色服装颜色与描述不符:-1分 |
| | | - 角色发型/面孔与描述不符:-1分 |
| | | - 场景环境与描述不符:-1分 |
| | | - 角色数量错误(多或少):-1分 |
| | | - 光线过暗或过亮:-1分 |
| | | - 构图严重偏斜:-1分 |
| | | - 出现文字/水印:-1分 |
| | | 【软性维度】 |
| | | 1. 人物静态状态匹配:图片体现片段开始前人物的站姿、坐姿、表情、情绪和准备状态,不需要表现具体动作的起始瞬间。 |
| | | 2. 人物站位与交互:人物之间的位置、朝向、视线关系是否清楚,例如是否看向对方、是否形成对话/对峙/协作关系。 |
| | | 3. 角色外观一致性:发型、服装、年龄气质是否大体贴合角色资产。 |
| | | 4. 场景一致性:地点、空间布局、关键物件是否大体贴合场景资产。 |
| | | 5. 镜头语言:景别、机位、平视/俯视/仰视等是否符合分镜视觉描述。 |
| | | 6. 视频可用性:主体清楚,人物状态和互动关系明确,适合后续 i2v。 |
| | | 7. 光线氛围:光线、色调、时间感是否服务剧情。 |
| | | 8. 图像质量:清晰度、细节、手脸身体质量是否足够。 |
| | | |
| | | 【最终评分规则】 |
| | | - 8分及以上:可接受(is_acceptable: true) |
| | | - 7分及以下:需要重新生成(is_acceptable: false) |
| | | 【合格标准】 |
| | | - 如果 hard_failures 非空:is_acceptable=false,score 最高不得超过6。 |
| | | - 如果 hard_failures 为空且 score >= 7:is_acceptable=true。 |
| | | - 如果 hard_failures 为空但 score < 7:is_acceptable=false。 |
| | | - “人物穿过桌子/椅子/墙/道具”属于硬性失败项,不得因为整体画面好看、人物清晰或构图不错而放行。 |
| | | - 不要因为“没有完全复刻所有台词细节”“光线不够电影感”“背景细节略少”等软问题直接判失败。 |
| | | |
| | | 重要:如果发现问题需要重新生成,请同时提供一个优化后的提示词,用于改善图片质量。优化提示词时: |
| | | - **不要改变角色的外貌描述**(如发型、服装、面孔等) |
| | | - 可以让光线、构图、氛围、姿态等描述更清晰具体 |
| | | - 保持与角色外观相关的描述不变 |
| | | 如果需要重新生成,请提供 suggested_prompt。优化提示词时: |
| | | - 不要改变角色的核心外貌描述,如发型、服装、年龄、性别。 |
| | | - 可以加强镜头、站位、人物视线、人物状态、构图、光线和场景元素。 |
| | | - 保持与分镜剧情和视觉描述一致。 |
| | | |
| | | 请输出纯JSON格式(不要用```包裹): |
| | | {{ |
| | | "score": 1-10, |
| | | "issues": ["问题1", "问题2", ...], |
| | | "hard_failures": ["硬性失败项1", "硬性失败项2"], |
| | | "soft_issues": ["软性问题1", "软性问题2"], |
| | | "issues": ["合并后的主要问题列表"], |
| | | "is_acceptable": true/false, |
| | | "suggestion": "修改建议(如果有问题)", |
| | | "suggested_prompt": "优化后的提示词(如果需要重新生成),如果不需重新生成则为空字符串" |
| | | "suggestion": "如果需要重新生成,说明最应该修正什么;如果可接受则为空字符串", |
| | | "suggested_prompt": "优化后的提示词;如果不需要重新生成则为空字符串" |
| | | }} |
| | | |
| | | 如果图片可接受,issues 返回空数组 [],suggested_prompt 为空字符串。 |
| | |
| | | 你是一个专业的AI图像质量评估师。请从以下{num_images}张图片中选择最好的一张作为视频参考图。 |
| | | 你是一个专业的视频首帧参考图评估师。请从以下{num_images}张图片中选择最适合作为视频模型首帧的一张。 |
| | | |
| | | 分镜剧情: |
| | | {plot} |
| | |
| | | |
| | | {images_list} |
| | | |
| | | 【选择标准】 |
| | | 请严格按照以下标准选择最佳图片: |
| | | 请先对每张图判断【硬性失败项】。优先从没有硬性失败项的图片中选择最佳图。 |
| | | |
| | | 1. 角色外观一致性:角色发型、服装、面孔是否与角色描述一致 |
| | | 2. 场景一致性:场景地点、布局是否与场景描述一致 |
| | | 3. 剧情相关性:图片是否体现分镜剧情的核心内容和情感 |
| | | 4. 姿态合理性:角色姿态是否体现动作的起始瞬间 |
| | | 5. 光线质量:光线是否自然、合理、有层次 |
| | | 6. 色调氛围:色调是否符合分镜设定的氛围(日/夜、暖/冷等) |
| | | 7. 构图美感:构图是否平衡、美观、符合影视镜头语言 |
| | | 8. 图片质量:无模糊、无畸变、无明显瑕疵 |
| | | 9. 细节完整:画面细节丰富,无缺失或残缺 |
| | | 10. 无无关元素:无文字、水印、标签等无关内容 |
| | | 【硬性失败项】 |
| | | 1. 核心角色数量错误:分镜需要出现的主要人物明显多了或少了。 |
| | | 2. 核心角色不可辨认:主要人物脸部/身体严重崩坏、被遮挡、被裁切,或无法看清是谁。 |
| | | 3. 角色资产明显不一致:主要人物的性别、年龄段、核心服装、核心发型与角色描述明显不符。 |
| | | 4. 场景地点错误:图片环境明显不是分镜要求的地点。 |
| | | 5. 人物状态/人物关系完全错误:图片没有体现片段开始前的人物状态、位置关系、视线方向或核心情绪,且无法作为该片段的视频起点。 |
| | | 6. 景别/构图不可用:主体严重偏出画面、构图严重倾斜、人物关系看不清,或不适合做视频首帧。 |
| | | 7. 人物与场景互动错误:人物不能与桌子、椅子、门、墙、车辆、道具等发生明显穿模、嵌入、悬浮、错位接触或不合理遮挡。必须专门检查人物身体、手臂、腿脚、衣服边缘与桌面、桌腿、椅背、门框、墙面、车辆和道具的接触边界;只要身体像是穿过/嵌入这些物体,必须列入 hard_failures。 |
| | | 8. 出现文字、水印、标签、标注线、说明文字或明显UI元素。 |
| | | 9. 图片严重模糊、过曝、过暗、低清或畸变,无法作为视频首帧。 |
| | | |
| | | 【排除原则】 |
| | | 以下情况必须排除: |
| | | - 角色服装颜色与描述严重不符 |
| | | - 角色发型/面孔与描述严重不符 |
| | | - 场景环境与描述严重不符 |
| | | - 角色数量错误(多或少) |
| | | - 光线过暗或过亮导致无法看清内容 |
| | | - 构图严重偏斜导致主体不清晰 |
| | | - 出现文字/水印/标签等无关元素 |
| | | 【选择规则】 |
| | | 1. 如果存在无硬性失败项的图片,只能从这些图片中选择。 |
| | | 2. 如果所有图片都有硬性失败项,选择硬性失败最少且最容易修复的一张。 |
| | | 3. 在硬性失败项相同的情况下,优先选择:角色数量正确 > 场景正确 > 人物状态/人物关系正确 > 主体清晰 > 构图和光线更好。 |
| | | 4. 软性问题如光线普通、背景细节略少、画面不够电影感,不应压过硬性可用性。 |
| | | 5. “人物穿过桌子/椅子/墙/道具”属于硬性失败项,不得因为整体画面好看、人物清晰或构图不错而放行。 |
| | | |
| | | 【软性维度】 |
| | | 1. 人物静态状态匹配:站姿、坐姿、表情、情绪和准备状态合理,不需要表现具体动作的起始瞬间。 |
| | | 2. 人物站位与交互清楚:位置、朝向、视线关系明确,例如看向对方、形成对话/对峙/协作关系。 |
| | | 3. 角色外观大体一致。 |
| | | 4. 场景布局和关键物件大体一致。 |
| | | 5. 镜头语言符合分镜视觉描述。 |
| | | 6. 主体清楚,人物状态和互动关系明确,适合后续 i2v。 |
| | | 7. 光线、色调、氛围服务剧情。 |
| | | 8. 图像质量稳定。 |
| | | |
| | | 请输出纯JSON格式(不要用```包裹): |
| | | {{ |
| | | "selected_index": 0到{num_images_minus_1}之间的整数, |
| | | "reason": "选择该图片的主要原因", |
| | | "reason": "选择该图片的主要原因,说明硬性失败项和视频可用性", |
| | | "score": 1-10, |
| | | "issues": ["该图片存在的问题列表,如果完美则为空数组"] |
| | | "hard_failures": ["该图片的硬性失败项,如果没有则为空数组"], |
| | | "soft_issues": ["该图片的软性问题,如果没有则为空数组"], |
| | | "issues": ["合并后的主要问题列表"] |
| | | }} |
| | | |
| | | selected_index 必须是从 0 到 {num_images_minus_1} 的整数,表示你选择的图片编号。 |
| | |
| | | You are an expert AI prompt engineer and cinematic storyboard director. Your task is to generate a purely English "Initial First Frame Visual Description Prompt" for an AI video generation tool (like SVD, Luma, Kling). |
| | | You are an expert AI prompt engineer and cinematic storyboard director. Generate a purely English "Static First Frame Visual Prompt" for an AI video generation tool. |
| | | |
| | | [Core Goal] |
| | | Your prompt must describe a **static high-quality image** representing the **exact first frame** of the shot. Video models will use this as a reference and then begin movement. |
| | | The prompt should create a static, high-quality image that works as a stable first frame for video generation. The first frame should establish characters, setting, positions, gaze, and relationships. The video model will create motion later. |
| | | |
| | | [Requirements] |
| | | 1. **Absolute Static Composition**: Focus solely on the **completely static freeze-frame** of the first frame. **Do NOT** include any time changes or passage of time. |
| | | 2. **No Actions or Processes**: **Do NOT** use action verbs, and **strictly avoid** describing process-oriented movements (e.g., running, jumping mid-air, getting up, sitting down, taking off). |
| | | 3. **Focus on Position & Static Pose**: |
| | | - Only describe the character's physical location and basic resting poses (e.g., standing, sitting, lying down, leaning, crouching). |
| | | - Convert any scripted actions into a **completely still state** before the action happens. |
| | | - **Do NOT** describe the character's psychological intentions (e.g., "trying to look outside", "about to leave"). |
| | | 4. **Orientation & Gaze (Mandatory)**: Clearly specify the body orientation and the exact gaze direction of each character (e.g., facing the camera, back to the camera, profile view, looking steadily at a specific object). |
| | | 5. **Quality & Environment**: Integrate character and setting details with high-quality modifiers (masterpiece, cinematic composition, etc.). The environment must be totally still, with no changes over time. |
| | | 6. **Output Format**: Pure English, comma-separated tags. No explanations, no ``` markers. |
| | | [Key Principle] |
| | | Do not depict the action itself, and do not depict the starting instant of an action. Treat actions and dialogue as context only. Extract the static visual state at the beginning of the segment: |
| | | - who is visible; |
| | | - where each character is positioned; |
| | | - whether each character is standing, sitting, leaning, crouching, or in another stable pose; |
| | | - each character's body orientation and gaze direction; |
| | | - whether characters are in dialogue, confrontation, cooperation, avoidance, pressure, or being pressured; |
| | | - the spatial relationship between characters and tables, chairs, doors, walls, vehicles, props, and other objects. |
| | | |
| | | [Hard Requirements] |
| | | 1. Absolute static image: describe a still frame only. Do not describe time changes, action processes, or motion paths. |
| | | 2. Do not show actions: avoid running, turning, sitting down, standing up, reaching, waving, pushing a door, fighting, falling, or any process-oriented movement. You may describe stable states such as "standing beside the door", "sitting on a chair", "one hand resting near the table", "body slightly leaning forward". |
| | | 3. Emphasize character state: posture, expression, emotion, body orientation, gaze direction, and relationship between characters. For example: "looking at each other", "avoiding eye contact", "facing each other across a conference table", "standing near the doorway". |
| | | 4. Emphasize character-scene interaction: characters must not intersect with objects. Clearly describe reasonable spatial relationships with tables, chairs, doors, walls, vehicles, and props, such as "standing beside the table", "sitting on the chair", "near the doorway". Avoid bodies embedded in tables, walls, chair backs, or props. |
| | | 5. Preserve character appearance: clothing, hairstyle, age impression, identity, and core visual traits must follow the character descriptions and script context. |
| | | 6. Preserve the setting: include location, main spatial structure, key objects, and lighting atmosphere. |
| | | 7. Include camera language: shot size, camera angle, composition, and subject placement. For multi-character segments, make relationships and gaze directions clear. |
| | | 8. Visual quality: cinematic composition, clear subjects, natural lighting, stable details. |
| | | |
| | | [Forbidden] |
| | | - Do not use words implying action process such as "about to", "starting to", "preparing to", "currently", "in the middle of". |
| | | - Do not describe psychological intentions such as "wants to leave" or "plans to fight back". |
| | | - Do not include text, watermark, subtitles, labels, signs, UI elements, or explanations. |
| | | - No Markdown. |
| | | |
| | | [Segment Plot] |
| | | {plot} |
| | |
| | | [Setting Description] |
| | | {setting_description} |
| | | |
| | | [Examples] |
| | | (Bad): A man running fast to the window, intending to jump out, shouting to the outside. |
| | | (Good): Cinematic shot, a man standing quietly in front of a large window, maintaining an upright standing pose, body angled 45 degrees toward the window, facing the glass, eyes gazing steadily at the stationary street outside, completely still, high contrast lighting. |
| | | [Example] |
| | | Bad: A man running fast to the window, about to jump out, shouting outside. |
| | | Good: Cinematic medium shot, a man standing in front of a large window, body angled 45 degrees toward the glass, gaze directed toward the still street outside; both feet planted steadily, arms relaxed at his sides, clear space between the person and the window frame, high contrast natural light, completely static image. |
| | | |
| | | [Output Format] |
| | | Output ONLY the final English prompt text. |
| | | Output ONLY the final English visual prompt text. |
| | |
| | | 你是一位专业的AI提示词工程师与影视分镜导演。你的任务是根据一个拍摄分段的剧情(包含景别、动作、对话等),结合场地背景描述和相关人物描述,为这个拍摄片段生成用于AI视频生成工具的「起始首帧视觉描述提示词」(用中文输出)。 |
| | | 你是一位专业的AI提示词工程师与影视分镜导演。你的任务是根据一个拍摄片段的剧情,结合场地背景描述和相关人物描述,为这个拍摄片段生成用于AI视频生成工具的「首帧静态视觉描述提示词」(用中文输出)。 |
| | | |
| | | 【核心目标】 |
| | | 你生成的提示词是用来生成**一幅静态的高质量首帧图片**。视频生成工具(如 SVD, Luma, Kling)将以此图为基准进行运动。 |
| | | 你生成的提示词用于生成一幅静态、高质量、可作为视频首帧的图片。首帧应该提供人物、场景、站位和关系的稳定初始状态,让视频模型后续再产生动作。 |
| | | |
| | | 【要求】 |
| | | 1. **绝对静态构图**:提示词必须聚焦于这个片段的**视频首帧(完全静态的截图)**画面。提示词中**绝对不能**涉及到任何时间的变化。 |
| | | 2. **禁止描述动作与过程**:**绝对不要**使用动词进行时,**严禁**描述过程性动作(如正在跑、腾空、起跳、转身、起身、坐下等)。 |
| | | 3. **聚焦物理位置与静态姿势**: |
| | | - 只能描述人物的具体位置和静止状态的基础姿势(例如:站立、坐着、躺着、靠着、蹲着)。 |
| | | - 将所有剧本里的动作转化为**动作开始前的完全静止状态**。 |
| | | - 绝对不要描述人物的心理意图(例如“想要看外面”、“打算离开”等)。 |
| | | 4. **朝向与目光(强制)**:必须明确规定每个角色的身体朝向以及目光看向的具体位置(例如:面向镜头、背对镜头、侧面视角、平静地注视具体物体等)。 |
| | | 5. **环境与质量**:将人设、场设细节融入。必须包含质量词(如:杰作、电影感构图等)。环境描述必须是那一瞬间的死物状态,不得有环境变迁。 |
| | | 6. **视觉外貌**:根据【完整剧本概览】判断当前人物的穿着和场地状态。如果发生过变装或破坏,只描述当前的静态外观表象(如:穿着西装、地上满是碎玻璃),**禁止出现“发生改变”、“逐渐变成”等动态转变描述**。 |
| | | 【关键原则】 |
| | | 首帧不需要表现动作,也不应该表现动作的起始瞬间。请把剧情中的动作和台词理解为上下文,只提炼出这一片段开始时画面中应该存在的静态信息: |
| | | - 谁在画面里; |
| | | - 每个人在什么位置; |
| | | - 每个人是站着、坐着、靠着、蹲着还是其他稳定姿态; |
| | | - 每个人的身体朝向和视线方向; |
| | | - 人物之间是否对话、对峙、协作、回避、压迫或被压迫; |
| | | - 场景中与人物相关的桌椅、门、墙、道具等空间关系。 |
| | | |
| | | --- |
| | | 【硬性要求】 |
| | | 1. 绝对静态:提示词必须描述静态画面,不要描述时间变化、动作过程或运动轨迹。 |
| | | 2. 不表现动作:不要写正在跑、正在转身、正在坐下、正在起身、伸手抓取、挥手、推门、打斗、摔倒等过程性动作。可以写“站在门边”“坐在椅子上”“手放在桌面旁”“身体微微前倾”等静态状态。 |
| | | 3. 强调人物状态:描述人物的姿态、表情、情绪、身体朝向、视线方向和人物间关系。例如“看向对方”“回避视线”“隔着会议桌对峙”“站在门口等待”。 |
| | | 4. 强调人物与场景关系:人物不能穿模,必须明确人物与桌椅、门、墙、车辆、道具等的合理空间关系,例如“站在桌旁”“坐在椅子上”“靠近门边”,避免“身体嵌入桌子/墙面/椅背”。 |
| | | 5. 保持角色外观:根据人物描述和完整剧本概览判断当前人物穿着、发型、年龄感、身份气质。不要改变角色核心外貌。 |
| | | 6. 保持场景准确:结合场地描述,写清地点、主要空间结构、关键物件和光线氛围。 |
| | | 7. 明确镜头语言:包含景别、机位、构图、主体位置。多人片段应尽量让人物关系和视线方向清楚。 |
| | | 8. 视觉质量:包含高质量静态图片描述,如电影感构图、清晰主体、自然光线、细节稳定。 |
| | | |
| | | 【禁止内容】 |
| | | - 不要描述“动作开始前”“即将”“准备要”“马上”“正在”等会暗示动作过程的词。 |
| | | - 不要描述心理意图,例如“想要离开”“打算反击”。 |
| | | - 不要加入文字、水印、字幕、标签、说明牌、UI元素。 |
| | | - 不要输出解释,不要使用 Markdown。 |
| | | |
| | | 【完整剧本概览】 |
| | | {original_text} |
| | |
| | | 【场地基础环境描述】 |
| | | {setting_description} |
| | | |
| | | --- |
| | | |
| | | 【示例参考】 |
| | | (反面): 一个男人快速跑向窗户,打算跳出去,对着外面大喊。 |
| | | (正面): 电影感构图,一个男人站在大窗户前,保持垂直站立的姿势,身体与大窗户成45度角,面向玻璃窗,眼神注视着玻璃窗外静止的街道,处于完全静止状态,高对比度光效。 |
| | | |
| | | --- |
| | | 反面:一个男人正在跑向窗户,打算跳出去,对着外面大喊。 |
| | | 正面:电影感中景,一个男人站在大窗户前,身体与玻璃窗成45度角,面向窗户,视线看向窗外静止的街道;人物双脚稳定站立,手臂自然垂在身体两侧,窗边和人物之间留有清晰空间关系,高对比度自然光,画面完全静止。 |
| | | |
| | | 【输出格式】 |
| | | 直接输出最终的视觉提示词文本,用中文输出。 |
| | | 直接输出最终的中文视觉提示词文本。只输出提示词,不要解释。 |
| | |
| | | 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's script must remain between 20-30 lines of action or dialogue (roughly 20-30 actions or dialogues). Do not output character bios, outlines, or prefaces. Directly output the script text starting from "## Episode 1". |
| | | 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". |
| | | 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. |
| | |
| | | [Content Requirements]: |
| | | 1. **Adaptation Principles**: Optimize narrative rhythm for short micro-dramas strictly maintaining the core plot, key dialogue structure, and character relationships provided in the "core inspiration/story setting". Do not deviate from the original spirit or arbitrarily inject irrelevant plotlines. |
| | | 2. **Extreme Conflict and Pacing (Max Satisfaction)**: The opening must instantly hit a boiling point of conflict (e.g., forced resignation, torn engagements, public humiliation). Dialogues must be sharp, aggressive, and weaponized like crossing swords—absolutely no polite transitions. The plot MUST include intense reversals and "face-slapping" payoffs (e.g., hidden god-tier identity exposed, dramatic comeback), ensuring each episode ends with a strong cliffhanger. |
| | | - Dialogue must stay complete and natural. Do not create tiny, choppy dialogue just to satisfy the line count. |
| | | 3. **High-Tension Body Language**: Use highly explosive and emotionally externalized physical action descriptions (e.g., "slamming a document on the table", "looking up sharply", "staring dead in the eyes", "walking in with full aura", "looking down upon") to maximize on-screen dramatic impact. |
| | | 4. **Exaggerated Bystander Reactions**: During key narrative twists or "face-slapping" moments, immediately dictate the intense physical reactions of antagonists or bystanders (e.g., "deadly silence", "unanimously gasping", "jumping up in shock", "trembling"). This elevates the protagonist's aura. (Note: These must be physical movements. DO NOT describe skin color changes or turning pale; use physical movements like staggering back instead). |
| | | 5. **Strict Action and Visual Restrictions**: |
| | |
| | | |
| | | --- |
| | | |
| | | Now, begin your creation. Based on the [User Core Inspiration/Story Setting], output the complete script text containing {episodes} episodes. Each episode is estimated at 1-2 minutes, with about 20-30 lines of action or dialogue. 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 {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. |
| | |
| | | ### 核心原则:对话为王 |
| | | 微短剧的成败在于台词。你必须遵循:**对话是骨架,动作是点缀**。 |
| | | - **对话比例**:每集台词必须占 70% 以上(约 15-20 条),动作描写仅占 30%(不超过 10 条)。 |
| | | - **台词完整**:台词要像真人说话,有完整的信息和回应,不要为了控制行数写成几个字的碎句。 |
| | | - **动作极简**:每个 <action> 描写不得超过 20 个字,严禁描述冗长的打斗或连续的肢体反应。 |
| | | - **信息全口述**:严禁通过画面传递信息。所有身份证明、反转契机、手机消息、合同内容,必须由角色“亲口说出来”。 |
| | | |
| | | ### 剧本格式规范 |
| | | 1. **分集结构**:严格按集划分,每集剧本情节 25-30 行。 |
| | | 1. **分集结构**:严格按集划分,每集剧本正文只能有 25-30 行动作或台词,推荐 26-29 行,绝对不能超过 30 行。 |
| | | 2. **场志格式(居中加粗)**:`**第x集-第y场 日/夜 内/外 场景名称**` |
| | | - 下行紧跟:`人物:xxx, xxx` |
| | | 3. **动作描写**:必须以 `<action>` 开头,独立成行。 |
| | | 4. **对话排版**:`角色名(情绪提示):台词内容`。 |
| | | 5. **行数计算**:只统计动作行和台词行;集标题、场志、人物行不计入 30 行上限。 |
| | | |
| | | ### 创作要求 |
| | | 1. **钩子开场**:第1集首句台词必须是冲突爆发点(如:离婚、破产、摊牌)。 |
| | |
| | | --- |
| | | |
| | | ### 开始创作 |
| | | 请直接从“## 第1集”开始输出。 |
| | | 请直接从“## 第1集”开始输出。输出前先自检每集动作/台词行数,任何一集超过 30 行都必须删除支线、删除重复反应、减少场次,而不是把台词改成不完整的短句。 |
| | |
| | | 1. Dialogues must absolutely not contain ellipses (... or ……), nor models, codes, special symbols, or any unreadable text. |
| | | 2. **Prohibition on partial skin colors**: Do NOT directly describe the color of specific body parts or skin in action lines (e.g., "fingertips turning white", "dark circles under eyes", "pale face"). |
| | | 3. Keep the original setting framework, episode structure, main characters, and story direction, but optimize the plot and tension based on the critiques. |
| | | 4. Keep the original episode count. Do not add side plots or expand the story. |
| | | 5. Each episode must contain 25-30 action/dialogue lines and must NEVER exceed 30. Episode headings, scene headings, and character-list lines do not count. |
| | | 6. If the revisions make the script longer, control the length by deleting repeated insults, repeated reaction actions, and empty transitions. Do not turn complete dialogue into short, choppy fragments. |
| | | 7. Each action line must start with `<action>` and remain concise. |
| | | 8. Dialogue must remain natural, complete, and coherent with the surrounding conversation. |
| | | |
| | | Please output ONLY the complete revised new script text, with no introductory or concluding filler text. |
| | |
| | | |
| | | 【情节修改意见】 |
| | | {plot_critique} |
| | | |
| | | 请根据意见优化剧本,但必须遵守以下硬性要求: |
| | | 1. 只输出完整修订后的剧本文本,不要解释,不要 Markdown 代码块。 |
| | | 2. 保持原有集数、主要人物、主要场景和主线方向,不要新增支线,不要扩写剧情。 |
| | | 3. 每集正文只能有 25-30 行动作或台词,绝对不能超过 30 行;集标题、场志、人物行不计入行数。 |
| | | 4. 如果修改意见会导致内容变长,必须通过删除重复羞辱、重复反应动作、无信息量过渡来控制行数;不要把完整台词压成几个字的短句。 |
| | | 5. 动作必须以 `<action>` 开头,且每条动作不超过 20 个字。 |
| | | 6. 严禁描写无法拍摄的心理活动,严禁通过画面文字传递信息。 |
| | | 7. 台词必须保持自然、完整、能承接上下文;修订完成前请自检每集动作/台词行数,超出 30 行必须继续删减重复内容后再输出。 |
| | |
| | | - **绝对不要描述场景变化**、环境变更或特效。剧本正文中只应该出现人物动作和人物台词。绝不写无法拍出的心理活动。 |
| | | 6. **生动的对话与同步独白**:对白要符合人物的身份与情绪,情绪和动作提示写在角色名后的括号里。例如:`林逸尘(冷笑):……` |
| | | * **严禁描述画面中的文字**:剧本中**绝对不能**出现“手机上显示着xxx”、“看纸条”等镜头对准文字的描述。一切需要传达的信息,**全部必须通过人物的自然对话、说出或画外音**来体现。不要指望观众能看到画面里的字。 |
| | | 7. **时长要求**:一集的时长在1-2分钟,大概是20-30个动作或台词(即每集剧本20-30行),注意控制每集剧本的篇幅。 |
| | | 7. **时长要求**:一集的时长在1-2分钟,大概是25-30个动作或台词(即每集剧本25-30行),注意控制每集剧本的篇幅。 |
| | | |
| | | 【输出要求】 |
| | | 请直接给出续写的 {episodes_to_add} 集剧本正文即可,不要包含任何 json 格式或 ```。 |
| | | 明确分集标题(如“第{start_episode_num}集”),且必须严格按照上述**场次排版规则**输出剧本正文。 |
| | | 每集时长预估1到2分钟,大概20-30个动作或台词(即每集剧本20-30行),注意控制每集剧本的篇幅。 |
| | | 每集时长预估1到2分钟,大概25-30个动作或台词(即每集剧本25-30行),注意控制每集剧本的篇幅。 |
| | | 只输出剧本正文,不需要任何前言或总结。 |
| New file |
| | |
| | | You are a micro-drama structural trimming editor. Reduce the script to the strict length requirements below. |
| | | |
| | | [Hard Length Requirements] |
| | | 1. Each episode must keep {min_lines}-{max_lines} action/dialogue lines and must NEVER exceed {max_lines} lines. |
| | | 2. Episode headings, scene headings, and character-list lines do not count. |
| | | 3. Preserve the original episode count, main plot, main characters, main settings, and each episode's cliffhanger. |
| | | 4. Do not add new plot, do not expand, and do not explain. |
| | | 5. This is line-level trimming, not dialogue summarization. Do NOT turn complete dialogue into short, choppy lines. Do NOT make dialogue unnatural or incoherent. |
| | | 6. Prefer deleting whole low-value lines: repeated insults, repeated reaction actions, repeated reversal explanations, empty bystander reactions, and optional transition actions. |
| | | 7. Preserve the original dialogue wording, causal flow, and emotional escalation as much as possible. If a dialogue line must be edited, only lightly polish it for clarity; do not significantly shorten its meaning. |
| | | 8. Do not merge dialogue from different speakers. Do not skip necessary responses in a conversation. |
| | | 9. Action lines must start with `<action>`. Dialogue must keep the character-name-colon format. |
| | | |
| | | [Current Line Counts] |
| | | {line_report} |
| | | |
| | | [Script To Compress] |
| | | {script_text} |
| | | |
| | | Output only the complete trimmed script text. |
| New file |
| | |
| | | 你是微短剧剧本结构删减编辑。请把下面的剧本控制到严格篇幅要求内。 |
| | | |
| | | 【硬性篇幅要求】 |
| | | 1. 每集正文必须保留 {min_lines}-{max_lines} 行动作或台词,绝对不能超过 {max_lines} 行。 |
| | | 2. 集标题、场志、人物行不计入行数。 |
| | | 3. 保持原有集数、主线、主要人物、主要场景和每集结尾钩子。 |
| | | 4. 不要新增剧情,不要扩写,不要解释。 |
| | | 5. 这是“删减行数”,不是“缩写台词”。不要把一句完整台词改成几个字的短句,不要把台词改得口语不通顺。 |
| | | 6. 优先整行删除:重复羞辱、重复反应动作、重复转折说明、无信息量的围观反应、可有可无的过渡动作。 |
| | | 7. 尽量保留原台词的完整句式、因果和情绪推进;如必须改台词,只能轻微润色使其更顺,不能明显缩短语义。 |
| | | 8. 不要合并不同人物的台词;不要让角色突然跳过回应,导致上下文断裂。 |
| | | 9. 动作必须以 `<action>` 开头,台词格式保持“角色:台词”或“角色(情绪):台词”。 |
| | | |
| | | 【当前行数统计】 |
| | | {line_report} |
| | | |
| | | 【待压缩剧本】 |
| | | {script_text} |
| | | |
| | | 请只输出删减后的完整剧本文本。 |
| | |
| | | 你是一个专业的AI图像质量评估师。请根据以下信息评估生成的场景参考图。 |
| | | 你是一个专业的AI场景资产图评估师。请评估生成的场景参考图是否可作为后续视频生成的稳定环境资产。 |
| | | |
| | | 场景描述: |
| | | {setting_description} |
| | | |
| | | 请严格按照以下标准评估并给出1-10分: |
| | | 请先判断【硬性失败项】。只要命中任意硬性失败项,is_acceptable 必须为 false,即使图片美观也不能通过。 |
| | | |
| | | 【评分标准】 |
| | | 满分10分,每个检查项符合得1分,不符合扣1分,最高10分: |
| | | 【硬性失败项】 |
| | | 1. 场景类型错误:描述是办公室/教室/会议室/街道/病房等,但图片明显是另一个地点。 |
| | | 2. 核心空间不可用:画面无法看出主要空间结构,不能作为环境参考。 |
| | | 3. 关键元素缺失或错误:描述中的核心物件不存在或完全错位,例如会议桌、黑板、病床、前台、工位等。 |
| | | 4. 出现无关主角或大量无关人物,导致场景资产不可复用;如果描述明确需要空场景,则人物出现属于硬性失败。 |
| | | 5. 出现文字、水印、标签、标注线、说明文字或明显UI元素。 |
| | | 6. 图片严重模糊、过曝、过暗、透视严重崩坏或低清,无法看清场景结构。 |
| | | |
| | | 1. 地点一致性(+1/-1):场景地点是否与描述一致 |
| | | 2. 布局还原(+1/-1):场景布局、物品摆放是否与描述一致 |
| | | 3. 光线氛围(+1/-1):光线是否与描述一致(日/夜、暖/冷) |
| | | 4. 色彩还原(+1/-1):场景色彩是否与描述一致 |
| | | 5. 风格一致性(+1/-1):整体风格是否符合设定 |
| | | 6. 细节完整(+1/-1):细节是否丰富,无明显缺失 |
| | | 7. 空间感(+1/-1):空间透视是否合理 |
| | | 8. 构图质量(+1/-1):构图是否均衡、美观 |
| | | 9. 图片质量(+1/-1):清晰度良好,无模糊、无畸变 |
| | | 10. 无无关元素(+1/-1):无文字、水印、标签等无关内容 |
| | | 若没有硬性失败项,再评估【软性维度】并给出1-10分。软性问题可以扣分,但不应单独导致不合格。 |
| | | |
| | | 【扣分项】(发现以下问题必须扣分并在issues中列出): |
| | | - 场景地点与描述不符:-1分 |
| | | - 光线氛围与描述不符:-1分 |
| | | - 出现不需要的元素:-1分 |
| | | - 构图严重偏斜:-1分 |
| | | - 出现文字/水印:-1分 |
| | | 【软性维度】 |
| | | 1. 布局匹配:空间布局、物品摆放是否贴合描述。 |
| | | 2. 关键元素质量:核心物件是否清晰、可信、可作为参考。 |
| | | 3. 光线氛围:日/夜、冷暖、明暗是否与描述大体一致。 |
| | | 4. 色彩风格:整体色彩与项目风格是否一致。 |
| | | 5. 空间透视:透视是否自然,空间深度是否可读。 |
| | | 6. 构图可用:主体空间清楚,后续视频生成容易引用。 |
| | | 7. 细节丰富度:环境细节足够,但不过度杂乱。 |
| | | |
| | | 【最终评分规则】 |
| | | - 8分及以上:可接受(is_acceptable: true) |
| | | - 7分及以下:需要重新生成(is_acceptable: false) |
| | | 【合格标准】 |
| | | - 如果 hard_failures 非空:is_acceptable=false,score 最高不得超过6。 |
| | | - 如果 hard_failures 为空且 score >= 7:is_acceptable=true。 |
| | | - 如果 hard_failures 为空但 score < 7:is_acceptable=false。 |
| | | - 布局不完全一致、光线普通、细节略少属于 soft_issues,不应直接作为硬性失败。 |
| | | |
| | | 请输出纯JSON格式(不要用```包裹): |
| | | {{ |
| | | "score": 1-10, |
| | | "issues": ["问题1", "问题2", ...], |
| | | "hard_failures": ["硬性失败项1", "硬性失败项2"], |
| | | "soft_issues": ["软性问题1", "软性问题2"], |
| | | "issues": ["合并后的主要问题列表"], |
| | | "is_acceptable": true/false, |
| | | "suggestion": "修改建议(如果有问题)" |
| | | "suggestion": "如果需要重新生成,说明最应该修正什么;如果可接受则为空字符串" |
| | | }} |
| | | |
| | | 如果图片可接受,issues 返回空数组 []。 |
| New file |
| | |
| | | 你是影视分镜设计师。请为第 {episode_number} 集《{episode_title}》的第 {segment_number} 个视频片段设计镜头。 |
| | | |
| | | 只输出一个 JSON 对象,不要 Markdown,不要解释。格式必须是: |
| | | {{ |
| | | "location": "{location}", |
| | | "characters": {characters}, |
| | | "shots": [ |
| | | {{ |
| | | "unit_id": "U001", |
| | | "shot_type": "中景", |
| | | "duration": 5, |
| | | "content": "中景,平视机位,..." |
| | | }} |
| | | ] |
| | | }} |
| | | |
| | | 硬性规则: |
| | | 1. shots 必须与输入 items 一一对应,unit_id 不能遗漏、不能重复、不能新增。 |
| | | 2. 每个 shot.duration 默认等于对应 item.duration;如果本片段 items 总时长不足 5 秒,请只延长最后一个 shot.duration,使 shots 总时长达到 5 秒。 |
| | | 3. shot_type 只能是“近景”“中景”“全景”。 |
| | | 4. 本片段第一个分镜必须是“中景”或“全景”,拍摄位置必须是“平视”,能同时拍到这个片段中的所有人物,并描述所有人物站位。 |
| | | 5. 每个 content 都必须包含拍摄位置:相机从什么角度拍摄,人物朝向在画面中怎样。 |
| | | 6. 动作/台词必须保留原文,不要改写;可以在 content 中补充镜头调度,但原文必须完整出现。 |
| | | 7. 风格参考:{style}。 |
| | | |
| | | {retry_feedback} |
| | | |
| | | 片段信息: |
| | | location: {location} |
| | | characters: {characters} |
| | | total_duration: {total_duration} |
| | | items: {items} |
| New file |
| | |
| | | 你是影视分镜前置规划助手。请把第 {episode_number} 集《{episode_title}》按动作/台词划分成视频生成片段。 |
| | | |
| | | 输入剧本已经在每一行动作或台词开头标注了 [时长][unit_id],例如 [6秒][U003] 角色:台词。 |
| | | 请只输出 JSON 数组,不要 Markdown,不要解释。每个数组元素格式: |
| | | [ |
| | | {{ |
| | | "segment_number": 1, |
| | | "location": "场景地点", |
| | | "unit_ids": ["U001", "U002"] |
| | | }} |
| | | ] |
| | | |
| | | 划分规则: |
| | | 1. 场景切换时必须切分片段,片段不能跨场景。 |
| | | 2. 有人物入场的情节必须切分片段,入场动作必须作为新片段的第一项,例如“某人走进办公室/推门进来/进入教室”。 |
| | | 3. 每个片段的总时长优先控制在大于等于 5 秒、小于等于 15 秒;如果因为场景切换、人物入场等硬性边界导致片段不足 5 秒,允许单独成片段,系统后续会把输出时长覆盖为 5 秒。 |
| | | 4. unit_ids 必须完整覆盖输入中的每一个动作/台词,顺序不能改变,不能重复,不能遗漏。 |
| | | 5. 不要输出动作原文、台词原文、items 或其他字段,只输出 segment_number、location、unit_ids。 |
| | | |
| | | {retry_feedback} |
| | | |
| | | 已有角色列表: |
| | | {asset_characters} |
| | | |
| | | 已有场景列表: |
| | | {asset_settings} |
| | | |
| | | 带时长剧本: |
| | | {annotated_script} |
| | |
| | | T2I_PROVIDERS, |
| | | VIDEO_PROVIDERS, |
| | | VIDEO_RATIOS, |
| | | VIDEO_RESOLUTIONS, |
| | | VLM_PROVIDERS, |
| | | STYLES, |
| | | type ProviderGroup, |
| | | } from '@/config/models'; |
| | | |
| | |
| | | { path: 'models.image_it2i', label: 'image_it2i', type: 'select', options: MODEL_SELECTS.image_it2i }, |
| | | { path: 'models.image_t2i', label: 'image_t2i', type: 'select', options: MODEL_SELECTS.image_t2i }, |
| | | { path: 'models.video', label: 'video', type: 'select', options: MODEL_SELECTS.video }, |
| | | { path: 'models.video_ratio', label: 'video_ratio', type: 'select', options: VIDEO_RATIOS }, |
| | | { path: 'models.eval', label: 'eval', type: 'select', options: MODEL_SELECTS.eval }, |
| | | ], |
| | | }, |
| | | { |
| | | title: '视频生成配置', |
| | | description: '只对主流程生效:风格、画幅比例和视频分辨率。', |
| | | fields: [ |
| | | { path: 'generation.style', label: '风格', type: 'select', options: STYLES }, |
| | | { path: 'generation.video_ratio', label: '视频长宽比', type: 'select', options: VIDEO_RATIOS }, |
| | | { path: 'generation.video_resolution', label: '视频分辨率', type: 'select', options: VIDEO_RESOLUTIONS }, |
| | | ], |
| | | }, |
| | | ]; |
| | | |
| | | function getValue(config: ConfigTree, path: string) { |
| | |
| | | import { usePathname, useRouter } from 'next/navigation'; |
| | | import { ChevronLeft, ChevronRight, Clapperboard, Clock, Hexagon, Home, Loader2, PanelLeftOpen, Repeat2, Settings, Trash2, UserRound } from 'lucide-react'; |
| | | import clsx from 'clsx'; |
| | | import { useEffect, useState } from 'react'; |
| | | import { useEffect, useState, type CSSProperties } from 'react'; |
| | | import { clearTempCache, fetchPipelineTasks, fetchSandboxTasks, fetchSessions, type PipelineTask, type SandboxTask } from '@/lib/workflowApi'; |
| | | |
| | | const NAV_ITEMS = [ |
| | |
| | | }; |
| | | |
| | | return ( |
| | | <div className="min-h-screen bg-gray-50 text-gray-800"> |
| | | <div |
| | | className="min-h-screen bg-gray-50 text-gray-800" |
| | | style={{ '--app-sidebar-width': open ? '15rem' : '0px' } as CSSProperties} |
| | | > |
| | | <aside |
| | | className={clsx( |
| | | 'fixed inset-y-0 left-0 z-40 border-r border-gray-200 bg-white shadow-sm transition-all duration-300', |
| | |
| | | |
| | | export default function BrandHeader() { |
| | | return ( |
| | | <header className="min-h-14 bg-white border-b border-gray-200 flex items-center px-4 flex-shrink-0 z-10 min-w-0"> |
| | | <> |
| | | <header className="fixed top-0 right-0 left-[var(--app-sidebar-width)] z-30 h-14 bg-white border-b border-gray-200 flex items-center px-4 min-w-0 transition-[left] duration-300"> |
| | | <Link href="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity flex-shrink-0"> |
| | | <img |
| | | src="/logo.jpg" |
| | |
| | | </span> |
| | | </Link> |
| | | </header> |
| | | <div className="h-14 flex-shrink-0" /> |
| | | </> |
| | | ); |
| | | } |
| | |
| | | import { Sparkles, Play, Settings2, Clock, ArrowRight, Zap, CheckCircle, Trash2, X, Lock, Globe, ListOrdered, Upload, Loader2 } from 'lucide-react'; |
| | | import clsx from 'clsx'; |
| | | import { PROMPT_EXAMPLES } from '@/config/examples'; |
| | | import { STYLES, VIDEO_RATIOS, LLM_PROVIDERS, T2I_PROVIDERS, I2I_PROVIDERS, VIDEO_PROVIDERS, VLM_PROVIDERS } from '@/config/models'; |
| | | import { STYLES, VIDEO_RATIOS, VIDEO_RESOLUTIONS, LLM_PROVIDERS, T2I_PROVIDERS, I2I_PROVIDERS, VIDEO_PROVIDERS, VLM_PROVIDERS } from '@/config/models'; |
| | | import { STAGES } from './TopBar'; |
| | | |
| | | export interface ProjectParams { |
| | |
| | | file_path?: string; // 上传的文件路径 (由后端返回的文件名) |
| | | style: string; |
| | | video_ratio: string; |
| | | video_resolution: string; |
| | | llm_model: string; |
| | | vlm_model: string; |
| | | image_t2i_model: string; |
| | |
| | | const [selectedI2I, setSelectedI2I] = useState(''); |
| | | const [selectedVideo, setSelectedVideo] = useState(''); |
| | | const [selectedRatio, setSelectedRatio] = useState(''); |
| | | const [selectedResolution, setSelectedResolution] = useState('720P'); |
| | | const [configLoading, setConfigLoading] = useState(true); |
| | | const [configError, setConfigError] = useState(''); |
| | | const [enableConcurrency, setEnableConcurrency] = useState(true); |
| | |
| | | const [deleteTarget, setDeleteTarget] = useState<string | null>(null); |
| | | const [deleteError, setDeleteError] = useState(''); |
| | | const [deleting, setDeleting] = useState(false); |
| | | const modelConfigReady = Boolean(selectedLLM && selectedVLM && selectedT2I && selectedI2I && selectedVideo && selectedRatio); |
| | | const modelConfigReady = Boolean(selectedLLM && selectedVLM && selectedT2I && selectedI2I && selectedVideo && selectedRatio && selectedResolution); |
| | | const canStart = Boolean((idea.trim() || uploadedFile) && modelConfigReady && !configLoading); |
| | | |
| | | useEffect(() => { |
| | |
| | | if (!resp.ok) throw new Error('读取默认模型配置失败'); |
| | | const data = await resp.json(); |
| | | const models = data.config?.models || {}; |
| | | const generation = data.config?.generation || {}; |
| | | if (!models.llm || !models.vlm || !models.image_t2i || !models.image_it2i || !models.video) { |
| | | throw new Error('backend/config.yaml 缺少主流程默认模型'); |
| | | } |
| | | if (cancelled) return; |
| | | setSelectedStyle(generation.style || 'realistic'); |
| | | setSelectedLLM(models.llm); |
| | | setSelectedVLM(models.vlm); |
| | | setSelectedT2I(models.image_t2i); |
| | | setSelectedI2I(models.image_it2i); |
| | | setSelectedVideo(models.video); |
| | | setSelectedRatio(models.video_ratio || '16:9'); |
| | | setSelectedRatio(generation.video_ratio || '16:9'); |
| | | setSelectedResolution(generation.video_resolution || '720P'); |
| | | } catch (e: any) { |
| | | if (!cancelled) setConfigError(e.message || '读取默认模型配置失败'); |
| | | } finally { |
| | |
| | | file_path: uploadedFile?.path, // 如果上传了文件,传给后端 |
| | | style: selectedStyle, |
| | | video_ratio: selectedRatio, |
| | | video_resolution: selectedResolution, |
| | | llm_model: selectedLLM, |
| | | vlm_model: selectedVLM, |
| | | image_t2i_model: selectedT2I, |
| | |
| | | |
| | | {/* 模型设置折叠面板 */} |
| | | {showSettings && ( |
| | | <div className="mt-4 p-4 bg-gray-50 rounded-xl space-y-3 text-xs"> |
| | | <div className="grid grid-cols-2 gap-3"> |
| | | <div className="mt-4 p-4 bg-gray-50 rounded-xl space-y-4 text-xs"> |
| | | <div className="grid grid-cols-1 gap-3"> |
| | | <label className="flex flex-col gap-1"> |
| | | <span className="text-gray-500 font-medium">风格</span> |
| | | <select |
| | |
| | | ))} |
| | | </select> |
| | | </label> |
| | | </div> |
| | | |
| | | <div className="grid grid-cols-2 gap-3"> |
| | | <label className="flex flex-col gap-1"> |
| | | <span className="text-gray-500 font-medium">视频比例</span> |
| | | <span className="text-gray-500 font-medium">视频分辨率</span> |
| | | <select |
| | | value={selectedResolution} |
| | | onChange={e => setSelectedResolution(e.target.value)} |
| | | className="bg-white border border-gray-200 rounded-lg px-2.5 py-2 text-gray-700 outline-none min-h-[40px]" |
| | | > |
| | | {VIDEO_RESOLUTIONS.map(item => ( |
| | | <option key={item.id} value={item.id}>{item.label}</option> |
| | | ))} |
| | | </select> |
| | | </label> |
| | | <label className="flex flex-col gap-1"> |
| | | <span className="text-gray-500 font-medium">视频长宽比</span> |
| | | <div className="flex gap-1"> |
| | | {VIDEO_RATIOS.map(r => ( |
| | | <button |
| | |
| | | ))} |
| | | </div> |
| | | </label> |
| | | </div> |
| | | |
| | | <div className="space-y-3 border-t border-gray-200/70 pt-4"> |
| | | <div className="flex items-center justify-between"> |
| | | <span className="text-gray-500 font-semibold">模型配置</span> |
| | | <span className="text-[10px] text-gray-400">用于主流程各阶段调用</span> |
| | | </div> |
| | | <div className="grid grid-cols-2 gap-3"> |
| | | <label className="flex flex-col gap-1"> |
| | | <span className="text-gray-500 font-medium">LLM 模型</span> |
| | | <select |
| | |
| | | </label> |
| | | </div> |
| | | </div> |
| | | </div> |
| | | )} |
| | | </div> |
| | | |
| | |
| | | import React, { useState, useRef, useEffect } from 'react'; |
| | | import { CheckCircle, Circle, Loader, Edit3, AlertCircle, Square, Zap, Settings2, ChevronDown } from 'lucide-react'; |
| | | import clsx from 'clsx'; |
| | | import { LLM_PROVIDERS, T2I_PROVIDERS, I2I_PROVIDERS, VIDEO_PROVIDERS, VLM_PROVIDERS, VIDEO_RATIOS, ProviderGroup } from '@/config/models'; |
| | | import { LLM_PROVIDERS, T2I_PROVIDERS, I2I_PROVIDERS, VIDEO_PROVIDERS, VLM_PROVIDERS, VIDEO_RATIOS, VIDEO_RESOLUTIONS, ProviderGroup } from '@/config/models'; |
| | | |
| | | export type StageStatus = 'pending' | 'running' | 'waiting' | 'completed' | 'error' | 'stopped'; |
| | | |
| | |
| | | image_it2i_model: string; |
| | | video_model: string; |
| | | video_ratio: string; |
| | | video_resolution: string; |
| | | enable_concurrency: boolean; |
| | | } |
| | | |
| | |
| | | ))} |
| | | </div> |
| | | </label> |
| | | <label className="flex flex-col gap-1"> |
| | | <span className="text-[10px] text-gray-400 font-medium">视频分辨率</span> |
| | | <select |
| | | value={config.video_resolution} |
| | | onChange={e => update('video_resolution', e.target.value)} |
| | | className="bg-gray-50 border border-gray-200 rounded-lg px-2 py-1.5 text-xs text-gray-700 outline-none w-full" |
| | | > |
| | | {VIDEO_RESOLUTIONS.map(item => ( |
| | | <option key={item.id} value={item.id}>{item.label}</option> |
| | | ))} |
| | | </select> |
| | | </label> |
| | | <label className="flex items-center gap-2 text-xs cursor-pointer select-none"> |
| | | <input |
| | | type="checkbox" |
| | |
| | | }; |
| | | |
| | | return ( |
| | | <header className="min-h-14 bg-white border-b border-gray-200 flex items-center px-4 flex-shrink-0 z-10 min-w-0"> |
| | | <> |
| | | <header className="fixed top-0 right-0 left-[var(--app-sidebar-width)] z-30 h-14 bg-white border-b border-gray-200 flex items-center px-4 min-w-0 transition-[left] duration-300"> |
| | | {/* Logo & 名称 */} |
| | | <button |
| | | onClick={onHomeClick} |
| | |
| | | |
| | | </div> |
| | | </header> |
| | | <div className="h-14 flex-shrink-0" /> |
| | | </> |
| | | ); |
| | | } |
| | |
| | | setHistory( |
| | | sessions.map((s: any) => ({ |
| | | id: s.id, |
| | | idea: (s.idea || 'Untitled').slice(0, 60), |
| | | idea: (s.title || s.idea || 'Untitled').slice(0, 60), |
| | | style: s.style || '', |
| | | date: s.date |
| | | ? new Date(s.date * 1000).toLocaleDateString('zh-CN') |
| | |
| | | file_path: params.file_path, // 修复:将上传的文件路径传给后端 |
| | | style: params.style, |
| | | video_ratio: params.video_ratio, |
| | | video_resolution: params.video_resolution, |
| | | llm_model: params.llm_model, |
| | | vlm_model: params.vlm_model, |
| | | image_t2i_model: params.image_t2i_model, |
| | |
| | | session_id: result.session_id, |
| | | style: params.style, |
| | | video_ratio: params.video_ratio, |
| | | video_resolution: params.video_resolution, |
| | | llm_model: params.llm_model, |
| | | vlm_model: params.vlm_model, |
| | | image_t2i_model: params.image_t2i_model, |
| | |
| | | image_it2i_model: projectParams?.image_it2i_model, |
| | | video_model: projectParams?.video_model, |
| | | video_ratio: projectParams?.video_ratio, |
| | | video_resolution: projectParams?.video_resolution, |
| | | video_sound: videoSound, |
| | | video_shot_type: videoShotType, |
| | | }; |
| | |
| | | session_id: sessionId, |
| | | style: projectParams?.style, |
| | | video_ratio: projectParams?.video_ratio, |
| | | video_resolution: projectParams?.video_resolution, |
| | | llm_model: projectParams?.llm_model, |
| | | vlm_model: projectParams?.vlm_model, |
| | | image_t2i_model: projectParams?.image_t2i_model, |
| | |
| | | image_it2i_model: projectParams?.image_it2i_model, |
| | | video_model: projectParams?.video_model, |
| | | video_ratio: projectParams?.video_ratio, |
| | | video_resolution: projectParams?.video_resolution, |
| | | }; |
| | | |
| | | // 尝试获取场景数 |
| | |
| | | idea: s.idea || '', |
| | | style: s.style || '', |
| | | video_ratio: s.video_ratio || '16:9', |
| | | video_resolution: s.video_resolution || '720P', |
| | | llm_model: s.llm_model || '', |
| | | vlm_model: s.vlm_model || '', |
| | | image_t2i_model: s.image_t2i_model || '', |
| | |
| | | image_it2i_model: projectParams.image_it2i_model, |
| | | video_model: projectParams.video_model, |
| | | video_ratio: projectParams.video_ratio, |
| | | video_resolution: projectParams.video_resolution || '720P', |
| | | enable_concurrency: projectParams.enable_concurrency || false, |
| | | // web_search: projectParams.web_search || false, |
| | | // expand_idea: projectParams.expand_idea || false, |
| | |
| | | T2I_PROVIDERS, |
| | | VIDEO_PROVIDERS, |
| | | VIDEO_RATIOS, |
| | | VIDEO_RESOLUTIONS, |
| | | type ProviderGroup, |
| | | } from '@/config/models'; |
| | | import BrandHeader from '@/components/BrandHeader'; |
| | |
| | | pipeline === 'action_transfer' ? 'wan2.7-videoedit' : pipeline === 'digital_human' ? 'wan2.7-r2v' : DEFAULTS.video |
| | | ); |
| | | const [ratio, setRatio] = useState('9:16'); |
| | | const [videoResolution, setVideoResolution] = useState('720P'); |
| | | const [duration, setDuration] = useState(5); |
| | | const [ttsVoice, setTtsVoice] = useState('zh-CN-YunjianNeural'); |
| | | const [ttsSpeed, setTtsSpeed] = useState(1.2); |
| | |
| | | const common = { |
| | | video_model: videoModel, |
| | | video_ratio: ratio, |
| | | video_resolution: videoResolution, |
| | | duration, |
| | | negative_prompt: negativePrompt || undefined, |
| | | }; |
| | |
| | | llm_model: llmModel, |
| | | image_model: imageModel, |
| | | video_ratio: ratio, |
| | | video_resolution: videoResolution, |
| | | enable_subtitles: templateMode ? true : enableSubtitles, |
| | | subtitle_render_mode: !templateMode && enableSubtitles ? subtitleRenderMode : undefined, |
| | | subtitle_template: templateMode ? selectedTemplate?.id : undefined, |
| | |
| | | image_model: imageModel, |
| | | video_model: videoModel, |
| | | video_ratio: ratio, |
| | | video_resolution: videoResolution, |
| | | tts_voice: ttsVoice, |
| | | tts_speed: ttsSpeed, |
| | | negative_prompt: negativePrompt || undefined, |
| | |
| | | {VIDEO_RATIOS.map(item => <option key={item.id} value={item.id}>{item.label}</option>)} |
| | | </select> |
| | | </label> |
| | | <label className="flex flex-col gap-1.5"> |
| | | <span className="text-xs font-medium text-gray-500">视频分辨率</span> |
| | | <select value={videoResolution} onChange={e => setVideoResolution(e.target.value)} className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none"> |
| | | {VIDEO_RESOLUTIONS.map(item => <option key={item.id} value={item.id}>{item.label}</option>)} |
| | | </select> |
| | | </label> |
| | | {(pipeline === 'action_transfer' || (pipeline === 'standard' && (standardVideoMode === 'dynamic_video' || templateVideoEnabled))) && ( |
| | | <NumberField label="视频时长" value={duration} onChange={setDuration} min={1} max={10} /> |
| | | )} |
| | |
| | | { id: '3:4', label: '3:4', ratio: '3:4' }, |
| | | { id: '21:9', label: '21:9', ratio: '21:9' }, |
| | | ]; |
| | | |
| | | /* ─── 视频分辨率 ─── */ |
| | | export const VIDEO_RESOLUTIONS = [ |
| | | { id: '720P', label: '720P' }, |
| | | { id: '1080P', label: '1080P' }, |
| | | ]; |
| | |
| | | file_path?: string; |
| | | style?: string; |
| | | video_ratio?: string; |
| | | video_resolution?: string; |
| | | llm_model?: string; |
| | | vlm_model?: string; |
| | | image_t2i_model?: string; |
| | |
| | | |
| | | export async function updateModels( |
| | | sessionId: string, |
| | | models: Partial<Record<string, string>>, |
| | | models: Partial<Record<string, string | boolean>>, |
| | | ): Promise<{ status: string }> { |
| | | const resp = await fetch(`/api/project/${sessionId}/models`, { |
| | | method: 'PATCH', |