hit-cxf
2026-06-11 fa72856c7524be8b6345ee5454dda3a31f4d8cdb
Optimize video prompt words, assembled from three parts: style control, character list, and scene list
6 files modified
238 ■■■■■ changed files
video-claw/video-claw/backend/core/agents/character_agent.py 9 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/agents/reference_agent.py 15 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/agents/video_agent.py 135 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/frontend/components/WorkflowPanel.tsx 16 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/frontend/components/stages/VideoStage.tsx 59 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/frontend/components/stages/types.ts 4 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/agents/character_agent.py
@@ -606,6 +606,15 @@
            with ThreadPoolExecutor(max_workers=concurrency) as executor:
                futs = {}
                for atype, aid, name, desc, species in all_tasks:
                    existing_versions = self._list_versions(sid, atype, aid)
                    self._report_progress("角色设计", f"正在生成: {name}", 10, data={
                        "asset_complete": {
                            "type": atype,
                            "id": aid,
                            "status": "running",
                            "versions": existing_versions,
                        }
                    })
                    fut = executor.submit(
                        self._generate_one, img_client,
                        aid, name, desc, atype, style, species, t2i_model, vlm_model, sid,
video-claw/video-claw/backend/core/agents/reference_agent.py
@@ -661,6 +661,15 @@
                        return min(95, 5 + int(90 * completed / max(total, 1)))
                    def regen_segment_run(segment_id: str, index: int):
                        existing_versions = self._list_versions(sid, segment_id)
                        self._report_progress("参考图", f"正在生成: {segment_id}", 5, data={
                            "asset_complete": {
                                "type": "scenes",
                                "id": segment_id,
                                "status": "running",
                                "versions": existing_versions,
                            }
                        })
                        seg = fresh_segment_map.get(segment_id, {})
                        first_shot = seg.get('shots', [])[0] if seg.get('shots') else {}
                        plot = first_shot.get('content', '')
@@ -693,12 +702,6 @@
                                ff_prompt = plot[:200]
                        logger.info(f"[{segment_id}] first-frame prompt: {ff_prompt}...")
                        self._report_progress("参考图", f"正在生成: {segment_id}", 5, data={
                            "asset_complete": {
                                "type": "scenes", "id": segment_id,
                                "status": "running"
                            }
                        })
                        refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map)
                        char_desc, set_desc = self._get_descriptions(
video-claw/video-claw/backend/core/agents/video_agent.py
@@ -2,7 +2,7 @@
"""
阶段5: 视频生成智能体
- 从编排器注入的 artifacts["storyboard"] 读取拍摄片段(Segments)
- 视频提示词:风格前缀 + 分镜列表(分镜1: [时长] content...)
- 视频提示词:风格控制 + 人物列表 + 分镜列表(分镜1: [时长] content...)
- 参考图:从 artifacts["reference_generation"] 读取
- 支持逐项并发生成、实时预览、重新生成
"""
@@ -113,30 +113,88 @@
    # ─── 提示词组装 ───
    def _assemble_prompt(self, segment: dict, style_prompt: str, video_data: Optional[dict]=None) -> str:
        """组装视频提示词
        格式:
        风格控制:用户选择的风格提示词, 电影质感
        分镜列表:分镜1:[时长] content... 分镜2:[时长] content...
        """
        # 如果 video_data 中有 description,则优先使用
        # 前端修改后的提示词会存入 artifacts.video_generation.clips.description
        if video_data and "description" in video_data:
            return video_data["description"]
        # 否则从 segment 中组装
        prompt = f"风格控制:{style_prompt}\n"
        prompt += "分镜列表:"
    def _format_shot_section(self, segment: dict) -> str:
        prompt = "分镜列表:"
        shots = segment.get("shots", [])
        for i, shot in enumerate(shots, 1):
            dur = shot.get("duration", 5)
            content = shot.get("content", "").strip()
            prompt += f"\n分镜{i}:[{dur}秒] {content}"
        prompt += "\n不要生成字幕或水印"
        return prompt
    @staticmethod
    def _extract_shot_section(prompt: str) -> str:
        text = (prompt or "").strip()
        if not text:
            return "分镜列表:"
        marker = "分镜列表:"
        alt_marker = "分镜列表:"
        if marker in text:
            text = text[text.index(marker):].strip()
        elif alt_marker in text:
            text = marker + text[text.index(alt_marker) + len(alt_marker):].strip()
        else:
            text = f"{marker}\n{text}"
        no_caption_marker = "\n不要生成字幕或水印"
        if no_caption_marker in text:
            text = text[:text.index(no_caption_marker)].rstrip()
        return text
    def _display_prompt(self, segment: dict, video_data: Optional[dict] = None) -> str:
        """前端只展示可编辑的分镜列表;风格和人物信息在调用视频模型前即时拼接。"""
        if video_data and video_data.get("description"):
            return self._extract_shot_section(video_data["description"])
        return self._format_shot_section(segment)
    def _build_character_section(self, segment: dict, character_artifact: Optional[dict]) -> str:
        characters = character_artifact.get("characters", []) if isinstance(character_artifact, dict) else []
        if not characters:
            return "人物列表:无"
        character_map = self._build_name_asset_map(characters)
        selected_assets = []
        seen = set()
        for character_name in segment.get("characters") or []:
            asset = self._match_asset_by_name(str(character_name), characters, character_map)
            asset_key = str(asset.get("id") or asset.get("name") or "") if asset else ""
            if asset and asset_key not in seen:
                selected_assets.append(asset)
                seen.add(asset_key)
        lines = []
        for asset in selected_assets:
            name = str(asset.get("name") or asset.get("id") or "").strip()
            desc = str(asset.get("description") or "").strip()
            if name and desc:
                lines.append(f"- {name}:{desc}")
            elif name:
                lines.append(f"- {name}")
        return "人物列表:\n" + "\n".join(lines) if lines else "人物列表:无"
    def _assemble_prompt(self, segment: dict, style_prompt: str,
                         character_artifact: Optional[dict] = None,
                         video_data: Optional[dict] = None) -> str:
        """组装视频提示词
        格式:
        风格控制:用户选择的风格提示词, 电影质感
        人物列表:从第二阶段人物描述读取
        分镜列表:分镜1:[时长] content... 分镜2:[时长] content...
        """
        if video_data and "description" in video_data:
            # 前端修改后的提示词会存入 artifacts.video_generation.clips.description。
            # 兼容旧格式:保留用户修改过的分镜部分,重新补齐最新风格和人物列表。
            shot_section = self._extract_shot_section(video_data["description"])
        else:
            shot_section = self._format_shot_section(segment)
        return (
            f"风格控制:{style_prompt}\n"
            f"{self._build_character_section(segment, character_artifact)}\n"
            f"{shot_section}\n"
            "不要生成字幕或水印"
        )
    def _get_style_keywords(self, session_data: dict) -> str:
        """从会话数据获取风格关键词"""
@@ -269,8 +327,10 @@
    # ─── 预览 / Payload ───
    def _build_preview(self, sid: str, segments: list, scene_map: dict, style_prompt: str = "") -> list:
    def _build_preview(self, sid: str, segments: list, scene_map: dict,
                       video_clips: Optional[list] = None) -> list:
        preview = []
        clip_map = {c.get("id"): c for c in (video_clips or []) if isinstance(c, dict) and c.get("id")}
        for idx, seg in enumerate(segments, 1):
            segment_id = seg["segment_id"]
            versions = self._list_versions(sid, segment_id)
@@ -281,7 +341,7 @@
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": self._assemble_prompt(seg, style_prompt),
                "description": self._display_prompt(seg, clip_map.get(segment_id)),
                "duration": seg.get('total_duration', 10),
                "selected": versions[-1] if versions else "",
                "versions": versions,
@@ -289,8 +349,9 @@
            })
        return preview
    def _build_payload(self, sid: str, segments: list, style_prompt: str = "") -> dict:
    def _build_payload(self, sid: str, segments: list, video_clips: Optional[list] = None) -> dict:
        clips = []
        clip_map = {c.get("id"): c for c in (video_clips or []) if isinstance(c, dict) and c.get("id")}
        for idx, seg in enumerate(segments, 1):
            segment_id = seg["segment_id"]
            versions = self._list_versions(sid, segment_id)
@@ -301,7 +362,7 @@
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": self._assemble_prompt(seg, style_prompt),
                "description": self._display_prompt(seg, clip_map.get(segment_id)),
                "duration": seg.get('total_duration', 10),
                "selected": versions[-1] if versions else "",
                "versions": versions,
@@ -338,7 +399,8 @@
            segments = []
            for ep in episodes:
                segments.extend(ep.get("segments", []))
            payload = self._build_payload(sid, segments)
            video_clips = artifacts.get('video_generation', {}).get('clips', [])
            payload = self._build_payload(sid, segments, video_clips)
            for clip in payload.get("payload", {}).get("clips", []):
                clip_id = clip.get("id")
                if clip_id in selected_clips:
@@ -353,7 +415,8 @@
        
        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")
        video_sound = "on"
        video_shot_type = "multi"
        artifacts = self._session_artifacts(input_data)
        
@@ -404,7 +467,7 @@
                            seg = segment_map.get(seg_id)
                            clip = clip_map.get(seg_id) if clip_map.get(seg_id) else None
                            if not seg: continue
                            prompt = self._assemble_prompt(seg, style_prompt, video_data=clip)
                            prompt = self._assemble_prompt(seg, style_prompt, character_art, video_data=clip)
                            reference_image_paths = None
                            if video_generation_mode == "reference":
@@ -419,10 +482,18 @@
                            last_img_path = self._get_next_reference_image(sid, seg_index, segments, scene_map)
                            if video_generation_mode == "start_end_frame" and not last_img_path:
                                logger.warning("VideoDirectorAgent: %s 首尾帧模式缺少尾帧,回退为首帧生视频入参", seg_id)
                            existing_versions = self._list_versions(sid, seg_id)
                            self._report_progress("视频生成", f"启动生成: {seg_id}", 5, data={
                                "asset_complete": {
                                    "type": "clips", "id": seg_id,
                                    "status": "running",
                                    "versions": existing_versions,
                                }
                            })
                            fut = executor.submit(
                                self._generate_one, sid, seg_id, prompt,
                                img_path, video_model, duration,
                                "", video_shot_type, video_ratio, video_resolution,
                                video_sound, video_shot_type, video_ratio, video_resolution,
                                video_generation_mode, last_img_path, reference_image_paths
                            )
                            futs[fut] = seg_id
@@ -459,11 +530,11 @@
                # 同步到 session artifacts
                self._update_session_video_data(sid, segments, style_prompt)
                
                return self._build_payload(sid, segments, style_prompt)
                return self._build_payload(sid, segments, video_clips)
        # ═══ 正常流程:全量生成 ═══
        self._report_progress("视频生成", "正在准备数据...", 2)
        preview = self._build_preview(sid, segments, scene_map, style_prompt)
        preview = self._build_preview(sid, segments, scene_map, video_clips)
        self._report_progress("视频生成", "加载视频列表", 5, data={"assets_preview": {"clips": preview}})
        def run():
@@ -472,7 +543,7 @@
                seg_id = seg["segment_id"]
                existing = self._list_versions(sid, seg_id)
                if existing: continue
                prompt = self._assemble_prompt(seg, style_prompt)
                prompt = self._assemble_prompt(seg, style_prompt, character_art)
                reference_image_paths = None
                if video_generation_mode == "reference":
                    img_path = None
@@ -503,7 +574,7 @@
                    fut = executor.submit(
                        self._generate_one, sid, seg_id, prompt,
                        img_path, video_model, dur,
                        "", video_shot_type, video_ratio, video_resolution,
                        video_sound, video_shot_type, video_ratio, video_resolution,
                        video_generation_mode, last_img_path, reference_image_paths
                    )
                    futs[fut] = seg_id
@@ -545,4 +616,4 @@
        self._update_session_video_data(sid, segments, style_prompt)
        
        self._report_progress("视频生成", "完成", 100)
        return self._build_payload(sid, segments, style_prompt)
        return self._build_payload(sid, segments, video_clips)
video-claw/video-claw/frontend/components/WorkflowPanel.tsx
@@ -131,8 +131,6 @@
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [projectParams, setProjectParams] = useState<ProjectParams | null>(null);
  const [autoMode, setAutoMode] = useState(false);
  const [videoSound, setVideoSound] = useState('on');
  const [videoShotType, setVideoShotType] = useState('multi');
  // 用于顶栏流程图状态判断
  const [currentStageFromSession, setCurrentStageFromSession] = useState<string | null>(null);
  const [completedStagesFromSession, setCompletedStagesFromSession] = useState<string[]>([]);
@@ -663,8 +661,8 @@
          video_model: projectParams?.video_model,
          video_ratio: projectParams?.video_ratio,
          video_resolution: projectParams?.video_resolution,
          video_sound: videoSound,
          video_shot_type: videoShotType,
          video_sound: 'on',
          video_shot_type: 'multi',
        };
        // 从剧本产物获取实际场景数
        try {
@@ -768,8 +766,8 @@
      video_start_end_model: projectParams?.video_start_end_model,
      video_reference_model: projectParams?.video_reference_model,
      video_model: projectParams?.video_model,
      video_sound: videoSound,
      video_shot_type: videoShotType,
      video_sound: 'on',
      video_shot_type: 'multi',
    };
    // 设置 running 状态以便显示进度条(如 Logline 选择后生成剧本)
@@ -1374,12 +1372,6 @@
        isRunning={effectiveIsRunning}
        hasPendingItems={hasPendingItems}
        hasNextStageStarted={hasNextStageStarted}
        videoSound={videoSound}
        videoShotType={videoShotType}
        onVideoParamsChange={(params: { videoSound?: string; videoShotType?: string }) => {
          if (params.videoSound !== undefined) setVideoSound(params.videoSound);
          if (params.videoShotType !== undefined) setVideoShotType(params.videoShotType);
        }}
        referenceArtifact={referenceArtifact}
        scriptArtifact={scriptArtifact}
        artifacts={Object.keys(stageStates).reduce((acc: any, key) => {
video-claw/video-claw/frontend/components/stages/VideoStage.tsx
@@ -1,7 +1,7 @@
'use client';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { Film, RefreshCw, ChevronLeft, ChevronRight, Loader, AlertCircle, AlertTriangle, Play, Volume2, VolumeX, Clapperboard, Edit2, Save, X } from 'lucide-react';
import { Film, RefreshCw, ChevronLeft, ChevronRight, Loader, AlertCircle, AlertTriangle, Play, Edit2, Save, X } from 'lucide-react';
import type { StageViewProps } from './types';
import { assetUrl } from './utils';
import StageActions from './StageActions';
@@ -331,7 +331,7 @@
}
/* ─── 主组件 ─── */
export default function VideoStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, videoSound = 'on', videoShotType = 'multi', onVideoParamsChange, referenceArtifact, hasPendingItems, hasNextStageStarted, scriptArtifact }: StageViewProps) {
export default function VideoStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, referenceArtifact, hasPendingItems, hasNextStageStarted, scriptArtifact }: StageViewProps) {
  // 提取剧集标题映射
  const episodeTitleMap = React.useMemo(() => {
    const map: Record<number, string> = {};
@@ -520,61 +520,6 @@
        <p className="text-sm text-gray-500 mb-4">
          将场景参考图转化为视频片段,支持逐项重新生成
        </p>
        {/* ── 视频生成参数 ── */}
        <div className="flex flex-wrap items-center gap-4 sm:gap-6 mb-6 px-4 py-3 bg-white border border-gray-200 rounded-xl">
          {/* 音效开关 */}
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-500 font-medium">音效</span>
            <button
              onClick={() => onVideoParamsChange?.({ videoSound: videoSound === 'on' ? 'off' : 'on' })}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                videoSound === 'on' ? 'bg-rose-500' : 'bg-gray-300'
              }`}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                  videoSound === 'on' ? 'translate-x-6' : 'translate-x-1'
                }`}
              />
            </button>
            {videoSound === 'on' ? (
              <Volume2 className="w-3.5 h-3.5 text-rose-500" />
            ) : (
              <VolumeX className="w-3.5 h-3.5 text-gray-400" />
            )}
          </div>
          <div className="w-px h-5 bg-gray-200" />
          {/* 镜头模式 */}
          <div className="flex items-center gap-2">
            <Clapperboard className="w-3.5 h-3.5 text-gray-400" />
            <span className="text-xs text-gray-500 font-medium">镜头</span>
            <div className="flex gap-1 bg-gray-100 rounded-lg p-0.5">
              <button
                onClick={() => onVideoParamsChange?.({ videoShotType: 'single' })}
                className={`px-3 py-1 rounded-md text-xs font-medium transition-colors ${
                  videoShotType === 'single'
                    ? 'bg-white text-rose-600 shadow-sm'
                    : 'text-gray-500 hover:text-gray-700'
                }`}
              >
                单镜头
              </button>
              <button
                onClick={() => onVideoParamsChange?.({ videoShotType: 'multi' })}
                className={`px-3 py-1 rounded-md text-xs font-medium transition-colors ${
                  videoShotType === 'multi'
                    ? 'bg-white text-rose-600 shadow-sm'
                    : 'text-gray-500 hover:text-gray-700'
                }`}
              >
                多镜头
              </button>
            </div>
          </div>
        </div>
        {/* 运行中 */}
        {state.status === 'running' && (
video-claw/video-claw/frontend/components/stages/types.ts
@@ -23,10 +23,6 @@
  hasPendingItems?: boolean;
  /** 后续阶段是否已开始(阶段1、3使用) */
  hasNextStageStarted?: boolean;
  /** 视频生成参数(仅 VideoStage 使用) */
  videoSound?: string;
  videoShotType?: string;
  onVideoParamsChange?: (params: { videoSound?: string; videoShotType?: string }) => void;
  /** 用于组件访问其他阶段的数据 */
  artifacts?: Record<string, any>;
  /** 参考图阶段的 artifact(仅 VideoStage 使用,用于检查依赖) */