Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

Ship PRINTFILM studio UX and pipeline controls for kepu production.

yiba487fdd033e
diff --git a/.gitignore b/.gitignore
index f8f5747..a93438e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,8 +8,13 @@ __pycache__/
backend/.venv/
backend/ai_movie.db
backend/.env
+deploy/.env.prod
+deploy/scripts/deploy_kepu.py
backend/.celery_autoscale/
backend/static/generated/
+backend/static/voice_previews/
+backend/frontend/
+.claude/
frontend/.env
frontend/node_modules/
frontend/dist/
diff --git a/README.md b/README.md
index 8226dc7..5383027 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
- 6 套内置模板(剪纸 / 绘本 / 粉笔 / 拼贴 / 像素 / 水墨)
- 注册登录 + 额度
-- 主题/文案 → 分镜脚本 → 分镜图 → 视频片段 → 配音 → 合成(当前默认 **Mock 方舟**)
+- 主题/文案 → 分镜脚本 → 分镜图 → 视频片段 → 配音 → 合成
- 分镜编辑、单张重绘、单镜头重生视频
- 作品发布与简单浏览
@@ -14,24 +14,29 @@
### 依赖
-- Python 3.12 + FFmpeg(已加入 PATH)
-- Redis(Celery broker;无 Redis 时自动回退进程内异步)
+- Python 3.12 + FFmpeg(PATH)
+- Node.js(前端)
+- Docker 仅用于 **Postgres / Redis**(见 [deploy/README.md](deploy/README.md))
```bash
-# Redis(推荐 Docker)
-docker run -d --name framecut-redis -p 6379:6379 redis:7-alpine
+# 中间件
+cp deploy/.env.prod.example deploy/.env.prod
+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod up -d
+
+# 或开发只用 Redis + SQLite
+docker run -d --name printfilm-redis -p 6379:6379 redis:7-alpine
cd backend
python -m venv .venv
.\.venv\Scripts\activate
pip install -r requirements.txt
-copy .env.example .env # 填入 ARK_API_KEY,并把 MODEL_* 换成方舟接入点 ID
+copy .env.example .env # 填 ARK_API_KEY;正式库见 deploy/.env.prod.example
-# API
uvicorn app.main:app --reload --port 8000
-# Worker(另开终端;USE_CELERY=true 且 Redis 可用时需要)
+# 另开终端
celery -A app.workers.celery_app.celery_app worker -Q pipeline -l info --concurrency=2
+# 或: python -m app.workers.autoscale
```
### 前端
@@ -50,18 +55,16 @@ npm run dev
|---|---|
| `ARK_MOCK=false` | 关闭 mock |
| `ARK_API_KEY` | 方舟 API Key |
-| `MODEL_LLM` / `MODEL_IMAGE` / `MODEL_VIDEO` / `MODEL_AUDIO` | **控制台推理接入点 ID** |
+| `MODEL_LLM` / `MODEL_IMAGE` / `MODEL_VIDEO` / `MODEL_AUDIO` | 控制台推理接入点 ID |
| `USE_CELERY=true` | 走 Celery;Redis 不通时自动 in-process |
-素材落盘:`backend/static/generated/p{id}/`;成片 `final.mp4` 由 FFmpeg 拼接字幕烧录。
-
-TTS 若接入点未开通,会降级为静音轨,画面与字幕仍可合成。
+素材:`backend/static/generated/p{id}/`;成片由 FFmpeg 合成。
## 架构摘要
-- FastAPI + SQLite(可换 MySQL)
-- 模板表驱动风格:`style_prefix` / Seedream / Seedance / Audio / 字幕配置
-- 异步流水线:进程内 asyncio(可平滑换成 Celery + Redis)
+- FastAPI + PostgreSQL(Docker)/ 本地可 SQLite
+- Redis(Docker):Celery broker + 进度
+- Celery worker / `autoscale`:宿主机进程
- 前端:React + TS + Vite
## 目录
@@ -70,4 +73,5 @@ TTS 若接入点未开通,会降级为静音轨,画面与字幕仍可合成
backend/app/ API、模型、流水线、方舟适配
backend/static/ 模板封面与 mock 素材
frontend/src/ 首页模板墙 + 创作工作台
+deploy/ 仅 Postgres + Redis 的 compose
```
diff --git a/backend/.env.example b/backend/.env.example
index 0bd247d..1042b39 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -1,4 +1,7 @@
SECRET_KEY=dev-secret-change-me
+# 本地默认 SQLite;正式可改为 Postgres(Docker 见 deploy/docker-compose.yml)
+# DATABASE_URL=postgresql+asyncpg://printfilm:密码@127.0.0.1:5432/printfilm
+# DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:密码@127.0.0.1:5432/printfilm
DATABASE_URL=sqlite+aiosqlite:///./ai_movie.db
DATABASE_URL_SYNC=sqlite:///./ai_movie.db
REDIS_URL=redis://127.0.0.1:6379/0
@@ -43,3 +46,13 @@ ARK_VIDEO_POLL_TIMEOUT=900
PIPELINE_IMAGE_CONCURRENCY=3
PIPELINE_VIDEO_CONCURRENCY=2
PIPELINE_AUDIO_CONCURRENCY=4
+
+# Aliyun OSS(成片/分镜上传;FFmpeg 仍用本地文件。前端 dist 见 deploy/scripts/upload_oss_web.py)
+OSS_ENABLED=false
+OSS_ENDPOINT=oss-cn-beijing.aliyuncs.com
+OSS_REGION=cn-hangzhou
+OSS_BUCKET=your-bucket
+OSS_FOLDER=kepu
+OSS_ACCESS_KEY_ID=replace-me
+OSS_ACCESS_KEY_SECRET=replace-me
+# OSS_PUBLIC_BASE=https://cdn.example.com
diff --git a/backend/Dockerfile b/backend/Dockerfile
deleted file mode 100644
index 0aa3ffe..0000000
--- a/backend/Dockerfile
+++ /dev/null
@@ -1,7 +0,0 @@
-FROM python:3.12-slim
-WORKDIR /app
-COPY requirements.txt .
-RUN pip install --no-cache-dir -r requirements.txt
-COPY . .
-EXPOSE 8000
-CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
index 0196cb7..cf95f0c 100644
--- a/backend/app/api/projects.py
+++ b/backend/app/api/projects.py
@@ -5,7 +5,9 @@ import re
import zipfile
from datetime import datetime
-from fastapi import APIRouter, Depends, HTTPException
+from pathlib import Path
+
+from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
from fastapi.responses import StreamingResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -16,6 +18,8 @@ from app.database import get_db
from app.deps import get_current_user
from app.models import Project, ProjectStatus, Shot, User, Work
from app.schemas import (
+ ContentExpandOut,
+ ContentExpandRequest,
ProjectCreate,
ProjectDownloadRequest,
ProjectListItem,
@@ -23,11 +27,14 @@ from app.schemas import (
ProjectUpdate,
ShotOut,
ShotUpdate,
+ VoicePreviewOut,
+ VoicePreviewRequest,
WorkOut,
)
from app.services import pipeline, storage
+from app.services.ark import get_ark
from app.services.progress import redis_bridge, subscribe, unsubscribe
-from app.services.voices import list_voices
+from app.services.voices import ensure_voice_preview, list_voices
router = APIRouter(tags=["projects"])
@@ -37,6 +44,34 @@ async def get_voices() -> list[dict]:
return list_voices()
[email protected]("/voices/preview", response_model=VoicePreviewOut)
+async def preview_voice(
+ body: VoicePreviewRequest,
+ user: User = Depends(get_current_user),
+) -> VoicePreviewOut:
+ """Generate a short cached TTS sample for audition."""
+ _ = user
+ try:
+ url = await ensure_voice_preview(body.voice_id)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=f"试听生成失败:{exc}") from exc
+ return VoicePreviewOut(url=url, voice_id=body.voice_id)
+
+
[email protected]("/content/expand", response_model=ContentExpandOut)
+async def expand_content(
+ body: ContentExpandRequest,
+ user: User = Depends(get_current_user),
+) -> ContentExpandOut:
+ """AI-expand a short topic into a project title + theme brief or full script."""
+ _ = user
+ try:
+ result = await get_ark().expand_content(body.topic, body.mode)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=f"AI 生成失败:{exc}") from exc
+ return ContentExpandOut(title=result["title"], content=result["content"])
+
+
async def _get_owned_project(db: AsyncSession, project_id: int, user: User) -> Project:
result = await db.execute(
select(Project)
@@ -68,6 +103,7 @@ async def create_project(
source_text=body.source_text,
resolution_mode=body.resolution_mode,
pipeline_mode=body.pipeline_mode,
+ output_ratio=(body.output_ratio or "").strip(),
voice_id=(body.voice_id or "").strip(),
style_prompt=(body.style_prompt or "").strip(),
character_prompt=(body.character_prompt or "").strip(),
@@ -132,6 +168,12 @@ async def download_projects_zip(
skipped.append(f"#{pid}")
continue
path = storage.local_path_from_url(p.final_video_url)
+ try:
+ if (not path or not path.exists()) and str(p.final_video_url).startswith("http"):
+ dest = storage.project_dir(p.id) / "final.mp4"
+ path = await storage.ensure_local_media(p.final_video_url, dest)
+ except Exception: # noqa: BLE001
+ path = None
if not path or not path.exists():
skipped.append(f"#{pid}")
continue
@@ -201,18 +243,78 @@ async def update_project(
tpl = await db.get(Template, data["template_id"])
if not tpl or not tpl.is_active:
raise HTTPException(status_code=400, detail="无效模板")
+ if "cover_url" in data and data["cover_url"]:
+ url = str(data["cover_url"]).strip()
+ if not (url.startswith("/static/") or url.startswith("http://") or url.startswith("https://")):
+ raise HTTPException(status_code=400, detail="无效封面地址")
for k, v in data.items():
setattr(project, k, v)
await db.commit()
return await _get_owned_project(db, project_id, user)
[email protected]("/projects/{project_id}/cover", response_model=ProjectOut)
+async def upload_project_cover(
+ project_id: int,
+ file: UploadFile = File(...),
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ """Upload a custom cover image for the project."""
+ project = await _get_owned_project(db, project_id, user)
+ if project.status in {
+ ProjectStatus.SCRIPTING,
+ ProjectStatus.IMAGING,
+ ProjectStatus.VIDEOING,
+ ProjectStatus.AUDIOING,
+ ProjectStatus.COMPOSING,
+ ProjectStatus.AUDITING,
+ }:
+ raise HTTPException(status_code=409, detail="生成进行中,无法更换封面")
+
+ content_type = (file.content_type or "").lower()
+ allowed = {
+ "image/jpeg": ".jpg",
+ "image/jpg": ".jpg",
+ "image/png": ".png",
+ "image/webp": ".webp",
+ "image/gif": ".gif",
+ }
+ ext = allowed.get(content_type)
+ if not ext:
+ # Fallback from filename
+ suffix = Path(file.filename or "").suffix.lower()
+ if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
+ ext = ".jpg" if suffix == ".jpeg" else suffix
+ else:
+ raise HTTPException(status_code=400, detail="仅支持 JPG / PNG / WebP / GIF")
+
+ raw = await file.read()
+ if not raw:
+ raise HTTPException(status_code=400, detail="空文件")
+ if len(raw) > 8 * 1024 * 1024:
+ raise HTTPException(status_code=400, detail="封面不能超过 8MB")
+
+ dest = storage.project_dir(project_id) / f"cover{ext}"
+ dest.write_bytes(raw)
+ project.cover_url = storage.publish_local(dest)
+ await db.commit()
+ return await _get_owned_project(db, project_id, user)
+
+
@router.post("/projects/{project_id}/generate", response_model=ProjectOut)
async def generate_project(
project_id: int,
+ restart: bool = False,
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> Project:
+ """Start or resume the pipeline.
+
+ - First run / restart: script stage only, then pauses at SCRIPT_READY for review.
+ - Continue from SCRIPT_READY+: skip script, run assets → videos → compose.
+ - restart=true: wipe shots/media and regenerate storyboard from scratch.
+ """
project = await _get_owned_project(db, project_id, user)
if project.status in {
ProjectStatus.SCRIPTING,
@@ -224,11 +326,18 @@ async def generate_project(
}:
raise HTTPException(status_code=409, detail="生成进行中,请稍后")
+ if restart:
+ for shot in list(project.shots):
+ await db.delete(shot)
+ await db.flush()
+ await pipeline.delete_project_assets(project_id)
+ project.cover_url = None
+
# Resume: clear error, keep existing shots/media (pipeline skips finished stages)
project.error_msg = None
project.final_video_url = None
project.status = ProjectStatus.SCRIPTING
- if project.progress <= 0:
+ if project.progress <= 0 or restart:
project.progress = 1
await db.commit()
task_id = pipeline.start_pipeline(project_id)
@@ -251,9 +360,7 @@ async def cancel_project(
running = {
ProjectStatus.SCRIPTING,
ProjectStatus.IMAGING,
- ProjectStatus.IMAGE_READY,
ProjectStatus.VIDEOING,
- ProjectStatus.VIDEO_READY,
ProjectStatus.AUDIOING,
ProjectStatus.COMPOSING,
ProjectStatus.AUDITING,
@@ -278,9 +385,7 @@ async def delete_project(
running = {
ProjectStatus.SCRIPTING,
ProjectStatus.IMAGING,
- ProjectStatus.IMAGE_READY,
ProjectStatus.VIDEOING,
- ProjectStatus.VIDEO_READY,
ProjectStatus.AUDIOING,
ProjectStatus.COMPOSING,
ProjectStatus.AUDITING,
diff --git a/backend/app/config.py b/backend/app/config.py
index 2e79db2..879fa87 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -70,6 +70,17 @@ class Settings(BaseSettings):
tos_secret_key: str = ""
cdn_base: str = "http://localhost:8000/static"
+ # Aliyun OSS — 成片/分镜上传;FFmpeg 仍读本地文件
+ oss_enabled: bool = False
+ oss_endpoint: str = "oss-cn-beijing.aliyuncs.com"
+ oss_region: str = "cn-hangzhou"
+ oss_bucket: str = ""
+ oss_folder: str = "kepu"
+ oss_access_key_id: str = ""
+ oss_access_key_secret: str = ""
+ # 可选自定义域名;空则用 https://{bucket}.{endpoint}
+ oss_public_base: str = ""
+
cors_origins: str = "http://localhost:5173,http://127.0.0.1:5173"
diff --git a/backend/app/database.py b/backend/app/database.py
index a35b0ca..81280cd 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -7,7 +7,11 @@ from app.config import get_settings
settings = get_settings()
-engine = create_async_engine(settings.database_url, echo=settings.debug)
+_engine_kwargs: dict = {"echo": settings.debug}
+if settings.database_url.startswith("postgresql"):
+ _engine_kwargs.update(pool_pre_ping=True, pool_size=10, max_overflow=20)
+
+engine = create_async_engine(settings.database_url, **_engine_kwargs)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
@@ -25,3 +29,12 @@ async def init_db() -> None:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+
+
+async def dispose_engine() -> None:
+ """Drop pooled connections so the next asyncio.run can bind a fresh loop.
+
+ Celery (and any code that calls asyncio.run repeatedly) must dispose between
+ runs; otherwise asyncpg/SQLAlchemy futures stay attached to a closed loop.
+ """
+ await engine.dispose()
diff --git a/backend/app/main.py b/backend/app/main.py
index 447f619..88c1a48 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -53,21 +53,34 @@ async def on_startup() -> None:
async def _migrate_sqlite() -> None:
- """Lightweight additive migrations for SQLite MVP."""
+ """Lightweight additive migrations (SQLite + Postgres)."""
+ is_sqlite = settings.database_url.startswith("sqlite")
async with engine.begin() as conn:
- result = await conn.execute(text("PRAGMA table_info(shots)"))
- cols = {row[1] for row in result.fetchall()}
- if "image_ark_url" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN image_ark_url VARCHAR(1024)"))
- if "overlay_title" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN overlay_title VARCHAR(128) DEFAULT ''"))
- if "overlay_subtitle" not in cols:
- await conn.execute(text("ALTER TABLE shots ADD COLUMN overlay_subtitle VARCHAR(256) DEFAULT ''"))
-
- result = await conn.execute(text("PRAGMA table_info(projects)"))
- pcols = {row[1] for row in result.fetchall()}
+ if is_sqlite:
+ result = await conn.execute(text("PRAGMA table_info(shots)"))
+ cols = {row[1] for row in result.fetchall()}
+ if "image_ark_url" not in cols:
+ await conn.execute(text("ALTER TABLE shots ADD COLUMN image_ark_url VARCHAR(1024)"))
+ if "overlay_title" not in cols:
+ await conn.execute(text("ALTER TABLE shots ADD COLUMN overlay_title VARCHAR(128) DEFAULT ''"))
+ if "overlay_subtitle" not in cols:
+ await conn.execute(text("ALTER TABLE shots ADD COLUMN overlay_subtitle VARCHAR(256) DEFAULT ''"))
+
+ result = await conn.execute(text("PRAGMA table_info(projects)"))
+ pcols = {row[1] for row in result.fetchall()}
+ else:
+ result = await conn.execute(
+ text(
+ "SELECT column_name FROM information_schema.columns "
+ "WHERE table_name = 'projects'"
+ )
+ )
+ pcols = {row[0] for row in result.fetchall()}
+
if "pipeline_mode" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN pipeline_mode VARCHAR(32) DEFAULT 'full'"))
+ if "output_ratio" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN output_ratio VARCHAR(16) DEFAULT ''"))
if "voice_id" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN voice_id VARCHAR(128) DEFAULT ''"))
if "character_bible" not in pcols:
diff --git a/backend/app/models.py b/backend/app/models.py
index 7714922..7a36828 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -80,11 +80,14 @@ class Project(Base):
status: Mapped[str] = mapped_column(String(32), default=ProjectStatus.DRAFT)
progress: Mapped[int] = mapped_column(Integer, default=0)
error_msg: Mapped[str | None] = mapped_column(Text, nullable=True)
- cover_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
- final_video_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
+ cover_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ final_video_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
resolution_mode: Mapped[str] = mapped_column(String(16), default="preview") # preview | hd
# full = 图→视频→配音→合成;image_text = 静图+叠字+配音+Ken Burns(跳过 AI 视频)
+ # 由用户选择,不由模板锁定
pipeline_mode: Mapped[str] = mapped_column(String(32), default="full")
+ # 输出画幅,如 16:9 / 9:16;空则回退模板 default_ratio
+ output_ratio: Mapped[str] = mapped_column(String(16), default="")
# TTS voice id (openspeech speaker or preset alias); empty → template default
voice_id: Mapped[str] = mapped_column(String(128), default="")
# Canonical cast/look description for Seedream consistency across shots
@@ -93,7 +96,7 @@ class Project(Base):
style_prompt: Mapped[str] = mapped_column(Text, default="")
character_prompt: Mapped[str] = mapped_column(Text, default="")
extra_prompt: Mapped[str] = mapped_column(Text, default="")
- ref_image_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
+ ref_image_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
@@ -119,10 +122,10 @@ class Shot(Base):
video_prompt: Mapped[str] = mapped_column(Text, default="")
camera: Mapped[str] = mapped_column(String(64), default="slow pan")
bgm_mood: Mapped[str] = mapped_column(String(64), default="neutral")
- image_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
+ image_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
image_ark_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
- video_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
- audio_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
+ video_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ audio_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
status: Mapped[str] = mapped_column(String(32), default=ShotStatus.PENDING)
version: Mapped[int] = mapped_column(Integer, default=1)
@@ -152,8 +155,8 @@ class Work(Base):
project_id: Mapped[int] = mapped_column(ForeignKey("projects.id"), unique=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
title: Mapped[str] = mapped_column(String(200))
- cover_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
- video_url: Mapped[str] = mapped_column(String(512))
+ cover_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ video_url: Mapped[str] = mapped_column(String(1024))
visibility: Mapped[str] = mapped_column(String(16), default="public")
audit_status: Mapped[str] = mapped_column(String(16), default="passed")
published_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 6329e51..123ecbf 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -94,6 +94,11 @@ class ProjectCreate(BaseModel):
source_text: str = Field(min_length=2, max_length=20000)
resolution_mode: str = Field(default="preview", pattern="^(preview|hd)$")
pipeline_mode: str = Field(default="full", pattern="^(full|image_text)$")
+ output_ratio: str | None = Field(
+ default=None,
+ pattern=r"^(16:9|9:16|1:1|4:3|21:9)?$",
+ max_length=16,
+ )
voice_id: str | None = Field(default=None, max_length=128)
style_prompt: str | None = Field(default=None, max_length=2000)
character_prompt: str | None = Field(default=None, max_length=2000)
@@ -107,12 +112,18 @@ class ProjectUpdate(BaseModel):
source_text: str | None = Field(default=None, min_length=2, max_length=20000)
template_id: str | None = None
pipeline_mode: str | None = Field(default=None, pattern="^(full|image_text)$")
+ output_ratio: str | None = Field(
+ default=None,
+ pattern=r"^(16:9|9:16|1:1|4:3|21:9)$",
+ max_length=16,
+ )
resolution_mode: str | None = Field(default=None, pattern="^(preview|hd)$")
voice_id: str | None = Field(default=None, max_length=128)
style_prompt: str | None = Field(default=None, max_length=2000)
character_prompt: str | None = Field(default=None, max_length=2000)
extra_prompt: str | None = Field(default=None, max_length=2000)
ref_image_url: str | None = None
+ cover_url: str | None = Field(default=None, max_length=1024)
class ProjectOut(BaseModel):
@@ -128,6 +139,7 @@ class ProjectOut(BaseModel):
final_video_url: str | None
resolution_mode: str
pipeline_mode: str = "full"
+ output_ratio: str = ""
voice_id: str = ""
character_bible: str = ""
style_prompt: str = ""
@@ -151,6 +163,7 @@ class ProjectListItem(BaseModel):
final_video_url: str | None = None
error_msg: str | None = None
pipeline_mode: str = "full"
+ output_ratio: str = ""
created_at: datetime
updated_at: datetime | None = None
@@ -161,6 +174,25 @@ class ProjectDownloadRequest(BaseModel):
ids: list[int] = Field(default_factory=list, min_length=1, max_length=50)
+class ContentExpandRequest(BaseModel):
+ topic: str = Field(default="", max_length=2000)
+ mode: str = Field(default="theme", pattern="^(theme|script)$")
+
+
+class ContentExpandOut(BaseModel):
+ title: str
+ content: str
+
+
+class VoicePreviewRequest(BaseModel):
+ voice_id: str = Field(min_length=1, max_length=128)
+
+
+class VoicePreviewOut(BaseModel):
+ url: str
+ voice_id: str
+
+
class WorkOut(BaseModel):
id: int
project_id: int
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 1e83f7a..ceb398e 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -22,6 +22,73 @@ from app.services.ffmpeg_compose import is_near_silent_audio
logger = logging.getLogger(__name__)
+
+def _fallback_overlay_title(text: str, shot_no: int) -> str:
+ """Last resort when LLM omits title — never blind-slice mid-word (e.g. ERP→ER)."""
+ raw = re.sub(r"\s+", "", (text or "").strip())
+ if not raw:
+ return f"场景{shot_no}"
+ clause = re.split(r"[,。;!?、,:;]", raw, maxsplit=1)[0].strip()
+ if 2 <= len(clause) <= 10 and not _looks_truncated_token(clause, raw):
+ return clause
+ return f"场景{shot_no}"
+
+
+def _fallback_overlay_subtitle(text: str) -> str:
+ raw = (text or "").strip()
+ if not raw:
+ return ""
+ cleaned = re.sub(r"\s+", "", raw)
+ clause = re.split(r"[,。;!?、,:;]", cleaned, maxsplit=1)[0].strip()
+ if 4 <= len(clause) <= 22:
+ return clause
+ if len(clause) > 22:
+ # Prefer a trailing noun-ish chunk over a head that cuts mid-phrase
+ for n in range(18, 7, -1):
+ tail = clause[-n:].lstrip("的与和及")
+ if 6 <= len(tail) <= 18 and not re.match(r"[A-Za-z0-9]", tail[:1] or ""):
+ if not _looks_truncated_token(tail, clause):
+ return tail
+ head = clause[:18]
+ if re.search(r"[A-Za-z0-9]$", head) and re.match(r"[A-Za-z0-9]", clause[18:19] or ""):
+ m = re.search(r"[A-Za-z0-9]+$", head)
+ if m and m.start() > 6:
+ head = head[: m.start()]
+ return head
+ return cleaned[:22] if len(cleaned) > 22 else cleaned
+
+
+def _looks_truncated_token(title: str, full_text: str) -> bool:
+ """True if title is a prefix of narration that cuts a Latin/数字专有词 mid-way."""
+ t = re.sub(r"\s+", "", (title or "").strip())
+ full = re.sub(r"\s+", "", (full_text or "").strip())
+ if not t or not full.startswith(t):
+ return False
+ if len(full) <= len(t):
+ return False
+ # Truncated mid-ASCII token: title ends with alnum and next char is alnum
+ if re.search(r"[A-Za-z0-9]$", t) and re.match(r"[A-Za-z0-9]", full[len(t)]):
+ return True
+ # Obvious raw prefix grab of long narration
+ if len(t) <= 12 and len(full) > len(t) + 8 and full.startswith(t):
+ return True
+ return False
+
+
+def _normalize_overlay_title(title: str, text: str, shot_no: int) -> str:
+ t = (title or "").strip()
+ if not t or _looks_truncated_token(t, text):
+ return _fallback_overlay_title(text, shot_no)
+ return t[:32]
+
+
+def _normalize_overlay_subtitle(subtitle: str, text: str) -> str:
+ s = (subtitle or "").strip()
+ if not s or _looks_truncated_token(s, text):
+ return _fallback_overlay_subtitle(text)[:64]
+ return s[:64]
+
+
# Soften brand / IP names that Seedream often rejects as copyright
_SEEDREAM_SANITIZE: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"(?i)\bspacex\b"), "民营商业航天公司"),
@@ -117,6 +184,8 @@ class ArkGateway:
pipeline_mode: str = "full",
character_hint: str = "",
extra_requirements: str = "",
+ consistency_mode: str = "character",
+ output_ratio: str = "16:9",
) -> StoryboardResult:
if self.mock:
return await asyncio.to_thread(
@@ -137,49 +206,102 @@ class ArkGateway:
if (extra_requirements or "").strip():
user_constraints += f"用户其他画面要求:{(extra_requirements or '').strip()}。"
- consistency = (
- "必须输出严格 JSON 对象(不要数组、不要 markdown、不要代码围栏):"
- '{"character_bible":"...","shots":[...]}。'
- "character_bible:80-160字,固定描述本片反复出现的人物/主体外形"
- "(年龄感、发型发色、五官气质、体型、服装配色与辨识物),全片唯一设定,禁止每镜改人设。"
- f"画风要求(全片强制统一):{style_prefix}。"
- f"{user_constraints}"
- "禁止镜头间混用写实摄影/真人脸与插画或动漫;禁止换脸换装换发型。"
- "每镜 img_prompt 只写本镜场景与构图(景物、动作、光影),不要重复粘贴大段画风/人物锁定原文;"
- "出现人物时用短句点出与 character_bible 一致的关键特征即可。"
- )
+ mode = (consistency_mode or "character").strip().lower()
+ if mode not in {"character", "style", "diverse"}:
+ mode = "character"
+
+ if mode == "diverse":
+ consistency = (
+ "必须输出严格 JSON 对象(不要数组、不要 markdown、不要代码围栏):"
+ '{"character_bible":"...","shots":[...]}。'
+ "character_bible:填「无固定人物,各镜为独立系统/场景界面」。"
+ f"视觉气质仅作底线参考(不要被其颜色绑架):{style_prefix}。"
+ f"{user_constraints}"
+ "【动态规划】先分析用户内容的领域、产品形态与使用场景,再决定色板与界面类型,"
+ "再拆镜;每镜对应不同操作或能力(总览、接入、工作台、流程、结果、部署、生态等)。"
+ "配色与材质必须贴合内容(浅色SaaS、文档站、深色IDE、终端、架构图、白板均可),"
+ "禁止默认霓虹蓝/赛博大屏/蓝紫渐变HUD,禁止各镜画面雷同,禁止待办任务清单,"
+ "禁止同一仪表盘复制粘贴换字。"
+ "每镜 img_prompt 必须写清该镜独特的界面类型、布局分区、主色与信息层级,不要粘贴人物锁定。"
+ )
+ elif mode == "style":
+ consistency = (
+ "必须输出严格 JSON 对象(不要数组、不要 markdown、不要代码围栏):"
+ '{"character_bible":"...","shots":[...]}。'
+ "character_bible:可简写「无固定主角」或留空说明;不要强行统一人物外形。"
+ f"画风气质统一:{style_prefix}。"
+ f"{user_constraints}"
+ "各镜场景与构图应随内容变化,只需保持同类画风,禁止镜头间画面几乎一样。"
+ "每镜 img_prompt 只写本镜场景与构图。"
+ )
+ else:
+ consistency = (
+ "必须输出严格 JSON 对象(不要数组、不要 markdown、不要代码围栏):"
+ '{"character_bible":"...","shots":[...]}。'
+ "character_bible:80-160字,固定描述本片反复出现的人物/主体外形"
+ "(年龄感、发型发色、五官气质、体型、服装配色与辨识物),全片唯一设定,禁止每镜改人设。"
+ f"画风要求(全片强制统一):{style_prefix}。"
+ f"{user_constraints}"
+ "禁止镜头间混用写实摄影/真人脸与插画或动漫;禁止换脸换装换发型。"
+ "每镜 img_prompt 只写本镜场景与构图(景物、动作、光影),不要重复粘贴大段画风/人物锁定原文;"
+ "出现人物时用短句点出与 character_bible 一致的关键特征即可。"
+ )
if pipeline_mode == "image_text":
+ diversity_note = (
+ "拆成 5-10 个分镜,每镜一个独立视觉场景;"
+ + (
+ "画风气质可统一,但界面/场景构图必须明显不同。"
+ if mode != "character"
+ else "但画风与人物必须一致。"
+ )
+ )
+ ratio = (output_ratio or "16:9").strip() or "16:9"
+ orient = "竖屏" if ratio == "9:16" else ("方形" if ratio == "1:1" else "横屏")
system = (
- "你是竖屏图文短视频编剧。所有字段必须使用简体中文。"
+ f"你是{orient}图文短视频编剧。所有字段必须使用简体中文。"
f"{consistency}{llm_system_addon}"
f"每镜 duration 在 {duration_min}-{min(duration_max, max_shot_duration)} 秒。"
"这是「静图+叠字+配音」模式:不生成 AI 视频,但需要旁白配音;"
"画面禁止出现任何文字/水印/字幕。"
"shots 字段说明:"
- "shot(序号)、duration(秒)、title(画面顶部大标题,2-8字,有力)、"
- "subtitle(画面顶部副标题叠字,8-22字,可诗意)、"
+ "shot(序号)、duration(秒)、"
+ "title(对本镜内容的概括短标题,2-8字,语义完整有力;"
+ "必须是总结提炼,禁止从 text 截取前几个字,禁止截断专有名词如 ERP→ER)、"
+ "subtitle(对本镜卖点/要点的一句概括,8-22字,同样禁止原文截取前缀)、"
"text(旁白台词,口语化,约匹配该镜时长,可供 TTS 朗读,一般 20-60 字)、"
- "img_prompt(竖屏构图画面提示词,留出顶部约1/4给文字叠层,主体偏中下,"
- "含统一画风与人物锁定,禁止要求画面内写字;"
- "禁止出现真实商标/公司名/人名,用泛称)、"
+ f"img_prompt({orient} {ratio} 构图画面提示词,留出边缘给文字叠层,主体居中,"
+ "禁止要求画面内写字;禁止出现真实商标/公司名/人名,用泛称)、"
"video_prompt(可留空或写轻微推拉)、camera(如:缓慢推近/轻拉远)、bgm(情绪)。"
- "拆成 5-10 个分镜,每镜一个独立视觉场景,但画风与人物必须一致。"
+ f"{diversity_note}"
)
else:
+ diversity_note = (
+ "拆成 4-10 个分镜;各镜场景随内容变化,禁止雷同空镜。"
+ if mode != "character"
+ else "画风与人物必须全片一致。"
+ )
system = (
"你是短视频分镜编剧。所有字段必须使用简体中文"
- "(包括 text、img_prompt、video_prompt、camera、bgm)。"
+ "(包括 title、text、img_prompt、video_prompt、camera、bgm)。"
f"{consistency}{llm_system_addon}"
f"每镜 duration 在 {duration_min}-{min(duration_max, max_shot_duration)} 秒。"
"shots 字段说明:"
- "shot(序号)、duration(秒)、text(旁白台词)、"
- "img_prompt(画面生成中文提示词,含统一画风与人物锁定与具体景物;"
+ "shot(序号)、duration(秒)、"
+ "title(对本镜旁白的概括短标题,2-8字,语义完整;"
+ "必须是总结提炼,禁止从 text 截取前缀,禁止截断专有名词如 ERP→ER)、"
+ "subtitle(可选,一句要点概括 8-22字)、"
+ "text(旁白台词)、"
+ "img_prompt(画面生成中文提示词,含具体景物与构图;"
"禁止真实商标/公司名/人名,改用泛称)、"
"video_prompt(镜头运动与动态的中文提示词)、"
"camera(运镜,如:缓慢上摇/轻推/横移)、bgm(情绪,如:紧张平缓)。"
"img_prompt 与 video_prompt 禁止英文句子,专有名词可保留原文。"
+ f"{diversity_note}"
)
- user = f"输入类型:{source_type}。内容如下,请拆成 4-10 个分镜:\n{source_text}"
+ user = (
+ f"输入类型:{source_type}。请先理解内容与应用场景,再拆成 4-10 个分镜:\n"
+ f"{source_text}"
+ )
payload = {
"model": self.settings.model_llm,
"messages": [
@@ -211,7 +333,10 @@ class ArkGateway:
) -> ImageResult:
if self.mock:
local = await asyncio.to_thread(self._write_mock_image, prompt, size)
- return ImageResult(local_url=local, remote_url=None)
+ # _write_mock_image returns /static/...; publish to OSS when enabled
+ path = storage.local_path_from_url(local)
+ url = storage.publish_local(path) if path and path.exists() else local
+ return ImageResult(local_url=url, remote_url=None)
candidates = [
self._sanitize_seedream_prompt(prompt),
@@ -293,7 +418,7 @@ class ArkGateway:
name = f"shot_{(shot_no or 0):03d}_{hashlib.md5(prompt_hash_src.encode()).hexdigest()[:8]}.png"
dest = dest_dir / name
await storage.download_to(remote, dest)
- return ImageResult(local_url=storage.rel_static_url(dest), remote_url=remote)
+ return ImageResult(local_url=storage.publish_local(dest), remote_url=remote)
@staticmethod
def _sanitize_seedream_prompt(prompt: str) -> str:
@@ -480,7 +605,7 @@ class ArkGateway:
return result.url
dest = storage.project_dir(project_id) / f"shot_{shot_no:03d}.mp4"
await storage.download_to(result.url, dest)
- return storage.rel_static_url(dest)
+ return storage.publish_local(dest)
async def gen_and_wait_video(
self,
@@ -575,7 +700,7 @@ class ArkGateway:
if await asyncio.to_thread(is_near_silent_audio, dest):
logger.warning("%s produced near-silence shot=%s", label, shot_no)
return None
- return storage.rel_static_url(dest)
+ return storage.publish_local(dest)
# 1) 豆包 openspeech(需 APP ID + Access Key)
if self.settings.volc_tts_app_id and self.settings.volc_tts_access_key:
@@ -623,7 +748,7 @@ class ArkGateway:
# 最后才静音(保证合成不中断)
logger.error("TTS all providers failed; writing silence shot=%s", shot_no)
await asyncio.to_thread(self._write_silence_mp3, dest, duration_hint)
- return storage.rel_static_url(dest)
+ return storage.publish_local(dest)
def _tts_resource_id(self, speaker: str) -> str:
if speaker.startswith("S_"):
@@ -824,18 +949,19 @@ class ArkGateway:
)
plans: list[ShotPlan] = []
for i, text in enumerate(chunks, start=1):
- title = text[:6].replace(":", "").replace(":", "")
- subtitle = text[:22]
- if pipeline_mode == "image_text":
- title = re.sub(r"^(引入主题|核心概念解释|一个关键例子说明)", "", text)[:8] or f"场景{i}"
- subtitle = text[:22]
+ # Mock: invent short summary titles, do not slice narration mid-token
+ topic_bit = re.sub(r"^(引入主题|核心概念解释|一个关键例子说明)[::]?", "", text).strip()
+ title = f"要点{i}" if len(topic_bit) > 10 else (topic_bit[:8] or f"场景{i}")
+ if ":" in text or ":" in text:
+ title = text.split(":", 1)[0].split(":", 1)[0][-6:] or title
+ subtitle = _fallback_overlay_subtitle(text)
plans.append(
ShotPlan(
shot=i,
duration=float(mid),
text=text[:120],
- overlay_title=title[:16],
- overlay_subtitle=subtitle[:48],
+ overlay_title=_normalize_overlay_title(title, text, i),
+ overlay_subtitle=_normalize_overlay_subtitle(subtitle, text),
img_prompt=f"{style_prefix},{bible},画面表现:{text[:80]},竖屏构图,顶部留白,画面无文字",
video_prompt=f"轻微动态,{style_prefix},场景:{text[:60]}",
camera="缓慢推近" if i % 2 else "轻拉远",
@@ -875,10 +1001,8 @@ class ArkGateway:
text = str(item.get("text") or item.get("audio_text") or f"镜头{i}")
title = str(item.get("title") or item.get("overlay_title") or "").strip()
subtitle = str(item.get("subtitle") or item.get("overlay_subtitle") or "").strip()
- if not title:
- title = text[:8]
- if not subtitle:
- subtitle = text[:22]
+ title = _normalize_overlay_title(title, text, i)
+ subtitle = _normalize_overlay_subtitle(subtitle, text)
img = str(item.get("img_prompt") or f"{text}")
# Keep raw scene text; style/character applied later at image gen
video = str(item.get("video_prompt") or f"轻微动态,{text}")
@@ -887,8 +1011,8 @@ class ArkGateway:
shot=int(item.get("shot", i)),
duration=dur,
text=text,
- overlay_title=title[:32],
- overlay_subtitle=subtitle[:64],
+ overlay_title=title,
+ overlay_subtitle=subtitle,
img_prompt=img,
video_prompt=video,
camera=str(item.get("camera", "缓慢横移")),
@@ -897,6 +1021,91 @@ class ArkGateway:
)
return StoryboardResult(shots=plans, character_bible=character_bible)
+ async def expand_content(self, topic: str, mode: str = "theme") -> dict[str, str]:
+ """Expand a short topic into title + theme brief or full narration script."""
+ topic = (topic or "").strip() or "人工智能如何改变日常生活"
+ mode = "script" if mode == "script" else "theme"
+ if self.mock:
+ return self._mock_expand_content(topic, mode)
+
+ if mode == "script":
+ system = (
+ "你是科普短视频文案作者。根据用户主题写一篇可直接用于旁白的完整口播文案。"
+ "只输出严格 JSON:{\"title\":\"作品名\",\"content\":\"完整文案\"}。"
+ "title:8-18 字,吸引人、无标点堆砌。"
+ "content:300-700 字,口语化,分 4-8 个自然段,有开场钩子、知识点、收尾;"
+ "不要 markdown、不要分镜编号、不要标题行。"
+ )
+ else:
+ system = (
+ "你是科普短视频选题策划。把用户输入扩写成一句清晰具体的创作主题。"
+ "只输出严格 JSON:{\"title\":\"作品名\",\"content\":\"主题句\"}。"
+ "title:8-18 字。"
+ "content:一句话主题,40-90 字,写清受众与要讲清的核心知识点;不要换行。"
+ )
+ payload = {
+ "model": self.settings.model_llm,
+ "messages": [
+ {"role": "system", "content": system},
+ {"role": "user", "content": f"主题/素材:{topic}"},
+ ],
+ }
+ async with httpx.AsyncClient(timeout=90.0) as client:
+ resp = await client.post(
+ self._url("/chat/completions"),
+ headers=self._headers(),
+ json=payload,
+ )
+ if resp.status_code >= 400:
+ raise RuntimeError(f"LLM error {resp.status_code}: {resp.text[:800]}")
+ data = resp.json()
+ raw = data["choices"][0]["message"]["content"] or "{}"
+ return self._parse_expand_content(raw, topic, mode)
+
+ def _mock_expand_content(self, topic: str, mode: str) -> dict[str, str]:
+ short = topic[:18].rstrip("??。.!!") or "科普短片"
+ title = short if len(short) >= 4 else f"{short}的科普"
+ if mode == "script":
+ content = (
+ f"你有没有想过:{topic.rstrip('??')}?\n\n"
+ f"今天我们用三分钟,把这件事讲清楚。"
+ f"先从生活里最常见的现象说起,再拆开背后的原理,最后给你一个好记的结论。\n\n"
+ f"很多人第一反应会想当然,但真正关键在于因果链条,而不是表象。"
+ f"弄懂这一点,你就能解释身边更多类似的问题。\n\n"
+ f"记住:观察现象、追问机制、再用例子验证。"
+ f"下一次再遇到{short}相关话题,你也能自信地讲给别人听。"
+ )
+ else:
+ content = (
+ f"{topic.rstrip('??')}:面向普通观众,用生活例子讲清核心原理与常见误区。"
+ )[:100]
+ return {"title": title[:24], "content": content}
+
+ def _parse_expand_content(self, raw: str, topic: str, mode: str) -> dict[str, str]:
+ text = (raw or "").strip()
+ if text.startswith("```"):
+ text = re.sub(r"^```(?:json)?\s*", "", text)
+ text = re.sub(r"\s*```$", "", text)
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError:
+ m = re.search(r"\{[\s\S]*\}", text)
+ if not m:
+ return self._mock_expand_content(topic, mode)
+ try:
+ data = json.loads(m.group(0))
+ except json.JSONDecodeError:
+ return self._mock_expand_content(topic, mode)
+ title = str(data.get("title") or "").strip() or topic[:18]
+ content = str(data.get("content") or "").strip()
+ if not content:
+ return self._mock_expand_content(topic, mode)
+ if mode == "theme":
+ content = content.replace("\n", " ").strip()[:100]
+ else:
+ content = content[:8000]
+ return {"title": title[:24], "content": content}
+
_gateway: ArkGateway | None = None
diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.py
index 4deb4e2..79c7b39 100644
--- a/backend/app/services/ffmpeg_compose.py
+++ b/backend/app/services/ffmpeg_compose.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import logging
import os
+import re
import shutil
import subprocess
import tempfile
@@ -14,12 +15,19 @@ from app.config import get_settings
logger = logging.getLogger(__name__)
+# Punctuation removed from on-screen captions (TTS narration keeps original)
+_CAPTION_PUNCT_RE = re.compile(
+ r"[,。!?;:、,.!?;:…··〜~「」『』【】()\(\)\[\]\"'“”‘’《》〈〉"
+ r"—_\-/\\|@#$%^&*+=<>{}]+"
+)
+
# Output sizes keyed by aspect ratio
_RATIO_SIZE = {
"16:9": (854, 480),
"9:16": (720, 1280),
"1:1": (720, 720),
"4:3": (640, 480),
+ "21:9": (1280, 540),
}
@@ -42,6 +50,11 @@ class ComposeOptions:
resolution_mode: str = "preview" # preview | hd
# One continuous TTS track for the whole film (preferred over per-shot audio)
full_audio_path: Path | None = None
+ # Overlay / caption sizing & layout (from template.subtitle_config)
+ subtitle_layout: str = "top" # top | split (title top, subtitle bottom)
+ title_scale: float = 1.35
+ sub_scale: float = 1.3
+ caption_scale: float = 1.25
def allocate_durations_by_narration(
@@ -184,6 +197,12 @@ def _escape_drawtext(text: str) -> str:
return t
+def _strip_caption_punct(text: str) -> str:
+ """Remove punctuation/symbols from on-screen subtitle text."""
+ t = _CAPTION_PUNCT_RE.sub("", text or "")
+ return re.sub(r"\s+", " ", t).strip()
+
+
def _escape_fontfile(path: str) -> str:
# Windows paths need escaping for filtergraph: C\:/Windows/Fonts/msyh.ttc
p = Path(path).resolve().as_posix()
@@ -191,13 +210,13 @@ def _escape_fontfile(path: str) -> str:
def _one_line_caption(text: str, *, max_chars: int = 22) -> str:
- """Single-line bottom caption; truncate with ellipsis if too long."""
- raw = (text or "").replace("\n", " ").replace("\r", " ").strip()
+ """Single-line bottom caption; truncate if too long (no ellipsis punctuation)."""
+ raw = _strip_caption_punct((text or "").replace("\n", " ").replace("\r", " "))
if not raw:
return ""
if len(raw) <= max_chars:
return raw
- return raw[: max_chars - 1] + "…"
+ return raw[:max_chars]
def _split_caption_chunks(text: str, *, max_chars: int = 18) -> list[str]:
@@ -212,20 +231,23 @@ def _split_caption_chunks(text: str, *, max_chars: int = 18) -> list[str]:
for ch in raw:
buf += ch
if ch in ",。!?;、,.!?;:":
- piece = buf.strip()
+ piece = _strip_caption_punct(buf)
if piece:
pieces.append(piece)
buf = ""
if buf.strip():
- pieces.append(buf.strip())
+ piece = _strip_caption_punct(buf)
+ if piece:
+ pieces.append(piece)
if not pieces:
- pieces = [raw]
+ pieces = [_strip_caption_punct(raw)]
+ if not pieces[0]:
+ return []
# Further split long pieces so each cue stays one readable line
chunks: list[str] = []
for piece in pieces:
- # Drop trailing punctuation-only crumbs
- body = piece.strip()
+ body = _strip_caption_punct(piece)
if not body:
continue
if len(body) <= max_chars:
@@ -247,7 +269,8 @@ def _split_caption_chunks(text: str, *, max_chars: int = 18) -> list[str]:
merged[-1] = merged[-1] + c
else:
merged.append(c)
- return merged or [raw[:max_chars]]
+ clean = [_strip_caption_punct(c) for c in merged if _strip_caption_punct(c)]
+ return clean or [_strip_caption_punct(raw)[:max_chars]]
def _timed_caption_windows(
@@ -305,7 +328,7 @@ def _write_ass(
) -> None:
"""Write ASS with PlayRes matching canvas; captions refresh by clause over time."""
portrait = (h / max(w, 1)) > 1.2
- font_size = 30 if portrait else 26
+ font_size = 36 if portrait else 30
margin_v = 56 if portrait else 40
max_chars = 16 if portrait else 24
font_name = "Microsoft YaHei"
@@ -456,12 +479,14 @@ def _bottom_caption_drawtext(
w: int,
h: int,
font: str | None,
+ scale: float = 1.25,
) -> str:
"""Pixel-sized bottom captions via drawtext (avoids libass PlayRes blow-up)."""
portrait = (h / max(w, 1)) > 1.2
- max_chars = 16 if portrait else 24
- font_size = 26 if portrait else 24
- y = max(0, h - font_size - (56 if portrait else 44))
+ max_chars = 14 if portrait else 22
+ base = 32 if portrait else 28
+ font_size = max(24, min(44, int(base * max(0.8, scale))))
+ y = max(0, h - font_size - (64 if portrait else 48))
windows = _timed_caption_windows(
narration,
start=0.0,
@@ -487,39 +512,59 @@ def _bottom_caption_drawtext(
return ",".join(parts)
-def _overlay_drawtext(w: int, h: int, title: str, subtitle: str, font: str | None) -> str:
- """Top-centered short title + subtitle (kept small so it doesn't dominate)."""
- # Hard-cap length — LLM sometimes dumps the whole theme into overlay fields
- title = (title or "").strip()
- subtitle = (subtitle or "").strip()
- if len(title) > 12:
- title = title[:11] + "…"
- if len(subtitle) > 18:
- subtitle = subtitle[:17] + "…"
+def _overlay_drawtext(
+ w: int,
+ h: int,
+ title: str,
+ subtitle: str,
+ font: str | None,
+ *,
+ layout: str = "top",
+ title_scale: float = 1.35,
+ sub_scale: float = 1.3,
+) -> str:
+ """Title + subtitle overlays. layout=split → title top / subtitle bottom (开源展示风)."""
+ title = _strip_caption_punct(title)
+ subtitle = _strip_caption_punct(subtitle)
+ title_cap = 14 if layout == "split" else 12
+ sub_cap = 24 if layout == "split" else 18
+ if len(title) > title_cap:
+ title = title[:title_cap]
+ if len(subtitle) > sub_cap:
+ subtitle = subtitle[:sub_cap]
title_e = _escape_drawtext(title)
sub_e = _escape_drawtext(subtitle)
- # Portrait 720 → title ~30 / sub ~22(相对原字号大约大两号)
- title_size = max(26, min(32, int(w * 0.042)))
- sub_size = max(20, min(25, int(w * 0.032)))
- title_y = int(h * 0.045)
- sub_y = title_y + title_size + int(h * 0.012)
+ # Portrait 720 base ~ larger than before so 叠字更醒目
+ title_size = max(34, min(52, int(w * 0.058 * max(0.8, title_scale))))
+ sub_size = max(24, min(36, int(w * 0.042 * max(0.8, sub_scale))))
+ title_y = int(h * 0.055)
+ if layout == "split":
+ sub_y = max(0, h - sub_size - int(h * 0.07))
+ else:
+ sub_y = title_y + title_size + int(h * 0.014)
parts: list[str] = []
- # Soft top vignette so white text stays readable on bright skies
- parts.append(f"drawbox=x=0:y=0:w={w}:h={int(h * 0.18)}:[email protected]:t=fill")
+ # Soft vignette behind text
+ if layout == "split":
+ parts.append(f"drawbox=x=0:y=0:w={w}:h={int(h * 0.16)}:[email protected]:t=fill")
+ parts.append(
+ f"drawbox=x=0:y={h - int(h * 0.16)}:w={w}:h={int(h * 0.16)}:[email protected]:t=fill"
+ )
+ else:
+ parts.append(f"drawbox=x=0:y=0:w={w}:h={int(h * 0.2)}:[email protected]:t=fill")
font_opt = f":fontfile='{_escape_fontfile(font)}'" if font else ""
if title_e:
parts.append(
f"drawtext=text='{title_e}'{font_opt}:fontsize={title_size}:"
- f"fontcolor=white:borderw=3:[email protected]:"
+ f"fontcolor=white:borderw=4:[email protected]:"
f"x=(w-text_w)/2:y={title_y}"
)
if sub_e:
parts.append(
f"drawtext=text='{sub_e}'{font_opt}:fontsize={sub_size}:"
- f"fontcolor=white:borderw=3:[email protected]:"
+ f"fontcolor=white:borderw=3:[email protected]:"
f"x=(w-text_w)/2:y={sub_y}"
)
return ",".join(parts)
@@ -537,17 +582,32 @@ def _image_to_video_kenburns(
subtitle: str,
narration: str,
font: str | None,
+ subtitle_layout: str = "top",
+ title_scale: float = 1.35,
+ sub_scale: float = 1.3,
+ caption_scale: float = 1.25,
) -> None:
ffmpeg = _which("ffmpeg")
vf = _ken_burns_filter(w, h, duration, shot_no)
- overlay = _overlay_drawtext(w, h, title, subtitle, font)
+ overlay = _overlay_drawtext(
+ w,
+ h,
+ title,
+ subtitle,
+ font,
+ layout=subtitle_layout,
+ title_scale=title_scale,
+ sub_scale=sub_scale,
+ )
if overlay:
vf = f"{vf},{overlay}"
- captions = _bottom_caption_drawtext(
- narration, duration=duration, w=w, h=h, font=font
- )
- if captions:
- vf = f"{vf},{captions}"
+ # split 布局底部已是副标题,不再叠旁白滚动字幕以免抢戏
+ if subtitle_layout != "split":
+ captions = _bottom_caption_drawtext(
+ narration, duration=duration, w=w, h=h, font=font, scale=caption_scale
+ )
+ if captions:
+ vf = f"{vf},{captions}"
_run(
[
ffmpeg,
@@ -580,10 +640,11 @@ def _burn_captions_on_video(
w: int,
h: int,
font: str | None,
+ caption_scale: float = 1.25,
) -> None:
"""Burn timed bottom captions onto an existing video clip (full mode)."""
captions = _bottom_caption_drawtext(
- narration, duration=duration, w=w, h=h, font=font
+ narration, duration=duration, w=w, h=h, font=font, scale=caption_scale
)
ffmpeg = _which("ffmpeg")
if not captions:
@@ -633,8 +694,51 @@ def _image_to_video(image: Path, duration: float, out: Path, *, w: int, h: int)
)
+def _pad_or_trim_video(
+ src: Path,
+ dest: Path,
+ duration: float,
+ *,
+ w: int,
+ h: int,
+) -> None:
+ """Scale video to canvas and force exact duration: trim if longer, freeze-pad if shorter.
+
+ AI clips (Seedance) are often shorter than TTS-allocated shot length; without
+ padding, continuous mux -shortest truncates narration.
+ """
+ ffmpeg = _which("ffmpeg")
+ target = max(float(duration), 0.5)
+ src_dur = probe_duration(src) or 0.0
+ base_vf = f"{_scale_pad(w, h).replace(',format=yuv420p', '')},fps=24"
+ if src_dur > 0.05 and src_dur + 0.08 < target:
+ pad = target - src_dur
+ vf = f"{base_vf},tpad=stop_mode=clone:stop_duration={pad:.3f},format=yuv420p"
+ else:
+ vf = f"{base_vf},format=yuv420p"
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(src),
+ "-t",
+ f"{target:.3f}",
+ "-vf",
+ vf,
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-an",
+ str(dest),
+ ]
+ )
+
+
def _mux_shot(video: Path, audio: Path, duration: float, out: Path) -> None:
ffmpeg = _which("ffmpeg")
+ target = max(float(duration), 0.5)
_run(
[
ffmpeg,
@@ -644,19 +748,72 @@ def _mux_shot(video: Path, audio: Path, duration: float, out: Path) -> None:
"-i",
str(audio),
"-t",
- f"{max(duration, 0.5):.3f}",
+ f"{target:.3f}",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
- "-shortest",
+ # Video was already fitted to target; avoid -shortest cutting early
str(out),
]
)
+def _mux_continuous_narration(merged: Path, narration: Path, output: Path) -> None:
+ """Attach full-film TTS; pad video with freeze if shorter so旁白不被裁切."""
+ ffmpeg = _which("ffmpeg")
+ vid_d = probe_duration(merged) or 0.0
+ aud_d = probe_duration(narration) or 0.0
+ video_in = merged
+ tmp_pad: Path | None = None
+ if aud_d > 0.5 and vid_d > 0.05 and aud_d > vid_d + 0.12:
+ tmp_pad = merged.with_name(merged.stem + "_pad.mp4")
+ pad = aud_d - vid_d
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(merged),
+ "-vf",
+ f"tpad=stop_mode=clone:stop_duration={pad:.3f}",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-an",
+ str(tmp_pad),
+ ]
+ )
+ video_in = tmp_pad
+ out_t = max(aud_d, vid_d, 0.5)
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(video_in),
+ "-i",
+ str(narration),
+ "-map",
+ "0:v:0",
+ "-map",
+ "1:a:0",
+ "-c:v",
+ "copy",
+ "-c:a",
+ "aac",
+ "-t",
+ f"{out_t:.3f}",
+ "-movflags",
+ "+faststart",
+ str(output),
+ ]
+ )
+
+
def compose_project(
shots: list[ShotMedia],
output: Path,
@@ -708,7 +865,6 @@ def compose_project(
if opts.mode == "image_text" and shot.image_path and shot.image_path.exists():
title = (shot.overlay_title or "").strip()
subtitle = (shot.overlay_subtitle or "").strip()
- # Top: short titles. Bottom: timed narration via drawtext (not ASS).
_image_to_video_kenburns(
shot.image_path,
shot.duration,
@@ -720,6 +876,10 @@ def compose_project(
subtitle=subtitle,
narration=shot.narration or "",
font=font,
+ subtitle_layout=opts.subtitle_layout or "top",
+ title_scale=opts.title_scale,
+ sub_scale=opts.sub_scale,
+ caption_scale=opts.caption_scale,
)
elif shot.video_path and shot.video_path.exists() and shot.video_path.suffix.lower() in {
".mp4",
@@ -728,21 +888,12 @@ def compose_project(
".mkv",
}:
raw_v = tmp_path / f"shot_{shot.shot_no:03d}_raw.mp4"
- _run(
- [
- ffmpeg,
- "-y",
- "-i",
- str(shot.video_path),
- "-t",
- f"{max(shot.duration, 0.5):.3f}",
- "-vf",
- f"{_scale_pad(w, h).replace(',format=yuv420p', '')},fps=24,format=yuv420p",
- "-c:v",
- "libx264",
- "-an",
- str(raw_v),
- ]
+ _pad_or_trim_video(
+ shot.video_path,
+ raw_v,
+ shot.duration,
+ w=w,
+ h=h,
)
_burn_captions_on_video(
raw_v,
@@ -752,6 +903,7 @@ def compose_project(
w=w,
h=h,
font=font,
+ caption_scale=opts.caption_scale,
)
elif shot.image_path and shot.image_path.exists():
_image_to_video(shot.image_path, shot.duration, video, w=w, h=h)
@@ -764,6 +916,7 @@ def compose_project(
w=w,
h=h,
font=font,
+ caption_scale=opts.caption_scale,
)
video = capped
else:
@@ -811,28 +964,7 @@ def compose_project(
if continuous and opts.full_audio_path:
# Replace silent concat audio with one continuous narration track
voiced = tmp_path / "voiced.mp4"
- _run(
- [
- ffmpeg,
- "-y",
- "-i",
- str(merged),
- "-i",
- str(opts.full_audio_path),
- "-map",
- "0:v:0",
- "-map",
- "1:a:0",
- "-c:v",
- "copy",
- "-c:a",
- "aac",
- "-shortest",
- "-movflags",
- "+faststart",
- str(voiced),
- ]
- )
+ _mux_continuous_narration(merged, opts.full_audio_path, voiced)
shutil.copy2(voiced, output)
else:
# Captions already burned per-shot via drawtext — remux only.
diff --git a/backend/app/services/oss.py b/backend/app/services/oss.py
new file mode 100644
index 0000000..3b3b552
--- /dev/null
+++ b/backend/app/services/oss.py
@@ -0,0 +1,110 @@
+"""Aliyun OSS upload helpers.
+
+Local files stay on disk for FFmpeg; DB / frontend use public OSS URLs.
+Object key layout: {folder}/generated/p{id}/... and {folder}/ for SPA.
+"""
+
+from __future__ import annotations
+
+import logging
+import mimetypes
+from functools import lru_cache
+from pathlib import Path
+
+from app.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+
+@lru_cache
+def _bucket():
+ import oss2
+
+ s = get_settings()
+ if not s.oss_enabled:
+ raise RuntimeError("OSS disabled")
+ if not (s.oss_bucket and s.oss_access_key_id and s.oss_access_key_secret):
+ raise RuntimeError("OSS credentials incomplete")
+ auth = oss2.Auth(s.oss_access_key_id, s.oss_access_key_secret)
+ endpoint = s.oss_endpoint.strip()
+ if not endpoint.startswith("http"):
+ endpoint = f"https://{endpoint}"
+ return oss2.Bucket(auth, endpoint, s.oss_bucket)
+
+
+def oss_enabled() -> bool:
+ s = get_settings()
+ return bool(
+ s.oss_enabled
+ and s.oss_bucket
+ and s.oss_access_key_id
+ and s.oss_access_key_secret
+ )
+
+
+def folder_prefix() -> str:
+ return get_settings().oss_folder.strip().strip("/") or "kepu"
+
+
+def public_base() -> str:
+ s = get_settings()
+ if s.oss_public_base.strip():
+ return s.oss_public_base.rstrip("/")
+ ep = s.oss_endpoint.strip().removeprefix("https://").removeprefix("http://")
+ return f"https://{s.oss_bucket}.{ep}"
+
+
+def public_url(object_key: str) -> str:
+ key = object_key.lstrip("/")
+ return f"{public_base()}/{key}"
+
+
+def key_for_local(path: Path, *, static_root: Path) -> str:
+ """Map backend/static/... → {folder}/..."""
+ rel = path.resolve().relative_to(static_root.resolve()).as_posix()
+ return f"{folder_prefix()}/{rel}"
+
+
+def upload_file(local_path: Path, object_key: str | None = None) -> str:
+ """Upload local file; return public URL. Raises on failure."""
+ from app.services import storage
+
+ path = Path(local_path)
+ if not path.is_file():
+ raise FileNotFoundError(str(path))
+ key = object_key or key_for_local(path, static_root=storage.STATIC_ROOT)
+ key = key.lstrip("/")
+ mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
+ headers = {
+ "Content-Type": mime,
+ "x-oss-object-acl": "public-read",
+ }
+ bucket = _bucket()
+ bucket.put_object_from_file(key, str(path), headers=headers)
+ url = public_url(key)
+ logger.info("oss uploaded %s → %s", path.name, url)
+ return url
+
+
+def upload_bytes(data: bytes, object_key: str, *, content_type: str = "application/octet-stream") -> str:
+ key = object_key.lstrip("/")
+ headers = {"Content-Type": content_type, "x-oss-object-acl": "public-read"}
+ _bucket().put_object(key, data, headers=headers)
+ return public_url(key)
+
+
+def upload_dir(local_dir: Path, oss_prefix: str) -> int:
+ """Upload directory recursively under oss_prefix. Returns file count."""
+ root = Path(local_dir)
+ if not root.is_dir():
+ raise NotADirectoryError(str(root))
+ prefix = oss_prefix.strip().strip("/")
+ count = 0
+ for path in root.rglob("*"):
+ if not path.is_file():
+ continue
+ rel = path.relative_to(root).as_posix()
+ key = f"{prefix}/{rel}"
+ upload_file(path, key)
+ count += 1
+ return count
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index 922ac8d..ba5020e 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -29,6 +29,7 @@ from app.services.style_lock import (
merge_negative,
seedream_ref_urls,
strip_lock_blocks,
+ template_consistency_mode,
template_is_photoreal,
)
from app.services.voices import resolve_speaker
@@ -44,6 +45,8 @@ _IMAGE_SIZE_BY_RATIO = {
"9:16": "1440x2560",
"16:9": "2560x1440",
"1:1": "1920x1920",
+ "4:3": "1920x1440",
+ "21:9": "2560x1080",
}
IMAGE_TEXT_DURATION_MIN = 4
@@ -118,6 +121,18 @@ def _is_image_text(project: Project) -> bool:
return (project.pipeline_mode or "full") == "image_text"
+def _project_output_ratio(project: Project) -> str:
+ """User-selected output ratio, else template default, else 16:9."""
+ allowed = {"16:9", "9:16", "1:1", "4:3", "21:9"}
+ user = (getattr(project, "output_ratio", None) or "").strip()
+ if user in allowed:
+ return user
+ tpl_ratio = (project.template.default_ratio if project.template else None) or ""
+ if tpl_ratio in allowed:
+ return tpl_ratio
+ return "16:9"
+
+
def _project_voice(project: Project) -> str:
tpl_preset = ""
if project.template and project.template.audio_config:
@@ -204,7 +219,7 @@ async def _synthesize_continuous_audio(
raise RuntimeError("整片配音时长异常")
allocated = allocate_durations_by_narration(narrations, dur)
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
for shot, new_dur in zip(shot_rows, allocated):
row = await db.get(Shot, shot.id)
@@ -212,7 +227,7 @@ async def _synthesize_continuous_audio(
continue
row.duration = float(new_dur)
# Point every shot at the same continuous file (compose prefers full_narration)
- row.audio_url = storage.rel_static_url(dest)
+ row.audio_url = storage.publish_local(dest)
if row.status == ShotStatus.PENDING:
row.status = ShotStatus.AUDIO_READY
await db.commit()
@@ -248,8 +263,8 @@ async def _resume_plan(project_id: int) -> tuple[bool, bool, bool, bool]:
has_audio = _continuous_audio_ok(project_id) or all(_audio_ok(s) for s in shots)
has_videos = all(bool(s.video_url) for s in shots)
- # Keep existing storyboard if any media already exists
- skip_script = any(bool(s.image_url or s.audio_url or s.video_url) for s in shots)
+ # Keep existing storyboard whenever shots already exist (user may edit before continue)
+ skip_script = len(shots) > 0
skip_assets = has_images and has_audio
skip_videos = image_text or has_videos
return image_text, skip_script, skip_assets, skip_videos
@@ -263,24 +278,35 @@ async def run_pipeline(project_id: int) -> None:
if not skip_script:
await _script_stage(project_id)
await _ensure_not_cancelled(project_id)
- image_text, skip_script, skip_assets, skip_videos = await _resume_plan(project_id)
- else:
- logger.info(
- "pipeline resume project=%s skip_script=%s skip_assets=%s skip_videos=%s",
- project_id,
- skip_script,
- skip_assets,
- skip_videos,
- )
+ # Checkpoint: stop after storyboard so user can review/edit before assets
await publish_progress(
project_id,
{
- "event": "progress",
- "stage": "RESUME",
- "percent": 70 if skip_assets else 18,
- "message": "沿用已有分镜,继续后续阶段",
+ "event": "paused",
+ "stage": "SCRIPT_READY",
+ "percent": 15,
+ "message": "分镜已生成,请确认修改后手动继续",
},
)
+ logger.info("pipeline paused after script project=%s", project_id)
+ return
+
+ logger.info(
+ "pipeline resume project=%s skip_script=%s skip_assets=%s skip_videos=%s",
+ project_id,
+ skip_script,
+ skip_assets,
+ skip_videos,
+ )
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "RESUME",
+ "percent": 70 if skip_assets else 18,
+ "message": "沿用已有分镜,继续后续阶段",
+ },
+ )
# 分镜图 + 配音并行;完整模式再并行图生视频
if not skip_assets:
@@ -305,7 +331,11 @@ async def run_pipeline(project_id: int) -> None:
"event": "progress",
"stage": "ASSETS_READY",
"percent": 70 if image_text else 50,
- "message": "沿用已有分镜图与配音,开始合成",
+ "message": (
+ "沿用已有分镜图与配音,开始合成"
+ if image_text
+ else "沿用已有分镜图与配音,继续生成 AI 视频"
+ ),
},
)
@@ -440,6 +470,7 @@ async def _script_stage(project_id: int) -> None:
style = _effective_style(project)
extra = (getattr(project, "extra_prompt", None) or "").strip()
char_hint = (getattr(project, "character_prompt", None) or "").strip()
+ consist = template_consistency_mode(tpl)
plans_result = await ark.chat_storyboard(
source_text=project.source_text,
source_type=project.source_type,
@@ -449,11 +480,16 @@ async def _script_stage(project_id: int) -> None:
duration_max=d_max,
max_shot_duration=d_max if image_text else get_settings().max_shot_duration,
pipeline_mode=mode,
- character_hint=char_hint,
+ character_hint=char_hint if consist == "character" else "",
extra_requirements=extra,
+ consistency_mode=consist,
+ output_ratio=_project_output_ratio(project),
)
plans = plans_result.shots
- project.character_bible = _effective_character_bible(project, plans_result.character_bible)
+ if consist == "character":
+ project.character_bible = _effective_character_bible(project, plans_result.character_bible)
+ else:
+ project.character_bible = "无固定人物,各镜独立场景"
for shot in list(project.shots):
await db.delete(shot)
await db.flush()
@@ -508,11 +544,7 @@ def _effective_character_bible(project: Project, llm_bible: str = "") -> str:
def _image_size_for(project: Project) -> str | None:
- if not _is_image_text(project):
- return None
- ratio = (project.template.default_ratio if project.template else None) or "9:16"
- if _is_image_text(project) and ratio == "16:9":
- ratio = "9:16"
+ ratio = _project_output_ratio(project)
return _IMAGE_SIZE_BY_RATIO.get(ratio)
@@ -534,11 +566,14 @@ def _project_base_refs(project: Project) -> list[str]:
def _locked_shot_prompt(project: Project, img_prompt: str) -> str:
+ consist = template_consistency_mode(project.template)
return build_locked_image_prompt(
_effective_style(project),
strip_lock_blocks(img_prompt),
getattr(project, "character_bible", None) or "",
photoreal=template_is_photoreal(project.template),
+ lock_character=consist == "character",
+ lock_style=True,
)
@@ -554,7 +589,18 @@ def _consistency_ref_from_shots(shots: list) -> str | None:
return None
-_db_write_lock = asyncio.Lock()
+_db_write_locks: dict[int, asyncio.Lock] = {}
+
+
+def _db_write_lock() -> asyncio.Lock:
+ """Per-event-loop lock (module-level Lock breaks across Celery asyncio.run)."""
+ loop = asyncio.get_running_loop()
+ key = id(loop)
+ lock = _db_write_locks.get(key)
+ if lock is None:
+ lock = asyncio.Lock()
+ _db_write_locks[key] = lock
+ return lock
async def _parallel_image_and_audio(project_id: int) -> None:
@@ -594,9 +640,11 @@ async def _parallel_image_and_audio(project_id: int) -> None:
style_prefix = _effective_style(project)
character_bible = getattr(project, "character_bible", None) or ""
photoreal = template_is_photoreal(tpl)
+ consist = template_consistency_mode(tpl)
+ lock_character = consist == "character"
base_refs = _project_base_refs(project)
- # If some shots already have images (resume), use them as consistency anchors
- existing_anchor = _consistency_ref_from_shots(shot_rows)
+ # Only character mode chains shot-to-shot refs; diverse/style keep scenes independent
+ existing_anchor = _consistency_ref_from_shots(shot_rows) if lock_character else None
image_size = _image_size_for(project)
negative = _project_image_negative(project)
voice = _project_voice(project)
@@ -617,7 +665,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
img_w = 0.7 if image_text else 0.55
frac = (done_img / max(total, 1)) * img_w
pct = 18 + int(40 * frac)
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
project = await db.get(Project, project_id)
if project:
@@ -638,7 +686,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
)
async def persist_image(meta: dict, img) -> None:
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
shot = await db.get(Shot, meta["id"])
if not shot:
@@ -663,8 +711,10 @@ async def _parallel_image_and_audio(project_id: int) -> None:
prompt = build_locked_image_prompt(
style_prefix,
strip_lock_blocks(meta["img_prompt"]),
- character_bible,
+ character_bible if lock_character else "",
photoreal=photoreal,
+ lock_character=lock_character,
+ lock_style=True,
)
async with img_sem:
await _ensure_not_cancelled(project_id)
@@ -680,7 +730,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
return img.remote_url or img.local_url
async def run_images() -> None:
- """Anchor on first generated shot, then parallelize the rest with that ref."""
+ """Character mode: anchor first shot then parallelize. Diverse/style: all independent."""
need = [m for m in shot_meta if not m.get("has_image")]
already = [m for m in shot_meta if m.get("has_image")]
for _m in already:
@@ -689,6 +739,17 @@ async def _parallel_image_and_audio(project_id: int) -> None:
if not need:
return
+ if not lock_character:
+ # Content-driven: each shot uses only template base refs (if any)
+ results = await asyncio.gather(
+ *(one_image(m, list(base_refs)) for m in need),
+ return_exceptions=True,
+ )
+ for r in results:
+ if isinstance(r, Exception):
+ raise r
+ return
+
anchor = existing_anchor
first, rest = need[0], need[1:]
first_refs = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
@@ -727,7 +788,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
shot_rows=shot_rows,
force=False,
)
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
project = await db.get(Project, project_id)
if project:
@@ -756,7 +817,7 @@ async def _parallel_image_and_audio(project_id: int) -> None:
raise err
raise RuntimeError(str(errors[0]))
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
result = await db.execute(
select(Project)
@@ -794,12 +855,14 @@ async def _parallel_videos(project_id: int) -> None:
)
project = result.scalar_one()
tpl = project.template
- consistency = bool(tpl.seedance_config.get("character_consistency", True))
+ consistency = template_consistency_mode(tpl) == "character" and bool(
+ tpl.seedance_config.get("character_consistency", True)
+ )
motion = str(tpl.seedance_config.get("motion_bias", ""))
resolution = cfg.ark_video_resolution
if project.resolution_mode == "hd" and resolution == "480p":
resolution = "720p"
- ratio = tpl.default_ratio or cfg.ark_video_ratio
+ ratio = _project_output_ratio(project) or cfg.ark_video_ratio
shot_meta = [
{
"id": s.id,
@@ -886,7 +949,7 @@ async def _parallel_videos(project_id: int) -> None:
)
return
raise
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
shot = await db.get(Shot, meta["id"])
if not shot:
@@ -897,7 +960,7 @@ async def _parallel_videos(project_id: int) -> None:
async with progress_lock:
done += 1
pct = 55 + int(30 * done / max(total, 1))
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
project = await db.get(Project, project_id)
if project:
@@ -924,7 +987,7 @@ async def _parallel_videos(project_id: int) -> None:
raise err
raise RuntimeError(str(errors[0]))
- async with _db_write_lock:
+ async with _db_write_lock():
async with AsyncSessionLocal() as db:
project = await db.get(Project, project_id)
if project:
@@ -955,20 +1018,27 @@ async def _image_stage(project_id: int) -> None:
style_prefix = _effective_style(project)
bible = getattr(project, "character_bible", None) or ""
photoreal = template_is_photoreal(tpl)
+ consist = template_consistency_mode(tpl)
+ lock_character = consist == "character"
anchor: str | None = None
for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):
await _ensure_not_cancelled(project_id)
if shot.image_url or shot.image_ark_url:
- if not anchor:
+ if lock_character and not anchor:
anchor = shot.image_ark_url or shot.image_url
continue
- refs = seedream_ref_urls(anchor, *ref_urls) if anchor else list(ref_urls)
+ if lock_character:
+ refs = seedream_ref_urls(anchor, *ref_urls) if anchor else list(ref_urls)
+ else:
+ refs = list(ref_urls)
prompt = build_locked_image_prompt(
style_prefix,
strip_lock_blocks(shot.img_prompt),
- bible,
+ bible if lock_character else "",
photoreal=photoreal,
+ lock_character=lock_character,
+ lock_style=True,
)
img = await ark.gen_image(
prompt,
@@ -981,7 +1051,7 @@ async def _image_stage(project_id: int) -> None:
shot.image_url = img.local_url
shot.image_ark_url = img.remote_url
shot.status = ShotStatus.IMAGE_READY
- if not anchor:
+ if lock_character and not anchor:
anchor = img.remote_url or img.local_url
span = 55 if _is_image_text(project) else 25
pct = 20 + int(span * (idx + 1) / max(total, 1))
@@ -1015,14 +1085,16 @@ async def _video_stage(project_id: int) -> None:
)
project = result.scalar_one()
tpl = project.template
- consistency = bool(tpl.seedance_config.get("character_consistency", True))
+ consistency = template_consistency_mode(tpl) == "character" and bool(
+ tpl.seedance_config.get("character_consistency", True)
+ )
motion = str(tpl.seedance_config.get("motion_bias", ""))
total = len(project.shots)
cfg = get_settings()
resolution = cfg.ark_video_resolution
if project.resolution_mode == "hd" and resolution == "480p":
resolution = "720p"
- ratio = tpl.default_ratio or cfg.ark_video_ratio
+ ratio = _project_output_ratio(project) or cfg.ark_video_ratio
for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):
await _ensure_not_cancelled(project_id)
prompt = f"{shot.video_prompt}。运镜:{shot.camera}。{motion}"
@@ -1089,16 +1161,26 @@ async def _compose_stage(project_id: int) -> None:
project = result.scalar_one()
media: list[ShotMedia] = []
for shot in sorted(project.shots, key=lambda s: s.shot_no):
+ pdir = storage.project_dir(project_id)
+ # Resolve/download to local for FFmpeg; keep OSS URLs in DB for frontend preview
video_path = storage.local_path_from_url(shot.video_url or "")
audio_path = storage.local_path_from_url(shot.audio_url or "")
image_path = storage.local_path_from_url(shot.image_url or "")
- pdir = storage.project_dir(project_id)
- if shot.video_url and shot.video_url.startswith("http"):
- video_path = await storage.download_to(shot.video_url, pdir / f"shot_{shot.shot_no:03d}.mp4")
- shot.video_url = storage.rel_static_url(video_path)
- if shot.audio_url and shot.audio_url.startswith("http"):
- audio_path = await storage.download_to(shot.audio_url, pdir / f"shot_{shot.shot_no:03d}_tts.mp3")
- shot.audio_url = storage.rel_static_url(audio_path)
+ if shot.video_url and (not video_path or not video_path.exists()):
+ if shot.video_url.startswith("http"):
+ video_path = await storage.ensure_local_media(
+ shot.video_url, pdir / f"shot_{shot.shot_no:03d}.mp4"
+ )
+ if shot.audio_url and (not audio_path or not audio_path.exists()):
+ if shot.audio_url.startswith("http"):
+ audio_path = await storage.ensure_local_media(
+ shot.audio_url, pdir / f"shot_{shot.shot_no:03d}_tts.mp3"
+ )
+ if shot.image_url and (not image_path or not image_path.exists()):
+ if shot.image_url.startswith("http"):
+ image_path = await storage.ensure_local_media(
+ shot.image_url, pdir / f"shot_{shot.shot_no:03d}.png"
+ )
media.append(
ShotMedia(
shot_no=shot.shot_no,
@@ -1112,15 +1194,26 @@ async def _compose_stage(project_id: int) -> None:
)
)
- ratio = (project.template.default_ratio if project.template else None) or "16:9"
+ ratio = _project_output_ratio(project)
mode = project.pipeline_mode or "full"
- if mode == "image_text" and ratio == "16:9":
- ratio = "9:16"
full_audio = _full_narration_path(project_id)
if not full_audio.exists():
full_audio = None
+ sub_cfg = (project.template.subtitle_config if project.template else None) or {}
+ layout = str(sub_cfg.get("position") or "top")
+ if layout not in {"top", "split", "bottom", "center"}:
+ layout = "top"
+ # bottom/center still use top dual-line unless explicitly split
+ subtitle_layout = "split" if layout == "split" else "top"
+
+ def _f(key: str, default: float) -> float:
+ try:
+ return float(sub_cfg.get(key, default))
+ except (TypeError, ValueError):
+ return default
+
out = storage.project_dir(project_id) / "final.mp4"
await asyncio.to_thread(
compose_project,
@@ -1131,9 +1224,13 @@ async def _compose_stage(project_id: int) -> None:
mode=mode,
resolution_mode=project.resolution_mode or "preview",
full_audio_path=full_audio,
+ subtitle_layout=subtitle_layout,
+ title_scale=_f("title_scale", 1.35),
+ sub_scale=_f("sub_scale", 1.3),
+ caption_scale=_f("caption_scale", 1.25),
),
)
- project.final_video_url = storage.rel_static_url(out)
+ project.final_video_url = storage.publish_local(out)
if project.status != ProjectStatus.CANCELLED:
project.status = ProjectStatus.AUDITING
project.progress = 96
@@ -1160,8 +1257,12 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:
if not shot:
raise ValueError("shot not found")
base_refs = _project_base_refs(project)
- anchor = _consistency_ref_from_shots([s for s in project.shots if s.id != shot.id])
- ref_urls = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
+ lock_character = template_consistency_mode(project.template) == "character"
+ if lock_character:
+ anchor = _consistency_ref_from_shots([s for s in project.shots if s.id != shot.id])
+ ref_urls = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
+ else:
+ ref_urls = list(base_refs)
negative = _project_image_negative(project)
prompt = _locked_shot_prompt(project, shot.img_prompt)
img = await ark.gen_image(
@@ -1197,7 +1298,9 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
if not shot or not (shot.image_url or shot.image_ark_url):
raise ValueError("shot image required")
motion = str(project.template.seedance_config.get("motion_bias", ""))
- consistency = bool(project.template.seedance_config.get("character_consistency", True))
+ consistency = template_consistency_mode(project.template) == "character" and bool(
+ project.template.seedance_config.get("character_consistency", True)
+ )
cfg = get_settings()
resolution = cfg.ark_video_resolution
if project.resolution_mode == "hd" and resolution == "480p":
@@ -1212,7 +1315,7 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
shot_no=shot.shot_no,
character_consistency=consistency,
resolution=resolution,
- ratio=project.template.default_ratio or cfg.ark_video_ratio,
+ ratio=_project_output_ratio(project) or cfg.ark_video_ratio,
)
shot.video_url = local_video
shot.status = ShotStatus.VIDEO_READY
diff --git a/backend/app/services/storage.py b/backend/app/services/storage.py
index 3c662d1..807c355 100644
--- a/backend/app/services/storage.py
+++ b/backend/app/services/storage.py
@@ -1,8 +1,12 @@
-"""Download / persist generated assets under backend/static/generated."""
+"""Download / persist generated assets under backend/static/generated.
+
+When OSS is enabled, public URLs point to OSS while FFmpeg still uses local files.
+"""
from __future__ import annotations
import base64
+import logging
import mimetypes
from pathlib import Path
@@ -10,6 +14,8 @@ import httpx
from app.config import get_settings
+logger = logging.getLogger(__name__)
+
STATIC_ROOT = Path(__file__).resolve().parents[2] / "static"
GENERATED_ROOT = STATIC_ROOT / "generated"
@@ -31,12 +37,33 @@ def to_public_url(rel_or_abs: str) -> str:
def local_path_from_url(url: str) -> Path | None:
+ """Resolve DB/media URL to a local filesystem path when possible."""
+ if not url:
+ return None
if url.startswith("/static/"):
return STATIC_ROOT / url.removeprefix("/static/")
settings = get_settings()
prefix = settings.public_base_url.rstrip("/") + "/static/"
if url.startswith(prefix):
return STATIC_ROOT / url.removeprefix(prefix)
+
+ # OSS public URL → kepu/generated/... → static/generated/...
+ if url.startswith("http://") or url.startswith("https://"):
+ from app.services import oss as oss_svc
+
+ if oss_svc.oss_enabled():
+ folder = oss_svc.folder_prefix()
+ marker = f"/{folder}/"
+ idx = url.find(marker)
+ if idx >= 0:
+ rest = url[idx + len(marker) :].split("?", 1)[0]
+ return STATIC_ROOT / rest
+ # Generic: .../generated/pN/...
+ marker2 = "/generated/"
+ idx2 = url.find(marker2)
+ if idx2 >= 0:
+ rest = url[idx2 + 1 :].split("?", 1)[0] # generated/pN/...
+ return STATIC_ROOT / rest
return None
@@ -76,3 +103,23 @@ async def ensure_local_media(url: str, dest: Path) -> Path:
def rel_static_url(path: Path) -> str:
rel = path.resolve().relative_to(STATIC_ROOT.resolve())
return f"/static/{rel.as_posix()}"
+
+
+def publish_local(path: Path) -> str:
+ """Return frontend URL for a local media file.
+
+ Always keeps the file on disk for FFmpeg. When OSS is enabled, uploads and
+ returns the public OSS URL; otherwise returns /static/... relative path.
+ """
+ path = Path(path)
+ if not path.is_file():
+ raise FileNotFoundError(str(path))
+ from app.services import oss as oss_svc
+
+ if not oss_svc.oss_enabled():
+ return rel_static_url(path)
+ try:
+ return oss_svc.upload_file(path)
+ except Exception: # noqa: BLE001
+ logger.exception("OSS upload failed for %s, falling back to local URL", path)
+ return rel_static_url(path)
diff --git a/backend/app/services/style_lock.py b/backend/app/services/style_lock.py
index 497a490..f8fbb9c 100644
--- a/backend/app/services/style_lock.py
+++ b/backend/app/services/style_lock.py
@@ -81,28 +81,38 @@ def build_locked_image_prompt(
character_bible: str = "",
*,
photoreal: bool = False,
+ lock_character: bool = True,
+ lock_style: bool = True,
) -> str:
- """Canonical prompt sent to Seedream — style + cast locked every shot."""
+ """Prompt for Seedream. lock_* can be relaxed for diverse / showcase templates."""
body = strip_lock_blocks(strip_style_drift(img_prompt, photoreal=photoreal))
if style_prefix and style_prefix in body:
body = body.replace(style_prefix, "", 1).strip(",, ")
parts: list[str] = []
- if style_prefix:
+ if lock_style and style_prefix:
if photoreal:
parts.append(
f"【风格锁定】{style_prefix}。全片统一此画风,禁止卡通动漫与风格跳变"
)
- else:
+ elif lock_character:
parts.append(
f"【风格锁定】{style_prefix}。全片统一此画风,禁止写实摄影与风格跳变"
)
- if (character_bible or "").strip():
+ else:
+ parts.append(
+ f"【风格提示】{style_prefix}。"
+ "配色与界面类型优先服从【场景】描述;禁止无脑套用霓虹蓝赛博大屏"
+ )
+ if lock_character and (character_bible or "").strip():
parts.append(
f"【人物锁定】{(character_bible or '').strip()}。凡出现人物必须严格沿用以上外形,禁止换脸换装"
)
if body:
parts.append(f"【场景】{body}")
- parts.append("【约束】同一画风同一人物,画面干净无文字")
+ if lock_character:
+ parts.append("【约束】同一画风同一人物,画面干净无文字")
+ else:
+ parts.append("【约束】本镜场景必须独特、与其他镜头构图明显不同,画面干净无文字")
return "\n".join(parts)
@@ -121,6 +131,27 @@ def merge_negative(
return merged
+def template_consistency_mode(tpl) -> str:
+ """Return character | style | diverse.
+
+ - character: cast lock + shot-to-shot image ref chaining (叙事默认)
+ - style: keep style only, no cast lock, no ref chaining
+ - diverse: content-driven independent scenes (开源/产品演示)
+ """
+ if tpl is None:
+ return "character"
+ cfg = getattr(tpl, "seedream_config", None) or {}
+ if not isinstance(cfg, dict):
+ cfg = {}
+ mode = str(cfg.get("consistency_mode") or "").strip().lower()
+ if mode in {"character", "style", "diverse", "none"}:
+ return "diverse" if mode == "none" else mode
+ for conf in (cfg, getattr(tpl, "seedance_config", None) or {}):
+ if isinstance(conf, dict) and "character_consistency" in conf:
+ return "character" if conf.get("character_consistency") else "diverse"
+ return "character"
+
+
def template_is_photoreal(tpl) -> bool:
"""True when template opts into live-action / photoreal style."""
if tpl is None:
diff --git a/backend/app/services/templates_seed.py b/backend/app/services/templates_seed.py
index 6de2bc6..e3ef3c0 100644
--- a/backend/app/services/templates_seed.py
+++ b/backend/app/services/templates_seed.py
@@ -1,11 +1,82 @@
"""内置风格模板 — 提示词与风格描述统一中文。
分类约定(category[0] 为主分类,用于首页筛选):
-电影感 / 真人感 / 写实感 / 科普 / 儿童 / 国风 / 科幻 / 动漫 / 商业 / 复古 / 纪录片 / 奇幻 / 图文 / 悬疑
+电影感 / 真人感 / 写实感 / 科普 / 儿童 / 国风 / 科幻 / 动漫 / 商业 / 复古 / 纪录片 / 奇幻 / 图文 / 悬疑 / 开源
真人感、写实感模板须在 seedream_config 设 photoreal: true。
+
+一致性(seedream_config.consistency_mode):
+- character:人物+画风锁定,镜间图生图链式参考(叙事默认)
+- style:仅画风气质,不锁人物、不链式参考
+- diverse:按内容动态规划独立场景(开源/产品演示),禁止镜间雷同
+未设置时回退 seedance/seedream 的 character_consistency。
+
+成片方式(是否生成 AI 视频)由用户在风格配置页选择,不再由模板锁定。
+模板 default_ratio 仅作画幅默认建议。
"""
TEMPLATES: list[dict] = [
+ {
+ "id": "opensource_showcase",
+ "name": "开源项目展示",
+ "description": "按项目内容动态规划:人物操作系统界面与真实使用场景,适合开源工具与平台介绍。",
+ "category": ["开源", "图文", "商业"],
+ "preview_cover": "/static/templates/covers/opensource_showcase.png",
+ "style_prefix": (
+ "高品质产品演示静帧:人物在真实工位前操作软件/文档站/工作台,"
+ "手部点击与屏幕界面清晰,排版克制、信息层级清楚,"
+ "材质与配色由内容决定(浅色SaaS、纸感文档、深色IDE、终端均可),"
+ "电影级产品演示质感,干净留白便于叠字,非任务清单界面"
+ ),
+ "negative_prompt": (
+ "任务列表,todolist,勾选框,看板卡片堆叠,"
+ "霓虹蓝,赛博朋克蓝光,全屏蓝紫渐变,发光网格地板,科幻HUD堆叠,"
+ "卡通夸张,动漫美少女,手绘潦草,画面乱码文字,字幕水印,logo乱码,模糊,"
+ "空界面无操作者,纯抽象色块"
+ ),
+ "default_ratio": "9:16",
+ "shot_duration_min": 4,
+ "shot_duration_max": 10,
+ "llm_system_addon": (
+ "这是开源/产品展示片。先【分析】用户文案:项目类型、核心能力、典型用户与使用路径,"
+ "再规划分镜与视觉,不要套固定蓝光大屏。"
+ "【画面硬性要求】每镜必须出现「人在操作系统」:"
+ "操作员坐在工位前使用电脑/笔记本/平板,点击界面、填写配置、查看看板、"
+ "演示核心流程、部署发布或阅读文档;可辅以屏幕特写,但禁止整片只有空 UI 无人。"
+ "【视觉】色板与界面气质跟内容走(浅色后台、IDE、文档站、终端等),禁止默认霓虹蓝。"
+ "【分镜】每镜对应不同能力或操作场景,构图必须明显不同,禁止待办清单/人物剧情戏。"
+ "title=模块短名(2-8字),subtitle=能力卖点(10-22字),text=口播;"
+ "img_prompt 写清人物姿态、面前界面类型、操作动作与主色。"
+ ),
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.72,
+ "consistency_mode": "diverse",
+ "character_prompt": (
+ "产品演示操作员:侧脸或过肩视角,坐在工位前操作笔记本电脑或双屏,"
+ "商务休闲着装,手部与屏幕为视觉重点,五官不必抢戏,全片气质统一"
+ ),
+ "extra_prompt": (
+ "主体为人操作系统界面,手部点击可读,禁止霓虹蓝赛博大屏;"
+ "顶部与底部留白便于叠大字,画面内不要出现任何文字;"
+ "本镜布局与操作动作须与其他镜头明显不同"
+ ),
+ },
+ "seedance_config": {
+ "motion_bias": "手部轻微点击与屏幕内容切换,缓慢推近工位",
+ "character_consistency": False,
+ },
+ "audio_config": {"voice_preset": "urban_editorial", "bgm_mood": "轻快专业"},
+ "subtitle_config": {
+ "font": "SourceHanSans",
+ "position": "split",
+ "title_scale": 1.7,
+ "sub_scale": 1.55,
+ "caption_scale": 1.3,
+ },
+ "sort_order": 1,
+ "is_active": True,
+ "is_premium": False,
+ },
{
"id": "portrait_story",
"name": "竖屏图文故事",
@@ -21,7 +92,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "image_text",
"character_prompt": "故事主角外形固定:年龄感、发型发色、服装配色与辨识物全片一致,细腻插画五官,非真人照片",
"extra_prompt": "竖屏构图,主体偏中下,顶部约1/4留白,电影感光影,画面内无文字",
},
@@ -30,7 +100,13 @@ TEMPLATES: list[dict] = [
"character_consistency": True,
},
"audio_config": {"voice_preset": "narrator_calm", "bgm_mood": "叙事氛围"},
- "subtitle_config": {"font": "SourceHanSans", "position": "top"},
+ "subtitle_config": {
+ "font": "SourceHanSans",
+ "position": "top",
+ "title_scale": 1.4,
+ "sub_scale": 1.35,
+ "caption_scale": 1.3,
+ },
"sort_order": 5,
"is_active": True,
"is_premium": False,
@@ -50,7 +126,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.75,
- "pipeline_mode": "full",
"photoreal": True,
"character_prompt": "真人演员外形固定:年龄、发型发色、面部特征、服装全片一致,写实皮肤质感",
"extra_prompt": "电影打光、浅景深、胶片颗粒,真实场景材质",
@@ -60,7 +135,7 @@ TEMPLATES: list[dict] = [
"character_consistency": True,
},
"audio_config": {"voice_preset": "narrator_calm", "bgm_mood": "电影氛围"},
- "subtitle_config": {"font": "SourceHanSans", "position": "bottom"},
+ "subtitle_config": {"font": "SourceHanSans", "position": "bottom", "caption_scale": 1.3},
"sort_order": 6,
"is_active": True,
"is_premium": False,
@@ -80,7 +155,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.72,
- "pipeline_mode": "image_text",
"photoreal": True,
"character_prompt": "真人出镜主角:年龄气质、发型发色、服装日常感固定,自然表情,全片同一人",
"extra_prompt": "自然光、生活场景、竖屏主体清晰,顶部可留白叠字",
@@ -110,7 +184,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "full",
"photoreal": True,
"character_prompt": "若出现人物:写实五官与发型服装固定;若无人物则专注真实场景与材质",
"extra_prompt": "照片级细节、真实材质、自然色彩,清晰主体",
@@ -140,7 +213,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.72,
- "pipeline_mode": "full",
"character_prompt": "电影感插画主角,明确年龄与发型发色,服装轮廓与辨识物固定,面部细节适中非照片,全片同一人设",
"extra_prompt": "胶片颗粒、暗角、戏剧光影,青橙氛围,宽银幕主体明确",
},
@@ -169,7 +241,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.72,
- "pipeline_mode": "full",
"character_prompt": "Noir 风插画角色,轮廓清晰,大衣或标志性剪影,面部少光,外形全片一致",
"extra_prompt": "高对比阴影、冷调、雨夜或台灯,强构图张力",
},
@@ -186,24 +257,44 @@ TEMPLATES: list[dict] = [
{
"id": "vox_papercut",
"name": "Vox剪纸科普",
- "description": "低饱和扁平剪纸,适合硬核科普与纪录片节奏。",
+ "description": "低饱和扁平剪纸,以人物操作电脑/系统界面为主画面,适合硬核科普与产品讲解。",
"category": ["科普", "剪纸"],
"preview_cover": "/static/templates/covers/vox_papercut.png",
- "style_prefix": "Vox剪纸扁平插画,层叠剪纸边缘,低饱和,干净剪影,科普解说片气质",
- "negative_prompt": "写实照片,真人,真实人脸,三维渲染,日系动漫,模糊,噪点,水印,画面文字",
+ "style_prefix": (
+ "Vox剪纸扁平插画,层叠剪纸边缘,低饱和,干净剪影,科普解说片气质;"
+ "画面以人物操作电脑或业务系统为主:工位前操作、手指点击界面、多屏监控、"
+ "配置参数、流程演示,屏幕与手部动作清晰,信息图表为辅"
+ ),
+ "negative_prompt": (
+ "写实照片,真人照片级皮肤,三维写实渲染,日系动漫,模糊,噪点,水印,"
+ "画面乱码文字,空镜风景无人物无界面,纯抽象色块无操作场景"
+ ),
"default_ratio": "16:9",
"shot_duration_min": 4,
"shot_duration_max": 15,
- "llm_system_addon": "按科普讲解节奏拆镜,台词口语化、信息密度适中,每镜一个清晰视觉焦点。全片保持同一剪纸画风与角色外形。",
+ "llm_system_addon": (
+ "按科普讲解节奏拆镜,台词口语化、信息密度适中。"
+ "【画面硬性要求】每镜必须出现「人在操作系统」:"
+ "剪纸人物坐在工位/控制台前操作电脑或平板,点击鼠标键盘、切换菜单、"
+ "查看仪表盘、填写表单、对比前后状态、演示关键流程等;"
+ "可辅以屏幕特写或架构示意图,但禁止整片只有空概念图、无操作者。"
+ "title/subtitle 概括本镜知识点;img_prompt 写清人物姿态、面前屏幕内容类型与操作动作。"
+ "全片同一剪纸画风与同一操作员外形。"
+ ),
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "full",
- "character_prompt": "符号化科普角色或简洁人形剪影,低细节面部,服装色块固定,全片外形一致",
- "extra_prompt": "层叠纸片边缘清晰,低饱和,单镜一个视觉焦点,避免写实皮肤与复杂纹理",
+ "character_prompt": (
+ "固定剪纸操作员:简洁人形剪影、低细节面部、工装或休闲色块服装固定,"
+ "常坐工位前操作笔记本电脑或双屏控制台,发型与配色全片一致"
+ ),
+ "extra_prompt": (
+ "主体为人操作电脑/系统界面,屏幕区块与点击手势可读,"
+ "层叠纸片边缘清晰,低饱和,单镜一个视觉焦点,避免写实皮肤"
+ ),
},
"seedance_config": {
- "motion_bias": "缓慢横移,轻推镜头,纸层轻微错动",
+ "motion_bias": "手部轻微点击与光标移动感,屏幕内容轻切换,缓慢推近工位",
"character_consistency": True,
},
"audio_config": {"voice_preset": "narrator_calm", "bgm_mood": "好奇纪录片"},
@@ -227,7 +318,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.68,
- "pipeline_mode": "full",
"character_prompt": "纪实插画人物,生活化发型服装,亲切五官,年龄感明确,全片同一人设",
"extra_prompt": "暖色自然光,生活场景,纪录片式构图,柔和颗粒",
},
@@ -256,7 +346,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.65,
- "pipeline_mode": "full",
"character_prompt": "圆润可爱卡通角色,大眼睛简化五官,柔和配色服装,友好表情,全片同一角色外形",
"extra_prompt": "粉彩柔光,背景简洁,造型圆润,适合儿童观看",
},
@@ -285,7 +374,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "full",
"character_prompt": "日系动漫主角,发型发色瞳色固定,校服或常服配色固定,赛璐璐五官,全片同一人设",
"extra_prompt": "柔光、干净线稿、柔和天空,统一赛璐璐上色",
},
@@ -302,24 +390,33 @@ TEMPLATES: list[dict] = [
{
"id": "chalk_whiteboard",
"name": "粉笔白板手绘",
- "description": "黑板粉笔与白板简笔画,适合课堂讲解风。",
+ "description": "黑板粉笔讲解风,突出人物操作系统/画流程图的课堂演示。",
"category": ["科普", "手绘"],
"preview_cover": "/static/templates/covers/chalk_whiteboard.png",
- "style_prefix": "黑板粉笔与白板手绘讲解风,粉笔笔触,示意图箭头,素描线条",
- "negative_prompt": "写实照片,光滑三维,杂乱界面",
+ "style_prefix": (
+ "黑板粉笔与白板手绘讲解风,粉笔笔触,示意图箭头;"
+ "画面常含简笔人物在白板或电脑前操作系统、画流程、指点界面"
+ ),
+ "negative_prompt": "写实照片,光滑三维,杂乱界面,空教室无人物",
"default_ratio": "16:9",
"shot_duration_min": 4,
"shot_duration_max": 15,
- "llm_system_addon": "偏讲解结构:定义→例子→对比,画面多用示意图与箭头。",
+ "llm_system_addon": (
+ "偏讲解结构:定义→例子→对比。"
+ "每镜尽量出现简笔人物操作系统或在白板上演示系统流程"
+ "(指点屏幕、画模块箭头、对比操作前后),避免只有抽象符号没有操作者。"
+ ),
"seedream_config": {
"ref_images": [],
"strength": 0.6,
- "pipeline_mode": "full",
- "character_prompt": "粉笔简笔人物或火柴人讲解者,线条简洁,特征固定,可重复识别",
- "extra_prompt": "黑板/白板底,箭头与示意图清晰,教学感构图",
+ "character_prompt": (
+ "粉笔简笔讲解者/操作员,线条简洁特征固定,"
+ "常站在白板前或坐在电脑前指点界面"
+ ),
+ "extra_prompt": "黑板/白板底,人物操作系统或画流程图,箭头清晰,教学感构图",
},
"seedance_config": {
- "motion_bias": "线条逐步显现,镜头基本固定",
+ "motion_bias": "手部指点与线条逐步显现,镜头基本固定或轻推",
"character_consistency": True,
},
"audio_config": {"voice_preset": "teacher_clear", "bgm_mood": "专注氛围"},
@@ -343,7 +440,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.72,
- "pipeline_mode": "full",
"character_prompt": "赛博风插画角色,外套剪裁与发色固定,霓虹边缘光,面部非照片,全片同一人设",
"extra_prompt": "霓虹粉青、雨夜反光、未来都市,强对比夜景",
},
@@ -372,7 +468,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.72,
- "pipeline_mode": "full",
"character_prompt": "奇幻主角外形固定:盔甲或斗篷轮廓、发色、武器辨识物全片一致,插画五官非照片",
"extra_prompt": "宏大场景、暮光神性光束、戏剧构图,史诗氛围",
},
@@ -401,7 +496,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.75,
- "pipeline_mode": "image_text",
"character_prompt": "杂志剪贴人像剪影或印刷半调人物,外形与配色全片统一",
"extra_prompt": "撕边纸质、网纹印刷、大胆色块,竖屏强构图",
},
@@ -430,7 +524,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.68,
- "pipeline_mode": "image_text",
"character_prompt": "极简几何化人物或手部剪影,配色固定,低细节面部,全片外形一致",
"extra_prompt": "大留白、有限色板、几何构图,竖屏品牌感",
},
@@ -455,16 +548,18 @@ TEMPLATES: list[dict] = [
"default_ratio": "16:9",
"shot_duration_min": 3,
"shot_duration_max": 12,
- "llm_system_addon": "节奏偏游戏关卡感,信息点做成可辨识像素图标。",
+ "llm_system_addon": (
+ "节奏偏游戏关卡感,信息点做成可辨识像素图标。"
+ "涉及软件/系统/工具时,优先像素小人坐在电脑前操作系统、点击菜单、通关式演示流程。"
+ ),
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "full",
- "character_prompt": "16位像素小人角色,有限色板,外形与调色全片不变",
- "extra_prompt": "清晰像素块,无抗锯齿,游戏关卡式场景",
+ "character_prompt": "16位像素小人操作员,坐在电脑前,有限色板,外形与调色全片不变",
+ "extra_prompt": "像素小人操作系统界面,清晰像素块,无抗锯齿,游戏关卡式场景",
},
"seedance_config": {
- "motion_bias": "逐帧步进运动,轻微视差滚动",
+ "motion_bias": "逐帧点击与屏幕切换,轻微视差滚动",
"character_consistency": True,
},
"audio_config": {"voice_preset": "retro_host", "bgm_mood": "8位好奇"},
@@ -488,7 +583,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "full",
"character_prompt": "怀旧风插画人物,年代感发型服装固定,轻微色差边缘,非照片,全片同一人设",
"extra_prompt": "扫描线暗示、轻微色差、80/90年代色调,怀旧构图",
},
@@ -517,7 +611,6 @@ TEMPLATES: list[dict] = [
"seedream_config": {
"ref_images": [],
"strength": 0.7,
- "pipeline_mode": "image_text",
"character_prompt": "水墨写意人物,简笔眉眼,宽袍或古装轮廓固定,墨色淡雅,全片同一人设",
"extra_prompt": "大量留白,淡墨渲染,诗意意境,竖屏顶部可叠字",
},
diff --git a/backend/app/services/voices.py b/backend/app/services/voices.py
index b69e95d..9af404e 100644
--- a/backend/app/services/voices.py
+++ b/backend/app/services/voices.py
@@ -65,3 +65,34 @@ def resolve_speaker(voice_id: str | None, *, template_preset: str | None = None)
return str(preset["speaker"])
# Pass-through custom speaker ids
return raw
+
+
+PREVIEW_TEXT = "大家好,这是当前音色的试听效果,适合科普短视频旁白讲解。"
+
+
+async def ensure_voice_preview(voice_id: str) -> str:
+ """Generate (or reuse cached) short TTS sample; return public URL."""
+ import hashlib
+ from pathlib import Path
+
+ from app.services import storage
+ from app.services.ark import get_ark
+
+ speaker = resolve_speaker(voice_id)
+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in speaker)[:80]
+ cache_dir = Path(__file__).resolve().parents[2] / "static" / "voice_previews"
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ dest = cache_dir / f"{safe}.mp3"
+ if dest.exists() and dest.stat().st_size > 2000:
+ return storage.publish_local(dest)
+
+ ark = get_ark()
+ shot_no = int(hashlib.md5(speaker.encode()).hexdigest()[:4], 16) % 800 + 100
+ url = await ark.tts(PREVIEW_TEXT, speaker, project_id=0, shot_no=shot_no)
+ src = storage.local_path_from_url(url)
+ if src and src.exists():
+ dest.write_bytes(src.read_bytes())
+ return storage.publish_local(dest)
+ if dest.exists() and dest.stat().st_size > 2000:
+ return storage.publish_local(dest)
+ return url
diff --git a/backend/app/workers/autoscale.py b/backend/app/workers/autoscale.py
index 3c0bcc2..2ed17fa 100644
--- a/backend/app/workers/autoscale.py
+++ b/backend/app/workers/autoscale.py
@@ -232,7 +232,16 @@ class CeleryAutoscaler:
reclaim_unacked(self.settings.redis_url)
import asyncio
- asyncio.run(redispatch_stale_projects(older_than_sec=120))
+ from app.database import dispose_engine
+
+ async def _boot_recover() -> None:
+ await dispose_engine()
+ try:
+ await redispatch_stale_projects(older_than_sec=120)
+ finally:
+ await dispose_engine()
+
+ asyncio.run(_boot_recover())
except Exception: # noqa: BLE001
logger.exception("startup recover failed")
@@ -253,7 +262,16 @@ class CeleryAutoscaler:
from app.workers.recover import redispatch_stale_projects
import asyncio
- asyncio.run(redispatch_stale_projects())
+ from app.database import dispose_engine
+
+ async def _periodic_recover() -> None:
+ await dispose_engine()
+ try:
+ await redispatch_stale_projects()
+ finally:
+ await dispose_engine()
+
+ asyncio.run(_periodic_recover())
except redis.RedisError as exc:
logger.error("redis error: %s", exc)
except Exception: # noqa: BLE001
diff --git a/backend/app/workers/tasks.py b/backend/app/workers/tasks.py
index 4d21496..03a3d65 100644
--- a/backend/app/workers/tasks.py
+++ b/backend/app/workers/tasks.py
@@ -11,7 +11,22 @@ logger = logging.getLogger(__name__)
def _run(coro):
- return asyncio.run(coro)
+ """Drive an async coroutine in a fresh event loop, disposing DB pool after.
+
+ Prevents 'Future attached to a different loop' when Celery reuses the
+ process across multiple asyncio.run() invocations.
+ """
+
+ async def _wrapped():
+ from app.database import dispose_engine
+
+ await dispose_engine()
+ try:
+ return await coro
+ finally:
+ await dispose_engine()
+
+ return asyncio.run(_wrapped())
@celery_app.task(
diff --git a/backend/requirements.txt b/backend/requirements.txt
index bec8e09..37c1d06 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -2,6 +2,8 @@ fastapi==0.115.12
uvicorn[standard]==0.34.2
sqlalchemy==2.0.40
aiosqlite==0.21.0
+asyncpg==0.30.0
+psycopg2-binary==2.9.10
pydantic==2.11.3
pydantic-settings==2.9.1
python-jose[cryptography]==3.4.0
@@ -15,4 +17,5 @@ sse-starlette==2.2.1
python-dotenv==1.1.0
email-validator==2.2.0
edge-tts==7.2.3
+oss2==2.19.1
# Optional: pip install "volcengine-python-sdk[ark]" if you prefer official SDK
diff --git a/backend/static/templates/covers/opensource_showcase.png b/backend/static/templates/covers/opensource_showcase.png
new file mode 100644
index 0000000..0ea4ba6
Binary files /dev/null and b/backend/static/templates/covers/opensource_showcase.png differ
diff --git a/deploy/.env.prod.example b/deploy/.env.prod.example
new file mode 100644
index 0000000..e65d0d2
--- /dev/null
+++ b/deploy/.env.prod.example
@@ -0,0 +1,22 @@
+# ── /opt/ai_movie 专用 Postgres + Redis(勿与 kepu 共用)────────
+POSTGRES_USER=printfilm
+POSTGRES_PASSWORD=change-me-strong-db-password
+POSTGRES_DB=printfilm
+POSTGRES_PORT=15432
+REDIS_PORT=16379
+
+SECRET_KEY=change-me-to-a-long-random-string
+DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm
+DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm
+REDIS_URL=redis://127.0.0.1:16379/0
+
+PUBLIC_BASE_URL=https://kepu.printfilm.com
+CORS_ORIGINS=https://kepu.printfilm.com
+
+ARK_MOCK=false
+ARK_API_KEY=your-ark-api-key
+USE_CELERY=true
+QUOTA_ENABLED=false
+
+CELERY_AUTOSCALE_MIN=1
+CELERY_AUTOSCALE_MAX=3
diff --git a/deploy/README.md b/deploy/README.md
new file mode 100644
index 0000000..461163d
--- /dev/null
+++ b/deploy/README.md
@@ -0,0 +1,100 @@
+# PRINTFILM 部署(Docker 只跑库与缓存)
+
+## 分工
+
+| 组件 | 运行方式 |
+|------|----------|
+| PostgreSQL | Docker |
+| Redis | Docker |
+| FastAPI / Celery worker | 宿主机 Python 进程 |
+| 前端 | 宿主机 `npm run dev` 或 `npm run build` + 静态托管 |
+
+## 1. 启动中间件(独立目录,不复用其它项目的库)
+
+```bash
+cp deploy/.env.prod.example deploy/.env.prod # 改密码;默认端口 15432 / 16379
+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod up -d
+docker compose -f deploy/docker-compose.yml ps
+```
+
+容器名:`ai-movie-pg`、`ai-movie-redis`。与 kepu(5432/6379)隔离。
+
+## 2. 配置应用
+
+将 `deploy/.env.prod` 中的 `DATABASE_URL` / `REDIS_URL` / `ARK_*` 等写入 `backend/.env`(密码与 compose 一致)。
+
+正式环境示例:
+
+```env
+DATABASE_URL=postgresql+asyncpg://printfilm:<密码>@127.0.0.1:5432/printfilm
+DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:<密码>@127.0.0.1:5432/printfilm
+REDIS_URL=redis://127.0.0.1:6379/0
+USE_CELERY=true
+```
+
+需本机已安装:Python 3.12、FFmpeg(PATH)、Node.js。
+
+## 3. 启动 API + Worker
+
+```bash
+cd backend
+python -m venv .venv
+# Windows: .\.venv\Scripts\activate
+# Linux: source .venv/bin/activate
+pip install -r requirements.txt
+
+uvicorn app.main:app --host 0.0.0.0 --port 8000
+
+# 另开终端 — 固定并发
+celery -A app.workers.celery_app.celery_app worker -Q pipeline -l info --concurrency=2
+
+# 或 Windows 动态加减进程
+python -m app.workers.autoscale
+```
+
+## 4. 前端
+
+```bash
+cd frontend
+npm install
+npm run dev # 开发
+# npm run build && npx serve dist # 简单静态托管
+```
+
+## 运维
+
+```bash
+# 看中间件日志
+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod logs -f
+
+# 停中间件(不删数据)
+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod down
+
+# 停并删卷(清库/清 Redis)
+docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod down -v
+```
+
+Worker 伸缩:改 Celery `--concurrency`,或跑 `python -m app.workers.autoscale`(按队列积压加减本机进程)。
+
+## OSS(成片 / 分镜 / 前端)
+
+在 `backend/.env` 开启:
+
+```env
+OSS_ENABLED=true
+OSS_ENDPOINT=oss-cn-beijing.aliyuncs.com
+OSS_BUCKET=your-bucket
+OSS_FOLDER=kepu
+OSS_ACCESS_KEY_ID=...
+OSS_ACCESS_KEY_SECRET=...
+```
+
+- 分镜图/视频/配音/成片:本地落盘供 FFmpeg,上传后 DB 存 OSS 公网 URL(前端预览走 OSS)
+- 对象前缀:`kepu/generated/p{id}/...`
+- 前端构建产物上传:
+
+```bash
+cd frontend && npm run build
+cd ../backend && .venv/bin/python ../deploy/scripts/upload_oss_web.py
+# → https://your-bucket.oss-cn-beijing.aliyuncs.com/kepu/index.html
+```
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 8d844e8..adaf932 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -1,43 +1,42 @@
-services:
- redis:
- image: redis:7-alpine
- ports:
- - "6379:6379"
+# 独立中间件:仅 Postgres + Redis(与 /opt/kepu 无关)
+# 默认端口避开 kepu 的 5432/6379
+# 启动: docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod up -d
+name: ai-movie-infra
- api:
- build: ./backend
+services:
+ postgres:
+ image: postgres:16-alpine
+ container_name: ai-movie-pg
+ restart: unless-stopped
ports:
- - "8000:8000"
- env_file:
- - ../backend/.env
+ - "127.0.0.1:${POSTGRES_PORT:-15432}:5432"
environment:
- REDIS_URL: redis://redis:6379/0
- PUBLIC_BASE_URL: http://127.0.0.1:8000
- DATABASE_URL: sqlite+aiosqlite:///./data/ai_movie.db
- DATABASE_URL_SYNC: sqlite:///./data/ai_movie.db
+ POSTGRES_USER: ${POSTGRES_USER:-printfilm}
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in deploy/.env.prod}
+ POSTGRES_DB: ${POSTGRES_DB:-printfilm}
volumes:
- - ../backend:/app
- - api-data:/app/data
- depends_on:
- - redis
- command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
+ - ai_movie_pgdata:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-printfilm} -d ${POSTGRES_DB:-printfilm}"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
- worker:
- build: ./backend
- env_file:
- - ../backend/.env
- environment:
- REDIS_URL: redis://redis:6379/0
- DATABASE_URL: sqlite+aiosqlite:///./data/ai_movie.db
- DATABASE_URL_SYNC: sqlite:///./data/ai_movie.db
- PUBLIC_BASE_URL: http://127.0.0.1:8000
+ redis:
+ image: redis:7-alpine
+ container_name: ai-movie-redis
+ restart: unless-stopped
+ ports:
+ - "127.0.0.1:${REDIS_PORT:-16379}:6379"
+ command: ["redis-server", "--appendonly", "yes", "--maxmemory", "512mb", "--maxmemory-policy", "allkeys-lru"]
volumes:
- - ../backend:/app
- - api-data:/app/data
- depends_on:
- - redis
- - api
- command: celery -A app.workers.celery_app.celery_app worker -Q pipeline -l info --concurrency=2
+ - ai_movie_redisdata:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 5s
+ timeout: 3s
+ retries: 20
volumes:
- api-data:
+ ai_movie_pgdata:
+ ai_movie_redisdata:
diff --git a/deploy/scripts/up-infra.ps1 b/deploy/scripts/up-infra.ps1
new file mode 100644
index 0000000..fced0eb
--- /dev/null
+++ b/deploy/scripts/up-infra.ps1
@@ -0,0 +1,9 @@
+# Start Postgres + Redis only
+$Root = Resolve-Path (Join-Path $PSScriptRoot "../..")
+$EnvFile = Join-Path $Root "deploy/.env.prod"
+if (-not (Test-Path $EnvFile)) {
+ Write-Error "Copy deploy/.env.prod.example → deploy/.env.prod first"
+ exit 1
+}
+docker compose -f (Join-Path $Root "deploy/docker-compose.yml") --env-file $EnvFile up -d
+docker compose -f (Join-Path $Root "deploy/docker-compose.yml") --env-file $EnvFile ps
diff --git a/deploy/scripts/up-infra.sh b/deploy/scripts/up-infra.sh
new file mode 100644
index 0000000..3a938ce
--- /dev/null
+++ b/deploy/scripts/up-infra.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Start Postgres + Redis only
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+ENV_FILE="$ROOT/deploy/.env.prod"
+if [[ ! -f "$ENV_FILE" ]]; then
+ echo "Copy deploy/.env.prod.example → deploy/.env.prod first"
+ exit 1
+fi
+docker compose -f "$ROOT/deploy/docker-compose.yml" --env-file "$ENV_FILE" up -d
+docker compose -f "$ROOT/deploy/docker-compose.yml" --env-file "$ENV_FILE" ps
diff --git a/deploy/scripts/upload_oss_web.py b/deploy/scripts/upload_oss_web.py
new file mode 100644
index 0000000..3410a4a
--- /dev/null
+++ b/deploy/scripts/upload_oss_web.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+"""Upload frontend/dist to Aliyun OSS under kepu/ (SPA + assets).
+
+Usage (from repo root, with backend venv):
+ backend\\.venv\\Scripts\\python deploy/scripts/upload_oss_web.py
+ backend\\.venv\\Scripts\\python deploy/scripts/upload_oss_web.py --dist frontend/dist
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+BACKEND = ROOT / "backend"
+sys.path.insert(0, str(BACKEND))
+
+# Load backend/.env via settings
+from app.config import reload_settings # noqa: E402
+from app.services import oss as oss_svc # noqa: E402
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Upload SPA dist to OSS kepu/")
+ parser.add_argument("--dist", type=Path, default=ROOT / "frontend" / "dist")
+ parser.add_argument(
+ "--prefix",
+ default=None,
+ help="OSS key prefix (default: oss_folder from settings, e.g. kepu)",
+ )
+ args = parser.parse_args()
+ dist: Path = args.dist
+ if not dist.is_dir():
+ raise SystemExit(f"dist not found: {dist} — run npm run build first")
+
+ reload_settings()
+ if not oss_svc.oss_enabled():
+ raise SystemExit("OSS not enabled — set OSS_ENABLED=true and credentials in backend/.env")
+
+ prefix = (args.prefix or oss_svc.folder_prefix()).strip().strip("/")
+ print(f"Uploading {dist} → oss://{reload_settings().oss_bucket}/{prefix}/")
+ n = oss_svc.upload_dir(dist, prefix)
+ base = oss_svc.public_base()
+ print(f"Uploaded {n} files")
+ print(f"Index: {base}/{prefix}/index.html")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/PRINTFILM_UI_ROADMAP.md b/docs/PRINTFILM_UI_ROADMAP.md
new file mode 100644
index 0000000..93486e3
--- /dev/null
+++ b/docs/PRINTFILM_UI_ROADMAP.md
@@ -0,0 +1,114 @@
+# PRINTFILM UI 还原与后续路线图
+
+本文档对应 6 张设计图的前端还原结果:已接线能力、占位能力与建议迭代顺序。
+
+## 路由与设计图对应
+
+| 设计图 | 路由 | 页面组件 |
+|--------|------|----------|
+| 首页 | `/` | `frontend/src/pages/HomePage.tsx` |
+| 新建项目 | `/studio/new` | `frontend/src/pages/studio/CreateProjectPage.tsx` |
+| 风格配置 | `/studio/:id/style` | `frontend/src/pages/studio/StyleConfigPage.tsx` |
+| 分镜工作台 | `/studio/:id` | `frontend/src/pages/studio/StoryboardPage.tsx` |
+| 成片编辑器 | `/studio/:id/editor` | `frontend/src/pages/studio/EditorPage.tsx` |
+| 我的项目 / 历史 | `/history` | `frontend/src/pages/HistoryPage.tsx` |
+| 模板库 | `/templates` | `frontend/src/pages/TemplatesPage.tsx` |
+| 定价 | `/pricing` | `frontend/src/pages/PricingPage.tsx` |
+
+兼容旧入口:`/studio?project=` → `/studio/:id`;`/studio?template=` → `/studio/new?template=`。
+
+共享壳层:`SiteNav` / `AppShell`(`frontend/src/components/layout/`),样式 token 见 `frontend/src/index.css` 与 `frontend/src/styles/printfilm.css`。
+
+## 已实现(接线现有 API)
+
+- 登录 / 注册 / 顶栏用户态
+- 模板列表、分类筛选、从模板进入创作
+- 创建项目(主题 / 完整文案)→ 风格配置 → `generate` 启动流水线
+- 风格:切换模板预设、风格/角色提示词、音色、`pipeline_mode`(16:9 全链路 / 9:16 图文)
+- 分镜台:进度轮询、分镜表、编辑镜头、重绘/重生视频/重配音、继续生成、合成、预览成片、发布
+- 编辑器:场景列表、预览真实媒体、保存旁白、重绘、重配音
+- 历史:列表、状态筛选、搜索、继续编辑、预览、删除、批量 zip 下载
+- 公开作品展示(首页)
+
+## 占位功能(UI 已出 / 禁用或「即将推出」)
+
+按页面列出,供后续迭代实现。
+
+### 全局顶栏
+
+1. 福利 / 礼物入口
+2. 帮助中心
+3. 通知中心
+4. 用户资料下拉(当前点击头像为退出)
+
+### 首页
+
+1. 「查看全部作品」独立社区页
+2. Hero 右侧真实 Demo 成片播放(当前为模板封面示意)
+3. 作品卡片播放量 / 点赞 / 作者信息
+
+### 新建项目
+
+1. 导入文章链接解析
+2. 上传文档(PDF/Word/TXT)
+3. 灵感示例「换一批」个性化推荐
+4. 预估时长精确计算
+5. 「加载更多模板」分页
+
+### 风格配置
+
+1. 「更多风格」商店 / 付费风格包
+2. BGM 曲库、波形预览、音量
+3. 字幕字体工具条(字号/对齐/颜色)
+4. 实时成片预览(非模板封面)
+5. 1:1 / 4:3 / 21:9 独立合成管线(当前非 9:16 暂映射全链路)
+
+### 分镜工作台
+
+1. ~~批量调整分镜~~(已实现:统一时长 + 可选重配音)
+2. ~~导出分镜脚本(CSV)~~
+3. ~~更换封面上传 / 用首镜封面~~
+4. 真正的「结构摘要」模型字段(当前由镜头旁白聚合示意)
+5. 大纲独立生成与编辑
+
+### 成片编辑器
+
+1. 撤销 / 重做 / 保存草稿
+2. 导出视频多格式 / 多平台封装
+3. 添加镜头、拖拽调序
+4. 素材库 / 收藏 / 上传 / 拖拽替换
+5. AI 优化文案
+6. 字幕样式与位置网格
+7. 转场效果
+8. 「应用到全部同类镜头」
+
+### 历史 / 我的项目
+
+1. 统计环比(较上月 ↑)真实数据
+2. 本月时长 / 额度条后端计量
+3. 快速发布:复制链接、二维码、嵌入
+4. 平台一键导出(抖音 / B 站 / 小红书 / 视频号 / YouTube)
+5. 「已发布」与「已完成」状态区分(当前均映射 DONE)
+6. 分页组件
+
+### 定价
+
+1. 套餐 SKU、支付、额度扣减
+
+## 建议迭代优先级
+
+1. **P0**:编辑器旁白保存 + 分镜重生闭环体验打磨;合成失败可恢复提示
+2. **P1**:BGM 选曲接入合成;字幕样式最小集;封面上传
+3. **P1**:素材库(本地上传替换镜头图)
+4. **P2**:平台导出 / 分享链接;通知中心
+5. **P2**:额度与定价;社区作品流
+6. **P3**:转场、时间线精修、批量调整、文档/链接导入
+
+## 视觉约定
+
+- 主色石灰绿:`#B6FF00`(`--pf-lime`)
+- 背景:`#F7F8FA`(`--pf-bg`)
+- 卡片白底、圆角约 14px、轻阴影
+- 顶栏居中导航 + 右侧「开始创作」
+
+字体:Space Grotesk(品牌英文)+ Noto Sans SC(正文,近似设计稿思源黑体)。
diff --git a/frontend/public/char-presets/anime.jpg b/frontend/public/char-presets/anime.jpg
new file mode 100644
index 0000000..1741a2b
Binary files /dev/null and b/frontend/public/char-presets/anime.jpg differ
diff --git a/frontend/public/char-presets/none.jpg b/frontend/public/char-presets/none.jpg
new file mode 100644
index 0000000..bff470a
Binary files /dev/null and b/frontend/public/char-presets/none.jpg differ
diff --git a/frontend/public/char-presets/real.jpg b/frontend/public/char-presets/real.jpg
new file mode 100644
index 0000000..f440781
Binary files /dev/null and b/frontend/public/char-presets/real.jpg differ
diff --git a/frontend/public/char-presets/sil.jpg b/frontend/public/char-presets/sil.jpg
new file mode 100644
index 0000000..ef27f37
Binary files /dev/null and b/frontend/public/char-presets/sil.jpg differ
diff --git a/frontend/public/mode-presets/full.jpg b/frontend/public/mode-presets/full.jpg
new file mode 100644
index 0000000..79a6f4e
Binary files /dev/null and b/frontend/public/mode-presets/full.jpg differ
diff --git a/frontend/public/mode-presets/image_text.jpg b/frontend/public/mode-presets/image_text.jpg
new file mode 100644
index 0000000..b49d4f9
Binary files /dev/null and b/frontend/public/mode-presets/image_text.jpg differ
diff --git a/frontend/src/App.css b/frontend/src/App.css
index 88819e1..2e87912 100644
--- a/frontend/src/App.css
+++ b/frontend/src/App.css
@@ -1,494 +1,11 @@
-.page {
- max-width: 1180px;
- margin: 0 auto;
- padding: 1.25rem 1.5rem 4rem;
-}
-
-.topbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 2rem;
-}
-
-.topbar nav {
- display: flex;
- gap: 1.25rem;
- align-items: center;
- color: var(--muted);
-}
-
-.brand-mark {
- display: inline-flex;
- align-items: center;
- gap: 0.55rem;
- font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif;
- font-size: 1.05rem;
- font-weight: 600;
- letter-spacing: 0.12em;
-}
-
-.brand-logo {
- width: 28px;
- height: 28px;
- border-radius: 6px;
- flex-shrink: 0;
-}
-
-.brand-word {
- letter-spacing: 0.14em;
-}
-
-.brand-mark-light {
- color: var(--hero-ink);
-}
-
-.lede {
- max-width: 36rem;
- color: var(--muted);
- margin: 0 0 1.5rem;
- font-size: 1.05rem;
-}
-
-.cta-row {
- display: flex;
- flex-wrap: wrap;
- gap: 0.75rem;
-}
-
-.btn {
- border: 1px solid var(--ink);
- background: transparent;
- color: var(--ink);
- padding: 0.7rem 1.2rem;
- border-radius: 2px;
- transition: transform 0.2s ease, background 0.2s ease, color 0.2s ease;
-}
-
-.btn:hover {
- transform: translateY(-1px);
-}
-
-.btn.primary {
- background: var(--ink);
- color: var(--paper);
-}
-
-.btn.primary.accent {
- background: var(--accent);
- border-color: var(--accent);
- color: var(--ink);
-}
-
-.btn.ghost {
- background: transparent;
-}
-
-/* ——— PRINTFILM marketing site ——— */
-
-.site {
- min-height: 100vh;
-}
-
-.site-nav {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- z-index: 5;
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 1.15rem clamp(1.25rem, 4vw, 3rem);
- color: var(--ink);
-}
-
-.site-nav nav {
- display: flex;
- gap: 1.15rem;
- align-items: center;
- font-size: 0.95rem;
- font-weight: 500;
- color: var(--ink);
-}
-
-.site-nav nav a,
-.site-nav nav .linkish {
- color: var(--ink);
- opacity: 0.92;
-}
-
-.site-nav nav a:hover,
-.site-nav nav .linkish:hover {
- opacity: 1;
- color: var(--teal);
-}
-
-.site-nav .nav-cta {
- border: 1px solid rgba(13, 18, 24, 0.45);
- padding: 0.4rem 0.85rem;
- color: var(--ink);
- opacity: 1;
-}
-
-.site-hero {
- position: relative;
- min-height: 100vh;
- min-height: 100dvh;
- display: flex;
- align-items: flex-end;
- overflow: hidden;
- color: var(--ink);
- background: #f3f6f8;
-}
-
-.site-hero-media {
- position: absolute;
- inset: 0;
-}
-
-.site-hero-img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- transform: scale(1.06);
- animation: hero-drift 22s ease-in-out infinite alternate;
-}
-
-.site-hero-shade {
- position: absolute;
- inset: 0;
- background:
- linear-gradient(105deg, rgba(248, 250, 252, 0.97) 0%, rgba(248, 250, 252, 0.88) 36%, rgba(248, 250, 252, 0.35) 68%, rgba(248, 250, 252, 0.08) 100%),
- linear-gradient(180deg, rgba(248, 250, 252, 0.82) 0%, rgba(248, 250, 252, 0.2) 28%, rgba(238, 241, 244, 0.85) 100%);
-}
-
-.site-hero-copy {
- position: relative;
- z-index: 1;
- width: min(720px, 100%);
- padding: 0 clamp(1.25rem, 4vw, 3rem) clamp(3.5rem, 8vh, 5.5rem);
- animation: hero-rise 1.1s cubic-bezier(0.22, 1, 0.36, 1) both;
-}
-
-.site-hero-logo {
- width: 56px;
- height: 56px;
- border-radius: 12px;
- margin-bottom: 1.1rem;
- animation: hero-rise 1.15s 0.08s cubic-bezier(0.22, 1, 0.36, 1) both;
-}
-
-.site-brand {
- font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif;
- font-size: clamp(3.4rem, 11vw, 7rem);
- font-weight: 700;
- line-height: 0.92;
- letter-spacing: 0.06em;
- margin: 0 0 0.85rem;
- color: var(--ink);
-}
-
-.site-headline {
- font-family: 'Noto Serif SC', 'Noto Sans SC', serif;
- font-size: clamp(1.45rem, 3.2vw, 2.1rem);
- font-weight: 500;
- margin: 0 0 0.65rem;
- letter-spacing: 0.06em;
- color: var(--ink);
-}
-
-.site-support {
- max-width: 28rem;
- margin: 0 0 1.75rem;
- color: #2a333c;
- font-size: 1.08rem;
- font-weight: 500;
- line-height: 1.65;
-}
-
-.site-section {
- max-width: 1180px;
- margin: 0 auto;
- padding: 4rem clamp(1.25rem, 4vw, 1.5rem) 0;
-}
-
-.site-section h2 {
- font-family: 'Space Grotesk', 'Noto Serif SC', sans-serif;
- font-size: clamp(1.7rem, 3vw, 2.2rem);
- letter-spacing: 0.04em;
- margin: 0 0 0.35rem;
-}
-
-.site-how {
- padding-top: 4.5rem;
-}
-
-.how-steps {
- list-style: none;
- margin: 2rem 0 0;
- padding: 0;
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 1.5rem;
- border-top: 1px solid var(--line);
-}
-
-.how-steps li {
- display: flex;
- flex-direction: column;
- gap: 0.4rem;
- padding: 1.5rem 0.25rem 0;
-}
-
-.how-num {
- font-family: 'Space Grotesk', sans-serif;
- font-size: 0.85rem;
- letter-spacing: 0.16em;
- color: var(--teal);
-}
-
-.how-steps strong {
- font-family: 'Noto Serif SC', serif;
- font-size: 1.2rem;
- font-weight: 600;
-}
-
-.how-steps span:last-child {
- color: var(--muted);
- font-size: 0.95rem;
-}
-
-.site-cta-band {
- margin: 4.5rem clamp(1.25rem, 4vw, 1.5rem) 0;
- padding: 3.25rem clamp(1.5rem, 4vw, 3rem);
- background:
- linear-gradient(135deg, #e8f1f3 0%, #f4f7e8 55%, #eef1f4 100%);
- color: var(--ink);
- text-align: left;
- border: 1px solid var(--line);
-}
-
-.site-cta-band h2 {
- font-family: 'Noto Serif SC', serif;
- font-size: clamp(1.5rem, 3vw, 2rem);
- margin: 0 0 0.5rem;
-}
-
-.site-cta-band p {
- margin: 0 0 1.4rem;
- color: var(--muted);
- max-width: 28rem;
-}
-
-.site-footer {
- max-width: 1180px;
- margin: 0 auto;
- padding: 2.5rem clamp(1.25rem, 4vw, 1.5rem) 3rem;
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- justify-content: space-between;
- gap: 1rem;
- color: var(--muted);
- font-size: 0.9rem;
-}
-
-@keyframes hero-drift {
- from {
- transform: scale(1.06) translate3d(0, 0, 0);
- }
- to {
- transform: scale(1.12) translate3d(-1.5%, 1%, 0);
- }
-}
-
-@keyframes hero-rise {
- from {
- opacity: 0;
- transform: translate3d(0, 28px, 0);
- }
- to {
- opacity: 1;
- transform: translate3d(0, 0, 0);
- }
-}
-
-@media (max-width: 800px) {
- .how-steps {
- grid-template-columns: 1fr;
- gap: 0;
- }
-
- .how-steps li {
- padding: 1.25rem 0;
- border-bottom: 1px solid var(--line);
- }
-
- .site-nav nav a:nth-child(1),
- .site-nav nav a:nth-child(2) {
- display: none;
- }
-}
-
-.btn.danger {
- border-color: var(--crimson);
- color: var(--crimson);
-}
-
-.btn.danger:hover {
- background: rgba(180, 35, 24, 0.08);
-}
-
-.btn:disabled {
- opacity: 0.55;
- cursor: not-allowed;
- transform: none;
-}
-
-.section {
- margin-top: 2.75rem;
-}
-
-.section h2 {
- font-family: 'Space Grotesk', 'Noto Serif SC', sans-serif;
- font-size: 1.8rem;
- letter-spacing: 0.04em;
- margin: 0 0 0.35rem;
-}
-
-.category-filters {
- display: flex;
- flex-wrap: wrap;
- gap: 0.45rem;
- margin-top: 1rem;
-}
-
-.cat-chip {
- border: 1px solid var(--line);
- background: transparent;
- color: var(--ink);
- padding: 0.35rem 0.75rem;
- font-size: 0.85rem;
- cursor: pointer;
- transition: border-color 0.2s ease, background 0.2s ease, color 0.2s ease;
-}
-
-.cat-chip:hover {
- border-color: rgba(42, 111, 122, 0.45);
-}
-
-.cat-chip.active {
- background: var(--ink);
- border-color: var(--ink);
- color: var(--paper);
-}
-
-.template-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
- gap: 1.1rem;
- margin-top: 1.25rem;
-}
-
-.template-card {
- text-align: left;
- border: 1px solid var(--line);
- background: rgba(255, 255, 255, 0.72);
- padding: 0;
- overflow: hidden;
- box-shadow: var(--shadow);
- transition: transform 0.25s ease, border-color 0.25s ease;
-}
-
-.template-card:hover {
- transform: translateY(-4px);
- border-color: rgba(42, 111, 122, 0.4);
-}
-
-.template-card img {
- width: 100%;
- aspect-ratio: 16 / 9;
- object-fit: cover;
- display: block;
-}
-
-.template-card > div {
- padding: 1rem 1rem 1.15rem;
-}
-
-.template-card h3 {
- margin: 0 0 0.35rem;
- font-size: 1.15rem;
-}
-
-.template-card p {
- margin: 0;
- color: var(--muted);
- font-size: 0.92rem;
-}
-
-.tags {
- display: flex;
- gap: 0.4rem;
- flex-wrap: wrap;
- margin-top: 0.75rem;
-}
-
-.tags span {
- border: 1px solid var(--line);
- padding: 0.15rem 0.45rem;
- font-size: 0.75rem;
- color: var(--teal);
-}
-
-.works-row {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
- gap: 1rem;
- margin-top: 1rem;
-}
-
-.work-item img {
- width: 100%;
- aspect-ratio: 16 / 9;
- object-fit: cover;
- background: var(--paper-deep);
-}
-
-.work-item h3 {
- font-size: 0.95rem;
- margin: 0.5rem 0 0;
-}
-
-.muted {
- color: var(--muted);
-}
-
-.small {
- font-size: 0.85rem;
-}
-
-.error {
- color: var(--crimson);
-}
-
-.quota {
- font-variant-numeric: tabular-nums;
- color: var(--moss);
-}
-
-.linkish {
- border: 0;
- background: none;
- color: var(--muted);
- padding: 0;
-}
+/* Residual styles for Auth and shared form utilities.
+ Marketing / studio shells live in styles/printfilm.css */
.auth-shell {
min-height: 100vh;
display: grid;
grid-template-columns: 1.1fr 0.9fr;
+ background: var(--pf-bg);
}
.auth-panel {
@@ -497,27 +14,28 @@
flex-direction: column;
justify-content: center;
gap: 0.75rem;
+ background: #fff;
}
.auth-panel h1 {
- font-family: 'Space Grotesk', 'Noto Serif SC', sans-serif;
- font-size: 2.2rem;
- letter-spacing: 0.06em;
+ font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif;
+ font-size: 2rem;
+ letter-spacing: 0.04em;
margin: 0.5rem 0 0;
}
.auth-visual {
position: relative;
overflow: hidden;
- background: #0d1218;
+ background: #111318;
}
.ink-wash {
position: absolute;
inset: -20%;
background:
- radial-gradient(circle at 30% 40%, rgba(42, 111, 122, 0.55), transparent 42%),
- radial-gradient(circle at 72% 58%, rgba(214, 255, 75, 0.18), transparent 38%),
+ radial-gradient(circle at 30% 40%, rgba(182, 255, 0, 0.35), transparent 42%),
+ radial-gradient(circle at 72% 58%, rgba(42, 111, 122, 0.35), transparent 38%),
repeating-linear-gradient(
-12deg,
transparent,
@@ -537,466 +55,38 @@
}
}
-.stack {
- display: flex;
- flex-direction: column;
- gap: 0.85rem;
-}
-
-.stack label {
- display: flex;
- flex-direction: column;
- gap: 0.35rem;
- font-size: 0.9rem;
- color: var(--muted);
-}
-
-.stack input,
-.stack textarea,
-.stack select,
-.modal input,
-.modal textarea {
- border: 1px solid var(--line);
- background: rgba(255, 255, 255, 0.92);
- padding: 0.65rem 0.75rem;
- color: var(--ink);
- border-radius: 2px;
-}
-
-.studio-layout {
- display: grid;
- grid-template-columns: 320px 1fr;
- gap: 1.5rem;
- align-items: start;
-}
-
-.studio-input,
-.studio-main,
-.shot-card,
-.modal {
- background: rgba(255, 255, 255, 0.82);
- border: 1px solid var(--line);
- box-shadow: var(--shadow);
-}
-
-.studio-input,
-.studio-main {
- padding: 1.25rem;
-}
-
-.studio-input h1 {
- font-family: 'Space Grotesk', 'Noto Serif SC', sans-serif;
- font-size: 1.5rem;
- letter-spacing: 0.04em;
+.lede {
+ max-width: 36rem;
+ color: var(--pf-muted);
margin: 0 0 1rem;
+ font-size: 1.05rem;
}
-.empty-state {
- min-height: 280px;
- display: grid;
- place-items: center;
- color: var(--muted);
- text-align: center;
-}
-
-.progress-head {
- display: flex;
- flex-direction: column;
- gap: 0.75rem;
- margin-bottom: 1.25rem;
-}
-
-.progress-head h2 {
- margin: 0;
- font-size: 1.35rem;
-}
-
-.progress-bar {
- height: 6px;
- background: var(--paper-deep);
- border-radius: 999px;
- overflow: hidden;
-}
-
-.progress-bar i {
- display: block;
- height: 100%;
- background: linear-gradient(90deg, var(--teal), var(--accent));
- transition: width 0.35s ease;
-}
-
-.shot-list {
- display: flex;
- flex-direction: column;
- gap: 0.85rem;
-}
-
-.shot-card {
- display: grid;
- grid-template-columns: 180px 1fr;
- overflow: hidden;
-}
-
-.shot-thumb img,
-.shot-thumb .placeholder {
- width: 100%;
- height: 100%;
- min-height: 120px;
- object-fit: cover;
- background: #2a2622;
- color: #d7cfc3;
- display: grid;
- place-items: center;
-}
-
-.shot-thumb.clickable {
- position: relative;
- border: 0;
- padding: 0;
- cursor: pointer;
- background: transparent;
- display: block;
- width: 100%;
- text-align: left;
-}
-
-.shot-thumb.clickable:disabled {
- cursor: default;
- opacity: 0.7;
-}
-
-.shot-thumb.clickable:not(:disabled):hover .play-badge {
- opacity: 1;
-}
-
-.play-badge {
- position: absolute;
- right: 0.45rem;
- bottom: 0.45rem;
- padding: 0.15rem 0.45rem;
- font-size: 0.72rem;
- color: #fff;
- background: rgba(26, 23, 20, 0.72);
- border: 1px solid rgba(255, 255, 255, 0.25);
- opacity: 0.85;
-}
-
-.shot-card:has(.shot-thumb.portrait) {
- grid-template-columns: 100px 1fr;
-}
-
-.shot-thumb.portrait {
- aspect-ratio: 9 / 16;
- max-height: 180px;
-}
-
-.shot-thumb.portrait img,
-.shot-thumb.portrait .placeholder {
- min-height: 160px;
- object-fit: cover;
-}
-
-.shot-body {
- padding: 0.9rem 1rem;
-}
-
-.shot-body header {
- display: flex;
- justify-content: space-between;
- margin-bottom: 0.35rem;
- color: var(--muted);
- font-size: 0.85rem;
-}
-
-.shot-actions {
- display: flex;
- gap: 0.5rem;
- margin-top: 0.65rem;
-}
-
-.shot-actions button {
- border: 1px solid var(--line);
+.btn {
+ border: 1px solid var(--pf-ink);
background: transparent;
- padding: 0.35rem 0.65rem;
- font-size: 0.82rem;
-}
-
-.modal-backdrop {
- position: fixed;
- inset: 0;
- background: rgba(26, 23, 20, 0.45);
- display: grid;
- place-items: center;
- padding: 1rem;
- z-index: 20;
-}
-
-.modal {
- width: min(560px, 100%);
- padding: 1.25rem;
- display: flex;
- flex-direction: column;
- gap: 0.75rem;
-}
-
-.modal h3 {
- margin: 0;
- font-family: 'Space Grotesk', 'Noto Serif SC', sans-serif;
-}
-
-.modal label {
- display: flex;
- flex-direction: column;
- gap: 0.3rem;
- color: var(--muted);
- font-size: 0.88rem;
-}
-
-.pad {
- padding: 0 0.25rem;
-}
-
-.history-section .history-head {
- display: flex;
- justify-content: space-between;
- align-items: flex-start;
- gap: 1rem;
- margin-bottom: 1.25rem;
-}
-
-.history-head-actions {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- justify-content: flex-end;
- gap: 0.55rem;
-}
-
-.history-select-all {
- display: inline-flex;
- align-items: center;
- gap: 0.35rem;
- font-size: 0.88rem;
- color: var(--muted);
- cursor: pointer;
- user-select: none;
-}
-
-.history-list {
- display: flex;
- flex-direction: column;
- gap: 0.85rem;
-}
-
-.history-card {
- display: grid;
- grid-template-columns: 36px 160px 1fr;
- gap: 0;
- border: 1px solid var(--line);
- background: rgba(255, 255, 255, 0.82);
- box-shadow: var(--shadow);
- overflow: hidden;
- transition: transform 0.2s ease, border-color 0.2s ease;
-}
-
-.history-card.selected {
- border-color: rgba(42, 111, 122, 0.5);
- background: rgba(238, 246, 248, 0.95);
-}
-
-.history-card:hover {
- transform: translateY(-2px);
- border-color: rgba(42, 111, 122, 0.4);
-}
-
-.history-select {
- display: grid;
- place-items: center;
- padding: 0.5rem 0;
- border-right: 1px solid var(--line);
- background: rgba(255, 255, 255, 0.35);
-}
-
-.history-select input {
- width: 1rem;
- height: 1rem;
- accent-color: #2a6f7a;
- cursor: pointer;
+ color: var(--pf-ink);
+ padding: 0.7rem 1.2rem;
+ border-radius: 10px;
+ font-weight: 600;
}
-.history-select input:disabled {
- cursor: not-allowed;
- opacity: 0.35;
+.btn.primary {
+ background: var(--pf-lime);
+ border-color: var(--pf-lime);
+ color: var(--pf-ink);
}
-.history-cover {
+.linkish {
border: 0;
+ background: none;
+ color: var(--pf-muted);
padding: 0;
- background: transparent;
- cursor: pointer;
- display: block;
- width: 100%;
- height: 100%;
-}
-
-.history-cover img,
-.history-cover .placeholder {
- width: 100%;
- height: 100%;
- min-height: 110px;
- object-fit: cover;
- background: #2a2622;
- color: #d7cfc3;
- display: grid;
- place-items: center;
-}
-
-.history-body {
- padding: 0.9rem 1rem;
- display: flex;
- flex-direction: column;
- gap: 0.45rem;
-}
-
-.history-body header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 0.75rem;
-}
-
-.history-body h3 {
- margin: 0;
- font-size: 1.05rem;
-}
-
-.title-btn {
- font: inherit;
- font-weight: 600;
- color: inherit;
text-align: left;
}
-.status-pill {
- font-size: 0.75rem;
- padding: 0.2rem 0.5rem;
- border: 1px solid var(--line);
- white-space: nowrap;
-}
-
-.status-pill.tone-ok,
-.history-card.tone-ok .status-pill {
- color: var(--moss);
- border-color: rgba(61, 90, 69, 0.35);
-}
-
-.status-pill.tone-bad,
-.history-card.tone-bad .status-pill {
+.error {
color: var(--crimson);
- border-color: rgba(180, 35, 24, 0.35);
-}
-
-.status-pill.tone-run,
-.history-card.tone-run .status-pill {
- color: #8a5a12;
- border-color: rgba(138, 90, 18, 0.35);
-}
-
-.history-meta {
- display: flex;
- flex-wrap: wrap;
- gap: 0.75rem;
- align-items: center;
- font-size: 0.85rem;
- color: var(--muted);
-}
-
-.history-actions {
- display: flex;
- flex-wrap: wrap;
- gap: 0.45rem;
- margin-top: 0.25rem;
-}
-
-.history-actions .btn {
- padding: 0.35rem 0.7rem;
- font-size: 0.82rem;
-}
-
-.truncate {
- max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.preview-modal {
- width: min(960px, 96vw);
- max-height: 96vh;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- gap: 0.65rem;
-}
-
-.preview-modal.portrait {
- width: min(480px, 96vw);
-}
-
-.preview-head {
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 0.75rem;
- flex: 0 0 auto;
-}
-
-.preview-head h3 {
- margin: 0;
-}
-
-.preview-media {
- width: 100%;
- height: min(82vh, 880px);
- max-height: min(82vh, 880px);
- object-fit: contain;
- background: #1a1714;
- display: block;
- margin: 0 auto;
- border-radius: 4px;
-}
-
-.preview-modal.portrait .preview-media {
- width: auto;
- max-width: 100%;
- height: min(84vh, 920px);
- max-height: min(84vh, 920px);
-}
-
-.preview-caption {
- margin: 0;
- flex: 0 0 auto;
- max-height: 4.5em;
- overflow: auto;
-}
-
-.preview-audio {
- width: 100%;
- margin: 0;
- flex: 0 0 auto;
-}
-
-@media (prefers-reduced-motion: reduce) {
- .site-hero-img,
- .site-hero-copy,
- .site-hero-logo,
- .ink-wash {
- animation: none !important;
- }
-
- .site-hero-img {
- transform: none;
- }
}
@media (max-width: 900px) {
@@ -1005,32 +95,12 @@
}
.auth-visual {
- min-height: 180px;
- }
-
- .studio-layout {
- grid-template-columns: 1fr;
- }
-
- .shot-card {
- grid-template-columns: 1fr;
- }
-
- .history-card {
- grid-template-columns: 36px 1fr;
- }
-
- .history-select {
- grid-row: 1 / span 2;
- border-right: 1px solid var(--line);
- }
-
- .history-cover {
- grid-column: 2;
- min-height: 140px;
+ min-height: 160px;
}
+}
- .history-body {
- grid-column: 2;
+@media (prefers-reduced-motion: reduce) {
+ .ink-wash {
+ animation: none !important;
}
}
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 20bb399..aa45c07 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -2,7 +2,14 @@ import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import AuthPage from './pages/AuthPage'
import HistoryPage from './pages/HistoryPage'
import HomePage from './pages/HomePage'
+import PricingPage from './pages/PricingPage'
import StudioPage from './pages/StudioPage'
+import TemplatesPage from './pages/TemplatesPage'
+import CreateProjectPage from './pages/studio/CreateProjectPage'
+import StyleConfigPage from './pages/studio/StyleConfigPage'
+import StoryboardPage from './pages/studio/StoryboardPage'
+import EditorPage from './pages/studio/EditorPage'
+import './styles/printfilm.css'
import './App.css'
export default function App() {
@@ -11,8 +18,14 @@ export default function App() {
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/auth" element={<AuthPage />} />
- <Route path="/studio" element={<StudioPage />} />
+ <Route path="/templates" element={<TemplatesPage />} />
+ <Route path="/pricing" element={<PricingPage />} />
<Route path="/history" element={<HistoryPage />} />
+ <Route path="/studio/new" element={<CreateProjectPage />} />
+ <Route path="/studio/:id/style" element={<StyleConfigPage />} />
+ <Route path="/studio/:id/editor" element={<EditorPage />} />
+ <Route path="/studio/:id" element={<StoryboardPage />} />
+ <Route path="/studio" element={<StudioPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 3d5587c..498661f 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -7,7 +7,10 @@ function defaultApiBase() {
return 'http://127.0.0.1:8000'
}
-const API_BASE = import.meta.env.VITE_API_BASE || defaultApiBase()
+// Empty string = same-origin (nginx proxies /api). Undefined = LAN default :8000.
+const _viteApiBase = import.meta.env.VITE_API_BASE
+const API_BASE =
+ _viteApiBase === undefined || _viteApiBase === null ? defaultApiBase() : String(_viteApiBase)
function authHeaders(): HeadersInit {
const token = localStorage.getItem('token')
@@ -54,9 +57,9 @@ export type Template = {
seedream_config?: {
ref_images?: string[]
strength?: number
- pipeline_mode?: PipelineMode
character_prompt?: string
extra_prompt?: string
+ consistency_mode?: 'character' | 'style' | 'diverse'
}
audio_config?: {
voice_preset?: string
@@ -79,20 +82,19 @@ export function defaultsFromTemplate(t: Template): {
character_prompt: string
extra_prompt: string
voice_id: string
- pipeline_mode: PipelineMode
+ output_ratio: string
} {
const cfg = t.seedream_config || {}
const preset = t.audio_config?.voice_preset || ''
const voice_id =
VOICE_PRESET_ALIASES[preset] ||
(preset.startsWith('zh_') ? preset : 'zh_female_cancan_uranus_bigtts')
- const mode = (cfg.pipeline_mode as PipelineMode) || (t.default_ratio === '9:16' ? 'image_text' : 'full')
return {
style_prompt: (t.style_prefix || '').trim(),
character_prompt: (cfg.character_prompt || '').trim(),
extra_prompt: (cfg.extra_prompt || '').trim(),
voice_id,
- pipeline_mode: mode === 'image_text' ? 'image_text' : 'full',
+ output_ratio: t.default_ratio || '16:9',
}
}
@@ -134,6 +136,7 @@ export type Project = {
final_video_url: string | null
resolution_mode: string
pipeline_mode?: PipelineMode
+ output_ratio?: string
voice_id?: string
character_bible?: string
style_prompt?: string
@@ -196,6 +199,7 @@ export const api = {
source_text: string
resolution_mode?: 'preview' | 'hd'
pipeline_mode?: PipelineMode
+ output_ratio?: string
voice_id?: string
style_prompt?: string
character_prompt?: string
@@ -211,11 +215,13 @@ export const api = {
source_text?: string
template_id?: string
pipeline_mode?: PipelineMode
+ output_ratio?: string
resolution_mode?: 'preview' | 'hd'
voice_id?: string
style_prompt?: string
character_prompt?: string
extra_prompt?: string
+ cover_url?: string | null
},
) {
return request<Project>(`/api/projects/${id}`, {
@@ -223,9 +229,37 @@ export const api = {
body: JSON.stringify(body),
})
},
+ async uploadCover(id: number, file: File) {
+ const token = localStorage.getItem('token')
+ const form = new FormData()
+ form.append('file', file)
+ const res = await fetch(`${API_BASE}/api/projects/${id}/cover`, {
+ method: 'POST',
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
+ body: form,
+ })
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ detail: res.statusText }))
+ const detail = err.detail
+ const message =
+ typeof detail === 'string'
+ ? detail
+ : Array.isArray(detail)
+ ? detail.map((d: { msg?: string }) => d.msg || JSON.stringify(d)).join('; ')
+ : res.statusText
+ throw new Error(message || '封面上传失败')
+ }
+ return res.json() as Promise<Project>
+ },
voices() {
return request<VoicePreset[]>('/api/voices')
},
+ previewVoice(voiceId: string) {
+ return request<{ url: string; voice_id: string }>('/api/voices/preview', {
+ method: 'POST',
+ body: JSON.stringify({ voice_id: voiceId }),
+ })
+ },
listProjects() {
return request<
Array<{
@@ -238,6 +272,7 @@ export const api = {
final_video_url?: string | null
error_msg?: string | null
pipeline_mode?: PipelineMode
+ output_ratio?: string
created_at: string
updated_at?: string
}>
@@ -269,8 +304,9 @@ export const api = {
getProject(id: number) {
return request<Project>(`/api/projects/${id}`)
},
- generate(id: number) {
- return request<Project>(`/api/projects/${id}/generate`, { method: 'POST' })
+ generate(id: number, opts?: { restart?: boolean }) {
+ const q = opts?.restart ? '?restart=true' : ''
+ return request<Project>(`/api/projects/${id}/generate${q}`, { method: 'POST' })
},
cancelProject(id: number) {
return request<Project>(`/api/projects/${id}/cancel`, { method: 'POST' })
@@ -305,6 +341,12 @@ export const api = {
compose(projectId: number) {
return request<Project>(`/api/projects/${projectId}/compose`, { method: 'POST' })
},
+ expandContent(topic: string, mode: 'theme' | 'script' = 'theme') {
+ return request<{ title: string; content: string }>('/api/content/expand', {
+ method: 'POST',
+ body: JSON.stringify({ topic, mode }),
+ })
+ },
publish(projectId: number) {
return request<Work>(`/api/projects/${projectId}/publish`, { method: 'POST' })
},
diff --git a/frontend/src/components/BrandMark.tsx b/frontend/src/components/BrandMark.tsx
index bb875b4..7ffc87d 100644
--- a/frontend/src/components/BrandMark.tsx
+++ b/frontend/src/components/BrandMark.tsx
@@ -2,12 +2,11 @@ import { Link } from 'react-router-dom'
type Props = {
to?: string
- light?: boolean
}
-export default function BrandMark({ to = '/', light = false }: Props) {
+export default function BrandMark({ to = '/' }: Props) {
return (
- <Link to={to} className={light ? 'brand-mark brand-mark-light' : 'brand-mark'}>
+ <Link to={to} className="brand-mark">
<img src="/logo.svg" alt="" className="brand-logo" width={28} height={28} />
<span className="brand-word">PRINTFILM</span>
</Link>
diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx
new file mode 100644
index 0000000..6ebdb13
--- /dev/null
+++ b/frontend/src/components/layout/AppShell.tsx
@@ -0,0 +1,20 @@
+import type { ReactNode } from 'react'
+import SiteNav from './SiteNav'
+
+type Props = {
+ children: ReactNode
+ active?: 'home' | 'templates' | 'studio' | 'history' | 'pricing'
+ wide?: boolean
+ flush?: boolean
+}
+
+export default function AppShell({ children, active, wide, flush }: Props) {
+ return (
+ <div className="pf-shell">
+ <SiteNav active={active} />
+ <main className={['pf-shell-main', wide ? 'wide' : '', flush ? 'flush' : ''].filter(Boolean).join(' ')}>
+ {children}
+ </main>
+ </div>
+ )
+}
diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsx
new file mode 100644
index 0000000..9dcb60e
--- /dev/null
+++ b/frontend/src/components/layout/SiteNav.tsx
@@ -0,0 +1,94 @@
+import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'
+import { useEffect, useState } from 'react'
+import { api } from '../../api'
+import type { User } from '../../api'
+import BrandMark from '../BrandMark'
+import { IconBell, IconGift, IconHelp } from '../ui/Icons'
+
+type Props = {
+ active?: 'home' | 'templates' | 'studio' | 'history' | 'pricing'
+}
+
+export default function SiteNav({ active }: Props) {
+ const nav = useNavigate()
+ const location = useLocation()
+ const [user, setUser] = useState<User | null>(null)
+
+ useEffect(() => {
+ if (!localStorage.getItem('token')) return
+ api.me().then(setUser).catch(() => localStorage.removeItem('token'))
+ }, [])
+
+ function logout() {
+ localStorage.removeItem('token')
+ setUser(null)
+ nav('/')
+ }
+
+ function goCreate() {
+ nav(user ? '/studio/new' : '/auth')
+ }
+
+ const linkClass = ({ isActive }: { isActive: boolean }) => (isActive ? 'active' : undefined)
+
+ return (
+ <header className="pf-nav">
+ <div className="pf-nav-left">
+ <BrandMark />
+ </div>
+ <nav className="pf-nav-center" aria-label="主导航">
+ <NavLink to="/" end className={active === 'home' ? () => 'active' : linkClass}>
+ 首页
+ </NavLink>
+ <NavLink to="/templates" className={active === 'templates' ? () => 'active' : linkClass}>
+ 模板
+ </NavLink>
+ <NavLink
+ to="/studio/new"
+ className={() =>
+ active === 'studio' || location.pathname.startsWith('/studio') ? 'active' : undefined
+ }
+ >
+ 创作台
+ </NavLink>
+ <NavLink to="/history" className={active === 'history' ? () => 'active' : linkClass}>
+ 历史
+ </NavLink>
+ <NavLink to="/pricing" className={active === 'pricing' ? () => 'active' : linkClass}>
+ 定价
+ </NavLink>
+ </nav>
+ <div className="pf-nav-right">
+ <button type="button" className="pf-icon-btn" title="福利(即将推出)" disabled>
+ <IconGift size={18} />
+ </button>
+ <button type="button" className="pf-icon-btn" title="帮助(即将推出)" disabled>
+ <IconHelp size={18} />
+ </button>
+ <button type="button" className="pf-icon-btn" title="通知(即将推出)" disabled>
+ <IconBell size={18} />
+ <span className="dot" />
+ </button>
+ {user ? (
+ <>
+ <button type="button" className="pf-avatar" title={`${user.nickname} · 点击退出`} onClick={logout}>
+ {user.nickname.slice(0, 1).toUpperCase()}
+ </button>
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-sm pf-btn-icon" onClick={goCreate}>
+ 开始创作
+ </button>
+ </>
+ ) : (
+ <>
+ <Link to="/auth" className="pf-link">
+ 登录
+ </Link>
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" onClick={goCreate}>
+ 开始创作
+ </button>
+ </>
+ )}
+ </div>
+ </header>
+ )
+}
diff --git a/frontend/src/components/ui/ComingSoon.tsx b/frontend/src/components/ui/ComingSoon.tsx
new file mode 100644
index 0000000..7aa9a15
--- /dev/null
+++ b/frontend/src/components/ui/ComingSoon.tsx
@@ -0,0 +1,7 @@
+type Props = {
+ label?: string
+}
+
+export default function ComingSoon({ label = '即将推出' }: Props) {
+ return <span className="pf-coming">{label}</span>
+}
diff --git a/frontend/src/components/ui/Icons.tsx b/frontend/src/components/ui/Icons.tsx
new file mode 100644
index 0000000..89fbd90
--- /dev/null
+++ b/frontend/src/components/ui/Icons.tsx
@@ -0,0 +1,235 @@
+import type { ReactNode } from 'react'
+
+type IconProps = {
+ size?: number
+ className?: string
+}
+
+function Svg({ size = 18, className, children }: IconProps & { children: ReactNode }) {
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.8"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className={className}
+ aria-hidden
+ >
+ {children}
+ </svg>
+ )
+}
+
+export function IconGift(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <rect x="3" y="8" width="18" height="13" rx="2" />
+ <path d="M12 8v13M3 12h18M12 8c0-2.2 1.2-4 3-4s3 .9 3 3-3 1-6 1-6-.1-6-1 1.2-3 3-3 3 1.8 3 4z" />
+ </Svg>
+ )
+}
+
+export function IconHelp(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <circle cx="12" cy="12" r="9" />
+ <path d="M9.5 9.5a2.5 2.5 0 1 1 3.7 2.2c-.8.5-1.2 1-1.2 2v.3" />
+ <circle cx="12" cy="17" r="0.8" fill="currentColor" stroke="none" />
+ </Svg>
+ )
+}
+
+export function IconBell(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M6 9a6 6 0 1 1 12 0c0 3.5 1.5 5 2 6H4c.5-1 2-2.5 2-6z" />
+ <path d="M10 19a2 2 0 0 0 4 0" />
+ </Svg>
+ )
+}
+
+export function IconChevronLeft(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M15 6l-6 6 6 6" />
+ </Svg>
+ )
+}
+
+export function IconPlay(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M8 6.5v11l9-5.5-9-5.5z" fill="currentColor" stroke="none" />
+ </Svg>
+ )
+}
+
+export function IconSliders(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M4 7h10M18 7h2M4 17h2M10 17h10M14 4v6M8 14v6" />
+ </Svg>
+ )
+}
+
+export function IconRefresh(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M20 6v5h-5" />
+ <path d="M4 18v-5h5" />
+ <path d="M18.5 11A7 7 0 0 0 7 7.5L4 11M5.5 13A7 7 0 0 0 17 16.5L20 13" />
+ </Svg>
+ )
+}
+
+export function IconMonitor(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <rect x="3" y="4" width="18" height="13" rx="2" />
+ <path d="M8 21h8M12 17v4" />
+ </Svg>
+ )
+}
+
+export function IconEdit(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M4 20h4l10-10-4-4L4 16v4z" />
+ <path d="M13 7l4 4" />
+ </Svg>
+ )
+}
+
+export function IconDownload(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M12 4v11M7 11l5 5 5-5M5 20h14" />
+ </Svg>
+ )
+}
+
+export function IconPlus(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M12 5v14M5 12h14" />
+ </Svg>
+ )
+}
+
+export function IconTrash(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M4 7h16M9 7V5h6v2M8 7l1 12h6l1-12" />
+ </Svg>
+ )
+}
+
+export function IconImage(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <rect x="3" y="5" width="18" height="14" rx="2" />
+ <circle cx="9" cy="10" r="1.5" />
+ <path d="M3 15l5-4 4 3 3-2 6 5" />
+ </Svg>
+ )
+}
+
+export function IconCheck(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M5 12l5 5L20 7" />
+ </Svg>
+ )
+}
+
+export function IconEye(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
+ <circle cx="12" cy="12" r="2.5" />
+ </Svg>
+ )
+}
+
+export function IconCopy(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <rect x="8" y="8" width="12" height="12" rx="2" />
+ <path d="M6 16H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
+ </Svg>
+ )
+}
+
+export function IconLink(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M10 13a5 5 0 0 0 7.1 0l2-2a5 5 0 0 0-7.1-7.1l-1.2 1.2" />
+ <path d="M14 11a5 5 0 0 0-7.1 0l-2 2a5 5 0 0 0 7.1 7.1l1.2-1.2" />
+ </Svg>
+ )
+}
+
+export function IconQr(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h2v2h-2zM18 14h2v2h-2zM14 18h2v2h-2zM18 18h2v2h-2z" />
+ </Svg>
+ )
+}
+
+export function IconCode(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M8 8l-4 4 4 4M16 8l4 4-4 4M13 5l-2 14" />
+ </Svg>
+ )
+}
+
+export function IconSearch(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <circle cx="11" cy="11" r="6.5" />
+ <path d="M16 16l4.5 4.5" />
+ </Svg>
+ )
+}
+
+export function IconClapper(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9z" />
+ <path d="M3 9l3.5-5 3 5 3-5 3 5 3-5L21 9" />
+ </Svg>
+ )
+}
+
+export function IconClock(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <circle cx="12" cy="12" r="9" />
+ <path d="M12 7v5l3 2" />
+ </Svg>
+ )
+}
+
+export function IconSend(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M4 12l16-7-7 16-2.5-6.5L4 12z" />
+ </Svg>
+ )
+}
+
+export function IconSparkles(p: IconProps) {
+ return (
+ <Svg {...p}>
+ <path d="M12 3l1.2 3.8L17 8l-3.8 1.2L12 13l-1.2-3.8L7 8l3.8-1.2L12 3z" />
+ <path d="M5 14l.7 2.1L8 17l-2.3.7L5 20l-.7-2.3L2 17l2.3-.9L5 14z" />
+ <path d="M18 13l.6 1.8L20.5 15.5l-1.9.6L18 18l-.6-1.9L15.5 15.5l1.9-.7L18 13z" />
+ </Svg>
+ )
+}
diff --git a/frontend/src/components/ui/PillTabs.tsx b/frontend/src/components/ui/PillTabs.tsx
new file mode 100644
index 0000000..e27d425
--- /dev/null
+++ b/frontend/src/components/ui/PillTabs.tsx
@@ -0,0 +1,26 @@
+type Props = {
+ items: string[]
+ value: string
+ onChange: (v: string) => void
+ ariaLabel?: string
+ lime?: boolean
+}
+
+export default function PillTabs({ items, value, onChange, ariaLabel, lime }: Props) {
+ return (
+ <div className="pf-pill-tabs" role="tablist" aria-label={ariaLabel}>
+ {items.map((item) => (
+ <button
+ key={item}
+ type="button"
+ role="tab"
+ aria-selected={value === item}
+ className={['pf-pill', lime ? 'lime' : '', value === item ? 'active' : ''].filter(Boolean).join(' ')}
+ onClick={() => onChange(item)}
+ >
+ {item}
+ </button>
+ ))}
+ </div>
+ )
+}
diff --git a/frontend/src/components/ui/StatCard.tsx b/frontend/src/components/ui/StatCard.tsx
new file mode 100644
index 0000000..c4637d4
--- /dev/null
+++ b/frontend/src/components/ui/StatCard.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from 'react'
+
+type Props = {
+ label: string
+ value: string | number
+ trend?: string
+ icon?: ReactNode
+}
+
+export default function StatCard({ label, value, trend, icon }: Props) {
+ return (
+ <article className="pf-stat">
+ <div className="pf-stat-top">
+ {icon ? <span className="pf-stat-icon">{icon}</span> : null}
+ <div className="label">{label}</div>
+ </div>
+ <div className="value">{value}</div>
+ {trend ? <div className="trend">{trend}</div> : null}
+ </article>
+ )
+}
diff --git a/frontend/src/components/ui/Stepper.tsx b/frontend/src/components/ui/Stepper.tsx
new file mode 100644
index 0000000..1b1a677
--- /dev/null
+++ b/frontend/src/components/ui/Stepper.tsx
@@ -0,0 +1,32 @@
+type Step = {
+ key: string
+ label: string
+}
+
+type Props = {
+ steps: Step[]
+ current: number
+ /** indices that are completed (0-based); defaults to all before current */
+ doneThrough?: number
+}
+
+export default function Stepper({ steps, current, doneThrough }: Props) {
+ const doneMax = doneThrough ?? current - 1
+ return (
+ <div className="pf-stepper" role="list">
+ {steps.map((s, i) => {
+ const done = i <= doneMax
+ const active = i === current
+ return (
+ <div key={s.key} className="pf-stepper" role="listitem">
+ {i > 0 ? <span className={done || active ? 'pf-step-line done' : 'pf-step-line'} /> : null}
+ <span className={['pf-step', done ? 'done' : '', active ? 'active' : ''].filter(Boolean).join(' ')}>
+ <span className="pf-step-dot">{done && !active ? '✓' : i + 1}</span>
+ {s.label}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/frontend/src/index.css b/frontend/src/index.css
index bbfa4ec..0bb1934 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -1,18 +1,32 @@
:root {
- --ink: #0d1218;
- --paper: #eef1f4;
- --paper-deep: #e0e6eb;
- --accent: #d6ff4b;
+ --pf-lime: #b6ff00;
+ --pf-lime-soft: #eefcc8;
+ --pf-ink: #111318;
+ --pf-muted: #6b7280;
+ --pf-bg: #f7f8fa;
+ --pf-card: #ffffff;
+ --pf-line: rgba(17, 19, 24, 0.1);
+ --pf-radius: 14px;
+ --pf-radius-sm: 10px;
+ --pf-shadow: 0 8px 28px rgba(17, 19, 24, 0.06);
+ --pf-nav-h: 64px;
+
+ /* legacy aliases used by residual styles */
+ --ink: var(--pf-ink);
+ --paper: var(--pf-bg);
+ --paper-deep: #e8eaee;
+ --accent: var(--pf-lime);
--teal: #2a6f7a;
--crimson: #c43c2e;
--moss: #2a6f7a;
- --muted: #5c6770;
- --line: rgba(13, 18, 24, 0.12);
- --shadow: 0 18px 50px rgba(13, 18, 24, 0.08);
+ --muted: var(--pf-muted);
+ --line: var(--pf-line);
+ --shadow: var(--pf-shadow);
--hero-ink: #e8eef2;
+
font-family: 'Noto Sans SC', 'PingFang SC', sans-serif;
- color: var(--ink);
- background: var(--paper);
+ color: var(--pf-ink);
+ background: var(--pf-bg);
line-height: 1.5;
font-weight: 400;
font-synthesis: none;
@@ -32,11 +46,7 @@ body,
}
body {
- background:
- radial-gradient(1000px 520px at 8% -8%, rgba(42, 111, 122, 0.12), transparent 55%),
- radial-gradient(800px 420px at 100% 0%, rgba(214, 255, 75, 0.08), transparent 48%),
- linear-gradient(180deg, #f5f7f9 0%, var(--paper) 42%, #e8edf1 100%);
- background-attachment: fixed;
+ background: var(--pf-bg);
}
a {
diff --git a/frontend/src/lib/categories.ts b/frontend/src/lib/categories.ts
new file mode 100644
index 0000000..12359ca
--- /dev/null
+++ b/frontend/src/lib/categories.ts
@@ -0,0 +1,36 @@
+export const CATEGORY_ORDER = [
+ '开源',
+ '科普',
+ '纪录片',
+ '写实感',
+ '真人感',
+ '电影感',
+ '儿童',
+ '动漫',
+ '国风',
+ '科幻',
+ '奇幻',
+ '悬疑',
+ '商业',
+ '复古',
+ '图文',
+]
+
+export const HOME_CATEGORY_LABELS: Record<string, string> = {
+ 全部: '全部',
+ 开源: '开源项目',
+ 科普: '知识科普',
+ 纪录片: '纪录片',
+ 写实感: '写实感',
+ 真人感: '人物故事',
+ 电影感: '电影解说',
+ 儿童: '情感治愈',
+ 动漫: '动漫',
+ 国风: '国风',
+ 科幻: '科幻',
+ 奇幻: '奇幻',
+ 悬疑: '悬疑',
+ 商业: '商业营销',
+ 复古: '复古',
+ 图文: '图文',
+}
diff --git a/frontend/src/lib/status.ts b/frontend/src/lib/status.ts
new file mode 100644
index 0000000..1e90346
--- /dev/null
+++ b/frontend/src/lib/status.ts
@@ -0,0 +1,79 @@
+export const RUNNING = new Set([
+ 'SCRIPTING',
+ 'IMAGING',
+ 'VIDEOING',
+ 'AUDIOING',
+ 'COMPOSING',
+ 'AUDITING',
+ 'PARALLEL_ASSETS',
+])
+
+export const STATUS_CN: Record<string, string> = {
+ DRAFT: '草稿',
+ SCRIPTING: '拆分镜中',
+ SCRIPT_READY: '分镜待确认',
+ IMAGING: '出图+配音并行中',
+ IMAGE_READY: '分镜图/配音完成',
+ VIDEOING: '生成 AI 视频',
+ VIDEO_READY: '镜头视频完成',
+ AUDIOING: '生成配音',
+ COMPOSING: '合成成片',
+ AUDITING: '审核中',
+ DONE: '已完成',
+ FAILED: '失败',
+ CANCELLED: '已取消',
+ REJECTED: '未通过',
+ PARALLEL_ASSETS: '出图+配音并行',
+ ASSETS_READY: '素材就绪',
+}
+
+export function isRunning(status: string) {
+ return RUNNING.has(status)
+}
+
+export function statusTone(status: string): 'ok' | 'bad' | 'run' | 'idle' {
+ if (status === 'DONE') return 'ok'
+ if (status === 'FAILED' || status === 'REJECTED' || status === 'CANCELLED') return 'bad'
+ if (isRunning(status)) return 'run'
+ return 'idle'
+}
+
+/** Per-shot statuses from pipeline */
+export const SHOT_STATUS_CN: Record<string, string> = {
+ PENDING: '等待中',
+ IMAGE_READY: '图已生成',
+ VIDEO_READY: '视频已生成',
+ AUDIO_READY: '已完成',
+ DONE: '已完成',
+ FAILED: '失败',
+}
+
+export function shotStatusLabel(status: string) {
+ return SHOT_STATUS_CN[status] || STATUS_CN[status] || status
+}
+
+export function shotIsDone(status: string) {
+ return ['AUDIO_READY', 'VIDEO_READY', 'DONE', 'IMAGE_READY'].includes(status)
+}
+
+export function formatMmSs(seconds: number) {
+ const s = Math.max(0, Math.round(seconds || 0))
+ const m = Math.floor(s / 60)
+ const r = s % 60
+ return `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}`
+}
+
+export const CREATE_STEPS = [
+ { key: 'template', label: '选择模板' },
+ { key: 'content', label: '输入内容' },
+ { key: 'style', label: '风格配置' },
+ { key: 'generate', label: '开始生成' },
+]
+
+export const BOARD_STEPS = [
+ { key: 'theme', label: '输入主题' },
+ { key: 'smart', label: '智能生成' },
+ { key: 'preset', label: '精细画面' },
+ { key: 'board', label: '生成分镜' },
+ { key: 'compose', label: '成片预览' },
+]
diff --git a/frontend/src/pages/AuthPage.tsx b/frontend/src/pages/AuthPage.tsx
index 73f01ba..c740891 100644
--- a/frontend/src/pages/AuthPage.tsx
+++ b/frontend/src/pages/AuthPage.tsx
@@ -23,7 +23,7 @@ export default function AuthPage() {
? await api.login(email, password)
: await api.register(email, password, nickname)
localStorage.setItem('token', res.access_token)
- nav('/')
+ nav('/studio/new')
} catch (err) {
setError(err instanceof Error ? err.message : '失败')
} finally {
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
index 647076f..990e377 100644
--- a/frontend/src/pages/HistoryPage.tsx
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -1,48 +1,39 @@
import { useEffect, useMemo, useState } from 'react'
-import { Link, useNavigate } from 'react-router-dom'
+import { useNavigate } from 'react-router-dom'
import { api } from '../api'
import type { Project } from '../api'
-import BrandMark from '../components/BrandMark'
+import AppShell from '../components/layout/AppShell'
+import PillTabs from '../components/ui/PillTabs'
+import StatCard from '../components/ui/StatCard'
+import ComingSoon from '../components/ui/ComingSoon'
+import {
+ IconClapper,
+ IconClock,
+ IconCode,
+ IconCopy,
+ IconDownload,
+ IconEdit,
+ IconEye,
+ IconLink,
+ IconPlus,
+ IconQr,
+ IconRefresh,
+ IconSearch,
+ IconSend,
+ IconTrash,
+} from '../components/ui/Icons'
+import { isRunning, STATUS_CN, statusTone } from '../lib/status'
type HistoryItem = Omit<Project, 'shots'>
-const STATUS_LABEL: Record<string, string> = {
- PARALLEL_ASSETS: '出图+配音并行',
- ASSETS_READY: '素材就绪',
- DRAFT: '草稿',
- SCRIPTING: '拆分镜中',
- SCRIPT_READY: '分镜完成',
- IMAGING: '出图+配音并行中',
- IMAGE_READY: '分镜图完成',
- VIDEOING: '生成 AI 视频',
- VIDEO_READY: '视频完成',
- AUDIOING: '生成配音',
- COMPOSING: '合成成片',
- AUDITING: '审核中',
- DONE: '已完成',
- FAILED: '失败',
- REJECTED: '未通过',
- CANCELLED: '已取消',
-}
-
-function isRunning(status: string) {
- return [
- 'SCRIPTING',
- 'IMAGING',
- 'VIDEOING',
- 'AUDIOING',
- 'COMPOSING',
- 'AUDITING',
- 'PARALLEL_ASSETS',
- ].includes(status)
-}
-
-function statusTone(status: string) {
- if (status === 'DONE') return 'ok'
- if (status === 'FAILED' || status === 'REJECTED' || status === 'CANCELLED') return 'bad'
- if (isRunning(status)) return 'run'
- return 'idle'
-}
+const PAGE_SIZE = 8
+const PLATFORMS = [
+ { name: 'YouTube', mark: 'YT' },
+ { name: '抖音', mark: '抖' },
+ { name: 'Bilibili', mark: 'B' },
+ { name: '小红书', mark: '红' },
+ { name: '视频号', mark: '视' },
+]
function canDownload(p: HistoryItem) {
return p.status === 'DONE' && Boolean(p.final_video_url)
@@ -59,29 +50,34 @@ function triggerBlobDownload(blob: Blob, filename: string) {
URL.revokeObjectURL(url)
}
+function statusBadgeClass(status: string) {
+ const tone = statusTone(status)
+ if (tone === 'ok') return 'ok'
+ if (tone === 'run') return 'run'
+ if (tone === 'bad') return 'bad'
+ if (status === 'DRAFT') return 'draft'
+ return ''
+}
+
export default function HistoryPage() {
const nav = useNavigate()
const [items, setItems] = useState<HistoryItem[]>([])
+ const [templates, setTemplates] = useState<Record<string, string>>({})
const [error, setError] = useState('')
const [loading, setLoading] = useState(true)
const [busyId, setBusyId] = useState<number | null>(null)
const [packing, setPacking] = useState(false)
const [selected, setSelected] = useState<Set<number>>(new Set())
- const [preview, setPreview] = useState<{ url: string; title: string; bust?: string } | null>(null)
+ const [tab, setTab] = useState('全部')
+ const [q, setQ] = useState('')
+ const [page, setPage] = useState(1)
+ const [preview, setPreview] = useState<{ url: string; title: string } | null>(null)
const hasRunning = useMemo(
() => items.some((p) => isRunning(p.status) && p.progress < 100),
[items],
)
- const downloadable = useMemo(() => items.filter(canDownload), [items])
- const selectedDownloadable = useMemo(
- () => downloadable.filter((p) => selected.has(p.id)),
- [downloadable, selected],
- )
- const allDownloadableSelected =
- downloadable.length > 0 && downloadable.every((p) => selected.has(p.id))
-
async function load() {
try {
const list = await api.listProjects()
@@ -104,278 +100,397 @@ export default function HistoryPage() {
return
}
load()
+ api.templates().then((list) => {
+ const map: Record<string, string> = {}
+ for (const t of list) map[t.id] = t.name
+ setTemplates(map)
+ })
}, [nav])
useEffect(() => {
if (!hasRunning) return
- const timer = setInterval(load, 2000)
+ const timer = setInterval(() => {
+ load().catch(() => undefined)
+ }, 2000)
return () => clearInterval(timer)
}, [hasRunning])
- function toggleOne(id: number, checked: boolean) {
- setSelected((prev) => {
- const next = new Set(prev)
- if (checked) next.add(id)
- else next.delete(id)
- return next
- })
- }
+ useEffect(() => {
+ setPage(1)
+ }, [tab, q])
- function toggleAllDownloadable() {
- if (allDownloadableSelected) {
- setSelected((prev) => {
- const next = new Set(prev)
- downloadable.forEach((p) => next.delete(p.id))
- return next
- })
- return
+ const stats = useMemo(() => {
+ const total = items.length
+ const generating = items.filter((p) => isRunning(p.status)).length
+ const done = items.filter((p) => p.status === 'DONE').length
+ return { total, generating, done }
+ }, [items])
+
+ const filtered = useMemo(() => {
+ let list = items
+ if (tab === '草稿') list = list.filter((p) => p.status === 'DRAFT')
+ else if (tab === '生成中') list = list.filter((p) => isRunning(p.status))
+ else if (tab === '已完成') list = list.filter((p) => p.status === 'DONE')
+ else if (tab === '已发布') list = list.filter((p) => p.status === 'DONE')
+ if (q.trim()) {
+ const s = q.trim().toLowerCase()
+ list = list.filter((p) => p.title.toLowerCase().includes(s))
}
+ return list
+ }, [items, tab, q])
+
+ const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
+ const pageItems = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE)
+
+ const downloadable = useMemo(() => items.filter(canDownload), [items])
+ const selectedDownloadable = useMemo(
+ () => downloadable.filter((p) => selected.has(p.id)),
+ [downloadable, selected],
+ )
+
+ function toggle(id: number) {
setSelected((prev) => {
const next = new Set(prev)
- downloadable.forEach((p) => next.add(p.id))
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
return next
})
}
- async function onBatchDownload() {
- const ids = selectedDownloadable.map((p) => p.id)
- if (!ids.length) {
- setError('请先勾选已完成的作品')
- return
- }
- setPacking(true)
- setError('')
+ async function remove(id: number) {
+ if (!window.confirm('确定删除该项目?')) return
+ setBusyId(id)
try {
- const { blob, filename } = await api.downloadZip(ids)
- triggerBlobDownload(blob, filename)
+ await api.deleteProject(id)
+ await load()
} catch (err) {
- setError(err instanceof Error ? err.message : '打包下载失败')
+ setError(err instanceof Error ? err.message : '删除失败')
} finally {
- setPacking(false)
+ setBusyId(null)
}
}
- async function onCancel(p: HistoryItem) {
- if (!window.confirm(`取消「${p.title || '未命名作品'}」的生成任务?`)) return
- setBusyId(p.id)
+ async function packSelected() {
+ if (!selectedDownloadable.length) return
+ setPacking(true)
try {
- await api.cancelProject(p.id)
- await load()
+ const { blob, filename } = await api.downloadZip(selectedDownloadable.map((p) => p.id))
+ triggerBlobDownload(blob, filename)
} catch (err) {
- setError(err instanceof Error ? err.message : '取消失败')
+ setError(err instanceof Error ? err.message : '打包失败')
} finally {
- setBusyId(null)
+ setPacking(false)
}
}
- async function onDelete(p: HistoryItem) {
- if (!window.confirm(`删除「${p.title || '未命名作品'}」?此操作不可恢复。`)) return
- setBusyId(p.id)
- try {
- await api.deleteProject(p.id)
- setItems((prev) => prev.filter((x) => x.id !== p.id))
- setSelected((prev) => {
- const next = new Set(prev)
- next.delete(p.id)
- return next
- })
- } catch (err) {
- setError(err instanceof Error ? err.message : '删除失败')
- } finally {
- setBusyId(null)
+ function continueEdit(p: HistoryItem) {
+ if (p.status === 'DRAFT') nav(`/studio/${p.id}/style`)
+ else nav(`/studio/${p.id}`)
+ }
+
+ function pageButtons() {
+ const buttons: (number | '…')[] = []
+ if (pageCount <= 7) {
+ for (let i = 1; i <= pageCount; i++) buttons.push(i)
+ return buttons
}
+ buttons.push(1)
+ if (page > 3) buttons.push('…')
+ for (let i = Math.max(2, page - 1); i <= Math.min(pageCount - 1, page + 1); i++) buttons.push(i)
+ if (page < pageCount - 2) buttons.push('…')
+ buttons.push(pageCount)
+ return buttons
}
return (
- <div className="page">
- <header className="topbar">
- <BrandMark />
- <nav>
- <Link to="/studio">创作</Link>
- <Link to="/history">历史</Link>
- <Link to="/">首页</Link>
- </nav>
- </header>
-
- <section className="section history-section">
- <div className="history-head">
- <div>
- <h2>创作历史</h2>
- <p className="lede">查看草稿、进行中任务与已完成作品,点击可继续编辑。</p>
- </div>
- <div className="history-head-actions">
- {downloadable.length > 0 && (
- <>
- <label className="history-select-all">
- <input
- type="checkbox"
- checked={allDownloadableSelected}
- onChange={toggleAllDownloadable}
- />
- 全选可下载({downloadable.length})
- </label>
- <button
- type="button"
- className="btn primary"
- disabled={packing || selectedDownloadable.length === 0}
- onClick={onBatchDownload}
- >
- {packing
- ? '打包中…'
- : `打包下载${selectedDownloadable.length ? `(${selectedDownloadable.length})` : ''}`}
- </button>
- </>
- )}
- <button type="button" className="btn ghost" onClick={() => load()} disabled={packing}>
- 刷新
- </button>
- </div>
+ <AppShell active="history" wide>
+ <div className="pf-history-head">
+ <div>
+ <h1>我的项目</h1>
+ <p>管理你的 AI 视频创作项目,继续编辑或发布你的作品。</p>
</div>
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-icon" onClick={() => nav('/studio/new')}>
+ <IconPlus size={16} />
+ 新建项目
+ </button>
+ </div>
- {loading && <p className="muted">加载中…</p>}
- {error && <p className="error">{error}</p>}
+ <div className="pf-stats">
+ <StatCard
+ label="总作品数"
+ value={stats.total}
+ trend="—"
+ icon={<IconClapper size={18} />}
+ />
+ <StatCard
+ label="生成中"
+ value={stats.generating}
+ trend={stats.generating ? '正在生成中' : '暂无任务'}
+ icon={<IconRefresh size={18} />}
+ />
+ <StatCard
+ label="已完成"
+ value={stats.done}
+ trend="—"
+ icon={<IconSend size={18} />}
+ />
+ <StatCard
+ label="本月时长"
+ value="—"
+ trend="额度统计即将推出"
+ icon={<IconClock size={18} />}
+ />
+ </div>
- {!loading && items.length === 0 && (
- <div className="empty-state">
- <p>还没有创作记录。</p>
- <button type="button" className="btn primary" onClick={() => nav('/studio')}>
- 去创作
+ <div className="pf-history-layout">
+ <section className="pf-history-main">
+ <div className="pf-history-filters">
+ <PillTabs
+ items={['全部', '草稿', '生成中', '已完成', '已发布']}
+ value={tab}
+ onChange={setTab}
+ ariaLabel="项目状态"
+ />
+ <div className="pf-history-filter-right">
+ <button type="button" className="pf-type-select" disabled title="即将推出">
+ 全部类型
+ </button>
+ <label className="pf-search-field">
+ <IconSearch size={15} />
+ <input
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ placeholder="搜索项目名称"
+ />
+ </label>
+ </div>
+ </div>
+
+ <div className="pf-history-batch">
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={!selectedDownloadable.length || packing}
+ onClick={packSelected}
+ >
+ <IconDownload size={15} />
+ {packing ? '打包中…' : `打包下载 (${selectedDownloadable.length})`}
</button>
+ <span>可选中已完成项目批量下载</span>
</div>
- )}
- <div className="history-list">
- {items.map((p) => {
- const tone = statusTone(p.status)
- const label = STATUS_LABEL[p.status] || p.status
- const busy = busyId === p.id
- const downloadableItem = canDownload(p)
- const checked = selected.has(p.id)
- return (
- <article
- key={p.id}
- className={`history-card tone-${tone}${checked ? ' selected' : ''}`}
- >
- <div className="history-select">
- <input
- type="checkbox"
- checked={checked}
- disabled={!downloadableItem || packing}
- title={downloadableItem ? '勾选以打包下载' : '未完成,无法下载'}
- onChange={(e) => toggleOne(p.id, e.target.checked)}
- aria-label={`选择 ${p.title || p.id}`}
- />
- </div>
- <button
- type="button"
- className="history-cover clickable"
- onClick={() => nav(`/studio?project=${p.id}`)}
- >
- {p.cover_url ? (
- <img src={api.assetUrl(p.cover_url)} alt="" />
- ) : (
- <div className="placeholder">#{p.id}</div>
- )}
- </button>
- <div className="history-body">
- <header>
- <h3>
- <button
- type="button"
- className="linkish title-btn"
- onClick={() => nav(`/studio?project=${p.id}`)}
- >
- {p.title || '未命名作品'}
- </button>
- </h3>
- <span className={`status-pill tone-${tone}`}>{label}</span>
- </header>
- <p className="muted small">
- 模板 {p.template_id}
- {p.pipeline_mode === 'image_text' ? ' · 图文模式' : ' · 完整成片'}
- {' · '}
- {new Date(p.created_at).toLocaleString()}
- </p>
- <div className="progress-bar" aria-label={`进度 ${p.progress}%`}>
- <i style={{ width: `${Math.max(0, Math.min(100, p.progress))}%` }} />
- </div>
- <div className="history-meta">
- <span>进度 {p.progress}%</span>
- {p.error_msg && <span className="error small truncate">{p.error_msg}</span>}
+ {error ? <p className="pf-error">{error}</p> : null}
+ {loading ? <p className="pf-muted">加载中…</p> : null}
+ {!loading && filtered.length === 0 ? (
+ <div className="pf-history-empty">暂无项目,点击「新建项目」开始创作</div>
+ ) : null}
+
+ <div className="pf-project-list">
+ {pageItems.map((p) => {
+ const badge = statusBadgeClass(p.status)
+ const ratio =
+ p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9')
+ const tplName = templates[p.template_id] || p.template_id
+ const when = new Date(p.updated_at || p.created_at).toLocaleString()
+ return (
+ <article key={p.id} className="pf-project-card">
+ <label className="pf-project-check">
+ <input
+ type="checkbox"
+ checked={selected.has(p.id)}
+ disabled={!canDownload(p)}
+ onChange={() => toggle(p.id)}
+ />
+ </label>
+ <button
+ type="button"
+ className="pf-project-thumb"
+ onClick={() => continueEdit(p)}
+ >
+ {p.cover_url ? (
+ <img src={api.assetUrl(p.cover_url, p.updated_at)} alt="" />
+ ) : (
+ <div className="ph">无封面</div>
+ )}
+ {isRunning(p.status) ? (
+ <span className="pf-thumb-progress">{p.progress}%</span>
+ ) : null}
+ </button>
+ <div className="pf-project-info">
+ <h3>{p.title}</h3>
+ <div className="pf-project-meta">
+ <span className={`pf-badge ${badge}`}>
+ {STATUS_CN[p.status] || p.status}
+ </span>
+ <span className="pf-muted">
+ 模板 {tplName} · {when}
+ </span>
+ </div>
+ {isRunning(p.status) ? (
+ <div className="pf-inline-meter">
+ <i style={{ width: `${Math.min(100, p.progress)}%` }} />
+ </div>
+ ) : null}
+ {p.error_msg ? <p className="pf-error pf-project-err">{p.error_msg}</p> : null}
</div>
- <div className="history-actions">
+ <div className="pf-project-ratio">{ratio}</div>
+ <div className="pf-project-actions">
+ <button type="button" className="pf-btn-text" onClick={() => continueEdit(p)}>
+ <IconEdit size={14} />
+ 继续编辑
+ </button>
<button
type="button"
- className="btn ghost"
- onClick={() => nav(`/studio?project=${p.id}`)}
+ className="pf-btn-text"
+ disabled={!p.final_video_url}
+ onClick={() =>
+ p.final_video_url &&
+ setPreview({
+ url: api.assetUrl(p.final_video_url, p.updated_at),
+ title: p.title,
+ })
+ }
>
- 打开
+ <IconEye size={14} />
+ 预览
+ </button>
+ <button type="button" className="pf-btn-text" disabled title="即将推出">
+ <IconCopy size={14} />
+ 复制
</button>
- {p.status === 'DONE' && p.final_video_url && (
- <button
- type="button"
- className="btn primary"
- onClick={() =>
- setPreview({
- url: p.final_video_url!,
- title: p.title || '成片',
- bust: p.updated_at,
- })
- }
- >
- 播放
- </button>
- )}
- {isRunning(p.status) && (
- <button
- type="button"
- className="btn ghost"
- disabled={busy}
- onClick={() => onCancel(p)}
- >
- 取消任务
- </button>
- )}
<button
type="button"
- className="btn danger"
- disabled={busy}
- onClick={() => onDelete(p)}
+ className="pf-icon-btn danger"
+ disabled={busyId === p.id}
+ title="删除"
+ onClick={() => remove(p.id)}
>
- 删除
+ <IconTrash size={16} />
</button>
</div>
- </div>
- </article>
- )
- })}
- </div>
- </section>
+ </article>
+ )
+ })}
+ </div>
+
+ {filtered.length > 0 ? (
+ <div className="pf-pagination">
+ <button
+ type="button"
+ className="pf-page-btn"
+ disabled={page <= 1}
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
+ >
+ ‹
+ </button>
+ {pageButtons().map((b, i) =>
+ b === '…' ? (
+ <span key={`e-${i}`} className="pf-page-ellipsis">
+ …
+ </span>
+ ) : (
+ <button
+ key={b}
+ type="button"
+ className={page === b ? 'pf-page-btn active' : 'pf-page-btn'}
+ onClick={() => setPage(b)}
+ >
+ {b}
+ </button>
+ ),
+ )}
+ <button
+ type="button"
+ className="pf-page-btn"
+ disabled={page >= pageCount}
+ onClick={() => setPage((p) => Math.min(pageCount, p + 1))}
+ >
+ ›
+ </button>
+ </div>
+ ) : null}
+ </section>
- {preview && (
- <div className="modal-backdrop" role="presentation" onClick={() => setPreview(null)}>
- <div
- className={`modal preview-modal${preview.url.includes('/generated/') ? ' portrait' : ''}`}
- role="dialog"
- onClick={(e) => e.stopPropagation()}
- >
- <header className="preview-head">
- <h3>{preview.title}</h3>
- <button type="button" className="btn ghost" onClick={() => setPreview(null)}>
+ <aside className="pf-history-side">
+ <div className="pf-side-box">
+ <h3>快速发布</h3>
+ <p className="pf-side-desc">将作品发布到平台或分享给更多人</p>
+ <div className="pf-quick-grid">
+ <button type="button" className="pf-quick-tile" disabled>
+ <IconLink size={20} />
+ <span>复制链接</span>
+ <ComingSoon />
+ </button>
+ <button type="button" className="pf-quick-tile" disabled>
+ <IconQr size={20} />
+ <span>二维码</span>
+ <ComingSoon />
+ </button>
+ <button type="button" className="pf-quick-tile" disabled>
+ <IconCode size={20} />
+ <span>嵌入网页</span>
+ <ComingSoon />
+ </button>
+ </div>
+ </div>
+
+ <div className="pf-side-box">
+ <h3>平台导出</h3>
+ <p className="pf-side-desc">一键导出到各大平台</p>
+ <ul className="pf-platform-list">
+ {PLATFORMS.map((p) => (
+ <li key={p.name}>
+ <span className="pf-platform-mark">{p.mark}</span>
+ <span className="pf-platform-name">{p.name}</span>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 导出
+ </button>
+ </li>
+ ))}
+ </ul>
+ <button type="button" className="pf-link pf-side-foot" disabled>
+ 查看发布记录 → <ComingSoon />
+ </button>
+ </div>
+
+ <div className="pf-side-box">
+ <h3>本月使用情况</h3>
+ <div className="pf-usage-row">
+ <span>时长额度</span>
+ <span className="pf-muted">— / 30h</span>
+ </div>
+ <div className="pf-meter">
+ <i style={{ width: '0%' }} />
+ </div>
+ <div className="pf-usage-row">
+ <span>生成次数</span>
+ <span className="pf-muted">
+ {stats.total} / 200
+ </span>
+ </div>
+ <div className="pf-meter">
+ <i style={{ width: `${Math.min(100, stats.total * 2)}%` }} />
+ </div>
+ <p className="pf-muted" style={{ fontSize: '0.75rem', margin: '0.5rem 0 0' }}>
+ 额度统计即将推出
+ </p>
+ </div>
+ </aside>
+ </div>
+
+ {preview ? (
+ <div className="modal-backdrop" onClick={() => setPreview(null)}>
+ <div className="modal preview-modal" onClick={(e) => e.stopPropagation()}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <h3 style={{ margin: 0 }}>{preview.title}</h3>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => setPreview(null)}>
关闭
</button>
- </header>
- <video
- key={`${preview.url}:${preview.bust || ''}`}
- className="preview-media"
- src={api.assetUrl(preview.url, preview.bust)}
- controls
- autoPlay
- playsInline
- />
+ </div>
+ <video className="preview-media" src={preview.url} controls autoPlay />
</div>
</div>
- )}
- </div>
+ ) : null}
+ </AppShell>
)
}
diff --git a/frontend/src/pages/HomePage.tsx b/frontend/src/pages/HomePage.tsx
index 5064dd5..fa1ff45 100644
--- a/frontend/src/pages/HomePage.tsx
+++ b/frontend/src/pages/HomePage.tsx
@@ -1,34 +1,20 @@
import { useEffect, useMemo, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api } from '../api'
-import type { Template, User, Work } from '../api'
-import BrandMark from '../components/BrandMark'
-
-/** Primary filter chips; 科普 first for PRINTFILM. */
-const CATEGORY_ORDER = [
- '科普',
- '纪录片',
- '写实感',
- '真人感',
- '电影感',
- '儿童',
- '动漫',
- '国风',
- '科幻',
- '奇幻',
- '悬疑',
- '商业',
- '复古',
- '图文',
-]
+import type { Template, Work } from '../api'
+import AppShell from '../components/layout/AppShell'
+import PillTabs from '../components/ui/PillTabs'
+import { CATEGORY_ORDER, HOME_CATEGORY_LABELS } from '../lib/categories'
export default function HomePage() {
const nav = useNavigate()
- const [user, setUser] = useState<User | null>(null)
const [templates, setTemplates] = useState<Template[]>([])
const [works, setWorks] = useState<Work[]>([])
const [error, setError] = useState('')
const [category, setCategory] = useState('全部')
+ const [showAllWorks, setShowAllWorks] = useState(false)
+ const [preview, setPreview] = useState<Work | null>(null)
+ const loggedIn = Boolean(localStorage.getItem('token'))
useEffect(() => {
api
@@ -36,12 +22,9 @@ export default function HomePage() {
.then(setTemplates)
.catch((e) => setError(String(e.message || e)))
api.works().then(setWorks).catch(() => undefined)
- if (localStorage.getItem('token')) {
- api.me().then(setUser).catch(() => localStorage.removeItem('token'))
- }
}, [])
- const categories = useMemo(() => {
+ const categoryKeys = useMemo(() => {
const found = new Set<string>()
for (const t of templates) {
for (const c of t.category || []) {
@@ -51,131 +34,120 @@ export default function HomePage() {
return ['全部', ...CATEGORY_ORDER.filter((c) => found.has(c))]
}, [templates])
+ const categoryLabels = categoryKeys.map((k) => HOME_CATEGORY_LABELS[k] || k)
+ const labelToKey = useMemo(() => {
+ const m = new Map<string, string>()
+ for (const k of categoryKeys) m.set(HOME_CATEGORY_LABELS[k] || k, k)
+ return m
+ }, [categoryKeys])
+
const filtered = useMemo(() => {
- if (category === '全部') return templates
- return templates.filter((t) => (t.category || []).includes(category))
+ if (category === '全部') return templates.slice(0, 6)
+ return templates.filter((t) => (t.category || []).includes(category)).slice(0, 6)
}, [templates, category])
- function logout() {
- localStorage.removeItem('token')
- setUser(null)
- }
-
function openTemplate(t: Template) {
- if (!user) {
+ if (!loggedIn) {
nav('/auth')
return
}
- const mode = t.seedream_config?.pipeline_mode
- const q =
- mode === 'image_text' || (!mode && t.default_ratio === '9:16')
- ? '&mode=image_text'
- : ''
- nav(`/studio?template=${t.id}${q}`)
+ nav(`/studio/new?template=${t.id}`)
}
- return (
- <div className="site">
- <header className="site-nav">
- <BrandMark />
- <nav>
- <a href="#how">流程</a>
- <a href="#templates">风格</a>
- <Link to="/studio">创作</Link>
- {user ? <Link to="/history">历史</Link> : null}
- {user ? (
- <button type="button" className="linkish" onClick={logout}>
- {user.nickname} · 退出
- </button>
- ) : (
- <Link to="/auth" className="nav-cta">
- 登录
- </Link>
- )}
- </nav>
- </header>
+ function goCreate() {
+ nav(loggedIn ? '/studio/new' : '/auth')
+ }
- <section className="site-hero" aria-label="PRINTFILM">
- <div className="site-hero-media" aria-hidden="true">
- <img src="/hero.jpg?v=light" alt="" className="site-hero-img" />
- <div className="site-hero-shade" />
- </div>
- <div className="site-hero-copy">
- <img src="/logo.svg" alt="" className="site-hero-logo" width={56} height={56} />
- <h1 className="site-brand">PRINTFILM</h1>
- <p className="site-headline">把知识拍成片</p>
- <p className="site-support">
- 科普视频平台:输入主题与风格,自动生成分镜、画面、旁白与成片。
+ const heroCover =
+ templates[0]?.preview_cover
+ ? api.assetUrl(templates[0].preview_cover)
+ : '/hero.jpg?v=light'
+
+ return (
+ <AppShell active="home">
+ <section className="pf-home-hero">
+ <div>
+ <h1>
+ 把知识拍成片
+ <br />
+ 让每个想法,都被看见
+ </h1>
+ <p className="lede">
+ PRINTFILM 是你的 AI 知识视频创作伙伴。从主题输入到成片发布,只需 3 步,轻松完成短片创作。
</p>
- <div className="cta-row">
- <button
- className="btn primary accent"
- type="button"
- onClick={() => nav(user ? '/studio' : '/auth')}
- >
+ <div className="pf-home-steps">
+ <div className="pf-home-step">
+ <strong>1 输入主题</strong>
+ <span>输入主题或粘贴文案,快速开始</span>
+ </div>
+ <div className="pf-home-step">
+ <strong>2 智能生成</strong>
+ <span>生成大纲、分镜与画面</span>
+ </div>
+ <div className="pf-home-step">
+ <strong>3 预览发布</strong>
+ <span>预览调整后导出成片</span>
+ </div>
+ </div>
+ <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
+ <button type="button" className="pf-btn pf-btn-lime" onClick={goCreate}>
开始创作
</button>
- <a className="btn ghost" href="#templates">
- 浏览风格
+ <a className="pf-btn pf-btn-ghost" href="#templates">
+ 探索模板
</a>
</div>
</div>
+ <div className="pf-hero-visual">
+ <div className="pf-hero-player">
+ <img src={heroCover} alt="" />
+ <span className="pf-hero-badge">AI 生成短片</span>
+ </div>
+ <aside className="pf-hero-float">
+ <ul>
+ <li>
+ <span className="pf-check">✓</span> 主题解析
+ </li>
+ <li>
+ <span className="pf-check">✓</span> 分镜生成
+ </li>
+ <li>
+ <span className="pf-check">✓</span> 配音配乐
+ </li>
+ <li>
+ <span className="pf-check">✓</span> 输出成片
+ </li>
+ </ul>
+ </aside>
+ </div>
</section>
- <section id="how" className="site-section site-how">
- <h2>三步成片</h2>
- <p className="lede">从主题到成片,一条链路完成科普短视频。</p>
- <ol className="how-steps">
- <li>
- <span className="how-num">01</span>
- <strong>选定风格</strong>
- <span>科普、纪录、写实等模板锁定画面气质</span>
- </li>
- <li>
- <span className="how-num">02</span>
- <strong>写下主题</strong>
- <span>一句话讲清你要普及的知识点</span>
- </li>
- <li>
- <span className="how-num">03</span>
- <strong>生成成片</strong>
- <span>分镜、配图、旁白与剪辑自动完成</span>
- </li>
- </ol>
- </section>
-
- {error && <p className="error pad site-section">{error}</p>}
+ {error ? <p className="pf-error">{error}</p> : null}
- <section id="templates" className="site-section">
- <h2>风格模板</h2>
- <p className="lede">为科普内容挑选合适的画面语言。</p>
- <div className="category-filters" role="tablist" aria-label="模板分类">
- {categories.map((c) => (
- <button
- key={c}
- type="button"
- role="tab"
- aria-selected={category === c}
- className={category === c ? 'cat-chip active' : 'cat-chip'}
- onClick={() => setCategory(c)}
- >
- {c}
- </button>
- ))}
+ <section id="templates">
+ <div className="pf-section-head">
+ <div>
+ <h2>从模板开始</h2>
+ <p>选择合适的模板,快速开启你的创作</p>
+ </div>
+ <Link to="/templates" className="pf-link">
+ 查看全部模板 →
+ </Link>
</div>
- <div className="template-grid">
+ <PillTabs
+ items={categoryLabels}
+ value={HOME_CATEGORY_LABELS[category] || category}
+ onChange={(label) => setCategory(labelToKey.get(label) || '全部')}
+ ariaLabel="模板分类"
+ />
+ <div className="pf-template-grid" style={{ marginTop: '1rem' }}>
{filtered.map((t) => (
- <button
- key={t.id}
- type="button"
- className="template-card"
- onClick={() => openTemplate(t)}
- >
+ <button key={t.id} type="button" className="pf-template-card" onClick={() => openTemplate(t)}>
<img src={api.assetUrl(t.preview_cover)} alt="" />
- <div>
+ <div className="body">
<h3>{t.name}</h3>
<p>{t.description}</p>
- <div className="tags">
+ <div className="pf-tags">
{t.category.map((c) => (
<span key={c}>{c}</span>
))}
@@ -184,44 +156,84 @@ export default function HomePage() {
</button>
))}
</div>
- {filtered.length === 0 ? (
- <p className="muted" style={{ marginTop: '1rem' }}>
- 该分类暂无模板。
- </p>
- ) : null}
</section>
- {works.length > 0 ? (
- <section className="site-section">
- <h2>公开作品</h2>
- <p className="lede">社区里已经发布的科普短片。</p>
- <div className="works-row">
- {works.map((w) => (
- <article key={w.id} className="work-item">
- <img src={api.assetUrl(w.cover_url)} alt="" />
+ <section id="works" style={{ marginTop: '3rem' }}>
+ <div className="pf-section-head">
+ <div>
+ <h2>精选公开作品</h2>
+ <p>来自创作者社区的优质作品</p>
+ </div>
+ {works.length > 4 ? (
+ <button
+ type="button"
+ className="pf-link"
+ onClick={() => setShowAllWorks((v) => !v)}
+ >
+ {showAllWorks ? '收起 ↑' : '查看全部作品 →'}
+ </button>
+ ) : null}
+ </div>
+ {works.length === 0 ? (
+ <p className="pf-muted">还没有发布作品,去创作一条吧。</p>
+ ) : (
+ <div className="pf-works-grid">
+ {(showAllWorks ? works : works.slice(0, 4)).map((w) => (
+ <button
+ key={w.id}
+ type="button"
+ className="pf-work-card"
+ onClick={() => setPreview(w)}
+ >
+ <span className="pf-work-thumb">
+ <img src={api.assetUrl(w.cover_url) || api.assetUrl(w.video_url)} alt="" />
+ <span className="pf-work-play" aria-hidden>
+ ▶
+ </span>
+ </span>
<h3>{w.title}</h3>
- </article>
+ <p className="pf-muted" style={{ margin: 0, fontSize: '0.8rem' }}>
+ 公开作品 · 点击播放
+ </p>
+ </button>
))}
</div>
- </section>
- ) : null}
+ )}
+ </section>
- <section className="site-cta-band">
- <h2>下一支科普短片,从这里开始</h2>
- <p>主题进,成片出。PRINTFILM 帮你把知识印进每一帧。</p>
- <button
- className="btn primary accent"
- type="button"
- onClick={() => nav(user ? '/studio' : '/auth')}
- >
- 免费开始
+ <section className="pf-cta-band">
+ <div>
+ <h2>准备好创作你的短片了吗?</h2>
+ <p>加入 PRINTFILM,开启你的 AI 创作之旅</p>
+ </div>
+ <button type="button" className="pf-btn pf-btn-lime" onClick={goCreate}>
+ 立即开始创作 →
</button>
</section>
- <footer className="site-footer">
- <BrandMark />
- <p>PRINTFILM · 科普视频平台</p>
- </footer>
- </div>
+ {preview ? (
+ <div className="modal-backdrop" onClick={() => setPreview(null)}>
+ <div className="modal preview-modal" onClick={(e) => e.stopPropagation()}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '0.75rem' }}>
+ <h3 style={{ margin: 0 }}>{preview.title}</h3>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => setPreview(null)}>
+ 关闭
+ </button>
+ </div>
+ <video
+ className="preview-media"
+ src={api.assetUrl(preview.video_url)}
+ poster={preview.cover_url ? api.assetUrl(preview.cover_url) : undefined}
+ controls
+ autoPlay
+ playsInline
+ />
+ <p className="pf-muted" style={{ margin: 0, fontSize: '0.85rem' }}>
+ 发布于 {new Date(preview.published_at).toLocaleString()}
+ </p>
+ </div>
+ </div>
+ ) : null}
+ </AppShell>
)
}
diff --git a/frontend/src/pages/PricingPage.tsx b/frontend/src/pages/PricingPage.tsx
new file mode 100644
index 0000000..89e59c2
--- /dev/null
+++ b/frontend/src/pages/PricingPage.tsx
@@ -0,0 +1,26 @@
+import AppShell from '../components/layout/AppShell'
+import ComingSoon from '../components/ui/ComingSoon'
+
+export default function PricingPage() {
+ return (
+ <AppShell active="pricing">
+ <div className="pf-pricing">
+ <h1 style={{ margin: 0, fontSize: '2rem' }}>定价</h1>
+ <p className="pf-muted">套餐与额度体系规划中,当前创作额度不限。</p>
+ <div className="pf-card">
+ <ComingSoon label="定价方案即将推出" />
+ <h2 style={{ margin: '1rem 0 0.5rem' }}>Free · 体验版</h2>
+ <p className="pf-muted">免费使用基础模板与预览分辨率生成。</p>
+ <ul style={{ textAlign: 'left', color: 'var(--pf-muted)', lineHeight: 1.8 }}>
+ <li>知识科普模板</li>
+ <li>分镜 / 配图 / 配音流水线</li>
+ <li>成片下载(预览画质)</li>
+ <li>
+ 高清导出、团队空间、平台一键分发 <ComingSoon />
+ </li>
+ </ul>
+ </div>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/StudioPage.tsx b/frontend/src/pages/StudioPage.tsx
index a67af23..6399a3d 100644
--- a/frontend/src/pages/StudioPage.tsx
+++ b/frontend/src/pages/StudioPage.tsx
@@ -1,943 +1,19 @@
-import { useEffect, useMemo, useState } from 'react'
-import type { FormEvent } from 'react'
-import { Link, useNavigate, useSearchParams } from 'react-router-dom'
-import { api, defaultsFromTemplate } from '../api'
-import type { PipelineMode, Project, Shot, Template, VoicePreset } from '../api'
-import BrandMark from '../components/BrandMark'
-import { scenePromptForDisplay } from '../promptDisplay'
-
-const RUNNING = new Set([
- 'SCRIPTING',
- 'IMAGING',
- 'VIDEOING',
- 'AUDIOING',
- 'COMPOSING',
- 'AUDITING',
-])
-
-const RESUME_COMPOSE = new Set(['SCRIPT_READY', 'IMAGE_READY', 'VIDEO_READY'])
-
-const STATUS_CN: Record<string, string> = {
- DRAFT: '草稿',
- SCRIPTING: '拆分镜中',
- SCRIPT_READY: '分镜完成',
- IMAGING: '出图+配音并行中',
- IMAGE_READY: '分镜图完成',
- VIDEOING: '生成 AI 视频(并行)',
- VIDEO_READY: '镜头视频完成',
- AUDIOING: '生成配音',
- COMPOSING: '合成成片',
- AUDITING: '审核中',
- DONE: '已完成',
- FAILED: '失败',
- CANCELLED: '已取消',
-}
-
-const SHOT_STATUS_CN: Record<string, string> = {
- PENDING: '等待中',
- IMAGE_READY: '图已生成',
- VIDEO_READY: '视频已生成',
- AUDIO_READY: '配音已生成',
- FAILED: '失败',
-}
-
-type PreviewState =
- | {
- kind: 'shot'
- shotNo: number
- imageUrl: string | null
- videoUrl: string | null
- audioUrl: string | null
- caption: string
- portrait: boolean
- }
- | { kind: 'final'; url: string; title: string; bust?: string }
- | null
-
-function shotCaption(shot: Shot) {
- if (shot.overlay_title) {
- return `${shot.overlay_title}${
- shot.overlay_subtitle ? ` · ${shot.overlay_subtitle}` : ''
- }${shot.narration ? `|旁白:${shot.narration}` : ''}`
- }
- return shot.narration
-}
-
-function openShotPreview(shot: Shot, portrait: boolean): PreviewState {
- return {
- kind: 'shot',
- shotNo: shot.shot_no,
- imageUrl: shot.image_url,
- videoUrl: shot.video_url,
- audioUrl: shot.audio_url,
- caption: shotCaption(shot),
- portrait,
- }
-}
-
-function durationBounds(isImageText: boolean, tpl?: Template) {
- if (isImageText) return { min: 4, max: 12 }
- return {
- min: tpl?.shot_duration_min ?? 3,
- max: Math.min(tpl?.shot_duration_max ?? 12, 30),
- }
-}
-
-function canResumeCompose(project: Project) {
- if (!project.shots.length) return false
- const mode = project.pipeline_mode || 'full'
- return project.shots.every((s) => {
- if (!(s.image_url && s.audio_url)) return false
- if (mode === 'full' && !s.video_url && project.status === 'VIDEO_READY') return true
- if (mode === 'full') return Boolean(s.video_url) || project.status === 'IMAGE_READY'
- return true
- })
-}
+import { Navigate, useSearchParams } from 'react-router-dom'
+/** Legacy `/studio` entry — redirect to multi-step routes. */
export default function StudioPage() {
const [params] = useSearchParams()
- const nav = useNavigate()
- const [templates, setTemplates] = useState<Template[]>([])
- const [voices, setVoices] = useState<VoicePreset[]>([])
- const [voiceId, setVoiceId] = useState('zh_female_cancan_uranus_bigtts')
- const [stylePrompt, setStylePrompt] = useState('')
- const [characterPrompt, setCharacterPrompt] = useState('')
- const [extraPrompt, setExtraPrompt] = useState('')
- const [templateId, setTemplateId] = useState(params.get('template') || '')
- const [pipelineMode, setPipelineMode] = useState<PipelineMode>(
- (params.get('mode') as PipelineMode) === 'image_text' ? 'image_text' : 'full',
- )
- const [sourceType, setSourceType] = useState<'theme' | 'script'>('theme')
- const [title, setTitle] = useState('未命名作品')
- const [sourceText, setSourceText] = useState(
- '民营航天公司的首枚试验火箭首次发射失败,却成为后来成功的起点。',
- )
- const [project, setProject] = useState<Project | null>(null)
- const [busy, setBusy] = useState(false)
- const [error, setError] = useState('')
- const [editing, setEditing] = useState<Shot | null>(null)
- const [preview, setPreview] = useState<PreviewState>(null)
-
- const selected = useMemo(
- () => templates.find((t) => t.id === templateId),
- [templates, templateId],
- )
- const isImageText = (project?.pipeline_mode || pipelineMode) === 'image_text'
- const bounds = durationBounds(isImageText, selected)
- const running = Boolean(project && RUNNING.has(project.status))
-
- function applyTemplatePresets(tpl: Template) {
- const d = defaultsFromTemplate(tpl)
- setStylePrompt(d.style_prompt)
- setCharacterPrompt(d.character_prompt)
- setExtraPrompt(d.extra_prompt)
- setVoiceId(d.voice_id)
- setPipelineMode(d.pipeline_mode)
- }
-
- function onTemplateChange(id: string) {
- setTemplateId(id)
- const tpl = templates.find((t) => t.id === id)
- if (tpl && !running) applyTemplatePresets(tpl)
- }
-
- useEffect(() => {
- if (!localStorage.getItem('token')) {
- nav('/auth')
- return
- }
- api.me().catch(() => nav('/auth'))
- api.templates().then((list) => {
- setTemplates(list)
- const fromUrl = params.get('template') || ''
- const id = fromUrl || list[0]?.id || ''
- setTemplateId((prev) => prev || id)
- if (!params.get('project')) {
- const tpl = list.find((t) => t.id === (fromUrl || id)) || list[0]
- if (tpl) applyTemplatePresets(tpl)
- }
- })
- api.voices().then(setVoices)
- }, [nav, params])
-
- useEffect(() => {
- const projectId = Number(params.get('project') || '')
- if (!projectId) return
- api
- .getProject(projectId)
- .then((p) => {
- setProject(p)
- setTitle(p.title)
- setTemplateId(p.template_id)
- setSourceType(p.source_type as 'theme' | 'script')
- setSourceText(p.source_text)
- if (p.pipeline_mode) setPipelineMode(p.pipeline_mode)
- if (p.voice_id) setVoiceId(p.voice_id)
- setStylePrompt(p.style_prompt || '')
- setCharacterPrompt(p.character_prompt || '')
- setExtraPrompt(p.extra_prompt || '')
- })
- .catch((err) => setError(err instanceof Error ? err.message : '加载项目失败'))
- }, [params])
-
- // Project loaded before templates: backfill empty prompt fields from template presets
- useEffect(() => {
- if (!project || !templates.length) return
- const tpl = templates.find((t) => t.id === project.template_id)
- if (!tpl) return
- const d = defaultsFromTemplate(tpl)
- setStylePrompt((prev) => prev || d.style_prompt)
- setCharacterPrompt((prev) => prev || d.character_prompt)
- setExtraPrompt((prev) => prev || d.extra_prompt)
- }, [templates, project?.id, project?.template_id])
-
- useEffect(() => {
- if (!project) return
- const id = project.id
- const polling =
- RUNNING.has(project.status) ||
- (!['DONE', 'FAILED', 'CANCELLED', 'DRAFT'].includes(project.status) && project.progress < 100)
- if (!polling) return
- const timer = setInterval(() => {
- api
- .getProject(id)
- .then((next) => {
- setProject((prev) => {
- if (!prev || prev.id !== next.id) return next
- // Avoid useless identity churn when nothing meaningful changed
- if (
- prev.status === next.status &&
- prev.progress === next.progress &&
- prev.final_video_url === next.final_video_url &&
- prev.error_msg === next.error_msg &&
- prev.shots.length === next.shots.length &&
- prev.shots.every((s, i) => {
- const n = next.shots[i]
- return (
- s.id === n.id &&
- s.status === n.status &&
- s.image_url === n.image_url &&
- s.video_url === n.video_url &&
- s.audio_url === n.audio_url &&
- s.version === n.version
- )
- })
- ) {
- return prev
- }
- return next
- })
- })
- .catch(() => undefined)
- }, 1500)
- return () => clearInterval(timer)
- }, [project?.id, project?.status, project?.progress])
-
- async function applyFormToProject(existingId?: number) {
- if (existingId) {
- return api.updateProject(existingId, {
- template_id: templateId,
- title,
- source_type: sourceType,
- source_text: sourceText,
- pipeline_mode: pipelineMode,
- voice_id: voiceId,
- style_prompt: stylePrompt,
- character_prompt: characterPrompt,
- extra_prompt: extraPrompt,
- resolution_mode: 'preview',
- })
- }
- return api.createProject({
- template_id: templateId,
- title,
- source_type: sourceType,
- source_text: sourceText,
- resolution_mode: 'preview',
- pipeline_mode: pipelineMode,
- voice_id: voiceId,
- style_prompt: stylePrompt,
- character_prompt: characterPrompt,
- extra_prompt: extraPrompt,
- })
- }
+ const project = params.get('project')
+ const template = params.get('template')
+ const mode = params.get('mode')
- async function onCreateAndGenerate(e: FormEvent) {
- e.preventDefault()
- if (!templateId) return
- setBusy(true)
- setError('')
- try {
- const reuse =
- project &&
- !RUNNING.has(project.status) &&
- ['DRAFT', 'FAILED', 'CANCELLED', 'DONE', 'SCRIPT_READY', 'IMAGE_READY', 'VIDEO_READY'].includes(
- project.status,
- )
- const target = await applyFormToProject(reuse ? project.id : undefined)
- const started = await api.generate(target.id)
- setProject(started)
- nav(`/studio?project=${started.id}`, { replace: true })
- } catch (err) {
- setError(err instanceof Error ? err.message : '失败')
- } finally {
- setBusy(false)
- }
+ if (project) {
+ return <Navigate to={`/studio/${project}`} replace />
}
- async function onVoiceChange(next: string) {
- setVoiceId(next)
- if (!project || running) return
- try {
- const updated = await api.updateProject(project.id, { voice_id: next })
- setProject(updated)
- } catch (err) {
- setError(err instanceof Error ? err.message : '更新音色失败')
- }
- }
-
- async function regenAudio(shot: Shot) {
- if (!project) return
- setBusy(true)
- try {
- await api.regenAudio(project.id, shot.id)
- setProject(await api.getProject(project.id))
- } catch (err) {
- setError(err instanceof Error ? err.message : '重配音失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function regenAllAudioAndCompose() {
- if (!project) return
- setBusy(true)
- setError('')
- try {
- await api.updateProject(project.id, { voice_id: voiceId })
- const updated = await api.regenAllAudio(project.id)
- setProject(updated)
- } catch (err) {
- setError(err instanceof Error ? err.message : '重配音合成失败')
- try {
- setProject(await api.getProject(project.id))
- } catch {
- /* ignore */
- }
- } finally {
- setBusy(false)
- }
- }
-
- async function composeOnly() {
- if (!project) return
- setBusy(true)
- setError('')
- try {
- const updated = await api.compose(project.id)
- setProject(updated)
- } catch (err) {
- setError(err instanceof Error ? err.message : '合成失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function onModeChange(mode: PipelineMode) {
- setPipelineMode(mode)
- if (!project || running) return
- try {
- const updated = await api.updateProject(project.id, { pipeline_mode: mode })
- setProject(updated)
- } catch (err) {
- setError(err instanceof Error ? err.message : '更新模式失败')
- }
- }
-
- async function saveShot() {
- if (!project || !editing) return
- setBusy(true)
- try {
- const duration = Math.max(bounds.min, Math.min(bounds.max, Number(editing.duration) || bounds.min))
- await api.updateShot(project.id, editing.id, {
- narration: editing.narration,
- overlay_title: editing.overlay_title,
- overlay_subtitle: editing.overlay_subtitle,
- img_prompt: editing.img_prompt,
- video_prompt: editing.video_prompt,
- duration,
- camera: editing.camera,
- })
- setEditing(null)
- setProject(await api.getProject(project.id))
- } catch (err) {
- setError(err instanceof Error ? err.message : '保存失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function regenImage(shot: Shot) {
- if (!project) return
- setBusy(true)
- try {
- await api.regenImage(project.id, shot.id)
- setProject(await api.getProject(project.id))
- } catch (err) {
- setError(err instanceof Error ? err.message : '重绘失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function regenVideo(shot: Shot) {
- if (!project) return
- setBusy(true)
- try {
- await api.regenVideo(project.id, shot.id)
- setProject(await api.getProject(project.id))
- } catch (err) {
- setError(err instanceof Error ? err.message : '重生视频失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function publish() {
- if (!project) return
- setBusy(true)
- try {
- await api.publish(project.id)
- nav('/')
- } catch (err) {
- setError(err instanceof Error ? err.message : '发布失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function continueGenerate() {
- if (!project) return
- setBusy(true)
- setError('')
- try {
- const started = await api.generate(project.id)
- setProject(started)
- } catch (err) {
- setError(err instanceof Error ? err.message : '继续生成失败')
- try {
- setProject(await api.getProject(project.id))
- } catch {
- /* ignore */
- }
- } finally {
- setBusy(false)
- }
- }
-
- async function cancelTask() {
- if (!project) return
- if (!window.confirm('确定取消当前生成任务?')) return
- setBusy(true)
- try {
- const updated = await api.cancelProject(project.id)
- setProject(updated)
- } catch (err) {
- setError(err instanceof Error ? err.message : '取消失败')
- } finally {
- setBusy(false)
- }
- }
-
- async function deleteCurrent() {
- if (!project) return
- if (!window.confirm('确定删除该创作?素材与成片将一并清除。')) return
- setBusy(true)
- try {
- await api.deleteProject(project.id)
- setProject(null)
- nav('/history')
- } catch (err) {
- setError(err instanceof Error ? err.message : '删除失败')
- } finally {
- setBusy(false)
- }
- }
-
- return (
- <div className="page studio">
- <header className="topbar">
- <BrandMark />
- <nav>
- <span className="quota">额度不限</span>
- <Link to="/history">历史</Link>
- <Link to="/">首页</Link>
- </nav>
- </header>
-
- <div className="studio-layout">
- <aside className="studio-input">
- <h1>创作工作台</h1>
- <form className="stack" onSubmit={onCreateAndGenerate}>
- <label>
- 模板
- <select
- value={templateId}
- onChange={(e) => onTemplateChange(e.target.value)}
- required
- disabled={running}
- >
- {(() => {
- const groups = new Map<string, Template[]>()
- for (const t of templates) {
- const key = (t.category && t.category[0]) || '其他'
- if (!groups.has(key)) groups.set(key, [])
- groups.get(key)!.push(t)
- }
- return [...groups.entries()].map(([cat, list]) => (
- <optgroup key={cat} label={cat}>
- {list.map((t) => (
- <option key={t.id} value={t.id}>
- {t.name}
- {t.category?.length > 1 ? ` · ${t.category.slice(1).join('/')}` : ''}
- </option>
- ))}
- </optgroup>
- ))
- })()}
- </select>
- </label>
- <label>
- 生成模式
- <select
- value={pipelineMode}
- onChange={(e) => onModeChange(e.target.value as PipelineMode)}
- disabled={running}
- >
- <option value="full">完整成片(图→AI视频→配音)</option>
- <option value="image_text">图文短视频(出图+叠字+配音)</option>
- </select>
- </label>
- <label>
- 配音音色
- <select
- value={voiceId}
- onChange={(e) => onVoiceChange(e.target.value)}
- disabled={running}
- >
- {voices.map((v) => (
- <option key={v.id} value={v.id}>
- {v.label}
- </option>
- ))}
- </select>
- </label>
- <label>
- 画面风格
- <textarea
- rows={2}
- value={stylePrompt}
- onChange={(e) => setStylePrompt(e.target.value)}
- disabled={running}
- placeholder="随模板自动填入,可再改"
- />
- </label>
- <label>
- 人物设定
- <textarea
- rows={2}
- value={characterPrompt}
- onChange={(e) => setCharacterPrompt(e.target.value)}
- disabled={running}
- placeholder="随模板自动填入,可再改"
- />
- </label>
- <label>
- 其他画面要求
- <textarea
- rows={2}
- value={extraPrompt}
- onChange={(e) => setExtraPrompt(e.target.value)}
- disabled={running}
- placeholder="随模板自动填入,可再改"
- />
- </label>
- {project && !running && (
- <p className="muted small">可随时改模式/文案/音色/风格,再点下方按钮重新生成。</p>
- )}
- <label>
- 标题
- <input value={title} onChange={(e) => setTitle(e.target.value)} />
- </label>
- <label>
- 输入方式
- <select
- value={sourceType}
- onChange={(e) => setSourceType(e.target.value as 'theme' | 'script')}
- >
- <option value="theme">一句话主题</option>
- <option value="script">粘贴完整文案</option>
- </select>
- </label>
- <label>
- {sourceType === 'theme' ? '主题' : '文案'}
- <textarea
- rows={8}
- value={sourceText}
- onChange={(e) => setSourceText(e.target.value)}
- required
- />
- </label>
- {error && <p className="error">{error}</p>}
- <button className="btn primary" disabled={busy || running}>
- {busy
- ? '处理中…'
- : project &&
- (project.status === 'FAILED' || project.status === 'CANCELLED')
- ? '继续生成'
- : project && RESUME_COMPOSE.has(project.status) && canResumeCompose(project)
- ? '继续合成短视频'
- : project && !running
- ? '按当前设置重新生成'
- : pipelineMode === 'image_text'
- ? '生成图文短视频'
- : '生成分镜成片'}
- </button>
- </form>
- </aside>
-
- <main className="studio-main">
- {!project ? (
- <div className="empty-state">
- <p>选择模板并提交后,这里会展开分镜时间轴与进度。</p>
- </div>
- ) : (
- <>
- <div className="progress-head">
- <div>
- <h2>{project.title}</h2>
- <p className="muted">
- {isImageText ? '图文模式' : '完整成片'} ·{' '}
- {STATUS_CN[project.status] || project.status}
- {project.status === 'VIDEOING' && isImageText
- ? '(异常:图文模式不应生成 AI 视频)'
- : ''}{' '}
- · 进度 {project.progress}%
- {project.error_msg ? ` · ${project.error_msg}` : ''}
- </p>
- </div>
- <div className="progress-bar" aria-hidden>
- <i style={{ width: `${project.progress}%` }} />
- </div>
- <div className="cta-row">
- {running && (
- <button type="button" className="btn ghost" onClick={cancelTask} disabled={busy}>
- 取消任务
- </button>
- )}
- {!running &&
- project.shots.length > 0 &&
- (project.status === 'FAILED' ||
- project.status === 'CANCELLED' ||
- (project.progress > 0 &&
- project.progress < 100 &&
- project.status !== 'DONE' &&
- project.status !== 'DRAFT')) && (
- <button
- type="button"
- className="btn primary"
- onClick={continueGenerate}
- disabled={busy}
- >
- {busy ? '处理中…' : '继续生成'}
- </button>
- )}
- {project.shots.some((s) => s.image_url) && !running && (
- <>
- <button
- type="button"
- className="btn ghost"
- disabled={busy}
- onClick={regenAllAudioAndCompose}
- >
- 重配音并合成
- </button>
- <button
- type="button"
- className="btn ghost"
- disabled={busy}
- onClick={composeOnly}
- >
- 仅重新合成
- </button>
- </>
- )}
- {project.status === 'DONE' && project.final_video_url && (
- <>
- <button
- type="button"
- className="btn primary"
- onClick={() =>
- setPreview({
- kind: 'final',
- url: project.final_video_url!,
- title: project.title,
- bust: project.updated_at,
- })
- }
- >
- 播放成片
- </button>
- <a
- className="btn ghost"
- href={api.assetUrl(project.final_video_url)}
- target="_blank"
- rel="noreferrer"
- >
- 打开链接
- </a>
- <button type="button" className="btn ghost" onClick={publish} disabled={busy}>
- 发布
- </button>
- </>
- )}
- <button type="button" className="btn danger" onClick={deleteCurrent} disabled={busy}>
- 删除创作
- </button>
- </div>
- </div>
-
- <div className="shot-list">
- {project.shots
- .slice()
- .sort((a, b) => a.shot_no - b.shot_no)
- .map((shot) => (
- <article key={shot.id} className="shot-card">
- <button
- type="button"
- className={`shot-thumb clickable${isImageText ? ' portrait' : ''}`}
- onClick={() => setPreview(openShotPreview(shot, isImageText || !shot.video_url))}
- disabled={!shot.image_url && !shot.video_url}
- title="点击预览"
- >
- {shot.image_url ? (
- <img src={api.assetUrl(shot.image_url)} alt="" />
- ) : (
- <div className="placeholder">Shot {shot.shot_no}</div>
- )}
- {(shot.video_url || (isImageText && shot.image_url)) && (
- <span className="play-badge">预览</span>
- )}
- </button>
- <div className="shot-body">
- <header>
- <strong>#{shot.shot_no}</strong>
- <span>
- {shot.duration}s · {SHOT_STATUS_CN[shot.status] || shot.status}
- </span>
- </header>
- {isImageText && shot.overlay_title ? (
- <p>
- <strong>{shot.overlay_title}</strong>
- <br />
- <span className="muted">
- {shot.overlay_subtitle || shot.narration}
- </span>
- {shot.overlay_subtitle && shot.narration ? (
- <>
- <br />
- <span className="small">旁白:{shot.narration}</span>
- </>
- ) : null}
- </p>
- ) : (
- <p>{shot.narration}</p>
- )}
- <div className="shot-actions">
- <button type="button" onClick={() => setEditing(shot)}>
- 编辑
- </button>
- <button
- type="button"
- disabled={busy || running}
- onClick={() => regenImage(shot)}
- >
- 重绘
- </button>
- <button
- type="button"
- disabled={busy || running || !shot.narration}
- onClick={() => regenAudio(shot)}
- >
- 重配音
- </button>
- {!isImageText && (
- <button
- type="button"
- disabled={busy || running || !shot.image_url}
- onClick={() => regenVideo(shot)}
- >
- 重生视频
- </button>
- )}
- {(shot.video_url || shot.image_url) && (
- <button type="button" onClick={() => setPreview(openShotPreview(shot, isImageText || !shot.video_url))}>
- 查看
- </button>
- )}
- </div>
- </div>
- </article>
- ))}
- </div>
- </>
- )}
- </main>
- </div>
-
- {editing && (
- <div className="modal-backdrop" role="presentation" onClick={() => setEditing(null)}>
- <div className="modal" role="dialog" onClick={(e) => e.stopPropagation()}>
- <h3>编辑分镜 #{editing.shot_no}</h3>
- {isImageText && (
- <>
- <label>
- 顶部大标题(叠字)
- <input
- value={editing.overlay_title || ''}
- onChange={(e) => setEditing({ ...editing, overlay_title: e.target.value })}
- />
- </label>
- <label>
- 副标题(叠字)
- <input
- value={editing.overlay_subtitle || ''}
- onChange={(e) => setEditing({ ...editing, overlay_subtitle: e.target.value })}
- />
- </label>
- </>
- )}
- <label>
- {isImageText ? '旁白台词(配音)' : '台词'}
- <textarea
- rows={3}
- value={editing.narration}
- onChange={(e) => setEditing({ ...editing, narration: e.target.value })}
- />
- </label>
- <label>
- 画面提示词(场景描述,不含风格/人物锁定)
- <textarea
- rows={3}
- value={scenePromptForDisplay(editing.img_prompt)}
- onChange={(e) => setEditing({ ...editing, img_prompt: e.target.value })}
- />
- </label>
- {!isImageText && (
- <label>
- 视频提示词
- <textarea
- rows={3}
- value={editing.video_prompt}
- onChange={(e) => setEditing({ ...editing, video_prompt: e.target.value })}
- />
- </label>
- )}
- <label>
- 时长(秒,{bounds.min}–{bounds.max})
- <input
- type="number"
- min={bounds.min}
- max={bounds.max}
- step={1}
- value={editing.duration}
- onChange={(e) => {
- const n = Number(e.target.value)
- setEditing({
- ...editing,
- duration: Number.isFinite(n)
- ? Math.max(bounds.min, Math.min(bounds.max, n))
- : bounds.min,
- })
- }}
- />
- </label>
- <div className="cta-row">
- <button type="button" className="btn ghost" onClick={() => setEditing(null)}>
- 取消
- </button>
- <button type="button" className="btn primary" onClick={saveShot} disabled={busy}>
- 保存
- </button>
- </div>
- </div>
- </div>
- )}
-
- {preview && (
- <div className="modal-backdrop" role="presentation" onClick={() => setPreview(null)}>
- <div
- className={`modal preview-modal${
- preview.kind === 'shot' && preview.portrait ? ' portrait' : ''
- }${preview.kind === 'final' && isImageText ? ' portrait' : ''}`}
- role="dialog"
- onClick={(e) => e.stopPropagation()}
- >
- <header className="preview-head">
- <h3>
- {preview.kind === 'final'
- ? `成片 · ${preview.title}`
- : `分镜 #${preview.shotNo}`}
- </h3>
- <button type="button" className="btn ghost" onClick={() => setPreview(null)}>
- 关闭
- </button>
- </header>
- {preview.kind === 'final' ? (
- <video
- key={`${preview.url}:${preview.bust || ''}`}
- className="preview-media"
- src={api.assetUrl(preview.url, preview.bust)}
- controls
- autoPlay
- playsInline
- />
- ) : preview.videoUrl ? (
- <video
- key={preview.videoUrl}
- className="preview-media"
- src={api.assetUrl(preview.videoUrl)}
- controls
- autoPlay
- playsInline
- poster={preview.imageUrl ? api.assetUrl(preview.imageUrl) : undefined}
- />
- ) : preview.imageUrl ? (
- <>
- <img
- className="preview-media"
- src={api.assetUrl(preview.imageUrl)}
- alt=""
- />
- {preview.audioUrl && (
- <audio
- key={preview.audioUrl}
- className="preview-audio"
- src={api.assetUrl(preview.audioUrl)}
- controls
- autoPlay
- />
- )}
- </>
- ) : (
- <p className="muted">暂无预览素材</p>
- )}
- {preview.kind === 'shot' && preview.caption ? (
- <p className="muted small preview-caption">{preview.caption}</p>
- ) : null}
- </div>
- </div>
- )}
- </div>
- )
+ const q = new URLSearchParams()
+ if (template) q.set('template', template)
+ if (mode) q.set('mode', mode)
+ const qs = q.toString()
+ return <Navigate to={qs ? `/studio/new?${qs}` : '/studio/new'} replace />
}
diff --git a/frontend/src/pages/TemplatesPage.tsx b/frontend/src/pages/TemplatesPage.tsx
new file mode 100644
index 0000000..25c29a5
--- /dev/null
+++ b/frontend/src/pages/TemplatesPage.tsx
@@ -0,0 +1,101 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { api } from '../api'
+import type { Template } from '../api'
+import AppShell from '../components/layout/AppShell'
+import PillTabs from '../components/ui/PillTabs'
+import { CATEGORY_ORDER, HOME_CATEGORY_LABELS } from '../lib/categories'
+
+export default function TemplatesPage() {
+ const nav = useNavigate()
+ const [templates, setTemplates] = useState<Template[]>([])
+ const [error, setError] = useState('')
+ const [category, setCategory] = useState('全部')
+ const [q, setQ] = useState('')
+
+ useEffect(() => {
+ api
+ .templates()
+ .then(setTemplates)
+ .catch((e) => setError(String(e.message || e)))
+ }, [])
+
+ const categoryKeys = useMemo(() => {
+ const found = new Set<string>()
+ for (const t of templates) {
+ for (const c of t.category || []) {
+ if (CATEGORY_ORDER.includes(c)) found.add(c)
+ }
+ }
+ return ['全部', ...CATEGORY_ORDER.filter((c) => found.has(c))]
+ }, [templates])
+
+ const categoryLabels = categoryKeys.map((k) => HOME_CATEGORY_LABELS[k] || k)
+ const labelToKey = useMemo(() => {
+ const m = new Map<string, string>()
+ for (const k of categoryKeys) m.set(HOME_CATEGORY_LABELS[k] || k, k)
+ return m
+ }, [categoryKeys])
+
+ const filtered = useMemo(() => {
+ let list = templates
+ if (category !== '全部') list = list.filter((t) => (t.category || []).includes(category))
+ if (q.trim()) {
+ const s = q.trim().toLowerCase()
+ list = list.filter(
+ (t) => t.name.toLowerCase().includes(s) || t.description.toLowerCase().includes(s),
+ )
+ }
+ return list
+ }, [templates, category, q])
+
+ function openTemplate(t: Template) {
+ if (!localStorage.getItem('token')) {
+ nav('/auth')
+ return
+ }
+ nav(`/studio/new?template=${t.id}`)
+ }
+
+ return (
+ <AppShell active="templates">
+ <div className="pf-section-head">
+ <div>
+ <h2>模板库</h2>
+ <p>为科普与知识短片挑选画面语言</p>
+ </div>
+ </div>
+ <div className="pf-search" style={{ maxWidth: 420, marginBottom: '1rem' }}>
+ <input
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ placeholder="搜索模板名称或描述"
+ />
+ </div>
+ <PillTabs
+ items={categoryLabels}
+ value={HOME_CATEGORY_LABELS[category] || category}
+ onChange={(label) => setCategory(labelToKey.get(label) || '全部')}
+ ariaLabel="模板分类"
+ />
+ {error ? <p className="pf-error">{error}</p> : null}
+ <div className="pf-template-grid" style={{ marginTop: '1rem' }}>
+ {filtered.map((t) => (
+ <button key={t.id} type="button" className="pf-template-card" onClick={() => openTemplate(t)}>
+ <img src={api.assetUrl(t.preview_cover)} alt="" />
+ <div className="body">
+ <h3>{t.name}</h3>
+ <p>{t.description}</p>
+ <div className="pf-tags">
+ {t.category.map((c) => (
+ <span key={c}>{c}</span>
+ ))}
+ </div>
+ </div>
+ </button>
+ ))}
+ </div>
+ {filtered.length === 0 ? <p className="pf-muted">没有匹配的模板。</p> : null}
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/studio/CreateProjectPage.tsx b/frontend/src/pages/studio/CreateProjectPage.tsx
new file mode 100644
index 0000000..501a174
--- /dev/null
+++ b/frontend/src/pages/studio/CreateProjectPage.tsx
@@ -0,0 +1,504 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useNavigate, useSearchParams } from 'react-router-dom'
+import { api, defaultsFromTemplate } from '../../api'
+import type { Template } from '../../api'
+import AppShell from '../../components/layout/AppShell'
+import Stepper from '../../components/ui/Stepper'
+import PillTabs from '../../components/ui/PillTabs'
+import ComingSoon from '../../components/ui/ComingSoon'
+import { IconChevronLeft, IconRefresh, IconSparkles } from '../../components/ui/Icons'
+import { CATEGORY_ORDER } from '../../lib/categories'
+import { CREATE_STEPS } from '../../lib/status'
+
+type Inspiration = {
+ title: string
+ theme: string
+ script: string
+}
+
+const INSPIRATION_POOL: Inspiration[] = [
+ {
+ title: '黑洞是如何形成的',
+ theme: '黑洞是如何形成的?用通俗方式讲清恒星坍缩、事件视界与时空弯曲,面向中学生。',
+ script:
+ '夜空里最神秘的天体之一,就是黑洞。\n\n' +
+ '当一颗足够大的恒星燃料烧尽,核心会在引力下剧烈坍缩,密度高到连光都逃不出去,事件视界就此诞生。\n\n' +
+ '它不是宇宙吸尘器,而是时空被严重弯曲的区域。靠近它,时间流逝也会变得奇怪。\n\n' +
+ '记住:质量够大、坍缩够猛,黑洞就会出现。下一次看科普新闻,你就能分清传说与科学。',
+ },
+ {
+ title: '为什么天空是蓝色的',
+ theme: '为什么天空是蓝色的?用瑞利散射解释阳光、空气分子与傍晚火烧云,适合科普入门。',
+ script:
+ '抬头一看,白天的天空常常是蓝的,这是巧合吗?\n\n' +
+ '阳光看起来发白,其实包含多种颜色。空气分子对蓝光散射更强,蓝光更容易被「弹」向四面八方,于是我们眼里的天空偏蓝。\n\n' +
+ '早晚太阳更低,光穿过更厚大气,蓝光散得更干净,剩下的红橙光就染红了天边。\n\n' +
+ '所以天空的颜色,是光与空气的一场合作。',
+ },
+ {
+ title: 'AI 如何改变生活',
+ theme: 'AI 如何改变生活:从推荐、语音助手到医疗影像,讲清便利与需要警惕的偏见。',
+ script:
+ '打开手机,推荐视频、导航路线、语音助手——人工智能已经悄悄进了日常。\n\n' +
+ '它擅长从海量数据里找规律:帮医生看影像线索,帮工厂预判故障,也帮你把搜索变成对话。\n\n' +
+ '但 AI 不是魔法。数据有偏见,模型会犯错,隐私也需要边界。真正有用的,是把 AI 当工具,而不是当权威。\n\n' +
+ '理解它能做什么、不能做什么,你才能用得更聪明。',
+ },
+ {
+ title: '火星上的一天',
+ theme: '火星上的一天长什么样?对比地球日长、气温、沙尘与人类基地想象,做成场景化科普。',
+ script:
+ '想象你在火星醒来:太阳更远更小,天空偏奶油色,一天大约 24 小时 39 分钟。\n\n' +
+ '白天可能「温暖」到零下,夜晚更冷。薄薄的二氧化碳大气留不住热量,沙尘暴偶尔遮天。\n\n' +
+ '科学家仍在规划基地:要防辐射、造氧气、种食物。火星不是第二地球,却是最近的外太空课堂。\n\n' +
+ '了解火星的一天,就是在预习人类下一次远行。',
+ },
+ {
+ title: '梦的力量',
+ theme: '梦的力量:睡眠周期、快速眼动与记忆整理,用故事讲清做梦如何帮助大脑「复盘」。',
+ script:
+ '你睡着以后,大脑并没有下班。\n\n' +
+ '进入快速眼动睡眠时,大脑像在回放白天的片段,拼接成奇幻的梦。科学家认为,这有助于整理记忆、调节情绪。\n\n' +
+ '睡不够,注意力和创造力都会打折;规律睡眠,则像给大脑做夜间维护。\n\n' +
+ '下次做怪梦,别只觉得荒唐——那可能是大脑在加班学习。',
+ },
+ {
+ title: '一只流浪猫的春天',
+ theme: '一只流浪猫的春天:用拟人旁白讲城市生态、投喂边界与人宠共处,温暖向科普叙事。',
+ script:
+ '春天来了,巷口的橘猫开始换毛,也开始寻找更安全的角落。\n\n' +
+ '城市里的流浪动物,靠的是残存野性与人类不经意的善意。科学投喂、绝育与尊重距离,比冲动更重要。\n\n' +
+ '它们不是风景,也不是麻烦,而是城市生态的一部分。\n\n' +
+ '这个春天,愿每一只猫,都能遇见更稳妥的明天。',
+ },
+ {
+ title: '光合作用的秘密',
+ theme: '光合作用的秘密:叶子如何把阳光变成糖,讲清叶绿体、能量转化与地球氧气来源。',
+ script:
+ '绿叶不只是装饰,它们是地球上最安静的化工厂。\n\n' +
+ '叶绿体抓住阳光,把水和二氧化碳做成糖,并释放氧气。没有这个过程,绝大多数食物链都会断裂。\n\n' +
+ '你呼吸的氧气、餐桌上的米饭和蔬菜,都间接来自这场光的魔法。\n\n' +
+ '看懂光合作用,就看懂了生命运转的底层账本。',
+ },
+ {
+ title: '地震来了怎么办',
+ theme: '地震来了怎么办:用场景教学讲清震前准备、避险姿势与谣言辨别,实用安全科普。',
+ script:
+ '地面突然晃起来,第一反应往往是慌。\n\n' +
+ '正确做法是就近伏地、掩护、抓稳,远离窗户与高架物;不要一窝蜂挤电梯。提前准备应急包,比临时抱佛脚更管用。\n\n' +
+ '震后还要警惕余震和谣言。权威信息、互助秩序,才是真正的安全感。\n\n' +
+ '懂一点地震知识,关键时刻就能多一分从容。',
+ },
+ {
+ title: '咖啡因如何提神',
+ theme: '咖啡因如何提神:腺苷受体、耐受与睡眠代价,帮上班族科学喝咖啡。',
+ script:
+ '困的时候来杯咖啡,真的是「叫醒大脑」吗?\n\n' +
+ '咖啡因会抢占腺苷的位置,让你暂时感觉不困。但它不能替代睡眠,下午喝太多,夜里更容易翻来覆去。\n\n' +
+ '逐渐耐受后,同样一杯效果会变弱。更聪明的用法是:需要专注时再用,并给睡眠留窗口。\n\n' +
+ '提神可以靠咖啡,恢复还是得靠睡。',
+ },
+ {
+ title: '塑料去哪了',
+ theme: '塑料去哪了:微塑料、海洋环流与可替代材料,做成环保主题科普短片。',
+ script:
+ '扔掉的塑料袋,真的消失了吗?\n\n' +
+ '多数只是被撕成更小的碎片。微塑料进入河流与海洋,再进入食物链,最终可能回到我们的餐桌。\n\n' +
+ '减少一次性塑料、做好分类、推动更好的材料,比事后清理便宜得多。\n\n' +
+ '问「塑料去哪了」,其实是在问:我们愿为未来留什么。',
+ },
+ {
+ title: '疫苗为什么有效',
+ theme: '疫苗为什么有效:用「预演」比喻讲清抗原、抗体与群体免疫,澄清常见误解。',
+ script:
+ '疫苗不是药,更像给免疫系统发的预告片。\n\n' +
+ '它让身体提前认识病原体的关键特征,真正遇到时能更快调动抗体。这不是改写基因,而是训练记忆。\n\n' +
+ '足够多人获得保护,传播链会被削弱,这就是群体免疫的意义。\n\n' +
+ '科学接种,是把自己和身边人一起放进更安全的网络。',
+ },
+ {
+ title: '潮汐的涨落',
+ theme: '潮汐为何涨落:月球引力、离心效应与大潮小潮,海边场景化讲解。',
+ script:
+ '海边的人最懂:水位会按时涨、按时退。\n\n' +
+ '主要推手是月球的引力,太阳也来凑热闹。地球、月球、太阳排成一线时,潮差更大,就是大潮。\n\n' +
+ '潮汐还影响航行、发电甚至生物节律。抬头看月亮,脚下的海也在回应。\n\n' +
+ '涨落之间,是天地引力的可见痕迹。',
+ },
+]
+
+const PAGE_SIZE = 6
+
+function isDefaultTitle(value: string) {
+ const t = value.trim()
+ return !t || t === '未命名作品'
+}
+
+function deriveTitle(text: string) {
+ const line = text
+ .trim()
+ .split(/\n/)[0]
+ .replace(/["""'']/g, '')
+ .replace(/[。!?!?::].*$/, '')
+ .trim()
+ if (!line) return '未命名作品'
+ return line.slice(0, 18)
+}
+
+export default function CreateProjectPage() {
+ const nav = useNavigate()
+ const [params] = useSearchParams()
+ const [templates, setTemplates] = useState<Template[]>([])
+ const [templateId, setTemplateId] = useState(params.get('template') || '')
+ const [category, setCategory] = useState('全部')
+ const [q, setQ] = useState('')
+ const [inputTab, setInputTab] = useState('一句话主题')
+ const [sourceText, setSourceText] = useState(INSPIRATION_POOL[0].theme)
+ const [title, setTitle] = useState(INSPIRATION_POOL[0].title)
+ const [titleTouched, setTitleTouched] = useState(false)
+ const [inspPage, setInspPage] = useState(0)
+ const [busy, setBusy] = useState(false)
+ const [aiBusy, setAiBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ useEffect(() => {
+ if (!localStorage.getItem('token')) {
+ nav('/auth')
+ return
+ }
+ api.me().catch(() => nav('/auth'))
+ api.templates().then((list) => {
+ setTemplates(list)
+ const fromUrl = params.get('template') || ''
+ setTemplateId((prev) => prev || fromUrl || list[0]?.id || '')
+ })
+ }, [nav, params])
+
+ const categories = useMemo(() => {
+ const found = new Set<string>()
+ for (const t of templates) {
+ for (const c of t.category || []) {
+ if (CATEGORY_ORDER.includes(c)) found.add(c)
+ }
+ }
+ return ['全部', '热门推荐', ...CATEGORY_ORDER.filter((c) => found.has(c))]
+ }, [templates])
+
+ const filtered = useMemo(() => {
+ let list = templates
+ if (category === '热门推荐') list = [...templates].sort((a, b) => a.sort_order - b.sort_order).slice(0, 8)
+ else if (category !== '全部') list = list.filter((t) => (t.category || []).includes(category))
+ if (q.trim()) {
+ const s = q.trim().toLowerCase()
+ list = list.filter((t) => t.name.toLowerCase().includes(s))
+ }
+ return list
+ }, [templates, category, q])
+
+ const selected = templates.find((t) => t.id === templateId)
+ const sourceType = inputTab === '粘贴完整文案' ? 'script' : 'theme'
+ const disabledInput = inputTab === '导入文章链接' || inputTab === '上传文档'
+ const inspTotal = Math.ceil(INSPIRATION_POOL.length / PAGE_SIZE)
+ const inspirations = INSPIRATION_POOL.slice(inspPage * PAGE_SIZE, inspPage * PAGE_SIZE + PAGE_SIZE)
+
+ function applyInspiration(item: Inspiration) {
+ if (sourceType === 'script') {
+ setInputTab('粘贴完整文案')
+ setSourceText(item.script.slice(0, 8000))
+ } else {
+ setInputTab('一句话主题')
+ setSourceText(item.theme.slice(0, 100))
+ }
+ setTitle(item.title.slice(0, 24))
+ setTitleTouched(false)
+ setError('')
+ }
+
+ function shuffleInspirations() {
+ setInspPage((p) => (p + 1) % inspTotal)
+ }
+
+ async function aiExpand() {
+ if (disabledInput) {
+ setError('该输入方式即将推出,请使用一句话主题或粘贴文案')
+ return
+ }
+ const seed = sourceText.trim() || title.trim() || '人工智能如何改变生活'
+ setAiBusy(true)
+ setError('')
+ try {
+ const mode = sourceType === 'script' ? 'script' : 'theme'
+ const result = await api.expandContent(seed, mode)
+ setSourceText(result.content.slice(0, mode === 'theme' ? 100 : 8000))
+ if (!titleTouched || isDefaultTitle(title)) {
+ setTitle(result.title.slice(0, 24))
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'AI 生成失败')
+ } finally {
+ setAiBusy(false)
+ }
+ }
+
+ async function next() {
+ if (!templateId || !sourceText.trim()) {
+ setError('请选择模板并填写主题内容')
+ return
+ }
+ if (disabledInput) {
+ setError('该输入方式即将推出,请使用一句话主题或粘贴文案')
+ return
+ }
+ setBusy(true)
+ setError('')
+ try {
+ const tpl = templates.find((t) => t.id === templateId)
+ const d = tpl ? defaultsFromTemplate(tpl) : undefined
+ const modeParam = params.get('mode')
+ const pipeline_mode: 'full' | 'image_text' =
+ modeParam === 'image_text' || modeParam === 'full' ? modeParam : 'full'
+ const finalTitle =
+ title.trim() || deriveTitle(sourceText) || sourceText.trim().slice(0, 24) || '未命名作品'
+ const project = await api.createProject({
+ template_id: templateId,
+ title: finalTitle,
+ source_type: sourceType,
+ source_text: sourceText.trim(),
+ resolution_mode: 'preview',
+ pipeline_mode,
+ output_ratio: d?.output_ratio || '16:9',
+ voice_id: d?.voice_id,
+ style_prompt: d?.style_prompt,
+ character_prompt: d?.character_prompt,
+ extra_prompt: d?.extra_prompt,
+ })
+ nav(`/studio/${project.id}/style`)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '创建失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+ <AppShell active="studio" wide>
+ <header className="pf-page-head">
+ <div className="pf-page-head-row">
+ <div>
+ <button type="button" className="pf-back" onClick={() => nav('/')}>
+ <IconChevronLeft size={18} />
+ 新建项目 / 开始创作
+ </button>
+ <h1 className="pf-page-title">创建项目</h1>
+ </div>
+ <Stepper steps={CREATE_STEPS} current={1} doneThrough={0} />
+ </div>
+ </header>
+
+ <div className="pf-create">
+ <aside className="pf-create-col">
+ <h3>选择模板</h3>
+ <div className="pf-search">
+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="搜索模板…" />
+ </div>
+ <PillTabs items={categories.slice(0, 6)} value={category} onChange={setCategory} ariaLabel="模板分类" />
+ <div className="pf-tpl-list" style={{ marginTop: '0.75rem' }}>
+ {filtered.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ className={templateId === t.id ? 'pf-tpl-mini selected' : 'pf-tpl-mini'}
+ onClick={() => setTemplateId(t.id)}
+ >
+ <img src={api.assetUrl(t.preview_cover)} alt="" />
+ <div>
+ <strong>{t.name}</strong>
+ <span>
+ {t.default_ratio} · {(t.category || [])[0] || '通用'}
+ </span>
+ </div>
+ </button>
+ ))}
+ </div>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" style={{ marginTop: '0.75rem' }} disabled>
+ 加载更多模板 <ComingSoon />
+ </button>
+ </aside>
+
+ <section className="pf-create-col">
+ <h3>输入内容</h3>
+ <div className="pf-input-tabs">
+ {['一句话主题', '粘贴完整文案', '导入文章链接', '上传文档'].map((tab) => (
+ <button
+ key={tab}
+ type="button"
+ className={['pf-pill', inputTab === tab ? 'lime active' : ''].join(' ')}
+ onClick={() => setInputTab(tab)}
+ >
+ {tab}
+ {(tab === '导入文章链接' || tab === '上传文档') && (
+ <>
+ {' '}
+ <ComingSoon />
+ </>
+ )}
+ </button>
+ ))}
+ </div>
+
+ <label className="pf-field">
+ <span className="pf-field-label">项目名称</span>
+ <input
+ className="pf-field-input"
+ value={title}
+ onChange={(e) => {
+ setTitle(e.target.value)
+ setTitleTouched(true)
+ }}
+ onBlur={() => {
+ if (isDefaultTitle(title) && sourceText.trim()) {
+ setTitle(deriveTitle(sourceText))
+ setTitleTouched(false)
+ }
+ }}
+ placeholder="将根据内容自动填充"
+ />
+ </label>
+
+ <div className="pf-textarea-wrap">
+ <div className="pf-textarea-toolbar">
+ <button
+ type="button"
+ className="pf-btn pf-btn-ai pf-btn-sm pf-btn-icon"
+ disabled={aiBusy || busy || disabledInput}
+ onClick={aiExpand}
+ >
+ <IconSparkles size={14} />
+ {aiBusy ? '生成中…' : sourceType === 'script' ? 'AI 扩写文案' : 'AI 生成主题'}
+ </button>
+ <span className="pf-muted" style={{ fontSize: '0.75rem' }}>
+ {sourceType === 'script' ? '可从一句话扩成完整口播' : '补全受众与知识点'}
+ </span>
+ </div>
+ <textarea
+ value={sourceText}
+ onChange={(e) => {
+ const next = e.target.value.slice(0, sourceType === 'theme' ? 100 : 8000)
+ setSourceText(next)
+ if (!titleTouched || isDefaultTitle(title)) {
+ setTitle(deriveTitle(next))
+ }
+ }}
+ disabled={disabledInput}
+ placeholder={
+ disabledInput
+ ? '该方式即将推出'
+ : sourceType === 'theme'
+ ? '例如:黑洞是如何形成的?用通俗方式讲清引力与时空'
+ : '粘贴或 AI 生成完整口播文案…'
+ }
+ />
+ {sourceType === 'theme' ? (
+ <span className="pf-char-count">{sourceText.length}/100</span>
+ ) : (
+ <span className="pf-char-count">{sourceText.length} 字</span>
+ )}
+ </div>
+
+ <div className="pf-inspire">
+ <div className="pf-inspire-head">
+ <strong>灵感示例</strong>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon" onClick={shuffleInspirations}>
+ <IconRefresh size={14} />
+ 换一批
+ </button>
+ </div>
+ <div className="pf-chips">
+ {inspirations.map((item) => (
+ <button
+ key={item.title}
+ type="button"
+ className="pf-chip"
+ title={sourceType === 'script' ? item.script.slice(0, 80) : item.theme}
+ onClick={() => applyInspiration(item)}
+ >
+ {item.title}
+ </button>
+ ))}
+ </div>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0.55rem 0 0' }}>
+ 点击示例会填充完整{sourceType === 'script' ? '文案' : '主题'}并自动写入项目名称
+ </p>
+ </div>
+
+ <div className="pf-hint" style={{ marginTop: '1rem' }}>
+ 主题越具体,AI 越容易生成准确的科普分镜与旁白。可写清受众与核心知识点。
+ </div>
+ {error ? <p className="pf-error">{error}</p> : null}
+ </section>
+
+ <aside className="pf-create-col">
+ <h3>创作摘要</h3>
+ {selected ? (
+ <div style={{ marginBottom: '0.85rem' }}>
+ <img
+ src={api.assetUrl(selected.preview_cover)}
+ alt=""
+ style={{ width: '100%', borderRadius: 12, aspectRatio: '16/9', objectFit: 'cover' }}
+ />
+ <strong style={{ display: 'block', marginTop: '0.5rem' }}>{selected.name}</strong>
+ <p className="pf-muted" style={{ margin: '0.25rem 0 0', fontSize: '0.85rem' }}>
+ {selected.description}
+ </p>
+ </div>
+ ) : (
+ <p className="pf-muted">请选择模板</p>
+ )}
+ <div className="pf-summary-row">
+ <span>作品名称</span>
+ <span>{title.trim() || '未命名作品'}</span>
+ </div>
+ <div className="pf-summary-row">
+ <span>输出模式</span>
+ <span>{selected?.default_ratio === '9:16' ? '视频 · 9:16' : '视频 · 16:9'}</span>
+ </div>
+ <div className="pf-summary-row">
+ <span>预估时长</span>
+ <span>~1–3 分钟</span>
+ </div>
+ <div className="pf-summary-row">
+ <span>语言</span>
+ <span>中文(普通话)</span>
+ </div>
+ <div className="pf-summary-row">
+ <span>输入方式</span>
+ <span>{inputTab}</span>
+ </div>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-block pf-btn-lg pf-btn-icon"
+ style={{ marginTop: '1.25rem' }}
+ disabled={busy || aiBusy || !templateId || !sourceText.trim()}
+ onClick={next}
+ >
+ {busy ? '创建中…' : '下一步:风格配置'}
+ {!busy ? <span aria-hidden>→</span> : null}
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-block pf-btn-sm pf-btn-icon"
+ style={{ marginTop: '0.55rem' }}
+ disabled={aiBusy || busy || disabledInput}
+ onClick={aiExpand}
+ >
+ <IconSparkles size={14} />
+ {aiBusy ? 'AI 生成中…' : '不够完整?让 AI 帮你写'}
+ </button>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', marginTop: '0.5rem' }}>
+ 下一步可自定义风格、画面与配音。
+ </p>
+ </aside>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/studio/EditorPage.tsx b/frontend/src/pages/studio/EditorPage.tsx
new file mode 100644
index 0000000..3e058bf
--- /dev/null
+++ b/frontend/src/pages/studio/EditorPage.tsx
@@ -0,0 +1,433 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useNavigate, useParams } from 'react-router-dom'
+import { api } from '../../api'
+import type { Project, Shot } from '../../api'
+import AppShell from '../../components/layout/AppShell'
+import ComingSoon from '../../components/ui/ComingSoon'
+import { STATUS_CN } from '../../lib/status'
+
+const PANEL_TABS = ['文案', '画面', '配音', '转场'] as const
+
+export default function EditorPage() {
+ const { id } = useParams()
+ const projectId = Number(id)
+ const nav = useNavigate()
+ const [project, setProject] = useState<Project | null>(null)
+ const [activeShotId, setActiveShotId] = useState<number | null>(null)
+ const [tab, setTab] = useState<(typeof PANEL_TABS)[number]>('文案')
+ const [narration, setNarration] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ useEffect(() => {
+ if (!localStorage.getItem('token')) {
+ nav('/auth')
+ return
+ }
+ if (!projectId) {
+ nav('/studio/new')
+ return
+ }
+ api
+ .getProject(projectId)
+ .then((p) => {
+ setProject(p)
+ const first = p.shots[0]
+ if (first) {
+ setActiveShotId(first.id)
+ setNarration(first.narration || '')
+ }
+ })
+ .catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ }, [nav, projectId])
+
+ const shot: Shot | undefined = useMemo(
+ () => project?.shots.find((s) => s.id === activeShotId),
+ [project, activeShotId],
+ )
+
+ const totalDuration = useMemo(
+ () => (project?.shots || []).reduce((s, x) => s + (Number(x.duration) || 0), 0),
+ [project?.shots],
+ )
+
+ function selectShot(s: Shot) {
+ setActiveShotId(s.id)
+ setNarration(s.narration || '')
+ }
+
+ async function saveNarration() {
+ if (!project || !shot) return
+ setBusy(true)
+ setError('')
+ try {
+ await api.updateShot(project.id, shot.id, { narration })
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '保存失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function regenImage() {
+ if (!project || !shot) return
+ setBusy(true)
+ try {
+ await api.regenImage(project.id, shot.id)
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '重生成失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function regenAudio() {
+ if (!project || !shot) return
+ setBusy(true)
+ try {
+ await api.regenAudio(project.id, shot.id)
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '重配音失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ if (!project && !error) {
+ return (
+ <AppShell active="studio" flush>
+ <p className="pf-muted" style={{ padding: '2rem' }}>
+ 加载中…
+ </p>
+ </AppShell>
+ )
+ }
+
+ if (!project) {
+ return (
+ <AppShell active="studio">
+ <p className="pf-error">{error}</p>
+ </AppShell>
+ )
+ }
+
+ const isPortrait = (project.output_ratio || '') === '9:16' || (!project.output_ratio && project.pipeline_mode === 'image_text')
+ // Prefer current shot media; final film is for dedicated preview, not shot editing.
+ const shotVideo = shot?.video_url ? api.assetUrl(shot.video_url, shot.version) : null
+ const shotImage = shot?.image_url ? api.assetUrl(shot.image_url, shot.version) : null
+
+ return (
+ <AppShell active="studio" flush>
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '0.75rem 1.25rem',
+ borderBottom: '1px solid var(--pf-line)',
+ background: '#fff',
+ flexWrap: 'wrap',
+ gap: '0.5rem',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
+ <button type="button" className="pf-link" onClick={() => nav(`/studio/${project.id}`)}>
+ ← 返回项目
+ </button>
+ <strong>{project.title}</strong>
+ <span className="pf-muted" style={{ fontSize: '0.8rem' }}>
+ {STATUS_CN[project.status] || project.status}
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '0.4rem', flexWrap: 'wrap' }}>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 撤销 <ComingSoon />
+ </button>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 重做 <ComingSoon />
+ </button>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 保存草稿 <ComingSoon />
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={!shot?.video_url && !project.final_video_url}
+ onClick={() => {
+ const el = document.getElementById('pf-editor-player') as HTMLVideoElement | null
+ if (el) {
+ el.play()
+ return
+ }
+ if (project.final_video_url) {
+ window.open(api.assetUrl(project.final_video_url, project.updated_at), '_blank')
+ }
+ }}
+ >
+ 预览播放
+ </button>
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled>
+ 导出视频 <ComingSoon />
+ </button>
+ </div>
+ </div>
+
+ {error ? (
+ <p className="pf-error" style={{ padding: '0.5rem 1.25rem' }}>
+ {error}
+ </p>
+ ) : null}
+
+ <div className="pf-editor">
+ <aside>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.75rem' }}>
+ <strong>场景列表</strong>
+ <button type="button" className="pf-link" disabled>
+ + 添加镜头 <ComingSoon />
+ </button>
+ </div>
+ {project.shots.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ className={activeShotId === s.id ? 'pf-scene-item active' : 'pf-scene-item'}
+ onClick={() => selectShot(s)}
+ >
+ {s.image_url ? (
+ <img src={api.assetUrl(s.image_url, s.version)} alt="" />
+ ) : (
+ <div className="ph" />
+ )}
+ <div>
+ <strong style={{ fontSize: '0.82rem' }}>
+ {String(s.shot_no).padStart(2, '0')} {s.overlay_title || '镜头'}
+ </strong>
+ <div className="pf-muted" style={{ fontSize: '0.72rem' }}>
+ {(s.narration || '').slice(0, 28)}
+ </div>
+ </div>
+ </button>
+ ))}
+ <p className="pf-muted" style={{ fontSize: '0.8rem', marginTop: '0.75rem' }}>
+ 总时长{' '}
+ {Math.floor(totalDuration / 60)
+ .toString()
+ .padStart(2, '0')}
+ :
+ {Math.floor(totalDuration % 60)
+ .toString()
+ .padStart(2, '0')}
+ </p>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-block" disabled>
+ 调整顺序 <ComingSoon />
+ </button>
+ </aside>
+
+ <section>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.65rem' }}>
+ <strong>
+ {shot ? `镜头 ${shot.shot_no}` : '预览'} · {isPortrait ? '9:16' : '16:9'}
+ </strong>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled={busy} onClick={regenImage}>
+ 替换画面
+ </button>
+ </div>
+ <div className={isPortrait ? 'pf-editor-preview portrait' : 'pf-editor-preview'}>
+ {shotVideo ? (
+ <video
+ id="pf-editor-player"
+ key={`v-${shot?.id}-${shot?.version}`}
+ src={shotVideo}
+ poster={shotImage || undefined}
+ controls
+ playsInline
+ />
+ ) : shotImage ? (
+ <img key={`i-${shot?.id}-${shot?.version}`} src={shotImage} alt="" />
+ ) : (
+ <span className="empty">暂无画面</span>
+ )}
+ </div>
+ {shot?.audio_url ? (
+ <audio
+ src={api.assetUrl(shot.audio_url)}
+ controls
+ style={{ width: '100%', marginTop: '0.65rem' }}
+ />
+ ) : null}
+
+ <div
+ style={{
+ marginTop: '0.85rem',
+ display: 'flex',
+ gap: '0.4rem',
+ overflowX: 'auto',
+ paddingBottom: 4,
+ }}
+ >
+ {project.shots.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ onClick={() => selectShot(s)}
+ style={{
+ border: activeShotId === s.id ? '2px solid var(--pf-lime)' : '1px solid var(--pf-line)',
+ borderRadius: 8,
+ padding: 0,
+ background: 'transparent',
+ }}
+ >
+ {s.image_url ? (
+ <img
+ src={api.assetUrl(s.image_url, s.version)}
+ alt=""
+ style={{ width: 88, height: 50, objectFit: 'cover', display: 'block', borderRadius: 6 }}
+ />
+ ) : (
+ <div style={{ width: 88, height: 50, background: '#eee', borderRadius: 6 }} />
+ )}
+ </button>
+ ))}
+ </div>
+
+ <div
+ style={{
+ marginTop: '0.85rem',
+ border: '1px dashed var(--pf-line)',
+ borderRadius: 12,
+ padding: '1.25rem',
+ textAlign: 'center',
+ color: 'var(--pf-muted)',
+ fontSize: '0.9rem',
+ }}
+ >
+ 拖拽素材到此处替换当前镜头画面 <ComingSoon />
+ </div>
+
+ <div style={{ marginTop: '1rem' }}>
+ <div className="pf-panel-tabs">
+ {['素材库', '收藏素材', 'AI 生成素材', '我的上传'].map((t) => (
+ <button key={t} type="button" disabled>
+ {t}
+ </button>
+ ))}
+ </div>
+ <p className="pf-muted" style={{ fontSize: '0.85rem' }}>
+ 素材库与上传能力即将推出,当前可使用「替换画面」触发 AI 重绘。
+ </p>
+ </div>
+ </section>
+
+ <aside>
+ <div className="pf-panel-tabs">
+ {PANEL_TABS.map((t) => (
+ <button
+ key={t}
+ type="button"
+ className={tab === t ? 'active' : ''}
+ onClick={() => setTab(t)}
+ >
+ {t}
+ </button>
+ ))}
+ </div>
+
+ {tab === '文案' ? (
+ <>
+ <label className="pf-muted" style={{ fontSize: '0.85rem', display: 'block' }}>
+ 文案内容
+ <textarea
+ value={narration}
+ onChange={(e) => setNarration(e.target.value)}
+ rows={5}
+ style={{
+ width: '100%',
+ marginTop: 6,
+ borderRadius: 10,
+ border: '1px solid var(--pf-line)',
+ padding: '0.65rem',
+ }}
+ />
+ </label>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-block"
+ style={{ marginTop: 8 }}
+ disabled
+ >
+ AI 帮我优化这一镜 <ComingSoon />
+ </button>
+ <div style={{ marginTop: '0.85rem' }}>
+ <strong style={{ fontSize: '0.88rem' }}>
+ 样式设置 <ComingSoon />
+ </strong>
+ <p className="pf-muted" style={{ fontSize: '0.8rem' }}>
+ 字体 / 字号 / 颜色 / 对齐占位
+ </p>
+ </div>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-block"
+ style={{ marginTop: '1rem' }}
+ disabled={busy}
+ onClick={saveNarration}
+ >
+ 保存文案
+ </button>
+ </>
+ ) : null}
+
+ {tab === '画面' ? (
+ <>
+ <p className="pf-muted" style={{ fontSize: '0.88rem' }}>
+ 当前镜头画面可通过 AI 重绘替换。时间线精修即将推出。
+ </p>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-block"
+ disabled={busy}
+ onClick={regenImage}
+ >
+ 重新生成当前镜头
+ </button>
+ </>
+ ) : null}
+
+ {tab === '配音' ? (
+ <>
+ <p className="pf-muted" style={{ fontSize: '0.88rem' }}>
+ 替换当前镜头配音(沿用项目音色)。
+ </p>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-block"
+ disabled={busy}
+ onClick={regenAudio}
+ >
+ 替换配音
+ </button>
+ </>
+ ) : null}
+
+ {tab === '转场' ? (
+ <div className="pf-hint">
+ 转场效果(淡入淡出、闪白、运镜衔接等)即将推出。
+ </div>
+ ) : null}
+
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-block"
+ style={{ marginTop: '1rem' }}
+ disabled
+ >
+ 应用到全部同类镜头 <ComingSoon />
+ </button>
+ </aside>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsx
new file mode 100644
index 0000000..1d2c3d8
--- /dev/null
+++ b/frontend/src/pages/studio/StoryboardPage.tsx
@@ -0,0 +1,1319 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useNavigate, useParams } from 'react-router-dom'
+import { api } from '../../api'
+import type { Project, Shot, Template } from '../../api'
+import AppShell from '../../components/layout/AppShell'
+import Stepper from '../../components/ui/Stepper'
+import ComingSoon from '../../components/ui/ComingSoon'
+import {
+ IconChevronLeft,
+ IconDownload,
+ IconEdit,
+ IconImage,
+ IconMonitor,
+ IconPlay,
+ IconRefresh,
+ IconSliders,
+ IconTrash,
+} from '../../components/ui/Icons'
+import { scenePromptForDisplay } from '../../promptDisplay'
+import {
+ BOARD_STEPS,
+ formatMmSs,
+ isRunning,
+ shotIsDone,
+ shotStatusLabel,
+ STATUS_CN,
+} from '../../lib/status'
+
+function csvEscape(value: string | number | null | undefined) {
+ const s = String(value ?? '')
+ if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`
+ return s
+}
+
+function downloadStoryboardCsv(project: Project) {
+ const header = ['镜号', '旁白', '画面描述', '时长秒', '状态', '镜头标题']
+ const rows = (project.shots || [])
+ .slice()
+ .sort((a, b) => a.shot_no - b.shot_no)
+ .map((s) =>
+ [
+ s.shot_no,
+ s.narration,
+ scenePromptForDisplay(s.img_prompt || s.video_prompt || ''),
+ s.duration,
+ shotStatusLabel(s.status),
+ s.overlay_title || '',
+ ]
+ .map(csvEscape)
+ .join(','),
+ )
+ const bom = '\uFEFF'
+ const blob = new Blob([bom + [header.join(','), ...rows].join('\n')], {
+ type: 'text/csv;charset=utf-8',
+ })
+ const a = document.createElement('a')
+ a.href = URL.createObjectURL(blob)
+ a.download = `${project.title || `project_${project.id}`}_storyboard.csv`
+ a.click()
+ URL.revokeObjectURL(a.href)
+}
+
+type PreviewState =
+ | {
+ kind: 'shot'
+ shotNo: number
+ imageUrl: string | null
+ videoUrl: string | null
+ audioUrl: string | null
+ caption: string
+ }
+ | { kind: 'final'; url: string; title: string; bust?: string }
+ | null
+
+function shotCaption(shot: Shot) {
+ if (shot.overlay_title) {
+ return `${shot.overlay_title}${
+ shot.overlay_subtitle ? ` · ${shot.overlay_subtitle}` : ''
+ }${shot.narration ? `|旁白:${shot.narration}` : ''}`
+ }
+ return shot.narration
+}
+
+function boardStepIndex(project: Project) {
+ const status = project.status
+ if (status === 'DRAFT') return 0
+ if (status === 'SCRIPTING') return 1
+ // 分镜已出,停留在「生成分镜」供确认修改
+ if (status === 'SCRIPT_READY') return 3
+ // 成片阶段:合成中 / 已完成;或素材已齐、等待合成
+ if (['COMPOSING', 'AUDITING', 'DONE'].includes(status)) return 4
+ if (status === 'VIDEO_READY') return 4
+ if (status === 'IMAGE_READY' && project.pipeline_mode === 'image_text') return 4
+ if (status === 'FAILED' || status === 'CANCELLED') {
+ return project.final_video_url ? 4 : 3
+ }
+ // IMAGING / VIDEOING / AUDIOING / IMAGE_READY(full) 等仍在分镜生成
+ return 3
+}
+
+export default function StoryboardPage() {
+ const { id } = useParams()
+ const projectId = Number(id)
+ const nav = useNavigate()
+ const [project, setProject] = useState<Project | null>(null)
+ const [template, setTemplate] = useState<Template | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [editing, setEditing] = useState<Shot | null>(null)
+ const [editFocus, setEditFocus] = useState<string>('')
+ const [promptEdit, setPromptEdit] = useState<{
+ style_prompt: string
+ character_prompt: string
+ extra_prompt: string
+ } | null>(null)
+ const [preview, setPreview] = useState<PreviewState>(null)
+ const [menuShotId, setMenuShotId] = useState<number | null>(null)
+ const [batchOpen, setBatchOpen] = useState(false)
+ const [batchSelected, setBatchSelected] = useState<number[]>([])
+ const [batchDuration, setBatchDuration] = useState('')
+ const [batchRegenAudio, setBatchRegenAudio] = useState(false)
+ const coverInputRef = useRef<HTMLInputElement>(null)
+
+ useEffect(() => {
+ if (!localStorage.getItem('token')) {
+ nav('/auth')
+ return
+ }
+ if (!projectId) {
+ nav('/studio/new')
+ return
+ }
+ api
+ .getProject(projectId)
+ .then((p) => {
+ setProject(p)
+ return api.templates().then((list) => {
+ setTemplate(list.find((t) => t.id === p.template_id) || null)
+ })
+ })
+ .catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ }, [nav, projectId])
+
+ useEffect(() => {
+ if (!project) return
+ // Only poll while pipeline is actively running — idle checkpoints
+ // (IMAGE_READY / VIDEO_READY / SCRIPT_READY) must not spin forever.
+ if (!isRunning(project.status)) return
+ const timer = setInterval(() => {
+ api
+ .getProject(project.id)
+ .then(setProject)
+ .catch(() => undefined)
+ }, 1500)
+ return () => clearInterval(timer)
+ }, [project?.id, project?.status])
+
+ useEffect(() => {
+ if (menuShotId == null) return
+ function onDoc() {
+ setMenuShotId(null)
+ }
+ document.addEventListener('click', onDoc)
+ return () => document.removeEventListener('click', onDoc)
+ }, [menuShotId])
+
+ const running = Boolean(project && isRunning(project.status))
+ const step = project ? boardStepIndex(project) : 3
+ const totalDuration = useMemo(
+ () => (project?.shots || []).reduce((s, x) => s + (Number(x.duration) || 0), 0),
+ [project?.shots],
+ )
+
+ const shots = project?.shots || []
+ const isFullPipeline = project?.pipeline_mode !== 'image_text'
+ const imgDone = shots.filter((s) => s.image_url).length
+ const audDone = shots.filter((s) => s.audio_url).length
+ const vidDone = shots.filter((s) => s.video_url).length
+ const assetsReady =
+ shots.length > 0 && imgDone === shots.length && audDone === shots.length
+ /**
+ * Full pipeline: need AI videos before compose.
+ * VIDEO_READY+ means video stage finished (incl. privacy skips without video_url).
+ * image_text skips the video stage entirely.
+ */
+ const videosReady =
+ !isFullPipeline ||
+ ['VIDEO_READY', 'COMPOSING', 'AUDITING', 'DONE'].includes(project?.status || '') ||
+ (shots.length > 0 && vidDone === shots.length)
+ const readyToCompose = assetsReady && videosReady
+ const needsVideos = isFullPipeline && assetsReady && !videosReady
+ const needsScriptConfirm =
+ Boolean(project) &&
+ shots.length > 0 &&
+ !assetsReady &&
+ ['SCRIPT_READY', 'DRAFT', 'CANCELLED', 'FAILED'].includes(project!.status)
+ const hasFinal = Boolean(project?.final_video_url)
+ /** Primary CTA: confirm script → generate → (videos) → compose → preview */
+ const primaryAction: 'generate' | 'compose' | 'preview' | 'busy' = running
+ ? 'busy'
+ : hasFinal || project?.status === 'DONE'
+ ? 'preview'
+ : readyToCompose
+ ? 'compose'
+ : 'generate'
+
+ const generateLabel = running
+ ? '生成中…'
+ : needsScriptConfirm
+ ? '确认分镜,开始生成'
+ : needsVideos
+ ? '继续生成视频'
+ : '继续生成'
+
+ const progressItems = useMemo(() => {
+ if (!project) return []
+ const list = project.shots || []
+ const imgs = list.filter((s) => s.image_url).length
+ const auds = list.filter((s) => s.audio_url).length
+ const vids = list.filter((s) => s.video_url).length
+ const full = project.pipeline_mode !== 'image_text'
+ type ProgressItem = { label: string; done: boolean; run?: boolean; pct?: number }
+ const items: ProgressItem[] = [
+ { label: '主题解析', done: true },
+ { label: '分镜脚本', done: list.length > 0 || !['DRAFT', 'SCRIPTING'].includes(project.status) },
+ {
+ label: `画面生成 (${imgs}/${list.length || 0})`,
+ done: list.length > 0 && imgs === list.length,
+ },
+ {
+ label: `配音合成 (${auds}/${list.length || 0})`,
+ done: list.length > 0 && auds === list.length,
+ },
+ ]
+ if (full) {
+ items.push({
+ label: `AI 视频 (${vids}/${list.length || 0})`,
+ done:
+ list.length > 0 &&
+ (vids === list.length ||
+ ['VIDEO_READY', 'COMPOSING', 'AUDITING', 'DONE'].includes(project.status)),
+ run: project.status === 'VIDEOING',
+ pct: project.status === 'VIDEOING' ? project.progress : undefined,
+ })
+ }
+ items.push({
+ label: '成片渲染',
+ done: Boolean(project.final_video_url) || project.status === 'DONE',
+ run: project.status === 'COMPOSING',
+ pct: project.status === 'COMPOSING' ? project.progress : undefined,
+ })
+ return items
+ }, [project])
+
+ function openFinalPreview() {
+ if (!project?.final_video_url) return
+ setPreview({
+ kind: 'final',
+ url: api.assetUrl(project.final_video_url, project.updated_at),
+ title: project.title,
+ bust: project.updated_at,
+ })
+ }
+
+ async function continueGenerate() {
+ if (!project) return
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.generate(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '继续生成失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function restartGenerate() {
+ if (!project) return
+ if (
+ !window.confirm(
+ '确定推倒重做?将清空当前分镜与素材,重新拆分镜(生成后仍可先确认再继续)。',
+ )
+ )
+ return
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.generate(project.id, { restart: true }))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '重做失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function deleteProject() {
+ if (!project) return
+ if (!window.confirm('确定删除该项目?素材与成片将一并清除。')) return
+ setBusy(true)
+ try {
+ await api.deleteProject(project.id)
+ nav('/history')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '删除失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function composeOnly() {
+ if (!project) return
+ setBusy(true)
+ try {
+ setProject(await api.compose(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '合成失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function onCoverFile(file: File | null) {
+ if (!project || !file) return
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.uploadCover(project.id, file))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '封面上传失败')
+ } finally {
+ setBusy(false)
+ if (coverInputRef.current) coverInputRef.current.value = ''
+ }
+ }
+
+ async function useFirstShotCover() {
+ if (!project) return
+ const first = [...(project.shots || [])]
+ .sort((a, b) => a.shot_no - b.shot_no)
+ .find((s) => s.image_url)
+ if (!first?.image_url) {
+ setError('暂无可用镜头画面')
+ return
+ }
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.updateProject(project.id, { cover_url: first.image_url }))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '设置封面失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ function openBatchAdjust() {
+ if (!project) return
+ setBatchSelected((project.shots || []).map((s) => s.id))
+ setBatchDuration('')
+ setBatchRegenAudio(false)
+ setBatchOpen(true)
+ }
+
+ async function applyBatchAdjust() {
+ if (!project || batchSelected.length === 0) return
+ const durationVal = batchDuration.trim() === '' ? null : Number(batchDuration)
+ if (durationVal != null && (!Number.isFinite(durationVal) || durationVal <= 0)) {
+ setError('请输入有效时长(秒)')
+ return
+ }
+ if (durationVal == null && !batchRegenAudio) {
+ setError('请设置时长,或勾选重配音')
+ return
+ }
+ setBusy(true)
+ setError('')
+ try {
+ for (const shotId of batchSelected) {
+ if (durationVal != null) {
+ await api.updateShot(project.id, shotId, { duration: durationVal })
+ }
+ if (batchRegenAudio) {
+ await api.regenAudio(project.id, shotId)
+ }
+ }
+ setProject(await api.getProject(project.id))
+ setBatchOpen(false)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '批量调整失败')
+ try {
+ setProject(await api.getProject(project.id))
+ } catch {
+ /* ignore */
+ }
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function publish() {
+ if (!project) return
+ setBusy(true)
+ try {
+ await api.publish(project.id)
+ nav('/history')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '发布失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function regenImage(shot: Shot) {
+ if (!project) return
+ setBusy(true)
+ try {
+ await api.regenImage(project.id, shot.id)
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '重绘失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function regenVideo(shot: Shot) {
+ if (!project) return
+ setBusy(true)
+ try {
+ await api.regenVideo(project.id, shot.id)
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '重生视频失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function regenAudio(shot: Shot) {
+ if (!project) return
+ setBusy(true)
+ try {
+ await api.regenAudio(project.id, shot.id)
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '重配音失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ function openShotEdit(shot: Shot, focus = '') {
+ setEditFocus(focus)
+ setEditing({ ...shot })
+ setMenuShotId(null)
+ }
+
+ async function saveShot() {
+ if (!project || !editing) return
+ setBusy(true)
+ try {
+ await api.updateShot(project.id, editing.id, {
+ narration: editing.narration,
+ overlay_title: editing.overlay_title,
+ overlay_subtitle: editing.overlay_subtitle,
+ img_prompt: editing.img_prompt,
+ video_prompt: editing.video_prompt,
+ duration: Number(editing.duration) || 4,
+ camera: editing.camera,
+ })
+ setEditing(null)
+ setEditFocus('')
+ setProject(await api.getProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '保存失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function saveProjectPrompts() {
+ if (!project || !promptEdit) return
+ setBusy(true)
+ try {
+ const updated = await api.updateProject(project.id, {
+ style_prompt: promptEdit.style_prompt,
+ character_prompt: promptEdit.character_prompt,
+ extra_prompt: promptEdit.extra_prompt,
+ })
+ setProject(updated)
+ setPromptEdit(null)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '保存提示词失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ if (!project && !error) {
+ return (
+ <AppShell active="studio">
+ <p className="pf-muted">加载中…</p>
+ </AppShell>
+ )
+ }
+
+ if (!project) {
+ return (
+ <AppShell active="studio">
+ <p className="pf-error">{error}</p>
+ </AppShell>
+ )
+ }
+
+ const structure = (project.shots || []).slice(0, 5).map((s, i) => {
+ const labels = ['开端', '发展', '转折', '高潮', '结局']
+ return { label: labels[i] || `段落 ${i + 1}`, text: s.narration || s.overlay_title || '—' }
+ })
+
+ return (
+ <AppShell active="studio" wide>
+ <header className="pf-page-head">
+ <div className="pf-page-head-row">
+ <div>
+ <button type="button" className="pf-back" onClick={() => nav(`/studio/${project.id}/style`)}>
+ <IconChevronLeft size={18} />
+ AI 生成故事板 / 分镜工作台
+ </button>
+ <h1 className="pf-page-title">{project.title}</h1>
+ </div>
+ <div className="pf-toolbar">
+ {primaryAction === 'preview' ? (
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm pf-btn-icon"
+ disabled={busy || !hasFinal}
+ onClick={openFinalPreview}
+ >
+ <IconMonitor size={14} />
+ 预览成片
+ </button>
+ ) : primaryAction === 'compose' ? (
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm pf-btn-icon"
+ disabled={busy || running}
+ onClick={composeOnly}
+ >
+ <IconPlay size={14} />
+ 合成成片
+ </button>
+ ) : (
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm pf-btn-icon"
+ disabled={busy || running}
+ onClick={continueGenerate}
+ >
+ <IconPlay size={14} />
+ {generateLabel}
+ </button>
+ )}
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={busy || running || shots.length === 0}
+ onClick={openBatchAdjust}
+ >
+ <IconSliders size={15} />
+ 批量调整
+ </button>
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={busy || running}
+ onClick={restartGenerate}
+ >
+ <IconRefresh size={15} />
+ 推倒重做
+ </button>
+ {primaryAction !== 'preview' && hasFinal ? (
+ <button type="button" className="pf-btn-text" onClick={openFinalPreview}>
+ <IconMonitor size={15} />
+ 预览成片
+ </button>
+ ) : null}
+ {primaryAction === 'preview' && readyToCompose ? (
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={busy || running}
+ onClick={composeOnly}
+ title="用当前分镜重新合成"
+ >
+ 重新合成
+ </button>
+ ) : null}
+ {primaryAction !== 'generate' && !readyToCompose ? (
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={busy || running}
+ onClick={continueGenerate}
+ >
+ {generateLabel === '生成中…' ? '继续生成' : generateLabel}
+ </button>
+ ) : null}
+ <button
+ type="button"
+ className="pf-btn pf-btn-outline pf-btn-sm pf-btn-icon"
+ onClick={() => nav(`/studio/${project.id}/editor`)}
+ >
+ <IconEdit size={14} />
+ 打开编辑器
+ </button>
+ </div>
+ </div>
+ <Stepper steps={BOARD_STEPS} current={step} doneThrough={Math.max(0, step - 1)} />
+ </header>
+
+ {error ? <p className="pf-error">{error}</p> : null}
+ {project.error_msg ? <p className="pf-error">{project.error_msg}</p> : null}
+
+ <div className="pf-board">
+ <aside className="pf-create-col">
+ <h3>项目设置</h3>
+ {(project.cover_url || template?.preview_cover) ? (
+ <img
+ src={api.assetUrl(project.cover_url || template?.preview_cover)}
+ alt=""
+ style={{ width: '100%', borderRadius: 12, aspectRatio: '16/10', objectFit: 'cover' }}
+ />
+ ) : (
+ <div
+ style={{
+ width: '100%',
+ aspectRatio: '16/10',
+ borderRadius: 12,
+ background: '#e8eaee',
+ display: 'grid',
+ placeItems: 'center',
+ color: 'var(--pf-muted)',
+ }}
+ >
+ <IconImage size={28} />
+ </div>
+ )}
+ <input
+ ref={coverInputRef}
+ type="file"
+ accept="image/jpeg,image/png,image/webp,image/gif"
+ hidden
+ onChange={(e) => onCoverFile(e.target.files?.[0] || null)}
+ />
+ <div className="pf-side-actions">
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon"
+ disabled={busy || running}
+ onClick={() => coverInputRef.current?.click()}
+ >
+ <IconImage size={14} />
+ 更换封面
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon"
+ disabled={busy || running || !shots.some((s) => s.image_url)}
+ onClick={useFirstShotCover}
+ title="使用第一个有画面的镜头作为封面"
+ >
+ <IconImage size={14} />
+ 用首镜封面
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon"
+ disabled={shots.length === 0}
+ onClick={() => downloadStoryboardCsv(project)}
+ >
+ <IconDownload size={14} />
+ 草稿导出
+ </button>
+ </div>
+ <ul className="pf-meta-list" style={{ marginTop: '0.85rem' }}>
+ <li>
+ <span>项目名称</span>
+ <span>{project.title}</span>
+ </li>
+ <li>
+ <span>状态</span>
+ <span>{STATUS_CN[project.status] || project.status}</span>
+ </li>
+ <li>
+ <span>进度</span>
+ <span>{project.progress}%</span>
+ </li>
+ <li>
+ <span>时长</span>
+ <span>
+ {Math.floor(totalDuration / 60)
+ .toString()
+ .padStart(2, '0')}
+ :
+ {Math.floor(totalDuration % 60)
+ .toString()
+ .padStart(2, '0')}
+ </span>
+ </li>
+ <li>
+ <span>画面比例</span>
+ <span>{project.output_ratio || (project.pipeline_mode === 'image_text' ? '9:16' : '16:9')}</span>
+ </li>
+ <li>
+ <span>成片方式</span>
+ <span>{project.pipeline_mode === 'image_text' ? '静图成片' : 'AI 视频'}</span>
+ </li>
+ <li>
+ <span>风格</span>
+ <span>{template?.name || project.template_id}</span>
+ </li>
+ </ul>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-block pf-btn-sm"
+ onClick={() => nav(`/studio/${project.id}/style`)}
+ disabled={running}
+ >
+ 编辑项目设置
+ </button>
+ <div className="pf-prompt-panel">
+ <h4>内置提示词</h4>
+ <p className="pf-muted" style={{ fontSize: '0.72rem', margin: '0 0 0.45rem' }}>
+ 点击可查看并修改,影响后续重生成
+ </p>
+ {(
+ [
+ ['风格', project.style_prompt],
+ ['角色', project.character_prompt],
+ ['额外', project.extra_prompt],
+ ] as const
+ ).map(([label, value]) => (
+ <button
+ key={label}
+ type="button"
+ className="pf-prompt-chip"
+ disabled={busy || running}
+ onClick={() =>
+ setPromptEdit({
+ style_prompt: project.style_prompt || '',
+ character_prompt: project.character_prompt || '',
+ extra_prompt: project.extra_prompt || '',
+ })
+ }
+ >
+ <strong>{label}</strong>
+ <span>{(value || '').trim() || '(空,点击编辑)'}</span>
+ </button>
+ ))}
+ </div>
+ <p className="pf-muted" style={{ fontSize: '0.75rem', marginTop: '0.75rem' }}>
+ 内容由 AI 生成,请注意核对准确性
+ </p>
+ </aside>
+
+ <div className="pf-board-main">
+ <div className="pf-outline-grid">
+ <article className="pf-create-col">
+ <h3>AI 生成大纲</h3>
+ <p style={{ margin: 0, fontSize: '0.9rem', lineHeight: 1.65 }}>
+ {project.source_text}
+ </p>
+ <div className="pf-tags">
+ <span>核心主题</span>
+ <span>{project.source_type === 'script' ? '完整文案' : '一句话主题'}</span>
+ </div>
+ </article>
+ <article className="pf-create-col">
+ <h3>
+ 结构摘要 <ComingSoon label="示例聚合" />
+ </h3>
+ <ul className="pf-meta-list">
+ {structure.length ? (
+ structure.map((s) => (
+ <li key={s.label}>
+ <span>{s.label}</span>
+ <span style={{ maxWidth: '60%', textAlign: 'right' }}>{s.text.slice(0, 36)}</span>
+ </li>
+ ))
+ ) : (
+ <li>
+ <span>等待分镜</span>
+ <span>—</span>
+ </li>
+ )}
+ </ul>
+ </article>
+ </div>
+
+ <section className="pf-shot-card">
+ <div className="pf-shot-card-head">
+ <h3>分镜列表(共 {project.shots.length} 个场景)</h3>
+ <div className="pf-toolbar">
+ {project.status === 'DONE' && hasFinal ? (
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled={busy} onClick={publish}>
+ 发布
+ </button>
+ ) : null}
+ {hasFinal ? (
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={openFinalPreview}>
+ 预览成片
+ </button>
+ ) : (
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm"
+ disabled={busy || running || !readyToCompose}
+ onClick={composeOnly}
+ >
+ 合成成片
+ </button>
+ )}
+ </div>
+ </div>
+ {project.shots.length === 0 ? (
+ <p className="pf-muted" style={{ margin: '1.5rem 0', textAlign: 'center' }}>
+ {running
+ ? '正在拆分镜…'
+ : '暂无分镜。从风格配置页开始生成后,可先确认修改,再手动开始画面生成。'}
+ </p>
+ ) : needsScriptConfirm ? (
+ <p className="pf-muted" style={{ margin: '0 0 1rem' }}>
+ 分镜已就绪,请先检查旁白与画面描述,确认无误后点击「确认分镜,开始生成」。
+ </p>
+ ) : null}
+ {project.shots.length === 0 ? null : (
+ <div className="pf-shot-table-wrap">
+ <table className="pf-shot-table">
+ <thead>
+ <tr>
+ <th>场景</th>
+ <th>画面</th>
+ <th>旁白/台词</th>
+ <th>画面描述</th>
+ <th>时长</th>
+ <th>状态</th>
+ <th>操作</th>
+ </tr>
+ </thead>
+ <tbody>
+ {project.shots.map((shot) => {
+ // Full pipeline: shot is "done" only after AI video (or privacy skip left image-only while project advanced)
+ const done = isFullPipeline
+ ? Boolean(shot.video_url) || shot.status === 'VIDEO_READY'
+ : shotIsDone(shot.status) || Boolean(shot.image_url)
+ const failed = shot.status === 'FAILED'
+ const sceneTitle =
+ shot.overlay_title?.trim() || `场景 ${String(shot.shot_no).padStart(2, '0')}`
+ const narration = (shot.narration || '').trim()
+ const desc = scenePromptForDisplay(shot.img_prompt).trim()
+ return (
+ <tr key={shot.id}>
+ <td className="col-no">{String(shot.shot_no).padStart(2, '0')}</td>
+ <td className="col-thumb">
+ <button
+ type="button"
+ className="pf-shot-thumb-btn"
+ onClick={() =>
+ setPreview({
+ kind: 'shot',
+ shotNo: shot.shot_no,
+ imageUrl: shot.image_url,
+ videoUrl: shot.video_url,
+ audioUrl: shot.audio_url,
+ caption: shotCaption(shot),
+ })
+ }
+ >
+ {shot.image_url ? (
+ <img
+ className="pf-shot-thumb"
+ src={api.assetUrl(shot.image_url, shot.version)}
+ alt=""
+ />
+ ) : (
+ <div className="pf-shot-thumb empty">生成中</div>
+ )}
+ </button>
+ </td>
+ <td>
+ <button
+ type="button"
+ className="pf-shot-narration pf-shot-editable"
+ disabled={busy || running}
+ title="点击编辑旁白与标题"
+ onClick={() => openShotEdit(shot, 'narration')}
+ >
+ <span className="title">{sceneTitle}</span>
+ <span className="line">
+ {narration ? `“${narration}”` : '—'}
+ </span>
+ </button>
+ </td>
+ <td>
+ <button
+ type="button"
+ className="pf-shot-desc pf-shot-editable"
+ disabled={busy || running}
+ title="点击查看/修改画面提示词"
+ onClick={() => openShotEdit(shot, 'img_prompt')}
+ >
+ {desc || '(点击填写画面提示词)'}
+ </button>
+ </td>
+ <td className="col-dur">{formatMmSs(shot.duration)}</td>
+ <td className="col-status">
+ <span
+ className={[
+ 'pf-shot-status',
+ failed ? 'bad' : done ? '' : 'warn',
+ ]
+ .filter(Boolean)
+ .join(' ')}
+ >
+ {done && !failed ? <span className="mark">✓</span> : null}
+ {shotStatusLabel(shot.status)}
+ </span>
+ </td>
+ <td className="col-ops">
+ <div className="pf-shot-ops">
+ <button
+ type="button"
+ className="op"
+ disabled={busy || running}
+ onClick={() => openShotEdit(shot)}
+ >
+ 编辑
+ </button>
+ <button
+ type="button"
+ className="op"
+ disabled={busy || running}
+ onClick={() => regenImage(shot)}
+ >
+ 重生成
+ </button>
+ <button
+ type="button"
+ className="op"
+ disabled={busy || running}
+ onClick={() => regenImage(shot)}
+ >
+ 替换画面
+ </button>
+ <button
+ type="button"
+ className="more"
+ aria-label="更多操作"
+ disabled={busy || running}
+ onClick={(e) => {
+ e.stopPropagation()
+ setMenuShotId((id) => (id === shot.id ? null : shot.id))
+ }}
+ >
+ ⋮
+ </button>
+ {menuShotId === shot.id ? (
+ <div className="pf-shot-menu" onClick={(e) => e.stopPropagation()}>
+ {project.pipeline_mode !== 'image_text' ? (
+ <button
+ type="button"
+ disabled={busy || running}
+ onClick={() => {
+ setMenuShotId(null)
+ regenVideo(shot)
+ }}
+ >
+ 重生视频
+ </button>
+ ) : null}
+ <button
+ type="button"
+ disabled={busy || running}
+ onClick={() => {
+ setMenuShotId(null)
+ regenAudio(shot)
+ }}
+ >
+ 重配音
+ </button>
+ </div>
+ ) : null}
+ </div>
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+ <div className="pf-shot-footer">
+ <span className="pf-muted" style={{ fontSize: '0.82rem' }}>
+ 总时长: {formatMmSs(totalDuration)} | 画面: {project.shots.length} 个 | 音频:{' '}
+ {project.shots.filter((s) => s.audio_url).length} 段 | 分辨率: 预览
+ </span>
+ <div className="pf-toolbar">
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon"
+ disabled={shots.length === 0}
+ onClick={() => downloadStoryboardCsv(project)}
+ >
+ <IconDownload size={15} />
+ 导出分镜脚本
+ </button>
+ <button
+ type="button"
+ className="pf-btn-text"
+ disabled={busy || running}
+ onClick={deleteProject}
+ >
+ <IconTrash size={15} />
+ 删除项目
+ </button>
+ </div>
+ </div>
+ </section>
+ </div>
+
+ <aside className="pf-create-col">
+ <h3>生成进度</h3>
+ <ul className="pf-progress-list">
+ {progressItems.map((item) => (
+ <li key={item.label}>
+ <span>{item.label}</span>
+ <span>
+ {item.done ? (
+ <span className="pf-check">✓</span>
+ ) : item.run ? (
+ `${item.pct ?? 0}%`
+ ) : (
+ '…'
+ )}
+ </span>
+ </li>
+ ))}
+ </ul>
+ <div className="pf-meter" style={{ marginTop: '1rem' }}>
+ <i style={{ width: `${Math.min(100, project.progress)}%` }} />
+ </div>
+ <p className="pf-muted" style={{ fontSize: '0.82rem' }}>
+ {STATUS_CN[project.status] || project.status}
+ </p>
+ </aside>
+ </div>
+
+ {batchOpen && project ? (
+ <div className="modal-backdrop" onClick={() => !busy && setBatchOpen(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <h3>批量调整分镜</h3>
+ <p className="pf-muted" style={{ marginTop: 0 }}>
+ 已选 {batchSelected.length} / {project.shots.length} 个镜头
+ </p>
+ <div
+ style={{
+ maxHeight: 160,
+ overflow: 'auto',
+ border: '1px solid var(--pf-border, #e5e7eb)',
+ borderRadius: 10,
+ padding: '0.5rem 0.75rem',
+ marginBottom: '0.75rem',
+ }}
+ >
+ <label style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
+ <input
+ type="checkbox"
+ checked={batchSelected.length === project.shots.length && project.shots.length > 0}
+ onChange={(e) =>
+ setBatchSelected(e.target.checked ? project.shots.map((s) => s.id) : [])
+ }
+ />
+ 全选
+ </label>
+ {project.shots
+ .slice()
+ .sort((a, b) => a.shot_no - b.shot_no)
+ .map((s) => (
+ <label
+ key={s.id}
+ style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}
+ >
+ <input
+ type="checkbox"
+ checked={batchSelected.includes(s.id)}
+ onChange={(e) =>
+ setBatchSelected((prev) =>
+ e.target.checked ? [...prev, s.id] : prev.filter((id) => id !== s.id),
+ )
+ }
+ />
+ 镜头 {String(s.shot_no).padStart(2, '0')} · {formatMmSs(Number(s.duration) || 0)}
+ </label>
+ ))}
+ </div>
+ <label>
+ 统一时长(秒,留空则不改)
+ <input
+ type="number"
+ min={1}
+ step={0.5}
+ placeholder="例如 6"
+ value={batchDuration}
+ onChange={(e) => setBatchDuration(e.target.value)}
+ />
+ </label>
+ <label style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <input
+ type="checkbox"
+ checked={batchRegenAudio}
+ onChange={(e) => setBatchRegenAudio(e.target.checked)}
+ />
+ 对所选镜头重新配音
+ </label>
+ <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.75rem' }}>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime"
+ disabled={busy || batchSelected.length === 0}
+ onClick={applyBatchAdjust}
+ >
+ 应用
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost"
+ disabled={busy}
+ onClick={() => setBatchOpen(false)}
+ >
+ 取消
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+
+ {editing ? (
+ <div
+ className="modal-backdrop"
+ onClick={() => {
+ setEditing(null)
+ setEditFocus('')
+ }}
+ >
+ <div className="modal pf-prompt-modal" onClick={(e) => e.stopPropagation()}>
+ <h3>编辑镜头 {editing.shot_no} · 提示词</h3>
+ <label>
+ 镜头标题
+ <input
+ autoFocus={editFocus === 'title'}
+ value={editing.overlay_title || ''}
+ onChange={(e) => setEditing({ ...editing, overlay_title: e.target.value })}
+ />
+ </label>
+ <label>
+ 副标题
+ <input
+ value={editing.overlay_subtitle || ''}
+ onChange={(e) => setEditing({ ...editing, overlay_subtitle: e.target.value })}
+ />
+ </label>
+ <label>
+ 旁白
+ <textarea
+ autoFocus={editFocus === 'narration'}
+ value={editing.narration}
+ onChange={(e) => setEditing({ ...editing, narration: e.target.value })}
+ rows={3}
+ />
+ </label>
+ <label>
+ 画面提示词
+ <textarea
+ autoFocus={editFocus === 'img_prompt' || editFocus === ''}
+ value={editing.img_prompt}
+ onChange={(e) => setEditing({ ...editing, img_prompt: e.target.value })}
+ rows={4}
+ />
+ </label>
+ <label>
+ 视频提示词
+ <textarea
+ value={editing.video_prompt || ''}
+ onChange={(e) => setEditing({ ...editing, video_prompt: e.target.value })}
+ rows={2}
+ />
+ </label>
+ <div className="pf-prompt-modal-row">
+ <label>
+ 时长(秒)
+ <input
+ type="number"
+ value={editing.duration}
+ onChange={(e) => setEditing({ ...editing, duration: Number(e.target.value) })}
+ />
+ </label>
+ <label>
+ 运镜
+ <input
+ value={editing.camera || ''}
+ onChange={(e) => setEditing({ ...editing, camera: e.target.value })}
+ />
+ </label>
+ </div>
+ <div style={{ display: 'flex', gap: '0.5rem' }}>
+ <button type="button" className="pf-btn pf-btn-lime" disabled={busy} onClick={saveShot}>
+ 保存
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost"
+ onClick={() => {
+ setEditing(null)
+ setEditFocus('')
+ }}
+ >
+ 取消
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+
+ {promptEdit ? (
+ <div className="modal-backdrop" onClick={() => setPromptEdit(null)}>
+ <div className="modal pf-prompt-modal" onClick={(e) => e.stopPropagation()}>
+ <h3>项目内置提示词</h3>
+ <p className="pf-muted" style={{ fontSize: '0.8rem', marginTop: 0 }}>
+ 修改后对后续「重生成画面/视频」生效;已生成的镜头需点重生成才会更新。
+ </p>
+ <label>
+ 风格提示词
+ <textarea
+ value={promptEdit.style_prompt}
+ onChange={(e) => setPromptEdit({ ...promptEdit, style_prompt: e.target.value })}
+ rows={3}
+ />
+ </label>
+ <label>
+ 角色提示词
+ <textarea
+ autoFocus
+ value={promptEdit.character_prompt}
+ onChange={(e) => setPromptEdit({ ...promptEdit, character_prompt: e.target.value })}
+ rows={3}
+ />
+ </label>
+ <label>
+ 额外要求
+ <textarea
+ value={promptEdit.extra_prompt}
+ onChange={(e) => setPromptEdit({ ...promptEdit, extra_prompt: e.target.value })}
+ rows={2}
+ />
+ </label>
+ <div style={{ display: 'flex', gap: '0.5rem' }}>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime"
+ disabled={busy}
+ onClick={saveProjectPrompts}
+ >
+ 保存
+ </button>
+ <button type="button" className="pf-btn pf-btn-ghost" onClick={() => setPromptEdit(null)}>
+ 取消
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+
+ {preview ? (
+ <div className="modal-backdrop" onClick={() => setPreview(null)}>
+ <div className="modal preview-modal" onClick={(e) => e.stopPropagation()}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <h3 style={{ margin: 0 }}>
+ {preview.kind === 'final' ? preview.title : `镜头 ${preview.shotNo}`}
+ </h3>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => setPreview(null)}>
+ 关闭
+ </button>
+ </div>
+ {preview.kind === 'final' ? (
+ <video className="preview-media" src={preview.url} controls autoPlay />
+ ) : preview.videoUrl ? (
+ <video
+ className="preview-media"
+ src={api.assetUrl(preview.videoUrl)}
+ poster={preview.imageUrl ? api.assetUrl(preview.imageUrl) : undefined}
+ controls
+ autoPlay
+ />
+ ) : preview.imageUrl ? (
+ <img className="preview-media" src={api.assetUrl(preview.imageUrl)} alt="" />
+ ) : (
+ <p className="pf-muted">暂无预览</p>
+ )}
+ {preview.kind === 'shot' && preview.audioUrl ? (
+ <audio src={api.assetUrl(preview.audioUrl)} controls style={{ width: '100%' }} />
+ ) : null}
+ {preview.kind === 'shot' ? <p className="pf-muted">{preview.caption}</p> : null}
+ </div>
+ </div>
+ ) : null}
+ </AppShell>
+ )
+}
diff --git a/frontend/src/pages/studio/StyleConfigPage.tsx b/frontend/src/pages/studio/StyleConfigPage.tsx
new file mode 100644
index 0000000..9d00f4c
--- /dev/null
+++ b/frontend/src/pages/studio/StyleConfigPage.tsx
@@ -0,0 +1,557 @@
+import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
+import { useNavigate, useParams } from 'react-router-dom'
+import { api, defaultsFromTemplate } from '../../api'
+import type { PipelineMode, Project, Template, VoicePreset } from '../../api'
+import AppShell from '../../components/layout/AppShell'
+import Stepper from '../../components/ui/Stepper'
+import ComingSoon from '../../components/ui/ComingSoon'
+import { IconChevronLeft, IconPlay } from '../../components/ui/Icons'
+import { CREATE_STEPS } from '../../lib/status'
+
+const CHAR_PRESETS = [
+ {
+ id: 'real',
+ label: '写实人物',
+ desc: '真实人物质感',
+ image: '/char-presets/real.jpg',
+ promptHint: '写实人物操作电脑或系统界面,侧脸或过肩视角,手部与屏幕清晰',
+ },
+ {
+ id: 'anime',
+ label: '动漫角色',
+ desc: '二次元形象',
+ image: '/char-presets/anime.jpg',
+ promptHint: '动漫风格角色在工位前操作系统,造型简洁统一',
+ },
+ {
+ id: 'sil',
+ label: '剪影',
+ desc: '抽象剪影表达',
+ image: '/char-presets/sil.jpg',
+ promptHint: '剪影人物操作系统界面,抽象轮廓,信息层级清晰',
+ },
+ {
+ id: 'none',
+ label: '无角色',
+ desc: '纯场景解说',
+ image: '/char-presets/none.jpg',
+ promptHint: '无人物角色,专注产品界面、文档与架构示意',
+ },
+]
+
+const OUTPUT_MODES: { id: PipelineMode; label: string; desc: string; image: string }[] = [
+ { id: 'full', label: 'AI 视频', desc: '图→视频→配音→合成', image: '/mode-presets/full.jpg' },
+ {
+ id: 'image_text',
+ label: '静图成片',
+ desc: '静图+叠字+配音,不生成 AI 视频',
+ image: '/mode-presets/image_text.jpg',
+ },
+]
+
+const RATIOS: { id: string; label: string; w: number; h: number }[] = [
+ { id: '16:9', label: '16:9', w: 36, h: 20 },
+ { id: '9:16', label: '9:16', w: 18, h: 32 },
+ { id: '1:1', label: '1:1', w: 24, h: 24 },
+ { id: '4:3', label: '4:3', w: 28, h: 21 },
+ { id: '21:9', label: '21:9', w: 40, h: 17 },
+]
+
+export default function StyleConfigPage() {
+ const { id } = useParams()
+ const projectId = Number(id)
+ const nav = useNavigate()
+ const [project, setProject] = useState<Project | null>(null)
+ const [templates, setTemplates] = useState<Template[]>([])
+ const [voices, setVoices] = useState<VoicePreset[]>([])
+ const [stylePrompt, setStylePrompt] = useState('')
+ const [characterPrompt, setCharacterPrompt] = useState('')
+ const [extraPrompt, setExtraPrompt] = useState('')
+ const [voiceId, setVoiceId] = useState('')
+ const [pipelineMode, setPipelineMode] = useState<PipelineMode>('full')
+ const [ratio, setRatio] = useState('16:9')
+ const [charPreset, setCharPreset] = useState('real')
+ const [busy, setBusy] = useState(false)
+ const [previewBusy, setPreviewBusy] = useState<string | null>(null)
+ const [playingId, setPlayingId] = useState<string | null>(null)
+ const [error, setError] = useState('')
+ const audioRef = useRef<HTMLAudioElement | null>(null)
+
+ useEffect(() => {
+ if (!localStorage.getItem('token')) {
+ nav('/auth')
+ return
+ }
+ if (!projectId) {
+ nav('/studio/new')
+ }
+ api.templates().then(setTemplates)
+ api.voices().then(setVoices)
+ api
+ .getProject(projectId)
+ .then((p) => {
+ setProject(p)
+ setStylePrompt(p.style_prompt || '')
+ setCharacterPrompt(p.character_prompt || '')
+ setExtraPrompt(p.extra_prompt || '')
+ setVoiceId(p.voice_id || '')
+ setPipelineMode(p.pipeline_mode || 'full')
+ setRatio(p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9'))
+ })
+ .catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ }, [nav, projectId])
+
+ useEffect(() => {
+ return () => {
+ audioRef.current?.pause()
+ audioRef.current = null
+ }
+ }, [])
+
+ const currentTpl = useMemo(
+ () => templates.find((t) => t.id === project?.template_id),
+ [templates, project?.template_id],
+ )
+
+ const styleOptions = useMemo(() => templates.slice(0, 6), [templates])
+ const selectedVoice = voices.find((v) => v.speaker === voiceId || v.id === voiceId)
+
+ useEffect(() => {
+ if (!project || !currentTpl) return
+ if (!stylePrompt && !characterPrompt) {
+ const d = defaultsFromTemplate(currentTpl)
+ setStylePrompt((v) => v || d.style_prompt)
+ setCharacterPrompt((v) => v || d.character_prompt)
+ setExtraPrompt((v) => v || d.extra_prompt)
+ setVoiceId((v) => v || d.voice_id)
+ }
+ }, [project, currentTpl])
+
+ useEffect(() => {
+ if (!project || project.output_ratio || !currentTpl?.default_ratio) return
+ setRatio(currentTpl.default_ratio)
+ }, [project?.id, project?.output_ratio, currentTpl?.default_ratio])
+
+ function pickStyle(t: Template) {
+ const d = defaultsFromTemplate(t)
+ setStylePrompt(d.style_prompt)
+ setCharacterPrompt(d.character_prompt)
+ setExtraPrompt(d.extra_prompt)
+ setVoiceId(d.voice_id)
+ // Keep user's video-mode choice; only suggest template default ratio if untouched
+ setRatio((prev) => prev || d.output_ratio)
+ if (/无人物|无角色/.test(d.character_prompt)) setCharPreset('none')
+ else if (/剪影/.test(d.character_prompt)) setCharPreset('sil')
+ else if (/动漫|二次元/.test(d.character_prompt)) setCharPreset('anime')
+ else setCharPreset('real')
+ if (project) {
+ api
+ .updateProject(project.id, {
+ template_id: t.id,
+ style_prompt: d.style_prompt,
+ character_prompt: d.character_prompt || characterPrompt,
+ extra_prompt: d.extra_prompt,
+ voice_id: d.voice_id,
+ })
+ .then(setProject)
+ .catch((err) => setError(err instanceof Error ? err.message : '更新失败'))
+ }
+ }
+
+ function pickRatio(r: (typeof RATIOS)[0]) {
+ setRatio(r.id)
+ }
+
+ function stopPreview() {
+ audioRef.current?.pause()
+ audioRef.current = null
+ setPlayingId(null)
+ }
+
+ async function previewVoice(v: VoicePreset, e: MouseEvent) {
+ e.stopPropagation()
+ const vid = v.speaker || v.id
+ setVoiceId(vid)
+ setError('')
+
+ if (playingId === vid && audioRef.current && !audioRef.current.paused) {
+ stopPreview()
+ return
+ }
+
+ stopPreview()
+ setPreviewBusy(vid)
+ try {
+ const res = await api.previewVoice(vid)
+ const url = api.assetUrl(res.url)
+ const audio = new Audio(url)
+ audioRef.current = audio
+ audio.onended = () => setPlayingId(null)
+ audio.onerror = () => {
+ setPlayingId(null)
+ setError('试听播放失败')
+ }
+ setPlayingId(vid)
+ await audio.play()
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '试听失败')
+ setPlayingId(null)
+ } finally {
+ setPreviewBusy(null)
+ }
+ }
+
+ async function generate() {
+ if (!project) return
+ stopPreview()
+ setBusy(true)
+ setError('')
+ try {
+ const charNote =
+ charPreset === 'none'
+ ? '无人物角色,侧重场景与信息图表。'
+ : charPreset === 'anime'
+ ? '角色偏动漫造型。'
+ : charPreset === 'sil'
+ ? '角色以剪影呈现。'
+ : ''
+ await api.updateProject(project.id, {
+ style_prompt: stylePrompt,
+ character_prompt: [characterPrompt, charNote].filter(Boolean).join('\n'),
+ extra_prompt: extraPrompt,
+ voice_id: voiceId,
+ pipeline_mode: pipelineMode,
+ output_ratio: ratio,
+ })
+ const started = await api.generate(project.id)
+ nav(`/studio/${started.id}`)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '生成失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ if (!project && !error) {
+ return (
+ <AppShell active="studio">
+ <p className="pf-muted">加载中…</p>
+ </AppShell>
+ )
+ }
+
+ return (
+ <AppShell active="studio" wide>
+ <header className="pf-page-head">
+ <div className="pf-page-head-row">
+ <div>
+ <button type="button" className="pf-back" onClick={() => nav('/studio/new')}>
+ <IconChevronLeft size={18} />
+ 返回创作台
+ </button>
+ <h1 className="pf-page-title">{project?.title || '风格配置'}</h1>
+ </div>
+ <Stepper steps={CREATE_STEPS} current={2} doneThrough={1} />
+ </div>
+ </header>
+
+ <div className="pf-style-layout">
+ <aside className="pf-create-col">
+ <h3>项目信息</h3>
+ {currentTpl ? (
+ <div>
+ <img
+ src={api.assetUrl(currentTpl.preview_cover)}
+ alt=""
+ style={{ width: '100%', borderRadius: 12, aspectRatio: '16/9', objectFit: 'cover' }}
+ />
+ <p style={{ margin: '0.5rem 0 0', fontWeight: 600 }}>{currentTpl.name}</p>
+ <div className="pf-tags">
+ {currentTpl.category.map((c) => (
+ <span key={c}>{c}</span>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ <ul className="pf-meta-list" style={{ marginTop: '0.85rem' }}>
+ <li>
+ <span>主题</span>
+ <span style={{ maxWidth: '55%', textAlign: 'right' }}>
+ {(project?.source_text || '').slice(0, 40)}
+ </span>
+ </li>
+ <li>
+ <span>时长</span>
+ <span>~1–3 分钟</span>
+ </li>
+ <li>
+ <span>分镜数</span>
+ <span>AI 自动</span>
+ </li>
+ </ul>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-block pf-btn-sm" disabled>
+ 预览模板 <ComingSoon />
+ </button>
+ </aside>
+
+ <section className="pf-create-col">
+ <div className="pf-style-block">
+ <h3>
+ 画面风格
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 更多风格 <ComingSoon />
+ </button>
+ </h3>
+ <div className="pf-style-grid">
+ {styleOptions.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ className={
+ project?.template_id === t.id ? 'pf-style-opt selected' : 'pf-style-opt'
+ }
+ onClick={() => pickStyle(t)}
+ >
+ <img src={api.assetUrl(t.preview_cover)} alt="" />
+ <div className="cap">{t.name}</div>
+ </button>
+ ))}
+ </div>
+ <label className="pf-field" style={{ marginTop: '0.75rem' }}>
+ <span className="pf-field-label">风格提示词</span>
+ <textarea
+ className="pf-field-input"
+ value={stylePrompt}
+ onChange={(e) => setStylePrompt(e.target.value)}
+ rows={2}
+ style={{ resize: 'vertical', minHeight: 64 }}
+ />
+ </label>
+ </div>
+
+ <div className="pf-style-block">
+ <h3>角色设定</h3>
+ <div className="pf-style-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
+ {CHAR_PRESETS.map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ className={charPreset === c.id ? 'pf-style-opt selected' : 'pf-style-opt'}
+ onClick={() => {
+ setCharPreset(c.id)
+ setCharacterPrompt(c.promptHint)
+ }}
+ >
+ <img src={c.image} alt="" />
+ <div className="cap">{c.label}</div>
+ <div className="cap-sub">{c.desc}</div>
+ </button>
+ ))}
+ </div>
+ <label className="pf-field" style={{ marginTop: '0.75rem' }}>
+ <span className="pf-field-label">角色描述</span>
+ <textarea
+ className="pf-field-input"
+ value={characterPrompt}
+ onChange={(e) => setCharacterPrompt(e.target.value)}
+ rows={2}
+ style={{ resize: 'vertical', minHeight: 64 }}
+ />
+ </label>
+ </div>
+
+ <div className="pf-style-block">
+ <h3>
+ 配音音色
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled>
+ 更多音色 <ComingSoon />
+ </button>
+ </h3>
+ <div className="pf-voice-row">
+ {voices.map((v) => {
+ const vid = v.speaker || v.id
+ const selected = voiceId === vid
+ const loading = previewBusy === vid
+ const playing = playingId === vid
+ return (
+ <div
+ key={v.id}
+ className={selected ? 'pf-voice-card selected' : 'pf-voice-card'}
+ role="button"
+ tabIndex={0}
+ onClick={() => setVoiceId(vid)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ setVoiceId(vid)
+ }
+ }}
+ >
+ <strong className="pf-voice-name">{v.label}</strong>
+ <span className="pf-voice-meta">
+ {v.gender === 'female' ? '女声' : v.gender === 'male' ? '男声' : v.gender}
+ </span>
+ <button
+ type="button"
+ className={[
+ 'pf-btn',
+ 'pf-btn-sm',
+ 'pf-btn-icon',
+ playing ? 'pf-btn-lime' : 'pf-btn-ghost',
+ 'pf-voice-preview',
+ ].join(' ')}
+ disabled={loading || busy}
+ onClick={(e) => previewVoice(v, e)}
+ >
+ {loading ? (
+ '生成中…'
+ ) : playing ? (
+ '播放中'
+ ) : (
+ <>
+ <IconPlay size={12} />
+ 试听
+ </>
+ )}
+ </button>
+ </div>
+ )
+ })}
+ </div>
+ {selectedVoice ? (
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0.55rem 0 0' }}>
+ 当前:{selectedVoice.label} · 点击「试听」可听约 5 秒样例
+ </p>
+ ) : null}
+ </div>
+
+ <div className="pf-style-block">
+ <h3>
+ 背景音乐 <ComingSoon />
+ </h3>
+ <div className="pf-bgm-card">
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon" disabled>
+ <IconPlay size={14} />
+ </button>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <strong style={{ fontSize: '0.9rem' }}>星际远航</strong>
+ <div className="pf-bgm-wave" />
+ </div>
+ <span className="pf-muted">02:28</span>
+ </div>
+ </div>
+
+ <div className="pf-style-block">
+ <h3>
+ 字幕样式 <ComingSoon />
+ </h3>
+ <div className="pf-hint">字体、字号、对齐与颜色工具条将在成片编辑器中提供。</div>
+ </div>
+
+ <div className="pf-style-block">
+ <h3>成片方式</h3>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0 0 0.65rem' }}>
+ 任意模板都可选择是否生成 AI 视频,与画幅无关。
+ </p>
+ <div className="pf-style-grid" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
+ {OUTPUT_MODES.map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ className={pipelineMode === m.id ? 'pf-style-opt selected' : 'pf-style-opt'}
+ onClick={() => setPipelineMode(m.id)}
+ >
+ <img src={m.image} alt="" />
+ <div className="cap">{m.label}</div>
+ <div className="cap-sub">{m.desc}</div>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="pf-style-block">
+ <h3>输出比例</h3>
+ <div className="pf-ratio-row">
+ {RATIOS.map((r) => (
+ <button
+ key={r.id}
+ type="button"
+ className={ratio === r.id ? 'pf-ratio selected' : 'pf-ratio'}
+ onClick={() => pickRatio(r)}
+ >
+ <div className="box" style={{ width: r.w, height: r.h }} />
+ {r.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ {error ? <p className="pf-error">{error}</p> : null}
+ </section>
+
+ <aside className="pf-create-col">
+ <h3>实时预览</h3>
+ <div className="pf-editor-preview" style={{ marginBottom: '0.85rem' }}>
+ {currentTpl ? (
+ <img src={api.assetUrl(currentTpl.preview_cover)} alt="" />
+ ) : (
+ <span>预览占位</span>
+ )}
+ </div>
+ <p className="pf-muted" style={{ fontSize: '0.8rem' }}>
+ 生成后可在分镜台查看真实画面。当前为模板预览。
+ </p>
+ <h3 style={{ marginTop: '1rem' }}>当前配置概览</h3>
+ <ul className="pf-meta-list">
+ <li>
+ <span>风格</span>
+ <span>{currentTpl?.name || '—'}</span>
+ </li>
+ <li>
+ <span>角色</span>
+ <span>{CHAR_PRESETS.find((c) => c.id === charPreset)?.label}</span>
+ </li>
+ <li>
+ <span>配音</span>
+ <span>{selectedVoice?.label || '默认'}</span>
+ </li>
+ <li>
+ <span>比例</span>
+ <span>{ratio}</span>
+ </li>
+ <li>
+ <span>成片</span>
+ <span>{pipelineMode === 'image_text' ? '静图成片' : 'AI 视频'}</span>
+ </li>
+ </ul>
+ {selectedVoice ? (
+ <button
+ type="button"
+ className="pf-btn pf-btn-ghost pf-btn-block pf-btn-sm pf-btn-icon"
+ style={{ marginTop: '0.75rem' }}
+ disabled={busy || previewBusy === (selectedVoice.speaker || selectedVoice.id)}
+ onClick={(e) => previewVoice(selectedVoice, e)}
+ >
+ <IconPlay size={14} />
+ {playingId === (selectedVoice.speaker || selectedVoice.id)
+ ? '停止试听'
+ : `试听「${selectedVoice.label}」`}
+ </button>
+ ) : null}
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-block pf-btn-lg pf-btn-icon"
+ style={{ marginTop: '0.75rem' }}
+ disabled={busy || Boolean(previewBusy)}
+ onClick={generate}
+ >
+ {busy ? '启动中…' : '生成故事板'}
+ {!busy ? <span aria-hidden>→</span> : null}
+ </button>
+ <p className="pf-muted" style={{ fontSize: '0.78rem', marginTop: '0.5rem' }}>
+ 先生成分镜脚本,确认修改后再手动开始出图与配音。
+ </p>
+ </aside>
+ </div>
+ </AppShell>
+ )
+}
diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.css
new file mode 100644
index 0000000..80ff924
--- /dev/null
+++ b/frontend/src/styles/printfilm.css
@@ -0,0 +1,2283 @@
+/* PRINTFILM SaaS shell & page layouts */
+
+.pf-shell {
+ min-height: 100vh;
+ background: var(--pf-bg);
+ color: var(--pf-ink);
+}
+
+.pf-shell-main {
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: 1.25rem 1.5rem 3.5rem;
+}
+
+.pf-shell-main.wide {
+ max-width: 1440px;
+}
+
+.pf-shell-main.flush {
+ max-width: none;
+ padding: 0;
+}
+
+/* ——— Nav ——— */
+.pf-nav {
+ position: sticky;
+ top: 0;
+ z-index: 40;
+ height: var(--pf-nav-h);
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ gap: 1rem;
+ padding: 0 1.5rem;
+ background: rgba(255, 255, 255, 0.92);
+ border-bottom: 1px solid var(--pf-line);
+ backdrop-filter: blur(10px);
+}
+
+.pf-nav-left {
+ justify-self: start;
+}
+
+.pf-nav-center {
+ display: flex;
+ gap: 1.5rem;
+ align-items: center;
+ font-size: 0.95rem;
+ font-weight: 500;
+ color: var(--pf-muted);
+}
+
+.pf-nav-center a {
+ position: relative;
+ padding: 0.35rem 0;
+ color: var(--pf-muted);
+}
+
+.pf-nav-center a:hover {
+ color: var(--pf-ink);
+}
+
+.pf-nav-center a.active {
+ color: var(--pf-ink);
+ font-weight: 600;
+}
+
+.pf-nav-center a.active::after {
+ content: '';
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ height: 3px;
+ background: var(--pf-lime);
+ border-radius: 2px;
+}
+
+.pf-nav-right {
+ justify-self: end;
+ display: flex;
+ align-items: center;
+ gap: 0.65rem;
+}
+
+.pf-icon-btn {
+ position: relative;
+ width: 36px;
+ height: 36px;
+ border: 1px solid transparent;
+ border-radius: 999px;
+ background: transparent;
+ color: #4b5563;
+ display: grid;
+ place-items: center;
+ padding: 0;
+}
+
+.pf-icon-btn:hover:not(:disabled) {
+ background: var(--pf-bg);
+ border-color: var(--pf-line);
+ color: var(--pf-ink);
+}
+
+.pf-icon-btn:disabled {
+ cursor: not-allowed;
+ opacity: 0.55;
+}
+
+.pf-icon-btn .dot {
+ position: absolute;
+ top: 7px;
+ right: 7px;
+ width: 7px;
+ height: 7px;
+ border-radius: 999px;
+ background: #ef4444;
+ border: 1.5px solid #fff;
+}
+
+.pf-btn-icon {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+}
+
+.pf-btn-text {
+ border: 0;
+ background: transparent;
+ color: var(--pf-muted);
+ padding: 0.45rem 0.55rem;
+ border-radius: 8px;
+ font-weight: 500;
+ font-size: 0.88rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+}
+
+.pf-btn-text:hover:not(:disabled) {
+ color: var(--pf-ink);
+ background: var(--pf-bg);
+}
+
+.pf-btn-text:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.pf-btn-outline {
+ background: #fff;
+ border: 1px solid var(--pf-ink);
+ color: var(--pf-ink);
+}
+
+.pf-back {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ border: 0;
+ background: transparent;
+ padding: 0;
+ color: var(--pf-muted);
+ font-size: 0.9rem;
+ font-weight: 500;
+ cursor: pointer;
+}
+
+.pf-back:hover {
+ color: var(--pf-ink);
+}
+
+.pf-page-head {
+ margin-bottom: 1.25rem;
+}
+
+.pf-page-head-row {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 1rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.75rem;
+}
+
+.pf-page-title {
+ margin: 0.35rem 0 0;
+ font-size: clamp(1.45rem, 2.4vw, 1.85rem);
+ font-weight: 800;
+ letter-spacing: -0.02em;
+ line-height: 1.25;
+}
+
+.pf-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 0.35rem;
+ flex-wrap: wrap;
+}
+
+.pf-side-actions {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.45rem;
+ margin-top: 0.55rem;
+}
+
+.pf-avatar {
+ width: 34px;
+ height: 34px;
+ border-radius: 999px;
+ background: linear-gradient(135deg, #dfe7ee, #b8c4d0);
+ border: 1px solid var(--pf-line);
+ display: grid;
+ place-items: center;
+ font-size: 0.75rem;
+ font-weight: 700;
+ color: var(--pf-ink);
+}
+
+.pf-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.35rem;
+ border: 1px solid transparent;
+ border-radius: 10px;
+ padding: 0.55rem 1rem;
+ font-weight: 600;
+ transition: transform 0.15s ease, background 0.15s ease, border-color 0.15s ease;
+}
+
+.pf-btn:hover:not(:disabled) {
+ transform: translateY(-1px);
+}
+
+.pf-btn:disabled {
+ opacity: 0.55;
+ cursor: not-allowed;
+ transform: none;
+}
+
+.pf-btn-lime {
+ background: var(--pf-lime);
+ color: var(--pf-ink);
+ border-color: var(--pf-lime);
+}
+
+.pf-btn-dark {
+ background: var(--pf-ink);
+ color: #fff;
+}
+
+.pf-btn-ghost {
+ background: #fff;
+ border-color: var(--pf-line);
+ color: var(--pf-ink);
+}
+
+.pf-btn-sm {
+ padding: 0.35rem 0.75rem;
+ font-size: 0.85rem;
+ border-radius: 8px;
+}
+
+.pf-btn-block {
+ width: 100%;
+}
+
+.brand-mark {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.55rem;
+ font-family: 'Space Grotesk', 'Noto Sans SC', sans-serif;
+ font-size: 1.05rem;
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ color: var(--pf-ink);
+}
+
+.brand-logo {
+ width: 28px;
+ height: 28px;
+ border-radius: 7px;
+ flex-shrink: 0;
+}
+
+.brand-word {
+ letter-spacing: 0.12em;
+}
+
+/* ——— Common ——— */
+.pf-card {
+ background: var(--pf-card);
+ border: 1px solid var(--pf-line);
+ border-radius: var(--pf-radius);
+ box-shadow: var(--pf-shadow);
+}
+
+.pf-section-head {
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 1rem;
+ margin-bottom: 1.1rem;
+}
+
+.pf-section-head h2 {
+ margin: 0;
+ font-size: 1.45rem;
+ font-weight: 700;
+}
+
+.pf-section-head p {
+ margin: 0.25rem 0 0;
+ color: var(--pf-muted);
+ font-size: 0.92rem;
+}
+
+.pf-link {
+ color: var(--pf-muted);
+ font-size: 0.9rem;
+ font-weight: 500;
+}
+
+.pf-link:hover {
+ color: var(--pf-ink);
+}
+
+.pf-pill-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.45rem;
+}
+
+.pf-pill {
+ border: 1px solid var(--pf-line);
+ background: #fff;
+ color: var(--pf-ink);
+ padding: 0.4rem 0.9rem;
+ border-radius: 999px;
+ font-size: 0.88rem;
+ font-weight: 500;
+}
+
+.pf-pill:hover {
+ border-color: rgba(17, 19, 24, 0.25);
+}
+
+.pf-pill.active {
+ background: var(--pf-ink);
+ border-color: var(--pf-ink);
+ color: #fff;
+}
+
+.pf-pill.lime.active {
+ background: var(--pf-lime);
+ border-color: var(--pf-lime);
+ color: var(--pf-ink);
+}
+
+.pf-stepper {
+ display: flex;
+ align-items: center;
+ gap: 0.35rem;
+ flex-wrap: wrap;
+}
+
+.pf-step {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ color: var(--pf-muted);
+ font-size: 0.88rem;
+ font-weight: 500;
+}
+
+.pf-step-dot {
+ width: 26px;
+ height: 26px;
+ border-radius: 999px;
+ border: 2px solid #d1d5db;
+ display: grid;
+ place-items: center;
+ font-size: 0.75rem;
+ font-weight: 700;
+ background: #fff;
+}
+
+.pf-step.done {
+ color: var(--pf-ink);
+}
+
+.pf-step.done .pf-step-dot {
+ background: var(--pf-lime);
+ border-color: var(--pf-lime);
+ color: var(--pf-ink);
+}
+
+.pf-step.active {
+ color: var(--pf-ink);
+ font-weight: 700;
+}
+
+.pf-step.active .pf-step-dot {
+ background: var(--pf-lime);
+ border-color: var(--pf-lime);
+}
+
+.pf-step-line {
+ width: 28px;
+ height: 2px;
+ background: #e5e7eb;
+ margin: 0 0.15rem;
+}
+
+.pf-step-line.done {
+ background: var(--pf-lime);
+}
+
+.pf-coming {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ font-size: 0.75rem;
+ color: var(--pf-muted);
+ background: var(--pf-bg);
+ border: 1px dashed var(--pf-line);
+ border-radius: 999px;
+ padding: 0.15rem 0.55rem;
+}
+
+.pf-muted {
+ color: var(--pf-muted);
+}
+
+.pf-error {
+ color: var(--crimson);
+ font-size: 0.9rem;
+}
+
+.pf-hint {
+ background: var(--pf-lime-soft);
+ border: 1px solid rgba(182, 255, 0, 0.45);
+ border-radius: var(--pf-radius-sm);
+ padding: 0.85rem 1rem;
+ font-size: 0.9rem;
+ color: #3a4518;
+}
+
+/* ——— Home ——— */
+.pf-home-hero {
+ display: grid;
+ grid-template-columns: 1.05fr 0.95fr;
+ gap: 2.5rem;
+ align-items: center;
+ padding: 2.5rem 0 3rem;
+}
+
+.pf-home-hero h1 {
+ margin: 0 0 0.85rem;
+ font-size: clamp(2rem, 4vw, 2.85rem);
+ line-height: 1.2;
+ font-weight: 800;
+ letter-spacing: -0.02em;
+}
+
+.pf-home-hero .lede {
+ margin: 0 0 1.5rem;
+ color: var(--pf-muted);
+ font-size: 1.05rem;
+ max-width: 34rem;
+}
+
+.pf-home-steps {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 0.75rem;
+ margin-bottom: 1.5rem;
+}
+
+.pf-home-step {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: 12px;
+ padding: 0.85rem;
+}
+
+.pf-home-step strong {
+ display: block;
+ margin-bottom: 0.25rem;
+ font-size: 0.92rem;
+}
+
+.pf-home-step span {
+ font-size: 0.8rem;
+ color: var(--pf-muted);
+}
+
+.pf-hero-visual {
+ position: relative;
+}
+
+.pf-hero-player {
+ border-radius: 18px;
+ overflow: hidden;
+ border: 1px solid var(--pf-line);
+ box-shadow: 0 20px 50px rgba(17, 19, 24, 0.12);
+ background: #111;
+ aspect-ratio: 16 / 10;
+}
+
+.pf-hero-player img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+
+.pf-hero-badge {
+ position: absolute;
+ top: 1rem;
+ left: 1rem;
+ background: rgba(17, 19, 24, 0.75);
+ color: #fff;
+ font-size: 0.78rem;
+ padding: 0.3rem 0.65rem;
+ border-radius: 999px;
+}
+
+.pf-hero-float {
+ position: absolute;
+ right: -0.5rem;
+ bottom: 1.25rem;
+ width: 200px;
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: 14px;
+ padding: 0.85rem 1rem;
+ box-shadow: var(--pf-shadow);
+ font-size: 0.85rem;
+}
+
+.pf-hero-float li {
+ list-style: none;
+ margin: 0.35rem 0;
+ display: flex;
+ align-items: center;
+ gap: 0.4rem;
+}
+
+.pf-hero-float ul {
+ margin: 0;
+ padding: 0;
+}
+
+.pf-check {
+ color: #5a8f00;
+ font-weight: 700;
+}
+
+.pf-template-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 1rem;
+}
+
+.pf-template-card {
+ text-align: left;
+ border: 1px solid var(--pf-line);
+ background: #fff;
+ border-radius: var(--pf-radius);
+ overflow: hidden;
+ padding: 0;
+ box-shadow: var(--pf-shadow);
+ transition: transform 0.2s ease, border-color 0.2s ease;
+}
+
+.pf-template-card:hover {
+ transform: translateY(-3px);
+ border-color: rgba(182, 255, 0, 0.65);
+}
+
+.pf-template-card.selected {
+ border: 2px solid var(--pf-lime);
+ box-shadow: 0 0 0 3px rgba(182, 255, 0, 0.25);
+}
+
+.pf-template-card img {
+ width: 100%;
+ aspect-ratio: 16 / 9;
+ object-fit: cover;
+ display: block;
+ background: #e5e7eb;
+}
+
+.pf-template-card .body {
+ padding: 0.9rem 1rem 1.05rem;
+}
+
+.pf-template-card h3 {
+ margin: 0 0 0.3rem;
+ font-size: 1.05rem;
+}
+
+.pf-template-card p {
+ margin: 0;
+ color: var(--pf-muted);
+ font-size: 0.88rem;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.pf-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.35rem;
+ margin-top: 0.65rem;
+}
+
+.pf-tags span {
+ font-size: 0.72rem;
+ color: var(--pf-muted);
+ background: var(--pf-bg);
+ border-radius: 999px;
+ padding: 0.12rem 0.45rem;
+}
+
+.pf-works-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 1rem;
+}
+
+.pf-work-card {
+ border: 0;
+ background: transparent;
+ padding: 0;
+ text-align: left;
+ cursor: pointer;
+ color: inherit;
+}
+
+.pf-work-card:hover .pf-work-thumb img {
+ transform: scale(1.03);
+}
+
+.pf-work-card:hover .pf-work-play {
+ opacity: 1;
+ transform: translate(-50%, -50%) scale(1);
+}
+
+.pf-work-thumb {
+ position: relative;
+ display: block;
+ border-radius: 12px;
+ overflow: hidden;
+}
+
+.pf-work-card img {
+ width: 100%;
+ aspect-ratio: 16 / 9;
+ object-fit: cover;
+ border-radius: 12px;
+ background: #ddd;
+ display: block;
+ transition: transform 0.25s ease;
+}
+
+.pf-work-play {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%) scale(0.92);
+ width: 44px;
+ height: 44px;
+ border-radius: 999px;
+ background: rgba(182, 255, 0, 0.92);
+ color: var(--pf-ink);
+ display: grid;
+ place-items: center;
+ font-size: 0.85rem;
+ opacity: 0.88;
+ transition: opacity 0.2s ease, transform 0.2s ease;
+ box-shadow: 0 6px 18px rgba(0, 0, 0, 0.2);
+}
+
+.pf-work-card h3 {
+ margin: 0.55rem 0 0.2rem;
+ font-size: 0.95rem;
+}
+
+.pf-cta-band {
+ margin-top: 3rem;
+ padding: 1.75rem 1.75rem;
+ border-radius: var(--pf-radius);
+ background: linear-gradient(90deg, var(--pf-lime-soft), #f7ffe8);
+ border: 1px solid rgba(182, 255, 0, 0.35);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ flex-wrap: wrap;
+}
+
+.pf-cta-band h2 {
+ margin: 0 0 0.25rem;
+ font-size: 1.35rem;
+}
+
+.pf-cta-band p {
+ margin: 0;
+ color: var(--pf-muted);
+}
+
+/* ——— Create / Style three-column ——— */
+.pf-create {
+ display: grid;
+ grid-template-columns: 300px 1fr 300px;
+ gap: 1rem;
+ min-height: calc(100vh - var(--pf-nav-h) - 5rem);
+}
+
+.pf-create-col {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: var(--pf-radius);
+ padding: 1rem;
+ min-height: 420px;
+}
+
+.pf-create-col h3 {
+ margin: 0 0 0.85rem;
+ font-size: 1rem;
+}
+
+.pf-search {
+ display: flex;
+ gap: 0.4rem;
+ margin-bottom: 0.75rem;
+}
+
+.pf-search input {
+ flex: 1;
+ border: 1px solid var(--pf-line);
+ border-radius: 10px;
+ padding: 0.55rem 0.75rem;
+ background: var(--pf-bg);
+}
+
+.pf-tpl-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.65rem;
+ max-height: 62vh;
+ overflow: auto;
+}
+
+.pf-tpl-mini {
+ display: grid;
+ grid-template-columns: 88px 1fr;
+ gap: 0.65rem;
+ border: 1px solid var(--pf-line);
+ border-radius: 12px;
+ padding: 0.45rem;
+ background: #fff;
+ text-align: left;
+}
+
+.pf-tpl-mini.selected {
+ border-color: var(--pf-lime);
+ box-shadow: 0 0 0 2px rgba(182, 255, 0, 0.35);
+}
+
+.pf-tpl-mini img {
+ width: 88px;
+ height: 56px;
+ object-fit: cover;
+ border-radius: 8px;
+ background: #eee;
+}
+
+.pf-tpl-mini strong {
+ display: block;
+ font-size: 0.88rem;
+ margin-bottom: 0.15rem;
+}
+
+.pf-tpl-mini span {
+ font-size: 0.75rem;
+ color: var(--pf-muted);
+}
+
+.pf-input-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem;
+ margin-bottom: 0.85rem;
+}
+
+.pf-field {
+ display: block;
+ margin-bottom: 0.85rem;
+}
+
+.pf-field-label {
+ display: block;
+ font-size: 0.85rem;
+ color: var(--pf-muted);
+ margin-bottom: 0.35rem;
+}
+
+.pf-field-input {
+ display: block;
+ width: 100%;
+ border: 1px solid var(--pf-line);
+ border-radius: 10px;
+ padding: 0.6rem 0.8rem;
+ background: #fff;
+ font: inherit;
+ color: var(--pf-ink);
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+}
+
+.pf-field-input:focus {
+ outline: none;
+ border-color: color-mix(in srgb, var(--pf-lime) 70%, var(--pf-ink));
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--pf-lime) 35%, transparent);
+}
+
+.pf-textarea-wrap {
+ position: relative;
+}
+
+.pf-textarea-toolbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ margin-bottom: 0.45rem;
+}
+
+.pf-textarea-wrap textarea {
+ width: 100%;
+ min-height: 180px;
+ border: 1px solid var(--pf-line);
+ border-radius: 12px;
+ padding: 0.9rem;
+ padding-bottom: 1.6rem;
+ resize: vertical;
+ background: #fff;
+ font: inherit;
+ line-height: 1.55;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
+}
+
+.pf-textarea-wrap textarea:focus {
+ outline: none;
+ border-color: color-mix(in srgb, var(--pf-lime) 70%, var(--pf-ink));
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--pf-lime) 35%, transparent);
+}
+
+.pf-char-count {
+ position: absolute;
+ right: 0.75rem;
+ bottom: 0.65rem;
+ font-size: 0.75rem;
+ color: var(--pf-muted);
+}
+
+.pf-inspire {
+ margin-top: 1rem;
+}
+
+.pf-inspire-head {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 0.75rem;
+}
+
+.pf-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.45rem;
+ margin-top: 0.75rem;
+}
+
+.pf-chip {
+ border: 1px solid var(--pf-line);
+ background: #fff;
+ border-radius: 999px;
+ padding: 0.38rem 0.85rem;
+ font-size: 0.82rem;
+ color: var(--pf-ink);
+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease;
+}
+
+.pf-chip:hover:not(:disabled) {
+ border-color: var(--pf-ink);
+ background: color-mix(in srgb, var(--pf-lime) 28%, #fff);
+ transform: translateY(-1px);
+}
+
+.pf-chip:disabled {
+ cursor: not-allowed;
+ opacity: 0.7;
+}
+
+.pf-btn-lg {
+ padding: 0.85rem 1.15rem;
+ font-size: 0.98rem;
+ border-radius: 12px;
+ min-height: 48px;
+}
+
+.pf-btn-ai {
+ background: color-mix(in srgb, var(--pf-lime) 55%, #fff);
+ border-color: color-mix(in srgb, var(--pf-lime) 80%, var(--pf-ink));
+ color: var(--pf-ink);
+}
+
+.pf-btn-ai:hover:not(:disabled) {
+ background: var(--pf-lime);
+ border-color: var(--pf-lime);
+}
+
+.pf-btn-lime:hover:not(:disabled) {
+ filter: brightness(0.97);
+ box-shadow: 0 6px 16px rgba(17, 19, 24, 0.08);
+}
+
+.pf-summary-row {
+ display: flex;
+ justify-content: space-between;
+ gap: 0.5rem;
+ padding: 0.65rem 0;
+ border-bottom: 1px solid var(--pf-line);
+ font-size: 0.88rem;
+}
+
+.pf-summary-row span:first-child {
+ color: var(--pf-muted);
+}
+
+.pf-subhead {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 1rem;
+ margin-bottom: 1rem;
+ flex-wrap: wrap;
+}
+
+.pf-subhead h1 {
+ margin: 0.35rem 0 0;
+ font-size: clamp(1.35rem, 2.2vw, 1.75rem);
+ font-weight: 800;
+}
+
+/* Style config */
+.pf-style-layout {
+ display: grid;
+ grid-template-columns: 240px 1fr 300px;
+ gap: 1rem;
+}
+
+.pf-style-block {
+ margin-bottom: 1.35rem;
+}
+
+.pf-style-block h3 {
+ margin: 0 0 0.65rem;
+ font-size: 1rem;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.pf-style-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 0.65rem;
+}
+
+.pf-style-opt {
+ border: 1px solid var(--pf-line);
+ border-radius: 12px;
+ overflow: hidden;
+ background: #fff;
+ padding: 0;
+ text-align: left;
+}
+
+.pf-style-opt.selected {
+ border-color: var(--pf-lime);
+ box-shadow: 0 0 0 2px rgba(182, 255, 0, 0.3);
+}
+
+.pf-style-opt img,
+.pf-style-opt .ph {
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ object-fit: cover;
+ display: block;
+ background: #e8eaee;
+}
+
+.pf-style-opt .ph {
+ display: grid;
+ place-items: center;
+ color: var(--pf-muted);
+ font-size: 0.8rem;
+}
+
+.pf-style-opt .cap {
+ padding: 0.45rem 0.6rem 0.1rem;
+ font-size: 0.82rem;
+ font-weight: 600;
+}
+
+.pf-style-opt .cap-sub {
+ padding: 0 0.6rem 0.55rem;
+ font-size: 0.72rem;
+ color: var(--pf-muted);
+ line-height: 1.35;
+}
+
+.pf-voice-row {
+ display: flex;
+ gap: 0.55rem;
+ overflow-x: auto;
+ padding-bottom: 0.25rem;
+}
+
+.pf-voice-card {
+ min-width: 132px;
+ border: 1px solid var(--pf-line);
+ border-radius: 12px;
+ padding: 0.7rem 0.7rem 0.55rem;
+ background: #fff;
+ text-align: left;
+ display: flex;
+ flex-direction: column;
+ gap: 0.2rem;
+ cursor: pointer;
+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease;
+}
+
+.pf-voice-card:hover {
+ border-color: rgba(17, 19, 24, 0.28);
+ transform: translateY(-1px);
+}
+
+.pf-voice-card.selected {
+ border-color: var(--pf-lime);
+ background: #f7ffe8;
+ box-shadow: 0 0 0 2px rgba(182, 255, 0, 0.28);
+}
+
+.pf-voice-name {
+ display: block;
+ font-size: 0.88rem;
+ line-height: 1.3;
+}
+
+.pf-voice-meta {
+ font-size: 0.75rem;
+ color: var(--pf-muted);
+ margin-bottom: 0.35rem;
+}
+
+.pf-voice-preview {
+ margin-top: auto;
+ width: 100%;
+ justify-content: center;
+}
+
+.pf-bgm-card {
+ padding: 0.85rem;
+ opacity: 0.8;
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ border: 1px solid var(--pf-line);
+ border-radius: 12px;
+ background: #fff;
+}
+
+.pf-bgm-wave {
+ height: 28px;
+ margin-top: 6px;
+ background: repeating-linear-gradient(90deg, #d1d5db 0 2px, transparent 2px 6px);
+ border-radius: 4px;
+ opacity: 0.55;
+}
+
+.pf-style-block > h3 {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+}
+
+.pf-ratio-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+
+.pf-ratio {
+ width: 72px;
+ border: 1px solid var(--pf-line);
+ border-radius: 10px;
+ padding: 0.55rem 0.35rem;
+ background: #fff;
+ text-align: center;
+ font-size: 0.8rem;
+ font-weight: 600;
+}
+
+.pf-ratio.selected {
+ border-color: var(--pf-lime);
+ background: #f7ffe8;
+}
+
+.pf-ratio .box {
+ margin: 0 auto 0.35rem;
+ border: 2px solid #9ca3af;
+ border-radius: 3px;
+}
+
+/* Storyboard */
+.pf-board {
+ display: grid;
+ grid-template-columns: 260px 1fr 260px;
+ gap: 1rem;
+}
+
+.pf-board-main {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.pf-outline-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.85rem;
+}
+
+.pf-shot-card {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: var(--pf-radius);
+ padding: 1rem 1.1rem 0.85rem;
+ box-shadow: var(--pf-shadow);
+}
+
+.pf-shot-card-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ margin-bottom: 0.85rem;
+}
+
+.pf-shot-card-head h3 {
+ margin: 0;
+ font-size: 1.05rem;
+ font-weight: 700;
+}
+
+.pf-shot-table-wrap {
+ overflow-x: auto;
+ margin: 0 -0.25rem;
+}
+
+.pf-shot-table {
+ width: 100%;
+ border-collapse: separate;
+ border-spacing: 0;
+ font-size: 0.88rem;
+ min-width: 920px;
+}
+
+.pf-shot-table thead th {
+ color: var(--pf-muted);
+ font-weight: 600;
+ font-size: 0.78rem;
+ text-align: left;
+ padding: 0.55rem 0.65rem;
+ border-bottom: 1px solid var(--pf-line);
+ background: #fafbfc;
+ white-space: nowrap;
+}
+
+.pf-shot-table tbody tr:nth-child(even) {
+ background: #fafbfc;
+}
+
+.pf-shot-table tbody tr:hover {
+ background: #f4fbe0;
+}
+
+.pf-shot-table td {
+ border-bottom: 1px solid var(--pf-line);
+ padding: 0.85rem 0.65rem;
+ text-align: left;
+ vertical-align: top;
+}
+
+.pf-shot-table td.col-no {
+ width: 52px;
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+ color: var(--pf-ink);
+ font-family: 'Space Grotesk', sans-serif;
+}
+
+.pf-shot-table td.col-thumb {
+ width: 140px;
+}
+
+.pf-shot-table td.col-dur,
+.pf-shot-table td.col-status {
+ width: 88px;
+ white-space: nowrap;
+}
+
+.pf-shot-table td.col-ops {
+ width: 200px;
+ white-space: nowrap;
+}
+
+.pf-shot-thumb-btn {
+ border: 0;
+ padding: 0;
+ background: transparent;
+ display: block;
+ border-radius: 10px;
+ overflow: hidden;
+ cursor: pointer;
+}
+
+.pf-shot-thumb-btn:hover {
+ outline: 2px solid rgba(182, 255, 0, 0.65);
+ outline-offset: 1px;
+}
+
+.pf-shot-thumb {
+ width: 128px;
+ height: 72px;
+ object-fit: cover;
+ border-radius: 10px;
+ background: linear-gradient(135deg, #e5e7eb, #d1d5db);
+ display: block;
+}
+
+.pf-shot-thumb.empty {
+ display: grid;
+ place-items: center;
+ color: #9ca3af;
+ font-size: 0.72rem;
+}
+
+.pf-shot-narration .title {
+ display: block;
+ font-weight: 700;
+ font-size: 0.9rem;
+ margin-bottom: 0.25rem;
+ color: var(--pf-ink);
+}
+
+.pf-shot-narration .line {
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ color: #4b5563;
+ font-size: 0.84rem;
+ line-height: 1.55;
+}
+
+.pf-shot-desc {
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ color: #6b7280;
+ font-size: 0.84rem;
+ line-height: 1.55;
+ max-width: 280px;
+}
+
+button.pf-shot-editable {
+ appearance: none;
+ border: 1px solid transparent;
+ background: transparent;
+ padding: 0.25rem 0.35rem;
+ margin: -0.25rem -0.35rem;
+ border-radius: 8px;
+ text-align: left;
+ cursor: pointer;
+ width: 100%;
+ font: inherit;
+ color: inherit;
+}
+
+button.pf-shot-editable:hover:not(:disabled) {
+ border-color: #c5d4a4;
+ background: #f4f7ec;
+}
+
+button.pf-shot-editable:disabled {
+ cursor: default;
+ opacity: 0.75;
+}
+
+.pf-prompt-panel {
+ margin-top: 0.85rem;
+ padding-top: 0.75rem;
+ border-top: 1px solid #e8e4dc;
+}
+
+.pf-prompt-panel h4 {
+ margin: 0 0 0.35rem;
+ font-size: 0.88rem;
+}
+
+.pf-prompt-chip {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.15rem;
+ width: 100%;
+ margin-bottom: 0.4rem;
+ padding: 0.55rem 0.65rem;
+ border: 1px solid #e5e1d8;
+ border-radius: 10px;
+ background: #faf9f6;
+ text-align: left;
+ cursor: pointer;
+ font: inherit;
+}
+
+.pf-prompt-chip:hover:not(:disabled) {
+ border-color: #b7c98a;
+ background: #f3f6ea;
+}
+
+.pf-prompt-chip strong {
+ font-size: 0.72rem;
+ color: #6b7280;
+ font-weight: 600;
+}
+
+.pf-prompt-chip span {
+ font-size: 0.78rem;
+ color: #1a1714;
+ line-height: 1.4;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ width: 100%;
+}
+
+.pf-prompt-modal {
+ max-width: 560px;
+ width: min(560px, 92vw);
+}
+
+.pf-prompt-modal label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+ margin-bottom: 0.75rem;
+ font-size: 0.85rem;
+ font-weight: 600;
+}
+
+.pf-prompt-modal textarea,
+.pf-prompt-modal input {
+ font-weight: 400;
+ font-size: 0.9rem;
+ padding: 0.55rem 0.65rem;
+ border: 1px solid #d8d3c8;
+ border-radius: 8px;
+ font-family: inherit;
+ resize: vertical;
+}
+
+.pf-prompt-modal-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 0.75rem;
+}
+
+.pf-shot-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ font-size: 0.82rem;
+ font-weight: 600;
+ color: #3d6500;
+}
+
+.pf-shot-status.warn {
+ color: #8a5a12;
+}
+
+.pf-shot-status.bad {
+ color: #a1261a;
+}
+
+.pf-shot-status .mark {
+ width: 16px;
+ height: 16px;
+ border-radius: 999px;
+ background: var(--pf-lime);
+ color: var(--pf-ink);
+ display: inline-grid;
+ place-items: center;
+ font-size: 0.65rem;
+ font-weight: 800;
+ flex-shrink: 0;
+}
+
+.pf-shot-ops {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.15rem;
+ position: relative;
+}
+
+.pf-shot-ops .op {
+ border: 0;
+ background: transparent;
+ color: #4b5563;
+ font-size: 0.82rem;
+ font-weight: 500;
+ padding: 0.25rem 0.4rem;
+ border-radius: 6px;
+ cursor: pointer;
+}
+
+.pf-shot-ops .op:hover:not(:disabled) {
+ color: var(--pf-ink);
+ background: rgba(182, 255, 0, 0.25);
+}
+
+.pf-shot-ops .op:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.pf-shot-ops .more {
+ width: 28px;
+ height: 28px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: #6b7280;
+ font-size: 1.1rem;
+ line-height: 1;
+ cursor: pointer;
+}
+
+.pf-shot-ops .more:hover {
+ background: var(--pf-bg);
+ color: var(--pf-ink);
+}
+
+.pf-shot-menu {
+ position: absolute;
+ right: 0;
+ top: 100%;
+ z-index: 8;
+ min-width: 128px;
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: 10px;
+ box-shadow: var(--pf-shadow);
+ padding: 0.3rem;
+}
+
+.pf-shot-menu button {
+ display: block;
+ width: 100%;
+ text-align: left;
+ border: 0;
+ background: transparent;
+ padding: 0.45rem 0.65rem;
+ border-radius: 7px;
+ font-size: 0.84rem;
+ color: var(--pf-ink);
+ cursor: pointer;
+}
+
+.pf-shot-menu button:hover:not(:disabled) {
+ background: #f4fbe0;
+}
+
+.pf-shot-menu button:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.pf-shot-footer {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 0.75rem;
+ flex-wrap: wrap;
+ margin-top: 0.85rem;
+ padding-top: 0.75rem;
+ border-top: 1px solid var(--pf-line);
+}
+
+.pf-progress-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.pf-progress-list li {
+ display: flex;
+ justify-content: space-between;
+ gap: 0.5rem;
+ padding: 0.45rem 0;
+ border-bottom: 1px solid var(--pf-line);
+ font-size: 0.88rem;
+}
+
+.pf-meta-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ font-size: 0.85rem;
+}
+
+.pf-meta-list li {
+ display: flex;
+ justify-content: space-between;
+ gap: 0.5rem;
+ padding: 0.4rem 0;
+ border-bottom: 1px solid var(--pf-line);
+}
+
+.pf-meta-list span:first-child {
+ color: var(--pf-muted);
+}
+
+/* Editor */
+.pf-editor {
+ display: grid;
+ grid-template-columns: 240px 1fr 300px;
+ gap: 0;
+ min-height: calc(100vh - var(--pf-nav-h));
+ border-top: 1px solid var(--pf-line);
+}
+
+.pf-editor > * {
+ border-right: 1px solid var(--pf-line);
+ background: #fff;
+ padding: 1rem;
+}
+
+.pf-editor > *:last-child {
+ border-right: 0;
+}
+
+.pf-editor-preview {
+ position: relative;
+ width: 100%;
+ max-width: 100%;
+ aspect-ratio: 16 / 9;
+ max-height: min(52vh, 480px);
+ margin: 0 auto;
+ background: #111;
+ border-radius: 12px;
+ overflow: hidden;
+ color: #fff;
+}
+
+.pf-editor-preview.portrait {
+ aspect-ratio: 9 / 16;
+ max-width: min(100%, 300px);
+ max-height: min(64vh, 560px);
+}
+
+.pf-editor-preview img,
+.pf-editor-preview video {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+ object-position: center;
+ background: #111;
+}
+
+.pf-editor-preview .empty {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: rgba(255, 255, 255, 0.65);
+ font-size: 0.9rem;
+}
+
+.pf-scene-item {
+ display: grid;
+ grid-template-columns: 56px 1fr;
+ gap: 0.5rem;
+ padding: 0.45rem;
+ border: 1px solid transparent;
+ border-radius: 10px;
+ margin-bottom: 0.4rem;
+ text-align: left;
+ background: transparent;
+ width: 100%;
+}
+
+.pf-scene-item.active {
+ border-color: var(--pf-lime);
+ background: #f7ffe8;
+}
+
+.pf-scene-item img,
+.pf-scene-item .ph {
+ width: 56px;
+ height: 36px;
+ object-fit: cover;
+ border-radius: 6px;
+ background: #eee;
+}
+
+.pf-panel-tabs {
+ display: flex;
+ gap: 0.35rem;
+ margin-bottom: 0.85rem;
+ flex-wrap: wrap;
+}
+
+.pf-panel-tabs button {
+ border: 0;
+ background: var(--pf-bg);
+ border-radius: 8px;
+ padding: 0.4rem 0.7rem;
+ font-size: 0.85rem;
+ color: var(--pf-muted);
+}
+
+.pf-panel-tabs button.active {
+ background: var(--pf-lime);
+ color: var(--pf-ink);
+ font-weight: 700;
+}
+
+/* History */
+.pf-history-head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 1rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.25rem;
+}
+
+.pf-history-head h1 {
+ margin: 0;
+ font-size: clamp(1.6rem, 2.5vw, 2rem);
+ font-weight: 800;
+ letter-spacing: -0.02em;
+}
+
+.pf-history-head p {
+ margin: 0.35rem 0 0;
+ color: var(--pf-muted);
+ font-size: 0.95rem;
+}
+
+.pf-history-layout {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 300px;
+ gap: 1.35rem;
+ align-items: start;
+}
+
+.pf-history-main {
+ min-width: 0;
+}
+
+.pf-stats {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 0.85rem;
+ margin: 1.25rem 0 1.5rem;
+}
+
+.pf-stat {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: var(--pf-radius);
+ padding: 1.05rem 1.1rem;
+ box-shadow: var(--pf-shadow);
+}
+
+.pf-stat-top {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.pf-stat-icon {
+ width: 32px;
+ height: 32px;
+ border-radius: 10px;
+ background: var(--pf-lime-soft);
+ color: #3d6500;
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+}
+
+.pf-stat .label {
+ color: var(--pf-muted);
+ font-size: 0.85rem;
+ font-weight: 500;
+}
+
+.pf-stat .value {
+ font-size: 1.85rem;
+ font-weight: 800;
+ margin: 0.45rem 0 0.15rem;
+ font-family: 'Space Grotesk', sans-serif;
+ line-height: 1;
+}
+
+.pf-stat .trend {
+ font-size: 0.78rem;
+ color: #5a8f00;
+ font-weight: 500;
+}
+
+.pf-history-filters {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.85rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.75rem;
+}
+
+.pf-history-filter-right {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.pf-type-select {
+ border: 1px solid var(--pf-line);
+ background: #fff;
+ border-radius: 10px;
+ padding: 0.5rem 0.75rem;
+ font-size: 0.85rem;
+ color: var(--pf-muted);
+}
+
+.pf-search-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ border: 1px solid var(--pf-line);
+ background: #f8f9fa;
+ border-radius: 10px;
+ padding: 0.45rem 0.75rem;
+ min-width: 220px;
+ color: var(--pf-muted);
+}
+
+.pf-search-field input {
+ border: 0;
+ background: transparent;
+ outline: none;
+ width: 100%;
+ color: var(--pf-ink);
+ font-size: 0.88rem;
+}
+
+.pf-history-batch {
+ display: flex;
+ align-items: center;
+ gap: 0.55rem;
+ margin-bottom: 0.85rem;
+ color: var(--pf-muted);
+ font-size: 0.82rem;
+}
+
+.pf-history-empty {
+ padding: 3rem 1rem;
+ text-align: center;
+ color: var(--pf-muted);
+ background: #fff;
+ border: 1px dashed var(--pf-line);
+ border-radius: var(--pf-radius);
+}
+
+.pf-project-list {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: var(--pf-radius);
+ overflow: hidden;
+ box-shadow: var(--pf-shadow);
+}
+
+.pf-project-card {
+ display: grid;
+ grid-template-columns: 40px 168px minmax(0, 1fr) 64px auto;
+ gap: 0.9rem;
+ align-items: center;
+ padding: 1rem 1.1rem;
+ border-bottom: 1px solid var(--pf-line);
+}
+
+.pf-project-card:last-child {
+ border-bottom: 0;
+}
+
+.pf-project-card:hover {
+ background: #fafbfc;
+}
+
+.pf-project-check {
+ display: grid;
+ place-items: center;
+}
+
+.pf-project-check input {
+ width: 1rem;
+ height: 1rem;
+ accent-color: #2a6f7a;
+}
+
+.pf-project-thumb {
+ position: relative;
+ border: 0;
+ padding: 0;
+ background: transparent;
+ border-radius: 12px;
+ overflow: hidden;
+ display: block;
+ cursor: pointer;
+}
+
+.pf-project-thumb img,
+.pf-project-thumb .ph {
+ width: 168px;
+ height: 94px;
+ object-fit: cover;
+ display: block;
+ background: #e5e7eb;
+ border-radius: 12px;
+}
+
+.pf-project-thumb .ph {
+ display: grid;
+ place-items: center;
+ color: var(--pf-muted);
+ font-size: 0.78rem;
+}
+
+.pf-thumb-progress {
+ position: absolute;
+ right: 0.4rem;
+ bottom: 0.4rem;
+ background: rgba(17, 19, 24, 0.72);
+ color: #fff;
+ font-size: 0.7rem;
+ padding: 0.15rem 0.4rem;
+ border-radius: 999px;
+}
+
+.pf-project-info h3 {
+ margin: 0 0 0.4rem;
+ font-size: 1.05rem;
+ font-weight: 700;
+ line-height: 1.3;
+}
+
+.pf-project-meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.45rem;
+ font-size: 0.8rem;
+}
+
+.pf-project-err {
+ margin: 0.4rem 0 0;
+ font-size: 0.8rem;
+}
+
+.pf-inline-meter {
+ height: 6px;
+ background: #e8eef8;
+ border-radius: 999px;
+ overflow: hidden;
+ margin-top: 0.55rem;
+ max-width: 220px;
+}
+
+.pf-inline-meter > i {
+ display: block;
+ height: 100%;
+ background: #4f7cff;
+}
+
+.pf-project-ratio {
+ color: var(--pf-muted);
+ font-size: 0.88rem;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ text-align: center;
+}
+
+.pf-project-actions {
+ display: flex;
+ align-items: center;
+ gap: 0.15rem;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+}
+
+.pf-icon-btn.danger {
+ color: #9ca3af;
+}
+
+.pf-icon-btn.danger:hover:not(:disabled) {
+ color: #a1261a;
+ background: #ffe8e5;
+ border-color: transparent;
+}
+
+.pf-badge {
+ display: inline-flex;
+ align-items: center;
+ font-size: 0.72rem;
+ font-weight: 600;
+ padding: 0.15rem 0.55rem;
+ border-radius: 999px;
+ background: var(--pf-bg);
+ color: var(--pf-muted);
+}
+
+.pf-badge.ok {
+ background: #eaffc4;
+ color: #3d6500;
+}
+
+.pf-badge.run {
+ background: #e8f0ff;
+ color: #2547a8;
+}
+
+.pf-badge.bad {
+ background: #ffe8e5;
+ color: #a1261a;
+}
+
+.pf-badge.draft {
+ background: #f3f4f6;
+ color: #6b7280;
+}
+
+.pf-pagination {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 0.35rem;
+ margin-top: 1.25rem;
+}
+
+.pf-page-btn {
+ min-width: 34px;
+ height: 34px;
+ border: 1px solid var(--pf-line);
+ background: #fff;
+ border-radius: 8px;
+ color: var(--pf-ink);
+ font-weight: 600;
+ font-size: 0.88rem;
+}
+
+.pf-page-btn:hover:not(:disabled) {
+ border-color: rgba(182, 255, 0, 0.7);
+}
+
+.pf-page-btn.active {
+ background: var(--pf-lime);
+ border-color: var(--pf-lime);
+}
+
+.pf-page-btn:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.pf-page-ellipsis {
+ color: var(--pf-muted);
+ padding: 0 0.2rem;
+}
+
+.pf-history-side {
+ position: sticky;
+ top: calc(var(--pf-nav-h) + 1rem);
+}
+
+.pf-side-box {
+ background: #fff;
+ border: 1px solid var(--pf-line);
+ border-radius: var(--pf-radius);
+ padding: 1.1rem;
+ margin-bottom: 0.85rem;
+ box-shadow: var(--pf-shadow);
+}
+
+.pf-side-box h3 {
+ margin: 0 0 0.35rem;
+ font-size: 1rem;
+ font-weight: 700;
+}
+
+.pf-side-desc {
+ margin: 0 0 0.85rem;
+ color: var(--pf-muted);
+ font-size: 0.82rem;
+ line-height: 1.45;
+}
+
+.pf-quick-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 0.45rem;
+}
+
+.pf-quick-tile {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.35rem;
+ border: 1px solid var(--pf-line);
+ background: #f8f9fa;
+ border-radius: 12px;
+ padding: 0.75rem 0.35rem;
+ color: var(--pf-muted);
+ font-size: 0.72rem;
+ font-weight: 500;
+}
+
+.pf-quick-tile:disabled {
+ cursor: not-allowed;
+ opacity: 0.75;
+}
+
+.pf-platform-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.pf-platform-list li {
+ display: grid;
+ grid-template-columns: 32px 1fr auto;
+ align-items: center;
+ gap: 0.55rem;
+ padding: 0.5rem 0;
+ border-bottom: 1px solid var(--pf-line);
+}
+
+.pf-platform-list li:last-child {
+ border-bottom: 0;
+}
+
+.pf-platform-mark {
+ width: 32px;
+ height: 32px;
+ border-radius: 9px;
+ background: var(--pf-lime-soft);
+ color: #3d6500;
+ display: grid;
+ place-items: center;
+ font-size: 0.72rem;
+ font-weight: 800;
+}
+
+.pf-platform-name {
+ font-size: 0.88rem;
+ font-weight: 500;
+}
+
+.pf-side-foot {
+ margin-top: 0.65rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ font-size: 0.82rem;
+}
+
+.pf-usage-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ font-size: 0.85rem;
+ margin-bottom: 0.25rem;
+}
+
+.pf-meter {
+ height: 8px;
+ background: #eceff3;
+ border-radius: 999px;
+ overflow: hidden;
+ margin: 0.25rem 0 0.85rem;
+}
+
+.pf-meter > i {
+ display: block;
+ height: 100%;
+ background: var(--pf-lime);
+}
+
+.pf-pricing {
+ max-width: 720px;
+ margin: 3rem auto;
+ text-align: center;
+}
+
+.pf-pricing .pf-card {
+ padding: 2rem;
+ margin-top: 1.5rem;
+}
+
+/* modal reuse */
+.modal-backdrop {
+ position: fixed;
+ inset: 0;
+ background: rgba(17, 19, 24, 0.45);
+ display: grid;
+ place-items: center;
+ padding: 1rem;
+ z-index: 50;
+}
+
+.modal {
+ width: min(560px, 100%);
+ padding: 1.25rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ background: #fff;
+ border-radius: var(--pf-radius);
+ border: 1px solid var(--pf-line);
+}
+
+.modal label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+ color: var(--pf-muted);
+ font-size: 0.88rem;
+}
+
+.modal input,
+.modal textarea {
+ border: 1px solid var(--pf-line);
+ border-radius: 8px;
+ padding: 0.55rem 0.7rem;
+}
+
+.preview-modal {
+ width: min(960px, 96vw);
+ max-height: 96vh;
+ overflow: hidden;
+}
+
+.preview-media {
+ width: 100%;
+ height: min(72vh, 720px);
+ object-fit: contain;
+ background: #111;
+ border-radius: 8px;
+}
+
+.stack {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
+
+.stack label {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+ font-size: 0.88rem;
+ color: var(--pf-muted);
+}
+
+.stack input,
+.stack textarea,
+.stack select {
+ border: 1px solid var(--pf-line);
+ border-radius: 8px;
+ padding: 0.55rem 0.7rem;
+ background: #fff;
+ color: var(--pf-ink);
+}
+
+@media (max-width: 1100px) {
+ .pf-home-hero,
+ .pf-create,
+ .pf-style-layout,
+ .pf-board,
+ .pf-editor,
+ .pf-history-layout {
+ grid-template-columns: 1fr;
+ }
+
+ .pf-history-side {
+ position: static;
+ }
+
+ .pf-template-grid,
+ .pf-works-grid,
+ .pf-stats,
+ .pf-home-steps,
+ .pf-outline-grid,
+ .pf-style-grid {
+ grid-template-columns: 1fr 1fr;
+ }
+
+ .pf-nav {
+ grid-template-columns: auto 1fr;
+ }
+
+ .pf-nav-center {
+ display: none;
+ }
+}
+
+@media (max-width: 700px) {
+ .pf-template-grid,
+ .pf-works-grid,
+ .pf-stats,
+ .pf-home-steps,
+ .pf-style-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .pf-project-card {
+ grid-template-columns: 28px 1fr;
+ }
+
+ .pf-project-thumb,
+ .pf-project-thumb img,
+ .pf-project-thumb .ph {
+ width: 100%;
+ height: auto;
+ aspect-ratio: 16 / 9;
+ grid-column: 1 / -1;
+ }
+
+ .pf-project-ratio,
+ .pf-project-actions {
+ grid-column: 1 / -1;
+ justify-content: flex-start;
+ }
+}