静态短视频改名为文艺短视频,支持图片拼接和视频生成两种模式,并优化WebUI
1 files added
8 files modified
310 ■■■■■ changed files
aigc-director/aigc-claw/backend/api/routers/pipelines.py 4 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/api/schemas/pipelines.py 2 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/pipelines/standard.py 179 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/pipelines/utils.py 24 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/app/pipelines/standard/page.tsx 4 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/AppShell.tsx 2 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/BrandHeader.tsx 20 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/Sandbox/Sandbox.tsx 25 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx 50 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/api/routers/pipelines.py
@@ -38,8 +38,8 @@
            {
                "id": "standard",
                "aliases": ["quick_create"],
                "name": "Static Short Video",
                "description": "Split narration by periods, generate one image per segment, and assemble a static short video without calling a video model.",
                "name": "Artistic Short Video",
                "description": "Split narration by periods, generate one image per segment, and assemble either an image-concat short video or dynamic image-to-video clips.",
            },
            {
                "id": "action_transfer",
aigc-director/aigc-claw/backend/api/schemas/pipelines.py
@@ -7,11 +7,13 @@
    text: str = Field(..., description="Topic or fixed narration script")
    mode: str = "copy"
    title: Optional[str] = None
    segment_count: Optional[int] = Field(None, ge=1, le=20, description="Target narration segment count for inspiration mode")
    n_scenes: int = 5
    split_mode: str = "paragraph"
    llm_model: Optional[str] = None
    image_model: Optional[str] = None
    video_model: Optional[str] = None
    video_mode: str = Field("image_concat", description="image_concat or dynamic_video")
    video_ratio: str = "9:16"
    image_resolution: str = "1080P"
    video_resolution: Optional[str] = None
aigc-director/aigc-claw/backend/pipelines/standard.py
@@ -1,10 +1,13 @@
import json
import logging
import os
import re
from config import settings
from models.llm_client import LLM
from prompts.loader import format_prompt, load_prompt
from .api_media import generate_image_api
from .api_media import generate_image_api, generate_video_api
from .storage import append_artifact, task_output_dir, update_task
from .tts import generate_edge_tts
from .utils import (
@@ -13,6 +16,7 @@
    create_static_image_clip,
    media_duration_seconds,
    render_static_text_image,
    replace_video_audio,
    run_blocking,
    write_json,
    write_text,
@@ -22,20 +26,104 @@
    "Minimalist black-and-white matchstick figure style illustration, clean lines, simple sketch style"
)
logger = logging.getLogger(__name__)
def split_by_periods(text: str) -> list[str]:
    parts = re.findall(r"[^。..]+[。..]?|[^。..]+$", text.strip())
    return [part.strip() for part in parts if part.strip()]
def build_image_prompt(narration: str, style_control: str) -> str:
def clamp_segment_count(value, default: int = 6) -> int:
    try:
        count = int(value)
    except (TypeError, ValueError):
        count = default
    return max(1, min(20, count))
def parse_json_object_response(text: str) -> dict:
    response = text.strip()
    try:
        return json.loads(response)
    except json.JSONDecodeError:
        match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", response, re.S)
        if not match:
            match = re.search(r"(\{.*\})", response, re.S)
        if not match:
            raise ValueError("Model response did not contain a JSON object.")
        return json.loads(match.group(1))
def parse_narrations_response(text: str, expected_count: int) -> list[str]:
    data = parse_json_object_response(text)
    narrations = data.get("narrations") if isinstance(data, dict) else None
    if not isinstance(narrations, list):
        raise ValueError("Model response missing narrations array.")
    segments = [str(item).strip() for item in narrations if str(item).strip()]
    if len(segments) != expected_count:
        raise ValueError(f"Expected {expected_count} narrations, got {len(segments)}.")
    return segments
def parse_image_prompts_response(text: str, expected_count: int) -> list[str]:
    data = parse_json_object_response(text)
    prompts = data.get("image_prompts") if isinstance(data, dict) else None
    if not isinstance(prompts, list):
        raise ValueError("Model response missing image_prompts array.")
    image_prompts = [str(prompt).strip() for prompt in prompts if str(prompt).strip()]
    if len(image_prompts) != expected_count:
        raise ValueError(
            f"Expected {expected_count} image prompts, got {len(image_prompts)}."
        )
    return image_prompts
def build_image_prompt(visual_prompt: str, style_control: str) -> str:
    style = style_control.strip()
    no_text_instruction = (
        "Do not include any text, captions, logos, watermarks, labels, typography, "
        "or written characters in the image."
    )
    if not style:
        return f"{no_text_instruction}\n{narration}"
    return f"{style}\n{no_text_instruction}\n{narration}"
        return f"{no_text_instruction}\n{visual_prompt}"
    return f"{style}\n{no_text_instruction}\n{visual_prompt}"
async def generate_image_prompts(
    narrations: list[str],
    style_control: str,
    llm: LLM,
    llm_model: str,
) -> list[str]:
    template = load_prompt("pipelines", "standard_image_prompt_generation", "en")
    prompt = format_prompt(
        template,
        narrations_count=len(narrations),
        narrations_json=json.dumps({"narrations": narrations}, ensure_ascii=False, indent=2),
    )
    response = await run_blocking(llm.query, prompt, model=llm_model)
    visual_prompts = parse_image_prompts_response(response, len(narrations))
    return [build_image_prompt(visual_prompt, style_control) for visual_prompt in visual_prompts]
async def generate_narrations_from_inspiration(
    inspiration: str,
    segment_count: int,
    llm: LLM,
    llm_model: str,
) -> list[str]:
    template = load_prompt("pipelines", "standard_narration_generation", "zh")
    prompt = format_prompt(
        template,
        inspiration=inspiration,
        segment_count=segment_count,
    )
    response = await run_blocking(llm.query, prompt, model=llm_model)
    return parse_narrations_response(response, segment_count)
async def run(task_id: str, params: dict) -> tuple[dict, list[dict]]:
@@ -51,20 +139,19 @@
    llm = None
    llm_model = params.get("llm_model") or settings.LLM_MODEL
    if mode == "inspiration":
        segment_count = clamp_segment_count(params.get("segment_count"))
        update_task(task_id, progress=6, message="Writing narration from inspiration")
        llm = LLM()
        source_text = await run_blocking(
            llm.query,
            (
                "请根据下面的创作灵感,写一段适合静态短视频的中文旁白文案。"
                "要求语言口语化、有节奏感,按句号分成 4-8 句,只输出文案正文。\n"
                f"创作灵感:{text}"
            ),
            model=llm_model,
        narrations = await generate_narrations_from_inspiration(
            source_text,
            segment_count,
            llm,
            llm_model,
        )
        source_text = source_text.strip()
        source_text = "\n".join(narrations)
    else:
        narrations = split_by_periods(source_text)
    narrations = split_by_periods(source_text)
    if not narrations:
        raise RuntimeError("No narration segments were generated.")
@@ -75,7 +162,7 @@
            llm = LLM()
        title = await run_blocking(
            llm.query,
            f"为下面的静态短视频旁白生成一个简短中文标题,只输出标题:\n{source_text}",
            f"为下面的文艺短视频旁白生成一个简短中文标题,只输出标题:\n{source_text}",
            model=llm_model,
        )
        title = title.strip().splitlines()[0]
@@ -85,12 +172,30 @@
    image_model = params.get("image_model") or params.get("image_workflow") or settings.IMAGE_T2I_MODEL
    image_resolution = params.get("image_resolution") or "1080P"
    enable_subtitles = bool(params.get("enable_subtitles", False))
    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") or settings.VIDEO_MODEL
    video_duration = clamp_segment_count(params.get("video_duration") or params.get("duration") or 5, default=5)
    image_prompts = [build_image_prompt(narration, style_control) for narration in narrations]
    update_task(task_id, progress=9, message="Generating image prompts")
    if llm is None:
        llm = LLM()
    try:
        image_prompts = await generate_image_prompts(narrations, style_control, llm, llm_model)
    except Exception as exc:
        logger.warning(
            "Failed to generate structured image prompts, fallback to narration prompts: task_id=%s error=%s",
            task_id,
            exc,
        )
        image_prompts = [build_image_prompt(narration, style_control) for narration in narrations]
    storyboard = {
        "title": title,
        "mode": mode,
        "input_text": text,
        "segment_count": len(narrations),
        "video_mode": "dynamic_video" if dynamic_video else "image_concat",
        "style_control": style_control,
        "frames": [
            {"index": idx + 1, "narration": narration, "image_prompt": image_prompts[idx]}
@@ -153,7 +258,7 @@
        update_task(
            task_id,
            progress=70 + int(20 * idx / len(images)),
            message=f"Creating static clip {idx}/{len(images)}",
            message=f"{'Generating dynamic video' if dynamic_video else 'Creating static clip'} {idx}/{len(images)}",
        )
        duration = media_duration_seconds(audio_path) or 3.0
        clip_image_path = image_path
@@ -172,14 +277,36 @@
            append_artifact(task_id, captioned_artifact)
            storyboard["frames"][idx - 1]["captioned_image_path"] = clip_image_path
        video_path = os.path.join(output_dir, f"video_{idx:02d}.mp4")
        await run_blocking(
            create_static_image_clip,
            clip_image_path,
            audio_path,
            video_path,
            video_ratio=video_ratio,
            duration=duration,
        )
        if dynamic_video:
            video_only_segment_path = os.path.join(output_dir, f"video_{idx:02d}_motion.mp4")
            await run_blocking(
                generate_video_api,
                prompt=image_prompts[idx - 1],
                model=video_model,
                output_path=video_only_segment_path,
                image_path=clip_image_path,
                duration=max(video_duration, int(duration + 0.999)),
                video_ratio=video_ratio,
            )
            motion_artifact = artifact(video_only_segment_path, "video", f"video_{idx:02d}_motion")
            artifacts.append(motion_artifact)
            append_artifact(task_id, motion_artifact)
            storyboard["frames"][idx - 1]["motion_video_path"] = video_only_segment_path
            video_path = await run_blocking(
                replace_video_audio,
                video_only_segment_path,
                audio_path,
                video_path,
            )
        else:
            await run_blocking(
                create_static_image_clip,
                clip_image_path,
                audio_path,
                video_path,
                video_ratio=video_ratio,
                duration=duration,
            )
        videos.append(video_path)
        video_artifact = artifact(video_path, "video", f"video_{idx:02d}")
        artifacts.append(video_artifact)
@@ -207,6 +334,8 @@
        "images": images,
        "audios": audios,
        "videos": videos,
        "video_mode": "dynamic_video" if dynamic_video else "image_concat",
        "video_model": video_model if dynamic_video else None,
        "video_only_path": video_only_path,
        "final_video": final_path,
    }
aigc-director/aigc-claw/backend/pipelines/utils.py
@@ -254,7 +254,7 @@
    overlay = Image.new("RGBA", image.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)
    title_font = _load_font(max(34, int(height * 0.042)))
    title_font = _load_font(max(48, int(height * 0.06)))
    subtitle_font = _load_font(max(32, int(height * 0.035)))
    margin_x = max(48, int(width * 0.07))
    max_text_width = width - margin_x * 2
@@ -264,17 +264,6 @@
        title_line_height = max(1, draw.textbbox((0, 0), "国", font=title_font)[3])
        title_height = len(title_lines) * title_line_height + max(0, len(title_lines) - 1) * 10
        title_y = max(48, int(height * 0.055))
        box_padding = 18
        draw.rounded_rectangle(
            [
                margin_x - box_padding,
                title_y - box_padding,
                width - margin_x + box_padding,
                title_y + title_height + box_padding,
            ],
            radius=18,
            fill=(0, 0, 0, 96),
        )
        _draw_centered_lines(
            draw,
            title_lines,
@@ -291,17 +280,6 @@
    subtitle_line_height = max(1, draw.textbbox((0, 0), "国", font=subtitle_font)[3])
    subtitle_height = len(subtitle_lines) * subtitle_line_height + max(0, len(subtitle_lines) - 1) * 10
    subtitle_y = height - max(96, int(height * 0.08)) - subtitle_height
    box_padding = 20
    draw.rounded_rectangle(
        [
            margin_x - box_padding,
            subtitle_y - box_padding,
            width - margin_x + box_padding,
            subtitle_y + subtitle_height + box_padding,
        ],
        radius=18,
        fill=(0, 0, 0, 118),
    )
    _draw_centered_lines(
        draw,
        subtitle_lines,
aigc-director/aigc-claw/frontend/app/pipelines/standard/page.tsx
@@ -4,8 +4,8 @@
  return (
    <PipelinePage
      pipeline="standard"
      title="静态短视频"
      subtitle="输入旁白文案,按句号切分片段,为每句生成图片并合成为静态短视频"
      title="文艺短视频"
      subtitle="输入创作灵感或完整文案,生成图片拼接或动态视频短片"
    />
  );
}
aigc-director/aigc-claw/frontend/components/AppShell.tsx
@@ -9,7 +9,7 @@
const NAV_ITEMS = [
  { href: '/', label: 'AIGC-Claw', icon: Home },
  { href: '/sandbox', label: '临时工作台', icon: Hexagon },
  { href: '/pipelines/standard', label: '静态短视频', icon: Clapperboard },
  { href: '/pipelines/standard', label: '文艺短视频', icon: Clapperboard },
  { href: '/pipelines/action-transfer', label: '动作迁移', icon: Repeat2 },
  { href: '/pipelines/digital-human', label: '数字人口播', icon: UserRound },
];
aigc-director/aigc-claw/frontend/components/BrandHeader.tsx
New file
@@ -0,0 +1,20 @@
'use client';
import Link from 'next/link';
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">
      <Link href="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity flex-shrink-0">
        <img
          src="/logo.jpg"
          alt="Logo"
          className="w-8 h-8 rounded-lg object-contain"
        />
        <span className="font-bold text-sm text-gray-800 tracking-tight">
          AIGC-Claw
        </span>
      </Link>
    </header>
  );
}
aigc-director/aigc-claw/frontend/components/Sandbox/Sandbox.tsx
@@ -1,9 +1,10 @@
'use client';
import { useState, useEffect, useRef, DragEvent } from 'react';
import { Sparkles, Image, Video, MessageSquare, Zap, Loader2, Copy, Check, Trash2, X, FolderOpen, Upload, Globe } from 'lucide-react';
import { Sparkles, Image, Video, MessageSquare, Zap, Loader2, Copy, Check, Trash2, X, FolderOpen, Upload, Globe, Hexagon } from 'lucide-react';
import { useSearchParams } from 'next/navigation';
import { LLM_MODELS, T2I_MODELS, I2I_MODELS, VIDEO_MODELS, VLM_MODELS } from '@/config/models';
import BrandHeader from '@/components/BrandHeader';
// 辅助函数:将相对路径转换为完整 URL
const toMediaUrl = (path: string) => {
@@ -509,21 +510,19 @@
  };
  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-purple-50">
      {/* 顶部导航 */}
      <header className="bg-white border-b border-gray-200 px-6 py-4">
        <div className="max-w-5xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div>
              <h1 className="text-xl font-bold text-gray-800">临时工作台</h1>
              <p className="text-sm text-gray-500">独立调用各种 AI 工具</p>
            </div>
          </div>
        </div>
      </header>
    <div className="min-h-screen bg-gray-50/50">
      <BrandHeader />
      <main className="max-w-5xl mx-auto px-6 py-8">
        <>
            <div className="mb-8 text-center">
              <div className="inline-flex items-center gap-2 mb-3">
                <Hexagon className="w-7 h-7 text-blue-500" />
                <h1 className="text-2xl font-bold text-gray-800">临时工作台</h1>
              </div>
              <p className="text-sm text-gray-500">独立调用各种 AI 工具</p>
            </div>
            {/* 工具选择 */}
            <div className="grid grid-cols-5 gap-3 mb-8">
              {tools.map(tool => (
aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx
@@ -7,6 +7,7 @@
  Clapperboard,
  Clock,
  Image as ImageIcon,
  Lightbulb,
  Loader2,
  Play,
  RefreshCw,
@@ -575,6 +576,7 @@
  const [text, setText] = useState('');
  const [standardMode, setStandardMode] = useState<'inspiration' | 'copy'>('inspiration');
  const [standardVideoMode, setStandardVideoMode] = useState<'image_concat' | 'dynamic_video'>('image_concat');
  const [titleValue, setTitleValue] = useState('');
  const [standardSegmentCount, setStandardSegmentCount] = useState(6);
  const [enableSubtitles, setEnableSubtitles] = useState(false);
@@ -599,7 +601,11 @@
  useEffect(() => {
    const imageAbility = pipeline === 'digital_human' ? 'reference_image' : 'text_to_image';
    const videoAbility = pipeline === 'action_transfer' ? 'action_transfer' : 'digital_human';
    const videoAbility = pipeline === 'standard'
      ? 'first_frame_i2v'
      : pipeline === 'action_transfer'
        ? 'action_transfer'
        : 'digital_human';
    if (pipeline === 'standard') {
      setNegativePrompt(current => current || DEFAULT_STANDARD_STYLE_CONTROL);
@@ -613,17 +619,21 @@
      })
      .catch(() => {});
    if (pipeline !== 'standard') {
    if (pipeline !== 'standard' || standardVideoMode === 'dynamic_video') {
      fetchApiModels({ mediaType: 'video', ability: videoAbility, verifiedOnly: true })
        .then(models => {
          const groups = groupApiModels(models, VIDEO_PROVIDERS);
          setVideoModelGroups(groups);
          const preferred = pipeline === 'action_transfer' ? 'wan2.7-videoedit' : 'wan2.7-r2v';
          const preferred = pipeline === 'standard'
            ? DEFAULTS.video
            : pipeline === 'action_transfer'
              ? 'wan2.7-videoedit'
              : 'wan2.7-r2v';
          setVideoModel(current => firstModelId(groups, current || preferred));
        })
        .catch(() => {});
    }
  }, [pipeline]);
  }, [pipeline, standardVideoMode]);
  const canSubmit = useMemo(() => {
    if (pipeline === 'standard') return text.trim().length > 0;
@@ -695,6 +705,9 @@
            tts_speed: ttsSpeed,
            style_control: negativePrompt || undefined,
            segment_count: standardMode === 'inspiration' ? standardSegmentCount : undefined,
            video_mode: standardVideoMode,
            video_model: standardVideoMode === 'dynamic_video' ? videoModel : undefined,
            video_duration: standardVideoMode === 'dynamic_video' ? duration : undefined,
          })
        : pipeline === 'action_transfer'
          ? await startActionTransferPipeline({
@@ -742,6 +755,31 @@
          <section className="bg-white rounded-2xl shadow-sm border border-gray-200 p-5">
            {pipeline === 'standard' && (
              <div className="space-y-4">
                <div className="grid grid-cols-2 h-10 rounded-lg bg-gray-100 p-1 text-sm max-w-sm">
                  {[
                    { id: 'image_concat', label: '图片拼接' },
                    { id: 'dynamic_video', label: '动态视频' },
                  ].map(item => (
                    <button
                      key={item.id}
                      onClick={() => setStandardVideoMode(item.id as 'image_concat' | 'dynamic_video')}
                      className={clsx('rounded-md transition-colors', standardVideoMode === item.id ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500')}
                    >
                      {item.label}
                    </button>
                  ))}
                </div>
                <div className="rounded-xl border border-yellow-300 bg-yellow-100 px-4 py-3">
                  <div className="mb-1 flex items-center gap-1.5 text-xs font-semibold text-yellow-900">
                    <Lightbulb className="w-3.5 h-3.5" />
                    <span>说明</span>
                  </div>
                  <p className="text-sm leading-6 text-yellow-950">
                    {standardVideoMode === 'image_concat'
                      ? '图片拼接会为每个旁白片段生成一张图片,并配合 TTS 音频合成为静态图文短视频。等待时间主要取决于图片生成速度,通常每张图片约 10-20 秒。'
                      : '动态视频会先为每个旁白片段生成图片,再调用视频模型把图片扩展为动态片段,最后合成为完整短片。等待时间更长,通常每个视频片段约 1-2 分钟。'}
                  </p>
                </div>
                <div className="grid grid-cols-2 h-10 rounded-lg bg-gray-100 p-1 text-sm max-w-sm">
                  {[
                    { id: 'inspiration', label: '创作灵感' },
@@ -847,7 +885,7 @@
                  {pipeline !== 'action_transfer' && (
                    <SelectField label="图片模型" value={imageModel} onChange={setImageModel} groups={imageModelGroups} />
                  )}
                  {pipeline !== 'standard' && (
                  {(pipeline !== 'standard' || standardVideoMode === 'dynamic_video') && (
                    <SelectField label="视频模型" value={videoModel} onChange={setVideoModel} groups={videoModelGroups} />
                  )}
                  <label className="flex flex-col gap-1.5">
@@ -856,7 +894,7 @@
                      {VIDEO_RATIOS.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}
                    </select>
                  </label>
                  {pipeline === 'action_transfer' && (
                  {(pipeline === 'action_transfer' || (pipeline === 'standard' && standardVideoMode === 'dynamic_video')) && (
                    <NumberField label="视频时长" value={duration} onChange={setDuration} min={1} max={10} />
                  )}
                  {pipeline !== 'action_transfer' && (