Skip to content

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

Initial commit of FrameCut: AI short-video pipeline with LAN access, selectable TTS, style/character lock, Celery autoscale recovery, and history batch zip download.

yif9e9f7ff9e43
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f8f5747
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,15 @@
+.DS_Store
+Thumbs.db
+*.log
+.idea/
+.vscode/
+__pycache__/
+*.pyc
+backend/.venv/
+backend/ai_movie.db
+backend/.env
+backend/.celery_autoscale/
+backend/static/generated/
+frontend/.env
+frontend/node_modules/
+frontend/dist/
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..8e8bd0a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,73 @@
+# 纸戏 FrameCut
+
+模板驱动的 AI 短视频创作平台(MVP)。同一条生成流水线,多套视觉风格模板。
+
+## 能力(本期)
+
+- 6 套内置模板(剪纸 / 绘本 / 粉笔 / 拼贴 / 像素 / 水墨)
+- 注册登录 + 额度
+- 主题/文案 → 分镜脚本 → 分镜图 → 视频片段 → 配音 → 合成(当前默认 **Mock 方舟**)
+- 分镜编辑、单张重绘、单镜头重生视频
+- 作品发布与简单浏览
+
+## 本地启动
+
+### 依赖
+
+- Python 3.12 + FFmpeg(已加入 PATH)
+- Redis(Celery broker;无 Redis 时自动回退进程内异步)
+
+```bash
+# Redis(推荐 Docker)
+docker run -d --name framecut-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
+
+# 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
+```
+
+### 前端
+
+```bash
+cd frontend
+npm install
+npm run dev
+```
+
+### 真模型配置
+
+`backend/.env`:
+
+| 变量 | 说明 |
+|---|---|
+| `ARK_MOCK=false` | 关闭 mock |
+| `ARK_API_KEY` | 方舟 API Key |
+| `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 若接入点未开通,会降级为静音轨,画面与字幕仍可合成。
+
+## 架构摘要
+
+- FastAPI + SQLite(可换 MySQL)
+- 模板表驱动风格:`style_prefix` / Seedream / Seedance / Audio / 字幕配置
+- 异步流水线:进程内 asyncio(可平滑换成 Celery + Redis)
+- 前端:React + TS + Vite
+
+## 目录
+
+```
+backend/app/ API、模型、流水线、方舟适配
+backend/static/ 模板封面与 mock 素材
+frontend/src/ 首页模板墙 + 创作工作台
+```
diff --git a/backend/.env.example b/backend/.env.example
new file mode 100644
index 0000000..0bd247d
--- /dev/null
+++ b/backend/.env.example
@@ -0,0 +1,45 @@
+SECRET_KEY=dev-secret-change-me
+DATABASE_URL=sqlite+aiosqlite:///./ai_movie.db
+DATABASE_URL_SYNC=sqlite:///./ai_movie.db
+REDIS_URL=redis://127.0.0.1:6379/0
+CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173,http://192.168.110.88:5173
+PUBLIC_BASE_URL=http://192.168.110.88:8000
+
+ARK_MOCK=false
+ARK_API_KEY=replace-me
+USE_CELERY=true
+QUOTA_ENABLED=false
+
+# Celery 动态扩缩容(python -m app.workers.autoscale)
+# Windows 下每个 worker 为 solo×1,按队列积压自动加减进程数
+CELERY_AUTOSCALE_MIN=1
+CELERY_AUTOSCALE_MAX=3
+CELERY_AUTOSCALE_POLL_SEC=5
+CELERY_AUTOSCALE_IDLE_SEC=45
+CELERY_AUTOSCALE_QUEUE=pipeline
+# 防僵死:任务超时 + Redis 可见性超时(需 > time_limit)+ 进度停滞自动重派
+CELERY_TASK_SOFT_TIME_LIMIT=1800
+CELERY_TASK_TIME_LIMIT=2100
+CELERY_VISIBILITY_TIMEOUT=2400
+CELERY_STALE_PROJECT_SEC=900
+
+# 旗舰模型(需在方舟控制台开通;若账号仅支持接入点,可改为 ep-xxxxxxxx)
+MODEL_LLM=doubao-seed-2-0-pro-260215
+MODEL_IMAGE=doubao-seedream-5-0-260128
+MODEL_VIDEO=doubao-seedance-2-0-260128
+MODEL_AUDIO=seed-tts-2.0
+
+# 豆包语音合成(openspeech,与方舟 Key 不同)。不配则自动用 edge-tts 兜底
+# VOLC_TTS_APP_ID=
+# VOLC_TTS_ACCESS_KEY=
+# VOLC_TTS_RESOURCE_ID=seed-tts-2.0
+# VOLC_TTS_SPEAKER=zh_female_cancan_uranus_bigtts
+
+ARK_IMAGE_SIZE=2k
+ARK_VIDEO_RESOLUTION=480p
+ARK_VIDEO_RATIO=16:9
+ARK_VIDEO_POLL_INTERVAL=8
+ARK_VIDEO_POLL_TIMEOUT=900
+PIPELINE_IMAGE_CONCURRENCY=3
+PIPELINE_VIDEO_CONCURRENCY=2
+PIPELINE_AUDIO_CONCURRENCY=4
diff --git a/backend/.gitignore b/backend/.gitignore
new file mode 100644
index 0000000..19d43ac
--- /dev/null
+++ b/backend/.gitignore
@@ -0,0 +1,11 @@
+.venv/
+__pycache__/
+*.pyc
+.ai_movie.db
+ai_movie.db
+.env
+*.egg-info/
+.pytest_cache/
+data/
+.celery_autoscale/
+static/mock/image_*.svg
diff --git a/backend/Dockerfile b/backend/Dockerfile
new file mode 100644
index 0000000..0aa3ffe
--- /dev/null
+++ b/backend/Dockerfile
@@ -0,0 +1,7 @@
+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/__init__.py b/backend/app/__init__.py
new file mode 100644
index 0000000..0c696aa
--- /dev/null
+++ b/backend/app/__init__.py
@@ -0,0 +1 @@
+"""AI Movie platform backend."""
\ No newline at end of file
diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py
new file mode 100644
index 0000000..0e04737
--- /dev/null
+++ b/backend/app/api/auth.py
@@ -0,0 +1,47 @@
+from fastapi import APIRouter, Depends, HTTPException, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.database import get_db
+from app.deps import get_current_user
+from app.models import User
+from app.schemas import LoginRequest, RegisterRequest, TokenResponse, UserOut
+from app.services.auth import (
+ create_access_token,
+ get_user_by_email,
+ hash_password,
+ verify_password,
+)
+
+router = APIRouter(prefix="/auth", tags=["auth"])
+settings = get_settings()
+
+
[email protected]("/register", response_model=TokenResponse)
+async def register(body: RegisterRequest, db: AsyncSession = Depends(get_db)) -> TokenResponse:
+ existing = await get_user_by_email(db, body.email)
+ if existing:
+ raise HTTPException(status_code=400, detail="邮箱已注册")
+ user = User(
+ email=body.email.lower(),
+ nickname=body.nickname,
+ hashed_password=hash_password(body.password),
+ quota_left=settings.new_user_quota,
+ )
+ db.add(user)
+ await db.commit()
+ await db.refresh(user)
+ return TokenResponse(access_token=create_access_token(str(user.id)))
+
+
[email protected]("/login", response_model=TokenResponse)
+async def login(body: LoginRequest, db: AsyncSession = Depends(get_db)) -> TokenResponse:
+ user = await get_user_by_email(db, body.email.lower())
+ if not user or not verify_password(body.password, user.hashed_password):
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="邮箱或密码错误")
+ return TokenResponse(access_token=create_access_token(str(user.id)))
+
+
[email protected]("/me", response_model=UserOut)
+async def me(user: User = Depends(get_current_user)) -> User:
+ return user
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
new file mode 100644
index 0000000..8a9e9e5
--- /dev/null
+++ b/backend/app/api/projects.py
@@ -0,0 +1,544 @@
+import asyncio
+import io
+import json
+import re
+import zipfile
+from datetime import datetime
+
+from fastapi import APIRouter, Depends, HTTPException
+from fastapi.responses import StreamingResponse
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+from sse_starlette.sse import EventSourceResponse
+
+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 (
+ ProjectCreate,
+ ProjectDownloadRequest,
+ ProjectListItem,
+ ProjectOut,
+ ProjectUpdate,
+ ShotOut,
+ ShotUpdate,
+ WorkOut,
+)
+from app.services import pipeline, storage
+from app.services.progress import redis_bridge, subscribe, unsubscribe
+from app.services.voices import list_voices
+
+router = APIRouter(tags=["projects"])
+
+
+async def get_voices() -> list[dict]:
+ return list_voices()
+
+
+async def _get_owned_project(db: AsyncSession, project_id: int, user: User) -> Project:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id, Project.user_id == user.id)
+ .options(selectinload(Project.shots))
+ )
+ project = result.scalar_one_or_none()
+ if not project:
+ raise HTTPException(status_code=404, detail="项目不存在")
+ return project
+
+
[email protected]("/projects", response_model=ProjectOut)
+async def create_project(
+ body: ProjectCreate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ from app.models import Template
+
+ tpl = await db.get(Template, body.template_id)
+ if not tpl or not tpl.is_active:
+ raise HTTPException(status_code=400, detail="无效模板")
+ project = Project(
+ user_id=user.id,
+ template_id=body.template_id,
+ title=body.title,
+ source_type=body.source_type,
+ source_text=body.source_text,
+ resolution_mode=body.resolution_mode,
+ pipeline_mode=body.pipeline_mode,
+ voice_id=(body.voice_id or "").strip(),
+ style_prompt=(body.style_prompt or "").strip(),
+ character_prompt=(body.character_prompt or "").strip(),
+ extra_prompt=(body.extra_prompt or "").strip(),
+ ref_image_url=body.ref_image_url,
+ status=ProjectStatus.DRAFT,
+ )
+ db.add(project)
+ await db.commit()
+ await db.refresh(project)
+ result = await db.execute(
+ select(Project).where(Project.id == project.id).options(selectinload(Project.shots))
+ )
+ return result.scalar_one()
+
+
[email protected]("/projects", response_model=list[ProjectListItem])
+async def list_projects(
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> list[Project]:
+ result = await db.execute(
+ select(Project).where(Project.user_id == user.id).order_by(Project.id.desc())
+ )
+ return list(result.scalars().all())
+
+
+def _safe_zip_name(title: str, project_id: int) -> str:
+ raw = (title or "未命名作品").strip() or "未命名作品"
+ cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw)
+ cleaned = cleaned.strip(" .")[:60] or "未命名作品"
+ return f"p{project_id}_{cleaned}.mp4"
+
+
[email protected]("/projects/download-zip")
+async def download_projects_zip(
+ body: ProjectDownloadRequest,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> StreamingResponse:
+ """Zip final videos for selected owned projects (DONE with final_video_url)."""
+ ids = list(dict.fromkeys(int(i) for i in body.ids if int(i) > 0))
+ if not ids:
+ raise HTTPException(status_code=400, detail="请选择要下载的作品")
+ if len(ids) > 50:
+ raise HTTPException(status_code=400, detail="一次最多打包 50 个")
+
+ result = await db.execute(
+ select(Project).where(Project.user_id == user.id, Project.id.in_(ids))
+ )
+ projects = list(result.scalars().all())
+ by_id = {p.id: p for p in projects}
+ missing = [i for i in ids if i not in by_id]
+ if missing:
+ raise HTTPException(status_code=404, detail=f"项目不存在: {missing[:5]}")
+
+ entries: list[tuple[str, bytes]] = []
+ skipped: list[str] = []
+ for pid in ids:
+ p = by_id[pid]
+ if p.status != ProjectStatus.DONE or not p.final_video_url:
+ skipped.append(f"#{pid}")
+ continue
+ path = storage.local_path_from_url(p.final_video_url)
+ if not path or not path.exists():
+ skipped.append(f"#{pid}")
+ continue
+ entries.append((_safe_zip_name(p.title, p.id), path.read_bytes()))
+
+ if not entries:
+ raise HTTPException(
+ status_code=400,
+ detail="所选作品暂无成片可下载(需状态为已完成)",
+ )
+
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
+ used: set[str] = set()
+ for name, data in entries:
+ final_name = name
+ n = 1
+ while final_name in used:
+ stem = name.rsplit(".", 1)[0]
+ final_name = f"{stem}_{n}.mp4"
+ n += 1
+ used.add(final_name)
+ zf.writestr(final_name, data)
+ if skipped:
+ zf.writestr(
+ "skipped.txt",
+ "以下项目未打包(未完成或缺少成片文件):\n" + "\n".join(skipped),
+ )
+ buf.seek(0)
+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ filename = f"framecut_videos_{stamp}.zip"
+ headers = {"Content-Disposition": f'attachment; filename="{filename}"'}
+ return StreamingResponse(buf, media_type="application/zip", headers=headers)
+
+
[email protected]("/projects/{project_id}", response_model=ProjectOut)
+async def get_project(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ return await _get_owned_project(db, project_id, user)
+
+
[email protected]("/projects/{project_id}", response_model=ProjectOut)
+async def update_project(
+ project_id: int,
+ body: ProjectUpdate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> 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="生成进行中,无法修改")
+
+ data = body.model_dump(exclude_unset=True)
+ if "template_id" in data:
+ from app.models import Template
+
+ tpl = await db.get(Template, data["template_id"])
+ if not tpl or not tpl.is_active:
+ 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}/generate", response_model=ProjectOut)
+async def generate_project(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> 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="生成进行中,请稍后")
+
+ # 额度暂时不限制
+ project.status = ProjectStatus.SCRIPTING
+ project.progress = 1
+ project.error_msg = None
+ project.final_video_url = None
+ await db.commit()
+ task_id = pipeline.start_pipeline(project_id)
+ # Persist celery id on a job row when available
+ if task_id and task_id != "in-process":
+ from app.models import PipelineJob
+
+ db.add(PipelineJob(project_id=project_id, stage="DISPATCH", progress=1, celery_task_id=task_id))
+ await db.commit()
+ return await _get_owned_project(db, project_id, user)
+
+
[email protected]("/projects/{project_id}/cancel", response_model=ProjectOut)
+async def cancel_project(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ project = await _get_owned_project(db, project_id, user)
+ running = {
+ ProjectStatus.SCRIPTING,
+ ProjectStatus.IMAGING,
+ ProjectStatus.IMAGE_READY,
+ ProjectStatus.VIDEOING,
+ ProjectStatus.VIDEO_READY,
+ ProjectStatus.AUDIOING,
+ ProjectStatus.COMPOSING,
+ ProjectStatus.AUDITING,
+ }
+ if project.status not in running:
+ raise HTTPException(status_code=400, detail="当前状态不可取消")
+
+ pipeline.cancel_pipeline(project_id)
+ project.status = ProjectStatus.CANCELLED
+ project.error_msg = "用户取消"
+ await db.commit()
+ return await _get_owned_project(db, project_id, user)
+
+
[email protected]("/projects/{project_id}")
+async def delete_project(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ project = await _get_owned_project(db, project_id, user)
+ running = {
+ ProjectStatus.SCRIPTING,
+ ProjectStatus.IMAGING,
+ ProjectStatus.IMAGE_READY,
+ ProjectStatus.VIDEOING,
+ ProjectStatus.VIDEO_READY,
+ ProjectStatus.AUDIOING,
+ ProjectStatus.COMPOSING,
+ ProjectStatus.AUDITING,
+ }
+ if project.status in running:
+ pipeline.cancel_pipeline(project_id)
+
+ # Remove published work if any
+ work_result = await db.execute(select(Work).where(Work.project_id == project.id))
+ work = work_result.scalar_one_or_none()
+ if work:
+ await db.delete(work)
+
+ await pipeline.delete_project_assets(project_id)
+ await db.delete(project)
+ await db.commit()
+ return {"ok": True, "id": project_id}
+
+
[email protected]("/projects/{project_id}/events")
+async def project_events(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+):
+ await _get_owned_project(db, project_id, user)
+ queue = subscribe(project_id)
+ bridge = asyncio.create_task(redis_bridge(project_id, queue))
+
+ async def event_generator():
+ try:
+ while True:
+ try:
+ payload = await asyncio.wait_for(queue.get(), timeout=15.0)
+ yield {"event": "message", "data": json.dumps(payload, ensure_ascii=False)}
+ if payload.get("event") in {"done", "failed"}:
+ break
+ except TimeoutError:
+ yield {"event": "ping", "data": "{}"}
+ finally:
+ bridge.cancel()
+ unsubscribe(project_id, queue)
+
+ return EventSourceResponse(event_generator())
+
+
[email protected]("/projects/{project_id}/shots/{shot_id}", response_model=ShotOut)
+async def update_shot(
+ project_id: int,
+ shot_id: int,
+ body: ShotUpdate,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Shot:
+ from app.models import Template
+ from app.services.pipeline import clamp_shot_duration
+
+ project = await _get_owned_project(db, project_id, user)
+ shot = next((s for s in project.shots if s.id == shot_id), None)
+ if not shot:
+ raise HTTPException(status_code=404, detail="分镜不存在")
+ data = body.model_dump(exclude_unset=True)
+ if "duration" in data and data["duration"] is not None:
+ tpl = await db.get(Template, project.template_id)
+ data["duration"] = clamp_shot_duration(
+ float(data["duration"]),
+ pipeline_mode=project.pipeline_mode or "full",
+ tpl_min=tpl.shot_duration_min if tpl else 2,
+ tpl_max=tpl.shot_duration_max if tpl else 8,
+ )
+ for k, v in data.items():
+ setattr(shot, k, v)
+ # Invalidate downstream if visual prompts changed
+ if "img_prompt" in data:
+ shot.image_url = None
+ shot.video_url = None
+ shot.status = "PENDING"
+ project.final_video_url = None
+ elif "video_prompt" in data or "duration" in data or "camera" in data:
+ shot.video_url = None
+ project.final_video_url = None
+ shot.version += 1
+ await db.commit()
+ await db.refresh(shot)
+ return shot
+
+
[email protected]("/projects/{project_id}/shots/{shot_id}/regen-image", response_model=ShotOut)
+async def regen_image(
+ project_id: int,
+ shot_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Shot:
+ await _get_owned_project(db, project_id, user)
+ try:
+ await pipeline.regen_shot_image(project_id, shot_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ msg = str(exc)
+ if "PolicyViolation" in msg or "SensitiveContent" in msg:
+ raise HTTPException(
+ status_code=400,
+ detail="画面提示词触发内容安全策略,请编辑分镜去掉品牌/人名后重试",
+ ) from exc
+ raise HTTPException(status_code=502, detail=msg[:500]) from exc
+ project = await _get_owned_project(db, project_id, user)
+ shot = next(s for s in project.shots if s.id == shot_id)
+ return shot
+
+
[email protected]("/projects/{project_id}/shots/{shot_id}/regen-video", response_model=ShotOut)
+async def regen_video(
+ project_id: int,
+ shot_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Shot:
+ await _get_owned_project(db, project_id, user)
+ try:
+ await pipeline.regen_shot_video(project_id, shot_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc
+ project = await _get_owned_project(db, project_id, user)
+ shot = next(s for s in project.shots if s.id == shot_id)
+ return shot
+
+
[email protected]("/projects/{project_id}/shots/{shot_id}/regen-audio", response_model=ShotOut)
+async def regen_audio(
+ project_id: int,
+ shot_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Shot:
+ await _get_owned_project(db, project_id, user)
+ try:
+ await pipeline.regen_shot_audio(project_id, shot_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc
+ project = await _get_owned_project(db, project_id, user)
+ shot = next(s for s in project.shots if s.id == shot_id)
+ return shot
+
+
[email protected]("/projects/{project_id}/regen-audio", response_model=ProjectOut)
+async def regen_all_audio(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ """Re-TTS all shots with current voice_id, then recompose final video."""
+ 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="生成进行中,请稍后")
+ if not project.shots:
+ raise HTTPException(status_code=400, detail="暂无分镜,请先生成")
+ project.status = ProjectStatus.AUDIOING
+ project.progress = 80
+ project.error_msg = None
+ project.final_video_url = None
+ await db.commit()
+ try:
+ await pipeline.regen_project_audio_and_compose(project_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc
+ return await _get_owned_project(db, project_id, user)
+
+
[email protected]("/projects/{project_id}/compose", response_model=ProjectOut)
+async def compose_only(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Project:
+ """Recompose final video from existing images/audio/(videos)."""
+ 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="生成进行中,请稍后")
+ if not project.shots or not any(s.image_url for s in project.shots):
+ raise HTTPException(status_code=400, detail="缺少分镜图,无法合成")
+ project.status = ProjectStatus.COMPOSING
+ project.progress = 90
+ project.error_msg = None
+ await db.commit()
+ try:
+ await pipeline.compose_only(project_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)[:500]) from exc
+ return await _get_owned_project(db, project_id, user)
+
+
[email protected]("/projects/{project_id}/publish", response_model=WorkOut)
+async def publish_work(
+ project_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> Work:
+ project = await _get_owned_project(db, project_id, user)
+ if project.status != ProjectStatus.DONE or not project.final_video_url:
+ raise HTTPException(status_code=400, detail="成片未完成,无法发布")
+ existing = await db.execute(select(Work).where(Work.project_id == project.id))
+ work = existing.scalar_one_or_none()
+ if work:
+ work.title = project.title
+ work.cover_url = project.cover_url
+ work.video_url = project.final_video_url
+ else:
+ work = Work(
+ project_id=project.id,
+ user_id=user.id,
+ title=project.title,
+ cover_url=project.cover_url,
+ video_url=project.final_video_url,
+ )
+ db.add(work)
+ await db.commit()
+ await db.refresh(work)
+ return work
+
+
[email protected]("/works", response_model=list[WorkOut])
+async def list_works(db: AsyncSession = Depends(get_db)) -> list[Work]:
+ result = await db.execute(
+ select(Work).where(Work.visibility == "public").order_by(Work.id.desc()).limit(50)
+ )
+ return list(result.scalars().all())
+
+
+async def quota(user: User = Depends(get_current_user)) -> dict:
+ from app.config import get_settings
+
+ settings = get_settings()
+ return {
+ "quota_left": user.quota_left,
+ "quota_enabled": settings.quota_enabled,
+ "unlimited": not settings.quota_enabled,
+ }
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py
new file mode 100644
index 0000000..190b8a7
--- /dev/null
+++ b/backend/app/api/templates.py
@@ -0,0 +1,25 @@
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.models import Template
+from app.schemas import TemplateDetailOut, TemplateOut
+
+router = APIRouter(prefix="/templates", tags=["templates"])
+
+
[email protected]("", response_model=list[TemplateDetailOut])
+async def list_templates(db: AsyncSession = Depends(get_db)) -> list[Template]:
+ result = await db.execute(
+ select(Template).where(Template.is_active.is_(True)).order_by(Template.sort_order)
+ )
+ return list(result.scalars().all())
+
+
[email protected]("/{template_id}", response_model=TemplateDetailOut)
+async def get_template(template_id: str, db: AsyncSession = Depends(get_db)) -> Template:
+ tpl = await db.get(Template, template_id)
+ if not tpl or not tpl.is_active:
+ raise HTTPException(status_code=404, detail="模板不存在")
+ return tpl
diff --git a/backend/app/config.py b/backend/app/config.py
new file mode 100644
index 0000000..063148b
--- /dev/null
+++ b/backend/app/config.py
@@ -0,0 +1,83 @@
+from functools import lru_cache
+
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+
+class Settings(BaseSettings):
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
+
+ app_name: str = "AI Movie"
+ debug: bool = True
+ secret_key: str = "dev-secret-change-me"
+ access_token_expire_minutes: int = 60 * 24 * 7
+
+ database_url: str = "sqlite+aiosqlite:///./ai_movie.db"
+ database_url_sync: str = "sqlite:///./ai_movie.db"
+ redis_url: str = "redis://127.0.0.1:6379/0"
+
+ ark_api_key: str = ""
+ ark_base_url: str = "https://ark.cn-beijing.volces.com/api/v3"
+ model_llm: str = "doubao-seed-2-0-pro-260215"
+ model_image: str = "doubao-seedream-5-0-260128"
+ model_video: str = "doubao-seedance-2-0-260128"
+ model_audio: str = "seed-tts-2.0"
+ # 豆包语音(openspeech)— 与方舟 ARK_API_KEY 不同产品线
+ volc_tts_app_id: str = ""
+ volc_tts_access_key: str = ""
+ volc_tts_resource_id: str = "seed-tts-2.0"
+ volc_tts_speaker: str = "zh_female_cancan_uranus_bigtts"
+ volc_tts_url: str = "https://openspeech.bytedance.com/api/v3/tts/unidirectional"
+ # Seedream: 2k|3k|4k or WIDTHxHEIGHT,且总像素 >= 3686400(约 2560x1440)
+ ark_image_size: str = "2k"
+ ark_video_resolution: str = "480p"
+ ark_video_ratio: str = "16:9"
+ ark_video_poll_interval: float = 8.0
+ ark_video_poll_timeout: float = 900.0
+ # Parallel generation concurrency (per project)
+ pipeline_image_concurrency: int = 3
+ pipeline_video_concurrency: int = 2
+ pipeline_audio_concurrency: int = 4
+
+ ark_mock: bool = True
+ use_celery: bool = True
+
+ # Celery worker autoscaler (python -m app.workers.autoscale)
+ # Windows: each worker is solo/concurrency=1; scale by process count.
+ celery_autoscale_min: int = 1
+ celery_autoscale_max: int = 3
+ celery_autoscale_poll_sec: float = 5.0
+ celery_autoscale_idle_sec: float = 45.0
+ celery_autoscale_queue: str = "pipeline"
+ # Prevent zombie tasks: hard kill hung workers; Redis redelivers after visibility_timeout
+ celery_task_soft_time_limit: int = 1800 # 30 min soft
+ celery_task_time_limit: int = 2100 # 35 min hard
+ celery_visibility_timeout: int = 2400 # 40 min — must be > time_limit
+ celery_stale_project_sec: int = 900 # redispatch RUNNING with no progress for 15 min
+
+ max_shot_duration: int = 30
+ default_preview_resolution: str = "480p"
+ new_user_quota: int = 5
+ # MVP: set false to skip quota check/deduction
+ quota_enabled: bool = False
+
+ public_base_url: str = "http://127.0.0.1:8000"
+ ffmpeg_path: str = "ffmpeg"
+ ffprobe_path: str = "ffprobe"
+
+ tos_endpoint: str = ""
+ tos_bucket: str = ""
+ tos_access_key: str = ""
+ tos_secret_key: str = ""
+ cdn_base: str = "http://localhost:8000/static"
+
+ cors_origins: str = "http://localhost:5173,http://127.0.0.1:5173"
+
+
+@lru_cache
+def get_settings() -> Settings:
+ return Settings()
+
+
+def reload_settings() -> Settings:
+ get_settings.cache_clear()
+ return get_settings()
diff --git a/backend/app/database.py b/backend/app/database.py
new file mode 100644
index 0000000..a35b0ca
--- /dev/null
+++ b/backend/app/database.py
@@ -0,0 +1,27 @@
+from collections.abc import AsyncGenerator
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.orm import DeclarativeBase
+
+from app.config import get_settings
+
+settings = get_settings()
+
+engine = create_async_engine(settings.database_url, echo=settings.debug)
+AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+
+
+class Base(DeclarativeBase):
+ pass
+
+
+async def get_db() -> AsyncGenerator[AsyncSession, None]:
+ async with AsyncSessionLocal() as session:
+ yield session
+
+
+async def init_db() -> None:
+ from app import models # noqa: F401
+
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
diff --git a/backend/app/deps.py b/backend/app/deps.py
new file mode 100644
index 0000000..e737fbe
--- /dev/null
+++ b/backend/app/deps.py
@@ -0,0 +1,24 @@
+from fastapi import Depends, HTTPException, status
+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.database import get_db
+from app.models import User
+from app.services.auth import decode_token, get_user_by_id
+
+security = HTTPBearer(auto_error=False)
+
+
+async def get_current_user(
+ creds: HTTPAuthorizationCredentials | None = Depends(security),
+ db: AsyncSession = Depends(get_db),
+) -> User:
+ if not creds:
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="未登录")
+ sub = decode_token(creds.credentials)
+ if not sub:
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效")
+ user = await get_user_by_id(db, int(sub))
+ if not user:
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在")
+ return user
diff --git a/backend/app/main.py b/backend/app/main.py
new file mode 100644
index 0000000..447f619
--- /dev/null
+++ b/backend/app/main.py
@@ -0,0 +1,144 @@
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.staticfiles import StaticFiles
+from sqlalchemy import select, text
+
+from app.api import auth, projects, templates
+from app.config import get_settings
+from app.database import AsyncSessionLocal, engine, init_db
+from app.models import Template
+from app.services.templates_seed import TEMPLATES
+
+settings = get_settings()
+app = FastAPI(title=settings.app_name, version="0.2.0")
+
+origins = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
+# Allow LAN devices (phone/tablet) hitting Vite on private IPs
+_LAN_ORIGIN_RE = (
+ r"https?://("
+ r"localhost|127\.0\.0\.1|"
+ r"192\.168\.\d{1,3}\.\d{1,3}|"
+ r"10\.\d{1,3}\.\d{1,3}\.\d{1,3}|"
+ r"172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}"
+ r")(:\d+)?"
+)
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=origins or ["*"],
+ allow_origin_regex=_LAN_ORIGIN_RE,
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+static_dir = Path(__file__).resolve().parent.parent / "static"
+static_dir.mkdir(parents=True, exist_ok=True)
+(static_dir / "templates").mkdir(exist_ok=True)
+(static_dir / "mock").mkdir(exist_ok=True)
+(static_dir / "generated").mkdir(exist_ok=True)
+app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
+
+app.include_router(auth.router, prefix="/api")
+app.include_router(templates.router, prefix="/api")
+app.include_router(projects.router, prefix="/api")
+
+
[email protected]_event("startup")
+async def on_startup() -> None:
+ await init_db()
+ await _migrate_sqlite()
+ await seed_templates()
+
+
+async def _migrate_sqlite() -> None:
+ """Lightweight additive migrations for SQLite MVP."""
+ 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 "pipeline_mode" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN pipeline_mode VARCHAR(32) DEFAULT 'full'"))
+ 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:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN character_bible TEXT DEFAULT ''"))
+ if "style_prompt" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN style_prompt TEXT DEFAULT ''"))
+ if "character_prompt" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN character_prompt TEXT DEFAULT ''"))
+ if "extra_prompt" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN extra_prompt TEXT DEFAULT ''"))
+
+
+async def seed_templates() -> None:
+ async with AsyncSessionLocal() as db:
+ for item in TEMPLATES:
+ existing = await db.get(Template, item["id"])
+ if existing:
+ for k, v in item.items():
+ setattr(existing, k, v)
+ else:
+ db.add(Template(**item))
+ await db.commit()
+ result = await db.execute(select(Template))
+ _ = result.scalars().all()
+
+
[email protected]("/api/health")
+async def health() -> dict:
+ from app.config import reload_settings
+
+ s = reload_settings()
+ redis_ok = False
+ queue_pending = None
+ queue_unacked = None
+ try:
+ import redis
+
+ r = redis.Redis.from_url(
+ s.redis_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2
+ )
+ redis_ok = bool(r.ping())
+ if redis_ok:
+ q = (s.celery_autoscale_queue or "pipeline").strip() or "pipeline"
+ queue_pending = int(r.llen(q) or 0)
+ try:
+ queue_unacked = int(r.hlen("unacked") or 0)
+ except Exception: # noqa: BLE001
+ queue_unacked = None
+ except Exception: # noqa: BLE001
+ redis_ok = False
+ return {
+ "ok": True,
+ "ark_mock": s.ark_mock,
+ "use_celery": s.use_celery,
+ "redis_ok": redis_ok,
+ "queue": {"name": s.celery_autoscale_queue, "pending": queue_pending, "unacked": queue_unacked},
+ "autoscale": {
+ "min": s.celery_autoscale_min,
+ "max": s.celery_autoscale_max,
+ "poll_sec": s.celery_autoscale_poll_sec,
+ "idle_sec": s.celery_autoscale_idle_sec,
+ },
+ "models": {
+ "llm": s.model_llm,
+ "image": s.model_image,
+ "video": s.model_video,
+ "audio": s.model_audio,
+ },
+ "quality": {
+ "image_size": s.ark_image_size,
+ "video_resolution": s.ark_video_resolution,
+ },
+ "app": s.app_name,
+ }
diff --git a/backend/app/models.py b/backend/app/models.py
new file mode 100644
index 0000000..7714922
--- /dev/null
+++ b/backend/app/models.py
@@ -0,0 +1,159 @@
+from datetime import datetime
+from enum import StrEnum
+
+from sqlalchemy import JSON, Boolean, DateTime, Float, ForeignKey, Integer, String, Text, func
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from app.database import Base
+
+
+class ProjectStatus(StrEnum):
+ DRAFT = "DRAFT"
+ SCRIPTING = "SCRIPTING"
+ SCRIPT_READY = "SCRIPT_READY"
+ IMAGING = "IMAGING"
+ IMAGE_READY = "IMAGE_READY"
+ VIDEOING = "VIDEOING"
+ VIDEO_READY = "VIDEO_READY"
+ AUDIOING = "AUDIOING"
+ COMPOSING = "COMPOSING"
+ AUDITING = "AUDITING"
+ DONE = "DONE"
+ REJECTED = "REJECTED"
+ FAILED = "FAILED"
+ CANCELLED = "CANCELLED"
+
+
+class ShotStatus(StrEnum):
+ PENDING = "PENDING"
+ IMAGE_READY = "IMAGE_READY"
+ VIDEO_READY = "VIDEO_READY"
+ AUDIO_READY = "AUDIO_READY"
+ FAILED = "FAILED"
+
+
+class User(Base):
+ __tablename__ = "users"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
+ nickname: Mapped[str] = mapped_column(String(64), default="创作者")
+ hashed_password: Mapped[str] = mapped_column(String(255))
+ quota_left: Mapped[int] = mapped_column(Integer, default=5)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+ projects: Mapped[list["Project"]] = relationship(back_populates="owner")
+
+
+class Template(Base):
+ __tablename__ = "templates"
+
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
+ name: Mapped[str] = mapped_column(String(128))
+ description: Mapped[str] = mapped_column(Text, default="")
+ category: Mapped[list] = mapped_column(JSON, default=list)
+ preview_cover: Mapped[str] = mapped_column(String(512), default="")
+ style_prefix: Mapped[str] = mapped_column(Text)
+ negative_prompt: Mapped[str] = mapped_column(Text, default="")
+ default_ratio: Mapped[str] = mapped_column(String(16), default="16:9")
+ shot_duration_min: Mapped[int] = mapped_column(Integer, default=3)
+ shot_duration_max: Mapped[int] = mapped_column(Integer, default=8)
+ llm_system_addon: Mapped[str] = mapped_column(Text, default="")
+ seedream_config: Mapped[dict] = mapped_column(JSON, default=dict)
+ seedance_config: Mapped[dict] = mapped_column(JSON, default=dict)
+ audio_config: Mapped[dict] = mapped_column(JSON, default=dict)
+ subtitle_config: Mapped[dict] = mapped_column(JSON, default=dict)
+ sort_order: Mapped[int] = mapped_column(Integer, default=0)
+ is_active: Mapped[bool] = mapped_column(Boolean, default=True)
+ is_premium: Mapped[bool] = mapped_column(Boolean, default=False)
+
+
+class Project(Base):
+ __tablename__ = "projects"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
+ template_id: Mapped[str] = mapped_column(ForeignKey("templates.id"), index=True)
+ title: Mapped[str] = mapped_column(String(200), default="未命名作品")
+ source_type: Mapped[str] = mapped_column(String(16), default="theme") # theme | script
+ source_text: Mapped[str] = mapped_column(Text)
+ 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)
+ 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")
+ # 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
+ character_bible: Mapped[str] = mapped_column(Text, default="")
+ # User overrides from studio (optional)
+ 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)
+ 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()
+ )
+
+ owner: Mapped["User"] = relationship(back_populates="projects")
+ template: Mapped["Template"] = relationship()
+ shots: Mapped[list["Shot"]] = relationship(back_populates="project", cascade="all, delete-orphan")
+ jobs: Mapped[list["PipelineJob"]] = relationship(back_populates="project", cascade="all, delete-orphan")
+
+
+class Shot(Base):
+ __tablename__ = "shots"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ project_id: Mapped[int] = mapped_column(ForeignKey("projects.id"), index=True)
+ shot_no: Mapped[int] = mapped_column(Integer)
+ duration: Mapped[float] = mapped_column(Float, default=4.0)
+ narration: Mapped[str] = mapped_column(Text, default="") # TTS 旁白
+ overlay_title: Mapped[str] = mapped_column(String(128), default="") # 图文顶部大标题
+ overlay_subtitle: Mapped[str] = mapped_column(String(256), default="") # 图文顶部副标题(叠字)
+ img_prompt: Mapped[str] = mapped_column(Text, default="")
+ 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_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)
+ status: Mapped[str] = mapped_column(String(32), default=ShotStatus.PENDING)
+ version: Mapped[int] = mapped_column(Integer, default=1)
+
+ project: Mapped["Project"] = relationship(back_populates="shots")
+
+
+class PipelineJob(Base):
+ __tablename__ = "pipeline_jobs"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ project_id: Mapped[int] = mapped_column(ForeignKey("projects.id"), index=True)
+ stage: Mapped[str] = mapped_column(String(32))
+ celery_task_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ progress: Mapped[int] = mapped_column(Integer, default=0)
+ error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ error_msg: Mapped[str | None] = mapped_column(Text, nullable=True)
+ retry_count: Mapped[int] = mapped_column(Integer, default=0)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+ project: Mapped["Project"] = relationship(back_populates="jobs")
+
+
+class Work(Base):
+ __tablename__ = "works"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ 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))
+ 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
new file mode 100644
index 0000000..6329e51
--- /dev/null
+++ b/backend/app/schemas.py
@@ -0,0 +1,186 @@
+from datetime import datetime
+
+from pydantic import BaseModel, EmailStr, Field
+
+
+# ---- Auth ----
+class RegisterRequest(BaseModel):
+ email: EmailStr
+ password: str = Field(min_length=6, max_length=64)
+ nickname: str = Field(default="创作者", max_length=64)
+
+
+class LoginRequest(BaseModel):
+ email: EmailStr
+ password: str
+
+
+class TokenResponse(BaseModel):
+ access_token: str
+ token_type: str = "bearer"
+
+
+class UserOut(BaseModel):
+ id: int
+ email: EmailStr
+ nickname: str
+ quota_left: int
+
+ model_config = {"from_attributes": True}
+
+
+# ---- Templates ----
+class TemplateOut(BaseModel):
+ id: str
+ name: str
+ description: str
+ category: list[str]
+ preview_cover: str
+ default_ratio: str
+ shot_duration_min: int
+ shot_duration_max: int
+ is_premium: bool
+ sort_order: int
+
+ model_config = {"from_attributes": True}
+
+
+class TemplateDetailOut(TemplateOut):
+ style_prefix: str
+ negative_prompt: str
+ llm_system_addon: str
+ seedream_config: dict
+ seedance_config: dict
+ audio_config: dict
+ subtitle_config: dict
+
+
+# ---- Shots / Projects ----
+class ShotOut(BaseModel):
+ id: int
+ shot_no: int
+ duration: float
+ narration: str
+ overlay_title: str = ""
+ overlay_subtitle: str = ""
+ img_prompt: str
+ video_prompt: str
+ camera: str
+ bgm_mood: str
+ image_url: str | None
+ video_url: str | None
+ audio_url: str | None
+ status: str
+ version: int
+
+ model_config = {"from_attributes": True}
+
+
+class ShotUpdate(BaseModel):
+ narration: str | None = None
+ overlay_title: str | None = None
+ overlay_subtitle: str | None = None
+ img_prompt: str | None = None
+ video_prompt: str | None = None
+ duration: float | None = Field(default=None, ge=1, le=30)
+ camera: str | None = None
+ bgm_mood: str | None = None
+
+
+class ProjectCreate(BaseModel):
+ template_id: str
+ title: str = "未命名作品"
+ source_type: str = Field(default="theme", pattern="^(theme|script)$")
+ 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)$")
+ 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
+
+
+class ProjectUpdate(BaseModel):
+ title: str | None = Field(default=None, max_length=200)
+ source_type: str | None = Field(default=None, pattern="^(theme|script)$")
+ 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)$")
+ 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
+
+
+class ProjectOut(BaseModel):
+ id: int
+ template_id: str
+ title: str
+ source_type: str
+ source_text: str
+ status: str
+ progress: int
+ error_msg: str | None
+ cover_url: str | None
+ final_video_url: str | None
+ resolution_mode: str
+ pipeline_mode: str = "full"
+ voice_id: str = ""
+ character_bible: str = ""
+ style_prompt: str = ""
+ character_prompt: str = ""
+ extra_prompt: str = ""
+ ref_image_url: str | None
+ created_at: datetime
+ updated_at: datetime
+ shots: list[ShotOut] = []
+
+ model_config = {"from_attributes": True}
+
+
+class ProjectListItem(BaseModel):
+ id: int
+ title: str
+ template_id: str
+ status: str
+ progress: int
+ cover_url: str | None
+ final_video_url: str | None = None
+ error_msg: str | None = None
+ pipeline_mode: str = "full"
+ created_at: datetime
+ updated_at: datetime | None = None
+
+ model_config = {"from_attributes": True}
+
+
+class ProjectDownloadRequest(BaseModel):
+ ids: list[int] = Field(default_factory=list, min_length=1, max_length=50)
+
+
+class WorkOut(BaseModel):
+ id: int
+ project_id: int
+ user_id: int
+ title: str
+ cover_url: str | None
+ video_url: str
+ visibility: str
+ published_at: datetime
+
+ model_config = {"from_attributes": True}
+
+
+class ProgressEvent(BaseModel):
+ event: str
+ stage: str | None = None
+ shot: int | None = None
+ total: int | None = None
+ percent: int | None = None
+ message: str | None = None
+ video_url: str | None = None
+ retryable: bool | None = None
+ code: str | None = None
diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
new file mode 100644
index 0000000..74c35f2
--- /dev/null
+++ b/backend/app/services/ark.py
@@ -0,0 +1,804 @@
+"""Volcengine Ark gateway via HTTP (chat / Seedream / Seedance / TTS)."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import hashlib
+import json
+import logging
+import re
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import httpx
+
+from app.config import Settings, get_settings
+from app.services import storage
+from app.services.ffmpeg_compose import is_near_silent_audio
+
+logger = logging.getLogger(__name__)
+
+# Soften brand / IP names that Seedream often rejects as copyright
+_SEEDREAM_SANITIZE: list[tuple[re.Pattern[str], str]] = [
+ (re.compile(r"(?i)\bspacex\b"), "民营商业航天公司"),
+ (re.compile(r"(?i)\bspace\s*x\b"), "民营商业航天公司"),
+ (re.compile(r"(?i)\bfalcon\s*heavy\b"), "重型运载火箭"),
+ (re.compile(r"(?i)\bfalcon\s*1\b"), "首枚试验运载火箭"),
+ (re.compile(r"(?i)\bfalcon\s*9\b"), "可回收运载火箭"),
+ (re.compile(r"(?i)\bfalcon\b"), "试验运载火箭"),
+ (re.compile(r"(?i)\bstarship\b"), "巨型运载飞船"),
+ (re.compile(r"(?i)\belon\s*musk\b"), "航天企业家"),
+ (re.compile(r"(?i)\btesla\b"), "电动车企业"),
+ (re.compile(r"猎鹰一号"), "首枚试验运载火箭"),
+ (re.compile(r"猎鹰\s*9"), "可回收运载火箭"),
+ (re.compile(r"猎鹰重型"), "重型运载火箭"),
+ (re.compile(r"猎鹰"), "试验运载火箭"),
+ (re.compile(r"马斯克"), "航天企业家"),
+ (re.compile(r"埃隆"), "航天企业家"),
+ (re.compile(r"Space\s*X"), "民营商业航天公司"),
+]
+
+_SEEDREAM_STRIP_PROPER: re.Pattern[str] = re.compile(
+ r"(SpaceX|Space\s*X|Falcon\s*\d*|Starship|Elon\s*Musk|Tesla|"
+ r"猎鹰一号|猎鹰\s*9|猎鹰重型|猎鹰|马斯克|埃隆|特斯拉)"
+)
+
+
+@dataclass
+class ShotPlan:
+ shot: int
+ duration: float
+ text: str
+ img_prompt: str
+ video_prompt: str
+ camera: str
+ bgm: str
+ overlay_title: str = ""
+ overlay_subtitle: str = ""
+
+
+@dataclass
+class StoryboardResult:
+ shots: list[ShotPlan]
+ character_bible: str = ""
+
+
+@dataclass
+class TaskResult:
+ status: str # pending | running | succeeded | failed
+ url: str | None = None
+ error: str | None = None
+
+
+@dataclass
+class ImageResult:
+ local_url: str
+ remote_url: str | None = None
+
+
+class ArkGateway:
+ def __init__(self, settings: Settings | None = None) -> None:
+ self._settings_override = settings
+
+ @property
+ def settings(self) -> Settings:
+ return self._settings_override or get_settings()
+
+ @property
+ def mock(self) -> bool:
+ return self.settings.ark_mock or not self.settings.ark_api_key
+
+ def _headers(self) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {self.settings.ark_api_key}",
+ "Content-Type": "application/json",
+ }
+
+ def _url(self, path: str) -> str:
+ base = self.settings.ark_base_url.rstrip("/")
+ if not path.startswith("/"):
+ path = "/" + path
+ return f"{base}{path}"
+
+ async def chat_storyboard(
+ self,
+ source_text: str,
+ source_type: str,
+ style_prefix: str,
+ llm_system_addon: str,
+ duration_min: int,
+ duration_max: int,
+ max_shot_duration: int,
+ *,
+ pipeline_mode: str = "full",
+ character_hint: str = "",
+ extra_requirements: str = "",
+ ) -> StoryboardResult:
+ if self.mock:
+ return await asyncio.to_thread(
+ self._mock_storyboard,
+ source_text,
+ source_type,
+ style_prefix,
+ duration_min,
+ duration_max,
+ pipeline_mode,
+ )
+
+ user_constraints = ""
+ if (character_hint or "").strip():
+ user_constraints += (
+ f"用户指定人物设定(必须严格遵守,写入 character_bible):{(character_hint or '').strip()}。"
+ )
+ 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 一致的关键特征即可。"
+ )
+ if pipeline_mode == "image_text":
+ system = (
+ "你是竖屏图文短视频编剧。所有字段必须使用简体中文。"
+ 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字,可诗意)、"
+ "text(旁白台词,口语化,约匹配该镜时长,可供 TTS 朗读,一般 20-60 字)、"
+ "img_prompt(竖屏构图画面提示词,留出顶部约1/4给文字叠层,主体偏中下,"
+ "含统一画风与人物锁定,禁止要求画面内写字;"
+ "禁止出现真实商标/公司名/人名,用泛称)、"
+ "video_prompt(可留空或写轻微推拉)、camera(如:缓慢推近/轻拉远)、bgm(情绪)。"
+ "拆成 5-10 个分镜,每镜一个独立视觉场景,但画风与人物必须一致。"
+ )
+ else:
+ system = (
+ "你是短视频分镜编剧。所有字段必须使用简体中文"
+ "(包括 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(画面生成中文提示词,含统一画风与人物锁定与具体景物;"
+ "禁止真实商标/公司名/人名,改用泛称)、"
+ "video_prompt(镜头运动与动态的中文提示词)、"
+ "camera(运镜,如:缓慢上摇/轻推/横移)、bgm(情绪,如:紧张平缓)。"
+ "img_prompt 与 video_prompt 禁止英文句子,专有名词可保留原文。"
+ )
+ user = f"输入类型:{source_type}。内容如下,请拆成 4-10 个分镜:\n{source_text}"
+ payload = {
+ "model": self.settings.model_llm,
+ "messages": [
+ {"role": "system", "content": system},
+ {"role": "user", "content": user},
+ ],
+ }
+ async with httpx.AsyncClient(timeout=120.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()
+ content = data["choices"][0]["message"]["content"] or "{}"
+ return self._parse_storyboard(content, style_prefix, duration_min, duration_max, max_shot_duration)
+
+ async def gen_image(
+ self,
+ prompt: str,
+ negative: str = "",
+ ref_urls: list[str] | None = None,
+ *,
+ project_id: int | None = None,
+ shot_no: int | None = None,
+ size: str | None = None,
+ ) -> ImageResult:
+ if self.mock:
+ local = await asyncio.to_thread(self._write_mock_image, prompt, size)
+ return ImageResult(local_url=local, remote_url=None)
+
+ candidates = [
+ self._sanitize_seedream_prompt(prompt),
+ self._aggressive_sanitize_seedream(prompt),
+ self._generic_scene_prompt(prompt),
+ ]
+ # de-dupe while preserving order
+ seen: set[str] = set()
+ prompts: list[str] = []
+ for p in candidates:
+ p = (p or "").strip()
+ if p and p not in seen:
+ seen.add(p)
+ prompts.append(p)
+
+ last_err: Exception | None = None
+ for idx, base in enumerate(prompts):
+ full_prompt = f"{base}。避免:{negative}" if negative else base
+ try:
+ return await self._seedream_once(
+ full_prompt,
+ ref_urls,
+ project_id=project_id,
+ shot_no=shot_no,
+ size=size,
+ prompt_hash_src=prompt,
+ )
+ except Exception as exc: # noqa: BLE001
+ last_err = exc
+ msg = str(exc)
+ if "PolicyViolation" in msg or "SensitiveContent" in msg:
+ logger.warning(
+ "Seedream policy hit shot=%s attempt=%s; retrying softened prompt",
+ shot_no,
+ idx + 1,
+ )
+ continue
+ raise
+ raise RuntimeError(str(last_err) if last_err else "Seedream failed")
+
+ async def _seedream_once(
+ self,
+ full_prompt: str,
+ ref_urls: list[str] | None,
+ *,
+ project_id: int | None,
+ shot_no: int | None,
+ size: str | None,
+ prompt_hash_src: str,
+ ) -> ImageResult:
+ body: dict[str, Any] = {
+ "model": self.settings.model_image,
+ "prompt": full_prompt,
+ "size": size or self.settings.ark_image_size,
+ "response_format": "url",
+ "watermark": False,
+ }
+ from app.services.style_lock import seedream_ref_urls
+
+ refs = seedream_ref_urls(*(ref_urls or []))
+ if refs:
+ body["image"] = refs if len(refs) > 1 else refs[0]
+
+ async with httpx.AsyncClient(timeout=180.0) as client:
+ resp = await client.post(
+ self._url("/images/generations"),
+ headers=self._headers(),
+ json=body,
+ )
+ if resp.status_code >= 400:
+ raise RuntimeError(f"Seedream error {resp.status_code}: {resp.text[:800]}")
+ data = resp.json()
+
+ remote = self._extract_image_url(data)
+ if not remote:
+ raise RuntimeError(f"Seedream missing url: {json.dumps(data)[:500]}")
+
+ dest_dir = storage.project_dir(project_id or 0)
+ 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)
+
+ @staticmethod
+ def _sanitize_seedream_prompt(prompt: str) -> str:
+ out = prompt or ""
+ for pat, repl in _SEEDREAM_SANITIZE:
+ out = pat.sub(repl, out)
+ return out
+
+ @classmethod
+ def _aggressive_sanitize_seedream(cls, prompt: str) -> str:
+ out = cls._sanitize_seedream_prompt(prompt)
+ out = _SEEDREAM_STRIP_PROPER.sub("主体", out)
+ # Drop Latin brand leftovers
+ out = re.sub(r"[A-Za-z]{3,}", "场景", out)
+ return out
+
+ @classmethod
+ def _generic_scene_prompt(cls, prompt: str) -> str:
+ """Last-resort prompt: keep style cues, drop concrete names."""
+ style_bits: list[str] = []
+ for key in (
+ "水墨",
+ "插画",
+ "扁平",
+ "像素",
+ "剪纸",
+ "粉笔",
+ "拼贴",
+ "竖屏",
+ "电影感",
+ "绘本",
+ "写意",
+ "概念插画",
+ ):
+ if key in (prompt or ""):
+ style_bits.append(key)
+ style = ",".join(style_bits) + "," if style_bits else "统一插画风格,"
+ return (
+ f"{style}高质量画面,竖屏构图,主体偏中下,顶部留白,"
+ "同一画风贯穿,禁止写实摄影与真人脸,无文字水印"
+ )
+
+ def _extract_image_url(self, data: dict[str, Any]) -> str | None:
+ if "data" in data and data["data"]:
+ item = data["data"][0]
+ return item.get("url") or item.get("b64_json")
+ if "url" in data:
+ return data["url"]
+ return None
+
+ async def gen_video_i2v(
+ self,
+ image_url: str,
+ prompt: str,
+ duration: int,
+ *,
+ character_consistency: bool = True,
+ resolution: str = "480p",
+ ratio: str | None = None,
+ ) -> str:
+ if self.mock:
+ digest = hashlib.md5(f"{image_url}:{prompt}".encode()).hexdigest()[:10]
+ return f"mock-task-{digest}"
+
+ # Seedance needs reachable image: prefer http(s), else data URI from local file
+ image_ref = await self._resolve_image_ref(image_url)
+ content: list[dict[str, Any]] = [
+ {"type": "text", "text": prompt},
+ {"type": "image_url", "image_url": {"url": image_ref}},
+ ]
+ body: dict[str, Any] = {
+ "model": self.settings.model_video,
+ "content": content,
+ "duration": int(max(2, min(duration, self.settings.max_shot_duration))),
+ "ratio": ratio or self.settings.ark_video_ratio,
+ "resolution": resolution,
+ "watermark": False,
+ "generate_audio": False,
+ }
+ # Optional consistency flag — ignored if API rejects unknown fields
+ if character_consistency:
+ body["character_consistency"] = True
+
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ resp = await client.post(
+ self._url("/contents/generations/tasks"),
+ headers=self._headers(),
+ json=body,
+ )
+ if resp.status_code >= 400:
+ # Retry without character_consistency if rejected
+ body.pop("character_consistency", None)
+ resp = await client.post(
+ self._url("/contents/generations/tasks"),
+ headers=self._headers(),
+ json=body,
+ )
+ if resp.status_code >= 400:
+ raise RuntimeError(f"Seedance create error {resp.status_code}: {resp.text[:800]}")
+ data = resp.json()
+
+ task_id = data.get("id") or data.get("task_id")
+ if not task_id:
+ raise RuntimeError(f"Seedance missing task id: {data}")
+ return str(task_id)
+
+ async def poll_task(self, task_id: str) -> TaskResult:
+ if self.mock or task_id.startswith("mock-task-"):
+ return TaskResult(status="succeeded", url=f"/static/mock/video_{task_id[-8:]}.mp4")
+
+ deadline = time.monotonic() + self.settings.ark_video_poll_timeout
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ while time.monotonic() < deadline:
+ resp = await client.get(
+ self._url(f"/contents/generations/tasks/{task_id}"),
+ headers=self._headers(),
+ )
+ if resp.status_code >= 400:
+ return TaskResult(status="failed", error=resp.text[:500])
+ data = resp.json()
+ status = str(data.get("status", "")).lower()
+ if status in {"succeeded", "success"}:
+ url = None
+ content = data.get("content")
+ if isinstance(content, dict):
+ url = content.get("video_url")
+ if not url:
+ url = data.get("video_url")
+ return TaskResult(status="succeeded", url=url)
+ if status in {"failed", "cancelled", "canceled", "expired"}:
+ err = data.get("error") or data.get("message") or status
+ return TaskResult(status="failed", error=str(err))
+ await asyncio.sleep(self.settings.ark_video_poll_interval)
+ return TaskResult(status="failed", error="poll timeout")
+
+ async def wait_video(
+ self,
+ task_id: str,
+ *,
+ project_id: int,
+ shot_no: int,
+ ) -> str:
+ result = await self.poll_task(task_id)
+ if result.status != "succeeded" or not result.url:
+ raise RuntimeError(result.error or "video generation failed")
+ if result.url.startswith("/static/"):
+ 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)
+
+ async def tts(
+ self,
+ text: str,
+ voice: str,
+ *,
+ project_id: int | None = None,
+ shot_no: int | None = None,
+ duration_hint: float = 4.0,
+ ) -> str:
+ voice_map = {
+ "narrator_calm": "zh_female_cancan_uranus_bigtts",
+ "warm_storyteller": "zh_female_tianmeixiaoyuan_uranus_bigtts",
+ "teacher_clear": "zh_male_shaonianzixin_uranus_bigtts",
+ "urban_editorial": "zh_female_shuangkuaisisi_uranus_bigtts",
+ "retro_host": "zh_male_shaonianzixin_uranus_bigtts",
+ "guqin_narrator": "zh_female_vv_uranus_bigtts",
+ }
+ speaker = (
+ voice_map.get(voice, voice)
+ or self.settings.volc_tts_speaker
+ or "zh_female_cancan_uranus_bigtts"
+ )
+ clean = (text or "").strip() or "这一幕。"
+
+ if self.mock:
+ digest = hashlib.md5(f"{speaker}:{clean}".encode()).hexdigest()[:8]
+ dest = Path(__file__).resolve().parents[2] / "static" / "mock" / f"audio_{digest}.mp3"
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if not dest.exists() or dest.stat().st_size < 1000:
+ await self._tts_edge(clean, dest)
+ return f"/static/mock/audio_{digest}.mp3"
+
+ dest_dir = storage.project_dir(project_id or 0)
+ dest = dest_dir / f"shot_{(shot_no or 0):03d}_tts.mp3"
+
+ async def _accept_if_audible(label: str) -> str | None:
+ if not dest.exists() or dest.stat().st_size < 2000:
+ return None
+ 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)
+
+ # 1) 豆包 openspeech(需 APP ID + Access Key)
+ if self.settings.volc_tts_app_id and self.settings.volc_tts_access_key:
+ try:
+ ok = await self._tts_openspeech(clean, speaker, dest)
+ if ok:
+ url = await _accept_if_audible("openspeech")
+ if url:
+ return url
+ except Exception as exc: # noqa: BLE001
+ logger.warning("openspeech TTS failed: %s", exc)
+
+ # 2) edge-tts(无 openspeech 凭证时的主路径;有凭证时作兜底)
+ try:
+ await self._tts_edge(clean, dest, voice_hint=speaker)
+ url = await _accept_if_audible("edge-tts")
+ if url:
+ logger.info("TTS edge-tts ok shot=%s bytes=%s", shot_no, dest.stat().st_size)
+ return url
+ except Exception as exc: # noqa: BLE001
+ logger.warning("edge-tts failed: %s", exc)
+
+ # 3) 旧 Ark /audio/speech(多数账号 404,保留兼容)
+ try:
+ async with httpx.AsyncClient(timeout=120.0) as client:
+ resp = await client.post(
+ self._url("/audio/speech"),
+ headers=self._headers(),
+ json={
+ "model": self.settings.model_audio,
+ "input": clean,
+ "voice": speaker,
+ "response_format": "mp3",
+ },
+ )
+ if resp.status_code < 400 and resp.content and len(resp.content) > 1000:
+ dest.write_bytes(resp.content)
+ url = await _accept_if_audible("ark-speech")
+ if url:
+ return url
+ logger.warning("Ark TTS HTTP %s: %s", resp.status_code, (resp.text or "")[:300])
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Ark TTS failed: %s", exc)
+
+ # 最后才静音(保证合成不中断)
+ 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)
+
+ def _tts_resource_id(self, speaker: str) -> str:
+ if speaker.startswith("S_"):
+ return "seed-icl-2.0"
+ if "_uranus_" in speaker or speaker.startswith("saturn_"):
+ return self.settings.volc_tts_resource_id or "seed-tts-2.0"
+ return "seed-tts-1.0"
+
+ async def _tts_openspeech(self, text: str, speaker: str, dest: Path) -> bool:
+ resource = self._tts_resource_id(speaker)
+ headers = {
+ "Content-Type": "application/json",
+ "X-Api-App-Id": self.settings.volc_tts_app_id,
+ "X-Api-Access-Key": self.settings.volc_tts_access_key,
+ "X-Api-Resource-Id": resource,
+ }
+ body: dict[str, Any] = {
+ "user": {"uid": "framecut"},
+ "req_params": {
+ "text": text,
+ "speaker": speaker,
+ "audio_params": {"format": "mp3", "sample_rate": 24000},
+ },
+ }
+ if speaker.startswith("S_"):
+ body["req_params"]["additions"] = json.dumps({"model_type": 4}, ensure_ascii=False)
+
+ async with httpx.AsyncClient(timeout=120.0) as client:
+ resp = await client.post(self.settings.volc_tts_url, headers=headers, json=body)
+ if resp.status_code >= 400:
+ logger.warning("openspeech HTTP %s: %s", resp.status_code, resp.text[:400])
+ return False
+ audio = self._parse_openspeech_ndjson(resp.content)
+ if not audio:
+ logger.warning("openspeech empty audio body")
+ return False
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(audio)
+ return True
+
+ @staticmethod
+ def _parse_openspeech_ndjson(raw: bytes) -> bytes:
+ chunks: list[bytes] = []
+ text = raw.decode("utf-8", errors="ignore")
+ for line in text.splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ code = obj.get("code")
+ if code == 0 and obj.get("data"):
+ chunks.append(base64.b64decode(obj["data"]))
+ elif code in {20000000, 20000001}:
+ break
+ elif code not in (None, 0):
+ logger.warning("openspeech line error: %s", line[:300])
+ return b"".join(chunks)
+
+ async def _tts_edge(self, text: str, dest: Path, voice_hint: str = "") -> None:
+ import edge_tts
+
+ # Map rough gender from hint → Edge neural voice
+ female = "zh-CN-XiaoxiaoNeural"
+ male = "zh-CN-YunxiNeural"
+ voice = male if "male" in (voice_hint or "").lower() or "男" in voice_hint else female
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ communicate = edge_tts.Communicate(text, voice)
+ await communicate.save(str(dest))
+
+ def _write_silence_mp3(self, dest: Path, duration: float) -> None:
+ import shutil
+ import subprocess
+
+ ffmpeg = shutil.which(self.settings.ffmpeg_path) or shutil.which("ffmpeg")
+ if not ffmpeg:
+ dest.write_bytes(b"")
+ return
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(
+ [
+ ffmpeg,
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "anullsrc=r=44100:cl=mono",
+ "-t",
+ f"{max(duration, 0.5):.3f}",
+ "-q:a",
+ "9",
+ "-acodec",
+ "libmp3lame",
+ str(dest),
+ ],
+ capture_output=True,
+ check=False,
+ )
+
+ async def _resolve_image_ref(self, image_url: str) -> str:
+ if image_url.startswith("http://") or image_url.startswith("https://") or image_url.startswith("data:"):
+ return image_url
+ local = storage.local_path_from_url(image_url)
+ if local and local.exists():
+ # Prefer data URI so Seedance can read without public CDN
+ return storage.file_to_data_uri(local)
+ # Last resort: absolute local public URL (only works if Ark can reach your machine)
+ return storage.to_public_url(image_url)
+
+ def _write_mock_image(self, prompt: str, size: str | None = None) -> str:
+ digest = hashlib.md5(prompt.encode()).hexdigest()[:8]
+ root = Path(__file__).resolve().parents[2] / "static" / "mock"
+ root.mkdir(parents=True, exist_ok=True)
+ path = root / f"image_{digest}.svg"
+ hue = int(digest[:2], 16)
+ label = (prompt[:42] + "…") if len(prompt) > 42 else prompt
+ safe = (
+ label.replace("&", "&amp;")
+ .replace("<", "&lt;")
+ .replace(">", "&gt;")
+ .replace('"', "&quot;")
+ )
+ # Portrait mock for image_text / 9:16
+ portrait = bool(size and ("x" in size.lower()) and self._is_portrait_size(size))
+ w, h = (720, 1280) if portrait else (960, 540)
+ svg = f"""<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">
+ <defs>
+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="hsl({hue},28%,22%)"/>
+ <stop offset="100%" stop-color="hsl({(hue + 40) % 360},22%,38%)"/>
+ </linearGradient>
+ </defs>
+ <rect width="{w}" height="{h}" fill="url(#g)"/>
+ <rect x="{int(w*0.08)}" y="{int(h*0.28)}" width="{int(w*0.4)}" height="{int(h*0.28)}" rx="10" fill="hsl({(hue + 20) % 360},35%,72%)" opacity="0.9"/>
+ <circle cx="{int(w*0.72)}" cy="{int(h*0.38)}" r="{int(w*0.14)}" fill="hsl({(hue + 80) % 360},30%,65%)" opacity="0.55"/>
+ <text x="{int(w*0.08)}" y="{int(h*0.78)}" fill="#f2ebe0" font-family="Georgia, serif" font-size="28">Mock Storyboard</text>
+ <text x="{int(w*0.08)}" y="{int(h*0.84)}" fill="#d7cfc3" font-family="sans-serif" font-size="18">{safe}</text>
+</svg>"""
+ path.write_text(svg, encoding="utf-8")
+ return f"/static/mock/image_{digest}.svg"
+
+ @staticmethod
+ def _is_portrait_size(size: str) -> bool:
+ m = re.match(r"^(\d+)x(\d+)$", size.strip().lower())
+ if not m:
+ return False
+ return int(m.group(2)) > int(m.group(1))
+
+ def _mock_storyboard(
+ self,
+ source_text: str,
+ source_type: str,
+ style_prefix: str,
+ duration_min: int,
+ duration_max: int,
+ pipeline_mode: str = "full",
+ ) -> StoryboardResult:
+ chunks = [c.strip() for c in re.split(r"[。!?\n\.\!\?]+", source_text) if c.strip()]
+ if source_type == "theme" and len(chunks) <= 1:
+ topic = source_text.strip()
+ chunks = [
+ f"引入主题:{topic}",
+ f"核心概念解释:{topic}",
+ f"一个关键例子说明{topic}",
+ f"常见误解与澄清",
+ f"总结与启发",
+ ]
+ if len(chunks) < 3:
+ chunks = chunks + ["补充画面过渡", "收尾总结"]
+ chunks = chunks[:10]
+ mid = (duration_min + duration_max) // 2
+ if pipeline_mode == "image_text":
+ mid = min(mid, max(duration_min, 3))
+ bible = (
+ f"统一角色:与「{source_text.strip()[:24]}」相关的核心人物,"
+ "中等身材,简洁服饰配色固定,五官清晰可辨,全片外形不变"
+ )
+ 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]
+ plans.append(
+ ShotPlan(
+ shot=i,
+ duration=float(mid),
+ text=text[:120],
+ overlay_title=title[:16],
+ overlay_subtitle=subtitle[:48],
+ img_prompt=f"{style_prefix},{bible},画面表现:{text[:80]},竖屏构图,顶部留白,画面无文字",
+ video_prompt=f"轻微动态,{style_prefix},场景:{text[:60]}",
+ camera="缓慢推近" if i % 2 else "轻拉远",
+ bgm="好奇引入" if i == 1 else "平稳推进",
+ )
+ )
+ return StoryboardResult(shots=plans, character_bible=bible)
+
+ def _parse_storyboard(
+ self,
+ content: str,
+ style_prefix: str,
+ duration_min: int,
+ duration_max: int,
+ max_shot_duration: int,
+ ) -> StoryboardResult:
+ raw = content.strip()
+ if raw.startswith("```"):
+ raw = re.sub(r"^```(?:json)?\s*", "", raw)
+ raw = re.sub(r"\s*```$", "", raw)
+ data = json.loads(raw)
+ character_bible = ""
+ items = data
+ if isinstance(data, dict):
+ character_bible = str(
+ data.get("character_bible") or data.get("characters") or data.get("cast") or ""
+ ).strip()
+ items = data.get("shots") or data.get("storyboard") or data.get("scenes") or []
+ if not isinstance(items, list):
+ raise RuntimeError("LLM storyboard JSON 格式无效:需要 shots 数组")
+ plans: list[ShotPlan] = []
+ for i, item in enumerate(items, start=1):
+ if not isinstance(item, dict):
+ continue
+ dur = float(item.get("duration", (duration_min + duration_max) / 2))
+ dur = max(duration_min, min(dur, duration_max, max_shot_duration))
+ 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]
+ 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}")
+ plans.append(
+ ShotPlan(
+ shot=int(item.get("shot", i)),
+ duration=dur,
+ text=text,
+ overlay_title=title[:32],
+ overlay_subtitle=subtitle[:64],
+ img_prompt=img,
+ video_prompt=video,
+ camera=str(item.get("camera", "缓慢横移")),
+ bgm=str(item.get("bgm") or item.get("bgm_mood") or "平稳"),
+ )
+ )
+ return StoryboardResult(shots=plans, character_bible=character_bible)
+
+
+_gateway: ArkGateway | None = None
+
+
+def get_ark() -> ArkGateway:
+ global _gateway
+ if _gateway is None:
+ _gateway = ArkGateway()
+ return _gateway
+
+
+def reset_ark() -> None:
+ global _gateway
+ _gateway = None
diff --git a/backend/app/services/auth.py b/backend/app/services/auth.py
new file mode 100644
index 0000000..f1d2f55
--- /dev/null
+++ b/backend/app/services/auth.py
@@ -0,0 +1,45 @@
+from datetime import datetime, timedelta, timezone
+
+from jose import JWTError, jwt
+from passlib.context import CryptContext
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.models import User
+
+pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
+settings = get_settings()
+ALGORITHM = "HS256"
+
+
+def hash_password(password: str) -> str:
+ return pwd_context.hash(password)
+
+
+def verify_password(plain: str, hashed: str) -> bool:
+ return pwd_context.verify(plain, hashed)
+
+
+def create_access_token(subject: str) -> str:
+ expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
+ return jwt.encode({"sub": subject, "exp": expire}, settings.secret_key, algorithm=ALGORITHM)
+
+
+def decode_token(token: str) -> str | None:
+ try:
+ payload = jwt.decode(token, settings.secret_key, algorithms=[ALGORITHM])
+ sub = payload.get("sub")
+ return str(sub) if sub else None
+ except JWTError:
+ return None
+
+
+async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
+ result = await db.execute(select(User).where(User.email == email))
+ return result.scalar_one_or_none()
+
+
+async def get_user_by_id(db: AsyncSession, user_id: int) -> User | None:
+ result = await db.execute(select(User).where(User.id == user_id))
+ return result.scalar_one_or_none()
diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.py
new file mode 100644
index 0000000..fc13501
--- /dev/null
+++ b/backend/app/services/ffmpeg_compose.py
@@ -0,0 +1,791 @@
+"""FFmpeg compose: per-shot A/V mux → concat → soft/hard subtitles / image-text Ken Burns."""
+
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+import subprocess
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+
+from app.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+# Output sizes keyed by aspect ratio
+_RATIO_SIZE = {
+ "16:9": (854, 480),
+ "9:16": (720, 1280),
+ "1:1": (720, 720),
+ "4:3": (640, 480),
+}
+
+
+@dataclass
+class ShotMedia:
+ shot_no: int
+ duration: float
+ narration: str
+ video_path: Path | None
+ audio_path: Path | None
+ image_path: Path | None = None
+ overlay_title: str = ""
+ overlay_subtitle: str = ""
+
+
+@dataclass
+class ComposeOptions:
+ ratio: str = "16:9"
+ mode: str = "full" # full | image_text
+ resolution_mode: str = "preview" # preview | hd
+
+
+def probe_duration(path: Path) -> float | None:
+ """Return media duration in seconds via ffprobe, or None."""
+ ffprobe = shutil.which(get_settings().ffprobe_path) or shutil.which("ffprobe")
+ if not ffprobe or not path.exists():
+ return None
+ try:
+ proc = subprocess.run(
+ [
+ ffprobe,
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration",
+ "-of",
+ "default=noprint_wrappers=1:nokey=1",
+ str(path),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if proc.returncode != 0:
+ return None
+ return float(proc.stdout.strip())
+ except Exception: # noqa: BLE001
+ return None
+
+
+def is_near_silent_audio(path: Path, *, max_db: float = -70.0) -> bool:
+ """True when file missing/tiny or peak volume is below max_db (e.g. anullsrc)."""
+ if not path.exists() or path.stat().st_size < 2000:
+ return True
+ ffmpeg = shutil.which(get_settings().ffmpeg_path) or shutil.which("ffmpeg")
+ if not ffmpeg:
+ return False
+ try:
+ proc = subprocess.run(
+ [ffmpeg, "-i", str(path), "-af", "volumedetect", "-f", "null", "-"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ text = (proc.stderr or "") + (proc.stdout or "")
+ peak: float | None = None
+ for line in text.splitlines():
+ if "max_volume:" in line:
+ # e.g. max_volume: -91.0 dB
+ part = line.split("max_volume:", 1)[1].strip().split()[0]
+ peak = float(part)
+ break
+ if peak is None:
+ return False
+ return peak <= max_db
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _run(cmd: list[str]) -> None:
+ logger.info("ffmpeg: %s", " ".join(cmd))
+ proc = subprocess.run(cmd, capture_output=True, text=True)
+ if proc.returncode != 0:
+ raise RuntimeError(proc.stderr[-2000:] or proc.stdout[-2000:] or "ffmpeg failed")
+
+
+def _which(bin_name: str) -> str:
+ settings = get_settings()
+ configured = settings.ffmpeg_path if bin_name == "ffmpeg" else settings.ffprobe_path
+ path = shutil.which(configured) or shutil.which(bin_name)
+ if not path:
+ raise RuntimeError(f"{bin_name} not found in PATH")
+ return path
+
+
+def _canvas(opts: ComposeOptions) -> tuple[int, int]:
+ w, h = _RATIO_SIZE.get(opts.ratio, _RATIO_SIZE["16:9"])
+ if opts.resolution_mode == "hd":
+ # Scale up ~1.5x for HD preview of image_text / compose
+ return int(w * 1.5) // 2 * 2, int(h * 1.5) // 2 * 2
+ return w, h
+
+
+def _find_cjk_font() -> str | None:
+ """Return a path usable by drawtext fontfile=…"""
+ candidates = [
+ os.environ.get("FRAMECUT_FONT"),
+ r"C:\Windows\Fonts\msyhbd.ttc",
+ r"C:\Windows\Fonts\msyh.ttc",
+ r"C:\Windows\Fonts\simhei.ttf",
+ r"C:\Windows\Fonts\simkai.ttf",
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc",
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Bold.ttc",
+ "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
+ "/System/Library/Fonts/PingFang.ttc",
+ "/System/Library/Fonts/STHeiti Light.ttc",
+ ]
+ for c in candidates:
+ if c and Path(c).exists():
+ return c
+ return None
+
+
+def _escape_drawtext(text: str) -> str:
+ """Escape text for ffmpeg drawtext filter."""
+ t = (text or "").replace("\n", " ").replace("\r", " ").strip()
+ t = t.replace("\\", "\\\\")
+ t = t.replace(":", "\\:")
+ t = t.replace("'", "\\'")
+ t = t.replace("%", "\\%")
+ return t
+
+
+def _escape_fontfile(path: str) -> str:
+ # Windows paths need escaping for filtergraph: C\:/Windows/Fonts/msyh.ttc
+ p = Path(path).resolve().as_posix()
+ return p.replace(":", "\\:")
+
+
+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()
+ if not raw:
+ return ""
+ if len(raw) <= max_chars:
+ return raw
+ return raw[: max_chars - 1] + "…"
+
+
+def _split_caption_chunks(text: str, *, max_chars: int = 18) -> list[str]:
+ """Split narration into timed bottom-caption cues (one line each)."""
+ raw = (text or "").replace("\n", " ").replace("\r", " ").strip()
+ if not raw:
+ return []
+
+ # Prefer clause breaks on Chinese/English punctuation
+ pieces: list[str] = []
+ buf = ""
+ for ch in raw:
+ buf += ch
+ if ch in ",。!?;、,.!?;:":
+ piece = buf.strip()
+ if piece:
+ pieces.append(piece)
+ buf = ""
+ if buf.strip():
+ pieces.append(buf.strip())
+ if not pieces:
+ pieces = [raw]
+
+ # 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()
+ if not body:
+ continue
+ if len(body) <= max_chars:
+ chunks.append(body)
+ continue
+ cur = ""
+ for ch in body:
+ cur += ch
+ if len(cur) >= max_chars:
+ chunks.append(cur.strip())
+ cur = ""
+ if cur.strip():
+ chunks.append(cur.strip())
+
+ # Merge tiny leftovers into previous cue
+ merged: list[str] = []
+ for c in chunks:
+ if merged and len(c) <= 2:
+ merged[-1] = merged[-1] + c
+ else:
+ merged.append(c)
+ return merged or [raw[:max_chars]]
+
+
+def _timed_caption_windows(
+ text: str,
+ *,
+ start: float,
+ duration: float,
+ max_chars: int = 18,
+) -> list[tuple[float, float, str]]:
+ """Allocate each caption chunk a time window proportional to character length."""
+ chunks = _split_caption_chunks(text, max_chars=max_chars)
+ if not chunks:
+ return []
+ total = max(duration, 0.5)
+ weights = [max(len(c), 1) for c in chunks]
+ weight_sum = float(sum(weights))
+ cursor = start
+ windows: list[tuple[float, float, str]] = []
+ for i, (chunk, w) in enumerate(zip(chunks, weights)):
+ if i == len(chunks) - 1:
+ end = start + total
+ else:
+ end = start + total * (sum(weights[: i + 1]) / weight_sum)
+ end = max(end, cursor + 0.5)
+ end = min(end, start + total)
+ if end <= cursor:
+ continue
+ windows.append((cursor, end, chunk))
+ cursor = end
+ if windows:
+ s0, _, t0 = windows[-1]
+ windows[-1] = (s0, start + total, t0)
+ return windows
+
+
+def _ass_ts(seconds: float) -> str:
+ cs = int(round(max(seconds, 0) * 100))
+ h, rem = divmod(cs, 3600_00)
+ m, rem = divmod(rem, 60_00)
+ s, c = divmod(rem, 100)
+ return f"{h}:{m:02d}:{s:02d}.{c:02d}"
+
+
+def _escape_ass_text(text: str) -> str:
+ return text.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")
+
+
+def _write_ass(
+ shots: list[ShotMedia],
+ path: Path,
+ *,
+ w: int,
+ h: int,
+ font: str | None,
+) -> None:
+ """Write ASS with PlayRes matching canvas; captions refresh by clause over time."""
+ portrait = (h / max(w, 1)) > 1.2
+ font_size = 22 if portrait else 18
+ margin_v = 48 if portrait else 32
+ max_chars = 16 if portrait else 24
+ font_name = "Microsoft YaHei"
+ if font:
+ stem = Path(font).stem.lower()
+ if stem.startswith("msyh"):
+ font_name = "Microsoft YaHei"
+ elif stem == "simhei":
+ font_name = "SimHei"
+ elif stem == "simkai":
+ font_name = "KaiTi"
+ elif stem == "simsun":
+ font_name = "SimSun"
+
+ header = f"""[Script Info]
+ScriptType: v4.00+
+PlayResX: {w}
+PlayResY: {h}
+WrapStyle: 2
+ScaledBorderAndShadow: yes
+
+[V4+ Styles]
+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
+Style: Caption,{font_name},{font_size},&H00FFFFFF,&H000000FF,&H80000000,&H64000000,0,0,0,0,100,100,0,0,1,2,0,2,36,36,{margin_v},1
+
+[Events]
+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
+"""
+ events: list[str] = []
+ cursor = 0.0
+ for shot in shots:
+ shot_start = cursor
+ shot_dur = max(shot.duration, 0.5)
+ windows = _timed_caption_windows(
+ shot.narration,
+ start=shot_start,
+ duration=shot_dur,
+ max_chars=max_chars,
+ )
+ if not windows:
+ windows = [(shot_start, shot_start + shot_dur, f"镜头{shot.shot_no}")]
+ for a, b, text in windows:
+ if b - a < 0.25:
+ continue
+ events.append(
+ f"Dialogue: 0,{_ass_ts(a)},{_ass_ts(b)},Caption,,0,0,0,,{_escape_ass_text(text)}"
+ )
+ cursor = shot_start + shot_dur
+ path.write_text(header + "\n".join(events) + "\n", encoding="utf-8-sig")
+
+
+def _write_srt(shots: list[ShotMedia], path: Path) -> None:
+ """Legacy SRT helper with timed clause captions."""
+ lines: list[str] = []
+ cursor = 0.0
+ idx = 1
+
+ def ts(seconds: float) -> str:
+ ms = int(round(seconds * 1000))
+ h, rem = divmod(ms, 3600_000)
+ m, rem = divmod(rem, 60_000)
+ s, milli = divmod(rem, 1000)
+ return f"{h:02d}:{m:02d}:{s:02d},{milli:03d}"
+
+ for shot in shots:
+ shot_start = cursor
+ shot_dur = max(shot.duration, 0.5)
+ windows = _timed_caption_windows(
+ shot.narration,
+ start=shot_start,
+ duration=shot_dur,
+ max_chars=22,
+ )
+ for a, b, text in windows:
+ lines.append(str(idx))
+ lines.append(f"{ts(a)} --> {ts(b)}")
+ lines.append(text)
+ lines.append("")
+ idx += 1
+ cursor = shot_start + shot_dur
+ path.write_text("\n".join(lines), encoding="utf-8")
+
+def _make_silent_audio(path: Path, duration: float) -> None:
+ ffmpeg = _which("ffmpeg")
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "anullsrc=channel_layout=stereo:sample_rate=44100",
+ "-t",
+ f"{max(duration, 0.5):.3f}",
+ "-c:a",
+ "aac",
+ str(path),
+ ]
+ )
+
+
+def _scale_pad(w: int, h: int) -> str:
+ return (
+ f"scale={w}:{h}:force_original_aspect_ratio=decrease,"
+ f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,format=yuv420p"
+ )
+
+
+def _ken_burns_filter(w: int, h: int, duration: float, shot_no: int) -> str:
+ """Ken Burns zoom / pan — stronger push-in / pull-out with directional drift."""
+ frames = max(int(round(duration * 24)), 12)
+ last = max(frames - 1, 1)
+ # ~32% scale change (was ~12%) so motion reads clearly on short clips
+ amp = 0.32
+ z_max = f"{1.0 + amp:.2f}"
+ pattern = shot_no % 4
+ if pattern == 0:
+ # Push in, centered
+ z = f"min(1.0+{amp}*on/{last},{z_max})"
+ x = "iw/2-(iw/zoom/2)"
+ y = "ih/2-(ih/zoom/2)"
+ elif pattern == 1:
+ # Pull out + drift upward
+ z = f"max({z_max}-{amp}*on/{last},1.0)"
+ x = "iw/2-(iw/zoom/2)"
+ y = f"ih/2-(ih/zoom/2)-ih*0.08*on/{last}"
+ elif pattern == 2:
+ # Push in + pan right
+ z = f"min(1.0+{amp}*on/{last},{z_max})"
+ x = f"(iw-iw/zoom)*on/{last}"
+ y = "ih/2-(ih/zoom/2)"
+ else:
+ # Push in + pan left / slight down
+ z = f"min(1.0+{amp}*on/{last},{z_max})"
+ x = f"(iw-iw/zoom)*(1-on/{last})"
+ y = f"(ih-ih/zoom)*0.4*on/{last}"
+ return (
+ f"scale=8000:-1,"
+ f"zoompan=z='{z}':x='{x}':y='{y}':d={frames}:s={w}x{h}:fps=24,"
+ f"format=yuv420p"
+ )
+
+
+def _bottom_caption_drawtext(
+ narration: str,
+ *,
+ duration: float,
+ w: int,
+ h: int,
+ font: str | None,
+) -> 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 = 18 if portrait else 16
+ y = max(0, h - font_size - (48 if portrait else 36))
+ windows = _timed_caption_windows(
+ narration,
+ start=0.0,
+ duration=max(duration, 0.5),
+ max_chars=max_chars,
+ )
+ if not windows:
+ return ""
+ font_opt = f":fontfile='{_escape_fontfile(font)}'" if font else ""
+ parts: list[str] = []
+ for a, b, text in windows:
+ if b - a < 0.2:
+ continue
+ te = _escape_drawtext(text)
+ # Commas in enable= must be escaped for filtergraph
+ parts.append(
+ f"drawtext=text='{te}'{font_opt}:fontsize={font_size}:"
+ f"fontcolor=white:borderw=2:[email protected]:"
+ f"box=1:[email protected]:boxborderw=6:"
+ f"x=(w-text_w)/2:y={y}:"
+ f"enable='between(t\\,{a:.2f}\\,{b:.2f})'"
+ )
+ 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] + "…"
+ title_e = _escape_drawtext(title)
+ sub_e = _escape_drawtext(subtitle)
+ # Portrait 720 → title ~22 / sub ~15
+ title_size = max(18, min(24, int(w * 0.032)))
+ sub_size = max(14, min(17, int(w * 0.024)))
+ title_y = int(h * 0.05)
+ sub_y = title_y + title_size + int(h * 0.01)
+
+ 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.16)}:[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=2:[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=2:[email protected]:"
+ f"x=(w-text_w)/2:y={sub_y}"
+ )
+ return ",".join(parts)
+
+
+def _image_to_video_kenburns(
+ image: Path,
+ duration: float,
+ out: Path,
+ *,
+ w: int,
+ h: int,
+ shot_no: int,
+ title: str,
+ subtitle: str,
+ narration: str,
+ font: str | None,
+) -> None:
+ ffmpeg = _which("ffmpeg")
+ vf = _ken_burns_filter(w, h, duration, shot_no)
+ overlay = _overlay_drawtext(w, h, title, subtitle, font)
+ 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}"
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-loop",
+ "1",
+ "-i",
+ str(image),
+ "-t",
+ f"{max(duration, 0.5):.3f}",
+ "-vf",
+ vf,
+ "-r",
+ "24",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ str(out),
+ ]
+ )
+
+
+def _burn_captions_on_video(
+ video_in: Path,
+ video_out: Path,
+ *,
+ narration: str,
+ duration: float,
+ w: int,
+ h: int,
+ font: str | None,
+) -> 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
+ )
+ ffmpeg = _which("ffmpeg")
+ if not captions:
+ _run([ffmpeg, "-y", "-i", str(video_in), "-c", "copy", str(video_out)])
+ return
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(video_in),
+ "-vf",
+ captions,
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-an",
+ str(video_out),
+ ]
+ )
+
+
+
+def _image_to_video(image: Path, duration: float, out: Path, *, w: int, h: int) -> None:
+ ffmpeg = _which("ffmpeg")
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-loop",
+ "1",
+ "-i",
+ str(image),
+ "-t",
+ f"{max(duration, 0.5):.3f}",
+ "-vf",
+ _scale_pad(w, h),
+ "-r",
+ "24",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ str(out),
+ ]
+ )
+
+
+def _mux_shot(video: Path, audio: Path, duration: float, out: Path) -> None:
+ ffmpeg = _which("ffmpeg")
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(video),
+ "-i",
+ str(audio),
+ "-t",
+ f"{max(duration, 0.5):.3f}",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-shortest",
+ str(out),
+ ]
+ )
+
+
+def compose_project(
+ shots: list[ShotMedia],
+ output: Path,
+ opts: ComposeOptions | None = None,
+) -> Path:
+ if not shots:
+ raise ValueError("no shots to compose")
+
+ opts = opts or ComposeOptions()
+ w, h = _canvas(opts)
+ ffmpeg = _which("ffmpeg")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ font = _find_cjk_font()
+ if opts.mode == "image_text" and not font:
+ logger.warning("No CJK font found; drawtext may fail for Chinese")
+
+ with tempfile.TemporaryDirectory(prefix="framecut_") as tmp:
+ tmp_path = Path(tmp)
+ segment_paths: list[Path] = []
+
+ for shot in shots:
+ seg = tmp_path / f"shot_{shot.shot_no:03d}.mp4"
+ audio = tmp_path / f"shot_{shot.shot_no:03d}.m4a"
+ video = tmp_path / f"shot_{shot.shot_no:03d}_v.mp4"
+
+ if shot.audio_path and shot.audio_path.exists():
+ # Keep full narration; do not truncate to planned duration when audio is longer
+ audio_dur = probe_duration(shot.audio_path) or shot.duration
+ use_dur = max(shot.duration, audio_dur)
+ shot.duration = use_dur
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(shot.audio_path),
+ "-c:a",
+ "aac",
+ str(audio),
+ ]
+ )
+ else:
+ _make_silent_audio(audio, shot.duration)
+
+ 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,
+ video,
+ w=w,
+ h=h,
+ shot_no=shot.shot_no,
+ title=title,
+ subtitle=subtitle,
+ narration=shot.narration or "",
+ font=font,
+ )
+ elif shot.video_path and shot.video_path.exists() and shot.video_path.suffix.lower() in {
+ ".mp4",
+ ".mov",
+ ".webm",
+ ".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),
+ ]
+ )
+ _burn_captions_on_video(
+ raw_v,
+ video,
+ narration=shot.narration or "",
+ duration=shot.duration,
+ w=w,
+ h=h,
+ font=font,
+ )
+ elif shot.image_path and shot.image_path.exists():
+ _image_to_video(shot.image_path, shot.duration, video, w=w, h=h)
+ capped = tmp_path / f"shot_{shot.shot_no:03d}_cap.mp4"
+ _burn_captions_on_video(
+ video,
+ capped,
+ narration=shot.narration or "",
+ duration=shot.duration,
+ w=w,
+ h=h,
+ font=font,
+ )
+ video = capped
+ else:
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ f"color=c=0x1a1714:s={w}x{h}:d={max(shot.duration, 0.5):.3f}",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ str(video),
+ ]
+ )
+
+ _mux_shot(video, audio, shot.duration, seg)
+ segment_paths.append(seg)
+
+ concat_list = tmp_path / "concat.txt"
+ concat_list.write_text(
+ "\n".join(f"file '{p.resolve().as_posix()}'" for p in segment_paths),
+ encoding="utf-8",
+ )
+ merged = tmp_path / "merged.mp4"
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-f",
+ "concat",
+ "-safe",
+ "0",
+ "-i",
+ str(concat_list),
+ "-c",
+ "copy",
+ str(merged),
+ ]
+ )
+
+ # Captions already burned per-shot via drawtext — remux only.
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(merged),
+ "-c",
+ "copy",
+ "-movflags",
+ "+faststart",
+ str(output),
+ ]
+ )
+
+ return output
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
new file mode 100644
index 0000000..d069896
--- /dev/null
+++ b/backend/app/services/pipeline.py
@@ -0,0 +1,1218 @@
+"""Pipeline orchestration — stages shared by in-process and Celery runners."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+
+from sqlalchemy import select
+from sqlalchemy.orm import selectinload
+
+from app.config import get_settings
+from app.database import AsyncSessionLocal
+from app.models import PipelineJob, Project, ProjectStatus, Shot, ShotStatus
+from app.services.ark import get_ark
+from app.services.ffmpeg_compose import ComposeOptions, ShotMedia, compose_project, is_near_silent_audio, probe_duration
+from app.services.progress import publish_progress
+from app.services import storage
+from app.services.style_lock import (
+ build_locked_image_prompt,
+ merge_negative,
+ seedream_ref_urls,
+ strip_lock_blocks,
+)
+from app.services.voices import resolve_speaker
+
+logger = logging.getLogger(__name__)
+
+_running: dict[int, asyncio.Task] = {}
+_cancelled: set[int] = set()
+_celery_task_ids: dict[int, str] = {}
+
+# Seedream min pixels ~3686400; portrait 9:16 ≈ 1440x2560
+_IMAGE_SIZE_BY_RATIO = {
+ "9:16": "1440x2560",
+ "16:9": "2560x1440",
+ "1:1": "1920x1920",
+}
+
+IMAGE_TEXT_DURATION_MIN = 4
+IMAGE_TEXT_DURATION_MAX = 12
+
+
+class PipelineCancelled(Exception):
+ """Raised when user cancels a running pipeline."""
+
+
+def start_pipeline(project_id: int) -> str:
+ """Dispatch to Celery when enabled+Redis up; else in-process asyncio."""
+ _cancelled.discard(project_id)
+ settings = get_settings()
+ if settings.use_celery and _redis_ok():
+ from app.workers.tasks import run_pipeline_task
+
+ async_result = run_pipeline_task.apply_async(args=[project_id], queue="pipeline")
+ task_id = str(async_result.id)
+ _celery_task_ids[project_id] = task_id
+ return task_id
+
+ if project_id in _running and not _running[project_id].done():
+ return "in-process"
+ _running[project_id] = asyncio.create_task(run_pipeline(project_id))
+ return "in-process"
+
+
+def cancel_pipeline(project_id: int) -> bool:
+ """Request cancel; best-effort stop in-process task / Celery worker."""
+ _cancelled.add(project_id)
+ stopped = False
+
+ task = _running.get(project_id)
+ if task and not task.done():
+ task.cancel()
+ stopped = True
+
+ celery_id = _celery_task_ids.pop(project_id, None)
+ if celery_id and celery_id != "in-process":
+ try:
+ from app.workers.celery_app import celery_app
+
+ celery_app.control.revoke(celery_id, terminate=True, signal="SIGTERM")
+ stopped = True
+ except Exception: # noqa: BLE001
+ logger.warning("celery revoke failed project=%s task=%s", project_id, celery_id)
+
+ return stopped
+
+
+def is_cancelled(project_id: int) -> bool:
+ return project_id in _cancelled
+
+
+def _redis_ok() -> bool:
+ try:
+ import redis
+
+ r = redis.Redis.from_url(
+ get_settings().redis_url,
+ decode_responses=True,
+ socket_connect_timeout=2,
+ socket_timeout=2,
+ )
+ return bool(r.ping())
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _is_image_text(project: Project) -> bool:
+ return (project.pipeline_mode or "full") == "image_text"
+
+
+def _project_voice(project: Project) -> str:
+ tpl_preset = ""
+ if project.template and project.template.audio_config:
+ tpl_preset = str(project.template.audio_config.get("voice_preset") or "")
+ return resolve_speaker(getattr(project, "voice_id", None) or "", template_preset=tpl_preset)
+
+
+def clamp_shot_duration(duration: float, *, pipeline_mode: str, tpl_min: int, tpl_max: int) -> float:
+ settings = get_settings()
+ if pipeline_mode == "image_text":
+ lo = IMAGE_TEXT_DURATION_MIN
+ hi = IMAGE_TEXT_DURATION_MAX
+ else:
+ lo = max(1, tpl_min)
+ hi = min(max(tpl_max, lo), settings.max_shot_duration)
+ return float(max(lo, min(float(duration), hi)))
+
+
+async def _ensure_not_cancelled(project_id: int) -> None:
+ if is_cancelled(project_id):
+ raise PipelineCancelled(f"project {project_id} cancelled")
+ # Cross-process (Celery worker): cancel API writes CANCELLED to DB
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project and project.status == ProjectStatus.CANCELLED:
+ _cancelled.add(project_id)
+ raise PipelineCancelled(f"project {project_id} cancelled")
+
+
+async def _resume_plan(project_id: int) -> tuple[bool, bool, bool, bool]:
+ """Return (image_text, skip_script, skip_assets, skip_videos).
+
+ When shots already have images (+ audio / videos as needed), resume from
+ the next unfinished stage instead of wiping the storyboard.
+ """
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots))
+ )
+ project = result.scalar_one_or_none()
+ if not project or not project.shots:
+ return False, False, False, False
+ image_text = _is_image_text(project)
+ shots = list(project.shots)
+ has_images = all(bool(s.image_url or s.image_ark_url) for s in shots)
+
+ def _audio_ok(shot: Shot) -> bool:
+ if not shot.audio_url:
+ return False
+ path = storage.local_path_from_url(shot.audio_url)
+ if not path or not path.exists():
+ return False
+ return not is_near_silent_audio(path)
+
+ has_audio = 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)
+ skip_assets = has_images and has_audio
+ skip_videos = image_text or has_videos
+ return image_text, skip_script, skip_assets, skip_videos
+
+
+async def run_pipeline(project_id: int) -> None:
+ try:
+ await _ensure_not_cancelled(project_id)
+ image_text, skip_script, skip_assets, skip_videos = await _resume_plan(project_id)
+
+ 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,
+ )
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "RESUME",
+ "percent": 70 if skip_assets else 18,
+ "message": "沿用已有分镜,继续后续阶段",
+ },
+ )
+
+ # 分镜图 + 配音并行;完整模式再并行图生视频
+ if not skip_assets:
+ await _parallel_image_and_audio(project_id)
+ await _ensure_not_cancelled(project_id)
+ else:
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ if project.shots:
+ project.cover_url = sorted(project.shots, key=lambda s: s.shot_no)[0].image_url
+ project.status = ProjectStatus.IMAGE_READY
+ project.progress = 70 if image_text else 50
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "ASSETS_READY",
+ "percent": 70 if image_text else 50,
+ "message": "沿用已有分镜图与配音,开始合成",
+ },
+ )
+
+ if not image_text and not skip_videos:
+ await _parallel_videos(project_id)
+ await _ensure_not_cancelled(project_id)
+
+ await _compose_stage(project_id)
+
+ if is_cancelled(project_id):
+ raise PipelineCancelled(f"project {project_id} cancelled")
+
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project:
+ if project.status == ProjectStatus.CANCELLED:
+ raise PipelineCancelled(f"project {project_id} cancelled")
+ project.status = ProjectStatus.DONE
+ project.progress = 100
+ project.error_msg = None
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {"event": "done", "percent": 100, "video_url": await _final_url(project_id)},
+ )
+ except (PipelineCancelled, asyncio.CancelledError):
+ logger.info("pipeline cancelled project=%s", project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project and project.status != ProjectStatus.DONE:
+ project.status = ProjectStatus.CANCELLED
+ project.error_msg = "用户取消"
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "failed",
+ "stage": "CANCELLED",
+ "message": "用户取消",
+ "retryable": True,
+ "code": "CANCELLED",
+ },
+ )
+ except Exception as exc: # noqa: BLE001
+ if is_cancelled(project_id):
+ logger.info("pipeline cancelled (during error) project=%s", project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project and project.status != ProjectStatus.DONE:
+ project.status = ProjectStatus.CANCELLED
+ project.error_msg = "用户取消"
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "failed",
+ "stage": "CANCELLED",
+ "message": "用户取消",
+ "retryable": True,
+ "code": "CANCELLED",
+ },
+ )
+ return
+ logger.exception("pipeline failed project=%s", project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project:
+ project.status = ProjectStatus.FAILED
+ project.error_msg = str(exc)[:2000]
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "failed",
+ "stage": "PIPELINE",
+ "message": str(exc),
+ "retryable": True,
+ "code": "PIPELINE_ERROR",
+ },
+ )
+ raise
+ finally:
+ _cancelled.discard(project_id)
+ _celery_task_ids.pop(project_id, None)
+ _running.pop(project_id, None)
+
+
+async def delete_project_assets(project_id: int) -> None:
+ pdir = storage.GENERATED_ROOT / f"p{project_id}"
+ if pdir.exists():
+ shutil.rmtree(pdir, ignore_errors=True)
+
+
+async def _final_url(project_id: int) -> str | None:
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ return project.final_video_url if project else None
+
+
+async def _set_status(project_id: int, status: str, progress: int, stage: str) -> None:
+ await _ensure_not_cancelled(project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if not project:
+ return
+ project.status = status
+ project.progress = progress
+ db.add(PipelineJob(project_id=project_id, stage=stage, progress=progress))
+ await db.commit()
+ await publish_progress(project_id, {"event": "progress", "stage": stage, "percent": progress})
+
+
+async def _script_stage(project_id: int) -> None:
+ await _set_status(project_id, ProjectStatus.SCRIPTING, 5, "SCRIPTING")
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.template), selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ tpl = project.template
+ image_text = _is_image_text(project)
+ mode = project.pipeline_mode or "full"
+ if image_text:
+ d_min, d_max = IMAGE_TEXT_DURATION_MIN, IMAGE_TEXT_DURATION_MAX
+ else:
+ d_min = tpl.shot_duration_min
+ d_max = min(tpl.shot_duration_max, get_settings().max_shot_duration)
+
+ style = _effective_style(project)
+ extra = (getattr(project, "extra_prompt", None) or "").strip()
+ char_hint = (getattr(project, "character_prompt", None) or "").strip()
+ plans_result = await ark.chat_storyboard(
+ source_text=project.source_text,
+ source_type=project.source_type,
+ style_prefix=style,
+ llm_system_addon=tpl.llm_system_addon,
+ duration_min=d_min,
+ 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,
+ extra_requirements=extra,
+ )
+ plans = plans_result.shots
+ project.character_bible = _effective_character_bible(project, plans_result.character_bible)
+ for shot in list(project.shots):
+ await db.delete(shot)
+ await db.flush()
+ bible = project.character_bible
+ for plan in plans:
+ dur = clamp_shot_duration(
+ plan.duration,
+ pipeline_mode=mode,
+ tpl_min=tpl.shot_duration_min,
+ tpl_max=tpl.shot_duration_max,
+ )
+ # Store scene-only prompt for UI; locks applied at Seedream time
+ scene = strip_lock_blocks(plan.img_prompt)
+ # Drop duplicated style / bible text from stored scene prompt
+ if style and style in scene:
+ scene = scene.replace(style, "", 1)
+ if bible and bible[:24] in scene:
+ scene = scene.replace(bible, "", 1)
+ scene = strip_lock_blocks(scene)
+ img_prompt = ark._sanitize_seedream_prompt(scene)
+ db.add(
+ Shot(
+ project_id=project.id,
+ shot_no=plan.shot,
+ duration=dur,
+ narration=plan.text,
+ overlay_title=plan.overlay_title or "",
+ overlay_subtitle=plan.overlay_subtitle or "",
+ img_prompt=img_prompt,
+ video_prompt=plan.video_prompt,
+ camera=plan.camera,
+ bgm_mood=plan.bgm,
+ status=ShotStatus.PENDING,
+ )
+ )
+ project.status = ProjectStatus.SCRIPT_READY
+ project.progress = 15
+ await db.commit()
+ await publish_progress(project_id, {"event": "progress", "stage": "SCRIPT_READY", "percent": 15})
+
+
+def _effective_style(project: Project) -> str:
+ user = (getattr(project, "style_prompt", None) or "").strip()
+ tpl = project.template
+ base = (tpl.style_prefix if tpl else "") or ""
+ return user or base
+
+
+def _effective_character_bible(project: Project, llm_bible: str = "") -> str:
+ user = (getattr(project, "character_prompt", None) or "").strip()
+ return user or (llm_bible or "").strip()
+
+
+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"
+ return _IMAGE_SIZE_BY_RATIO.get(ratio)
+
+
+def _project_image_negative(project: Project) -> str:
+ tpl = project.template
+ return merge_negative(tpl.negative_prompt if tpl else "", image_text=_is_image_text(project))
+
+
+def _project_base_refs(project: Project) -> list[str]:
+ tpl = project.template
+ refs = list((tpl.seedream_config or {}).get("ref_images") or []) if tpl else []
+ if project.ref_image_url:
+ refs = [project.ref_image_url, *refs]
+ return seedream_ref_urls(*refs)
+
+
+def _locked_shot_prompt(project: Project, img_prompt: str) -> str:
+ return build_locked_image_prompt(
+ _effective_style(project),
+ strip_lock_blocks(img_prompt),
+ getattr(project, "character_bible", None) or "",
+ )
+
+
+def _consistency_ref_from_shots(shots: list) -> str | None:
+ """Prefer first finished shot's Ark CDN URL, else local static."""
+ ordered = sorted(shots, key=lambda s: s.shot_no)
+ for s in ordered:
+ if s.image_ark_url and str(s.image_ark_url).startswith("http"):
+ return s.image_ark_url
+ for s in ordered:
+ if s.image_url:
+ return s.image_url
+ return None
+
+
+_db_write_lock = asyncio.Lock()
+
+
+async def _parallel_image_and_audio(project_id: int) -> None:
+ """Generate storyboard images and TTS in parallel (audio does not need images)."""
+ await _set_status(project_id, ProjectStatus.IMAGING, 18, "PARALLEL_ASSETS")
+ cfg = get_settings()
+ ark = get_ark()
+
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots), selectinload(Project.template))
+ )
+ project = result.scalar_one()
+ tpl = project.template
+ image_text = _is_image_text(project)
+ shot_rows = sorted(project.shots, key=lambda s: s.shot_no)
+ total = len(shot_rows)
+ shot_meta = [
+ {
+ "id": s.id,
+ "shot_no": s.shot_no,
+ "img_prompt": s.img_prompt,
+ "narration": s.narration,
+ "duration": float(s.duration),
+ "has_image": bool(s.image_url or s.image_ark_url),
+ "has_audio": bool(
+ s.audio_url
+ and (p := storage.local_path_from_url(s.audio_url))
+ and p.exists()
+ and not is_near_silent_audio(p)
+ ),
+ }
+ for s in shot_rows
+ ]
+ style_prefix = _effective_style(project)
+ character_bible = getattr(project, "character_bible", None) or ""
+ 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)
+ image_size = _image_size_for(project)
+ negative = _project_image_negative(project)
+ voice = _project_voice(project)
+
+ if not shot_meta:
+ return
+
+ img_sem = asyncio.Semaphore(max(1, cfg.pipeline_image_concurrency))
+ aud_sem = asyncio.Semaphore(max(1, cfg.pipeline_audio_concurrency))
+ done_img = 0
+ done_aud = 0
+ progress_lock = asyncio.Lock()
+
+ async def bump(kind: str) -> None:
+ nonlocal done_img, done_aud
+ async with progress_lock:
+ if kind == "img":
+ done_img += 1
+ else:
+ done_aud += 1
+ # 18 → 70 while images+audio complete
+ img_w = 0.55 if image_text else 0.45
+ aud_w = 0.45 if image_text else 0.25
+ frac = (done_img / total) * img_w + (done_aud / total) * aud_w
+ pct = 18 + int(52 * frac)
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project:
+ project.progress = pct
+ project.status = ProjectStatus.IMAGING
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "PARALLEL_ASSETS",
+ "percent": pct,
+ "message": f"出图 {done_img}/{total} · 配音 {done_aud}/{total}",
+ "shot": None,
+ "total": total,
+ },
+ )
+
+ async def persist_image(meta: dict, img) -> None:
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ shot = await db.get(Shot, meta["id"])
+ if not shot:
+ return
+ shot.image_url = img.local_url
+ shot.image_ark_url = img.remote_url
+ if shot.status in {ShotStatus.PENDING, ShotStatus.AUDIO_READY}:
+ shot.status = (
+ ShotStatus.AUDIO_READY if shot.audio_url else ShotStatus.IMAGE_READY
+ )
+ elif not shot.video_url:
+ shot.status = ShotStatus.IMAGE_READY
+ await db.commit()
+ await bump("img")
+
+ async def one_image(meta: dict, ref_urls: list[str]) -> str | None:
+ """Generate one shot; return remote/local URL for consistency chaining."""
+ await _ensure_not_cancelled(project_id)
+ if meta.get("has_image"):
+ await bump("img")
+ return None
+ prompt = build_locked_image_prompt(style_prefix, strip_lock_blocks(meta["img_prompt"]), character_bible)
+ async with img_sem:
+ await _ensure_not_cancelled(project_id)
+ img = await ark.gen_image(
+ prompt,
+ negative,
+ ref_urls,
+ project_id=project_id,
+ shot_no=meta["shot_no"],
+ size=image_size,
+ )
+ await persist_image(meta, img)
+ 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."""
+ 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:
+ await bump("img")
+
+ if not need:
+ return
+
+ anchor = existing_anchor
+ first, rest = need[0], need[1:]
+ first_refs = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
+ first_url = await one_image(first, first_refs)
+ if first_url:
+ anchor = first_url
+
+ if not rest:
+ return
+ rest_refs = seedream_ref_urls(anchor, *base_refs) if anchor else list(base_refs)
+
+ results = await asyncio.gather(
+ *(one_image(m, rest_refs) for m in rest),
+ return_exceptions=True,
+ )
+ for r in results:
+ if isinstance(r, Exception):
+ raise r
+
+ async def one_audio(meta: dict) -> None:
+ await _ensure_not_cancelled(project_id)
+ if meta.get("has_audio"):
+ await bump("aud")
+ return
+ async with aud_sem:
+ await _ensure_not_cancelled(project_id)
+ audio_url = await ark.tts(
+ meta["narration"],
+ voice,
+ project_id=project_id,
+ shot_no=meta["shot_no"],
+ duration_hint=meta["duration"],
+ )
+ new_dur = meta["duration"]
+ audio_path = storage.local_path_from_url(audio_url or "")
+ if audio_path and audio_path.exists():
+ dur = await asyncio.to_thread(probe_duration, audio_path)
+ if dur and dur > 0.5:
+ new_dur = max(float(meta["duration"]), round(dur + 0.35, 2))
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ shot = await db.get(Shot, meta["id"])
+ if not shot:
+ return
+ shot.audio_url = audio_url
+ shot.duration = new_dur
+ if shot.status == ShotStatus.PENDING:
+ shot.status = ShotStatus.AUDIO_READY
+ elif shot.status == ShotStatus.IMAGE_READY and shot.audio_url:
+ # keep IMAGE_READY for UI; audio_url marks TTS done
+ pass
+ await db.commit()
+ await bump("aud")
+
+ results = await asyncio.gather(
+ run_images(),
+ *(one_audio(m) for m in shot_meta),
+ return_exceptions=True,
+ )
+ errors = [r for r in results if isinstance(r, Exception)]
+ if errors:
+ # Prefer cancel over generic failure
+ for err in errors:
+ if isinstance(err, (PipelineCancelled, asyncio.CancelledError)):
+ raise err
+ raise RuntimeError(str(errors[0]))
+
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ if project.shots:
+ project.cover_url = sorted(project.shots, key=lambda s: s.shot_no)[0].image_url
+ project.status = ProjectStatus.IMAGE_READY if image_text else ProjectStatus.IMAGE_READY
+ project.progress = 70 if image_text else 50
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "ASSETS_READY",
+ "percent": 70 if image_text else 50,
+ "message": "分镜图与配音已完成",
+ },
+ )
+
+
+async def _parallel_videos(project_id: int) -> None:
+ """Run Seedance i2v for all shots concurrently (after images exist)."""
+ await _set_status(project_id, ProjectStatus.VIDEOING, 55, "VIDEOING")
+ cfg = get_settings()
+ ark = get_ark()
+
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots), selectinload(Project.template))
+ )
+ project = result.scalar_one()
+ tpl = project.template
+ consistency = 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
+ shot_meta = [
+ {
+ "id": s.id,
+ "shot_no": s.shot_no,
+ "duration": float(s.duration),
+ "video_prompt": s.video_prompt,
+ "camera": s.camera,
+ "image_ref": s.image_ark_url or s.image_url or "",
+ "has_video": bool(s.video_url),
+ }
+ for s in sorted(project.shots, key=lambda s: s.shot_no)
+ ]
+ total = len(shot_meta)
+
+ if not shot_meta:
+ return
+
+ sem = asyncio.Semaphore(max(1, cfg.pipeline_video_concurrency))
+ done = 0
+ progress_lock = asyncio.Lock()
+
+ async def one_video(meta: dict) -> None:
+ nonlocal done
+ await _ensure_not_cancelled(project_id)
+ if meta.get("has_video"):
+ async with progress_lock:
+ done += 1
+ pct = 55 + int(30 * done / max(total, 1))
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "VIDEOING",
+ "shot": meta["shot_no"],
+ "percent": pct,
+ "message": f"沿用已有视频 {done}/{total}",
+ },
+ )
+ return
+ async with sem:
+ await _ensure_not_cancelled(project_id)
+ prompt = f"{meta['video_prompt']}。运镜:{meta['camera']}。{motion}"
+ task_id = await ark.gen_video_i2v(
+ meta["image_ref"],
+ prompt,
+ int(meta["duration"]),
+ character_consistency=consistency,
+ resolution=resolution,
+ ratio=ratio,
+ )
+ local_video = await ark.wait_video(
+ task_id, project_id=project_id, shot_no=meta["shot_no"]
+ )
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ shot = await db.get(Shot, meta["id"])
+ if not shot:
+ return
+ shot.video_url = local_video
+ shot.status = ShotStatus.VIDEO_READY
+ await db.commit()
+ async with progress_lock:
+ done += 1
+ pct = 55 + int(30 * done / max(total, 1))
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project:
+ project.progress = pct
+ project.status = ProjectStatus.VIDEOING
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "VIDEOING",
+ "shot": meta["shot_no"],
+ "total": total,
+ "percent": pct,
+ "message": f"AI 视频 {done}/{total}",
+ },
+ )
+
+ results = await asyncio.gather(*(one_video(m) for m in shot_meta), return_exceptions=True)
+ errors = [r for r in results if isinstance(r, Exception)]
+ if errors:
+ for err in errors:
+ if isinstance(err, (PipelineCancelled, asyncio.CancelledError)):
+ raise err
+ raise RuntimeError(str(errors[0]))
+
+ async with _db_write_lock:
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project:
+ project.status = ProjectStatus.VIDEO_READY
+ project.progress = 88
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {"event": "progress", "stage": "VIDEO_READY", "percent": 88, "message": "全部镜头视频完成"},
+ )
+
+
+async def _image_stage(project_id: int) -> None:
+ await _set_status(project_id, ProjectStatus.IMAGING, 20, "IMAGING")
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots), selectinload(Project.template))
+ )
+ project = result.scalar_one()
+ tpl = project.template
+ total = len(project.shots)
+ ref_urls = _project_base_refs(project)
+ image_size = _image_size_for(project)
+ negative = _project_image_negative(project)
+ style_prefix = _effective_style(project)
+ bible = getattr(project, "character_bible", None) or ""
+ 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:
+ anchor = shot.image_ark_url or shot.image_url
+ continue
+ refs = seedream_ref_urls(anchor, *ref_urls) if anchor else list(ref_urls)
+ prompt = build_locked_image_prompt(style_prefix, strip_lock_blocks(shot.img_prompt), bible)
+ img = await ark.gen_image(
+ prompt,
+ negative,
+ refs,
+ project_id=project_id,
+ shot_no=shot.shot_no,
+ size=image_size,
+ )
+ shot.image_url = img.local_url
+ shot.image_ark_url = img.remote_url
+ shot.status = ShotStatus.IMAGE_READY
+ if 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))
+ project.progress = pct
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "IMAGING",
+ "shot": shot.shot_no,
+ "total": total,
+ "percent": pct,
+ },
+ )
+ if project.shots:
+ project.cover_url = sorted(project.shots, key=lambda s: s.shot_no)[0].image_url
+ project.status = ProjectStatus.IMAGE_READY
+ project.progress = 75 if _is_image_text(project) else 45
+ await db.commit()
+
+
+async def _video_stage(project_id: int) -> None:
+ await _set_status(project_id, ProjectStatus.VIDEOING, 50, "VIDEOING")
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots), selectinload(Project.template))
+ )
+ project = result.scalar_one()
+ tpl = project.template
+ consistency = 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
+ 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}"
+ image_ref = shot.image_ark_url or shot.image_url or ""
+ task_id = await ark.gen_video_i2v(
+ image_ref,
+ prompt,
+ int(shot.duration),
+ character_consistency=consistency,
+ resolution=resolution,
+ ratio=ratio,
+ )
+ local_video = await ark.wait_video(task_id, project_id=project_id, shot_no=shot.shot_no)
+ shot.video_url = local_video
+ shot.status = ShotStatus.VIDEO_READY
+ pct = 50 + int(25 * (idx + 1) / max(total, 1))
+ project.progress = pct
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "VIDEOING",
+ "shot": shot.shot_no,
+ "total": total,
+ "percent": pct,
+ },
+ )
+ project.status = ProjectStatus.VIDEO_READY
+ project.progress = 75
+ await db.commit()
+
+
+async def _audio_stage(project_id: int) -> None:
+ await _set_status(project_id, ProjectStatus.AUDIOING, 80, "AUDIOING")
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots), selectinload(Project.template))
+ )
+ project = result.scalar_one()
+ voice = _project_voice(project)
+ total = len(project.shots)
+ for idx, shot in enumerate(sorted(project.shots, key=lambda s: s.shot_no)):
+ await _ensure_not_cancelled(project_id)
+ shot.audio_url = await ark.tts(
+ shot.narration,
+ voice,
+ project_id=project_id,
+ shot_no=shot.shot_no,
+ duration_hint=shot.duration,
+ )
+ audio_path = storage.local_path_from_url(shot.audio_url or "")
+ if audio_path and audio_path.exists():
+ dur = await asyncio.to_thread(probe_duration, audio_path)
+ if dur and dur > 0.5:
+ shot.duration = max(float(shot.duration), round(dur + 0.35, 2))
+ shot.status = ShotStatus.AUDIO_READY
+ pct = 80 + int(10 * (idx + 1) / max(total, 1))
+ project.progress = pct
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "AUDIOING",
+ "shot": shot.shot_no,
+ "total": total,
+ "percent": pct,
+ },
+ )
+
+
+async def _compose_stage(project_id: int) -> None:
+ await _set_status(project_id, ProjectStatus.COMPOSING, 92, "COMPOSING")
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.shots), selectinload(Project.template))
+ )
+ project = result.scalar_one()
+ media: list[ShotMedia] = []
+ for shot in sorted(project.shots, key=lambda s: s.shot_no):
+ 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)
+ media.append(
+ ShotMedia(
+ shot_no=shot.shot_no,
+ duration=float(shot.duration),
+ narration=shot.narration,
+ overlay_title=getattr(shot, "overlay_title", "") or "",
+ overlay_subtitle=getattr(shot, "overlay_subtitle", "") or "",
+ video_path=video_path if video_path and video_path.exists() else None,
+ audio_path=audio_path if audio_path and audio_path.exists() else None,
+ image_path=image_path if image_path and image_path.exists() else None,
+ )
+ )
+
+ ratio = (project.template.default_ratio if project.template else None) or "16:9"
+ mode = project.pipeline_mode or "full"
+ if mode == "image_text" and ratio == "16:9":
+ ratio = "9:16"
+
+ out = storage.project_dir(project_id) / "final.mp4"
+ await asyncio.to_thread(
+ compose_project,
+ media,
+ out,
+ ComposeOptions(
+ ratio=ratio,
+ mode=mode,
+ resolution_mode=project.resolution_mode or "preview",
+ ),
+ )
+ project.final_video_url = storage.rel_static_url(out)
+ if project.status != ProjectStatus.CANCELLED:
+ project.status = ProjectStatus.AUDITING
+ project.progress = 96
+ await db.commit()
+
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project and project.status != ProjectStatus.CANCELLED:
+ project.status = ProjectStatus.DONE
+ project.progress = 100
+ await db.commit()
+
+
+async def regen_shot_image(project_id: int, shot_id: int) -> None:
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.template), selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ shot = next((s for s in project.shots if s.id == shot_id), 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)
+ negative = _project_image_negative(project)
+ prompt = _locked_shot_prompt(project, shot.img_prompt)
+ img = await ark.gen_image(
+ prompt,
+ negative,
+ ref_urls,
+ project_id=project_id,
+ shot_no=shot.shot_no,
+ size=_image_size_for(project),
+ )
+ shot.image_url = img.local_url
+ shot.image_ark_url = img.remote_url
+ shot.video_url = None
+ shot.status = ShotStatus.IMAGE_READY
+ shot.version += 1
+ project.status = ProjectStatus.IMAGE_READY
+ project.final_video_url = None
+ await db.commit()
+
+
+async def regen_shot_video(project_id: int, shot_id: int) -> None:
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.template), selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ if _is_image_text(project):
+ raise ValueError("图文模式无需生成 AI 视频,请直接重新合成成片")
+ shot = next((s for s in project.shots if s.id == shot_id), 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))
+ cfg = get_settings()
+ resolution = cfg.ark_video_resolution
+ if project.resolution_mode == "hd" and resolution == "480p":
+ resolution = "720p"
+ prompt = f"{shot.video_prompt}。运镜:{shot.camera}。{motion}"
+ image_ref = shot.image_ark_url or shot.image_url or ""
+ task_id = await ark.gen_video_i2v(
+ image_ref,
+ prompt,
+ int(shot.duration),
+ character_consistency=consistency,
+ resolution=resolution,
+ ratio=project.template.default_ratio or cfg.ark_video_ratio,
+ )
+ local_video = await ark.wait_video(task_id, project_id=project_id, shot_no=shot.shot_no)
+ shot.video_url = local_video
+ shot.status = ShotStatus.VIDEO_READY
+ shot.version += 1
+ project.final_video_url = None
+ project.status = ProjectStatus.VIDEO_READY
+ await db.commit()
+
+
+async def regen_shot_audio(project_id: int, shot_id: int) -> None:
+ ark = get_ark()
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.template), selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ shot = next((s for s in project.shots if s.id == shot_id), None)
+ if not shot:
+ raise ValueError("shot not found")
+ if not (shot.narration or "").strip():
+ raise ValueError("旁白为空,无法配音")
+ voice = _project_voice(project)
+ audio_url = await ark.tts(
+ shot.narration,
+ voice,
+ project_id=project_id,
+ shot_no=shot.shot_no,
+ duration_hint=float(shot.duration),
+ )
+ shot.audio_url = audio_url
+ audio_path = storage.local_path_from_url(audio_url or "")
+ if audio_path and audio_path.exists():
+ dur = await asyncio.to_thread(probe_duration, audio_path)
+ if dur and dur > 0.5:
+ shot.duration = max(float(shot.duration), round(dur + 0.35, 2))
+ if shot.status == ShotStatus.PENDING:
+ shot.status = ShotStatus.AUDIO_READY
+ shot.version += 1
+ project.final_video_url = None
+ await db.commit()
+
+
+async def regen_project_audio_and_compose(project_id: int) -> None:
+ """Force re-TTS every shot with current voice, then compose."""
+ ark = get_ark()
+ await _set_status(project_id, ProjectStatus.AUDIOING, 80, "AUDIOING")
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ select(Project)
+ .where(Project.id == project_id)
+ .options(selectinload(Project.template), selectinload(Project.shots))
+ )
+ project = result.scalar_one()
+ voice = _project_voice(project)
+ shots = sorted(project.shots, key=lambda s: s.shot_no)
+ total = max(len(shots), 1)
+ for idx, shot in enumerate(shots):
+ if not (shot.narration or "").strip():
+ continue
+ audio_url = await ark.tts(
+ shot.narration,
+ voice,
+ project_id=project_id,
+ shot_no=shot.shot_no,
+ duration_hint=float(shot.duration),
+ )
+ shot.audio_url = audio_url
+ audio_path = storage.local_path_from_url(audio_url or "")
+ if audio_path and audio_path.exists():
+ dur = await asyncio.to_thread(probe_duration, audio_path)
+ if dur and dur > 0.5:
+ shot.duration = max(float(shot.duration), round(dur + 0.35, 2))
+ shot.version += 1
+ project.progress = 80 + int(10 * (idx + 1) / total)
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "AUDIOING",
+ "percent": project.progress,
+ "message": f"配音 {idx + 1}/{total}",
+ },
+ )
+ project.final_video_url = None
+ await db.commit()
+
+ await _compose_stage(project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project and project.status != ProjectStatus.CANCELLED:
+ project.status = ProjectStatus.DONE
+ project.progress = 100
+ project.error_msg = None
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {"event": "done", "percent": 100, "video_url": await _final_url(project_id)},
+ )
+
+
+async def compose_only(project_id: int) -> None:
+ await _compose_stage(project_id)
+ async with AsyncSessionLocal() as db:
+ project = await db.get(Project, project_id)
+ if project and project.status != ProjectStatus.CANCELLED:
+ project.status = ProjectStatus.DONE
+ project.progress = 100
+ project.error_msg = None
+ await db.commit()
+ await publish_progress(
+ project_id,
+ {"event": "done", "percent": 100, "video_url": await _final_url(project_id)},
+ )
diff --git a/backend/app/services/progress.py b/backend/app/services/progress.py
new file mode 100644
index 0000000..46338cd
--- /dev/null
+++ b/backend/app/services/progress.py
@@ -0,0 +1,108 @@
+"""Progress pub/sub — Redis when available, else in-process queues."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections import defaultdict
+from typing import Any
+
+from app.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+_queues: dict[int, list[asyncio.Queue]] = defaultdict(list)
+_latest: dict[int, dict[str, Any]] = {}
+_redis = None
+_redis_failed = False
+
+
+def _get_redis():
+ global _redis, _redis_failed
+ if _redis_failed:
+ return None
+ if _redis is not None:
+ return _redis
+ try:
+ import redis
+
+ client = redis.Redis.from_url(
+ get_settings().redis_url,
+ decode_responses=True,
+ socket_connect_timeout=2,
+ socket_timeout=2,
+ )
+ client.ping()
+ _redis = client
+ return _redis
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Redis unavailable for progress: %s", exc)
+ _redis_failed = True
+ return None
+
+
+def channel(project_id: int) -> str:
+ return f"framecut:progress:{project_id}"
+
+
+async def publish_progress(project_id: int, payload: dict[str, Any]) -> None:
+ _latest[project_id] = payload
+ r = _get_redis()
+ if r is not None:
+ try:
+ r.publish(channel(project_id), json.dumps(payload, ensure_ascii=False))
+ r.setex(f"framecut:latest:{project_id}", 3600, json.dumps(payload, ensure_ascii=False))
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Redis publish failed: %s", exc)
+
+ dead: list[asyncio.Queue] = []
+ for q in _queues[project_id]:
+ try:
+ q.put_nowait(payload)
+ except Exception: # noqa: BLE001
+ dead.append(q)
+ for q in dead:
+ _queues[project_id].remove(q)
+
+
+def subscribe(project_id: int) -> asyncio.Queue:
+ q: asyncio.Queue = asyncio.Queue()
+ _queues[project_id].append(q)
+ r = _get_redis()
+ if r is not None:
+ try:
+ raw = r.get(f"framecut:latest:{project_id}")
+ if raw:
+ q.put_nowait(json.loads(raw))
+ except Exception: # noqa: BLE001
+ pass
+ elif project_id in _latest:
+ q.put_nowait(_latest[project_id])
+ return q
+
+
+def unsubscribe(project_id: int, q: asyncio.Queue) -> None:
+ if q in _queues[project_id]:
+ _queues[project_id].remove(q)
+
+
+async def redis_bridge(project_id: int, q: asyncio.Queue) -> None:
+ """Background task: forward Redis pubsub messages into local queue."""
+ r = _get_redis()
+ if r is None:
+ return
+ pubsub = r.pubsub()
+ pubsub.subscribe(channel(project_id))
+ try:
+ while True:
+ msg = await asyncio.to_thread(pubsub.get_message, ignore_subscribe_messages=True, timeout=1.0)
+ if msg and msg.get("type") == "message":
+ data = msg.get("data")
+ if isinstance(data, str):
+ q.put_nowait(json.loads(data))
+ await asyncio.sleep(0.05)
+ except asyncio.CancelledError:
+ pubsub.unsubscribe(channel(project_id))
+ pubsub.close()
+ raise
diff --git a/backend/app/services/storage.py b/backend/app/services/storage.py
new file mode 100644
index 0000000..3c662d1
--- /dev/null
+++ b/backend/app/services/storage.py
@@ -0,0 +1,78 @@
+"""Download / persist generated assets under backend/static/generated."""
+
+from __future__ import annotations
+
+import base64
+import mimetypes
+from pathlib import Path
+
+import httpx
+
+from app.config import get_settings
+
+STATIC_ROOT = Path(__file__).resolve().parents[2] / "static"
+GENERATED_ROOT = STATIC_ROOT / "generated"
+
+
+def project_dir(project_id: int) -> Path:
+ path = GENERATED_ROOT / f"p{project_id}"
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def to_public_url(rel_or_abs: str) -> str:
+ """Convert /static/... path to absolute URL for frontend."""
+ if rel_or_abs.startswith("http://") or rel_or_abs.startswith("https://"):
+ return rel_or_abs
+ settings = get_settings()
+ if not rel_or_abs.startswith("/"):
+ rel_or_abs = "/" + rel_or_abs
+ return f"{settings.public_base_url.rstrip('/')}{rel_or_abs}"
+
+
+def local_path_from_url(url: str) -> Path | 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)
+ return None
+
+
+async def download_to(
+ url: str,
+ dest: Path,
+ *,
+ timeout: float = 120.0,
+) -> Path:
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
+ resp = await client.get(url)
+ resp.raise_for_status()
+ dest.write_bytes(resp.content)
+ return dest
+
+
+def file_to_data_uri(path: Path) -> str:
+ mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
+ b64 = base64.b64encode(path.read_bytes()).decode("ascii")
+ return f"data:{mime};base64,{b64}"
+
+
+async def ensure_local_media(url: str, dest: Path) -> Path:
+ """If url is remote, download; if already local, copy/resolve."""
+ local = local_path_from_url(url)
+ if local and local.exists():
+ if local.resolve() != dest.resolve():
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(local.read_bytes())
+ return dest
+ if url.startswith("http://") or url.startswith("https://"):
+ return await download_to(url, dest)
+ raise FileNotFoundError(f"cannot resolve media: {url}")
+
+
+def rel_static_url(path: Path) -> str:
+ rel = path.resolve().relative_to(STATIC_ROOT.resolve())
+ return f"/static/{rel.as_posix()}"
diff --git a/backend/app/services/style_lock.py b/backend/app/services/style_lock.py
new file mode 100644
index 0000000..b040cbc
--- /dev/null
+++ b/backend/app/services/style_lock.py
@@ -0,0 +1,123 @@
+"""Force visual style + character consistency across storyboard shots."""
+
+from __future__ import annotations
+
+import re
+from urllib.parse import urlparse
+
+# Terms that cause 真人 / 动漫 / 3D drift across shots
+_STYLE_DRIFT = re.compile(
+ r"(写实照片|照片级真实|真人实拍|真实人脸|真人脸|摄影棚人像|电影真人剧照|"
+ r"超写实皮肤|照片质感|live[\s-]?action|photoreal(?:istic)?|"
+ r"赛璐璐二次元|日系动漫脸|动漫大眼睛|萌系二次元|3D超写实|CGI写实人像)",
+ re.IGNORECASE,
+)
+
+_EXTRA_NEGATIVE = (
+ "写实照片,真人,真实人脸,摄影棚人像,电影真人剧照,照片级皮肤,"
+ "风格混杂,镜头间画风跳变,另一套画风,赛璐璐二次元与写实混用"
+)
+
+_SCENE_TAG = re.compile(r"【场景】\s*(.+?)(?=\n【|\Z)", re.S)
+_LOCK_LINE = re.compile(r"【(?:风格锁定|人物锁定|约束)】[^\n]*")
+_PERSON_SETTING = re.compile(r"(?:人物设定|角色设定)[::][^\n【]{0,400}")
+
+
+def strip_style_drift(prompt: str) -> str:
+ out = _STYLE_DRIFT.sub("", prompt or "")
+ out = re.sub(r"[,,]{2,}", ",", out)
+ return out.strip(",,。 \n\t")
+
+
+def strip_lock_blocks(prompt: str) -> str:
+ """Remove internal lock wrappers for UI / stored scene prompts."""
+ raw = (prompt or "").strip()
+ if not raw:
+ return ""
+ # New tagged format
+ m = _SCENE_TAG.search(raw)
+ if m:
+ return m.group(1).strip(",,。 \n\t")
+ # Drop tagged lock lines
+ out = _LOCK_LINE.sub("", raw)
+ out = _PERSON_SETTING.sub("", out)
+ # Legacy: drop comma segments that start with lock tags / boilerplate
+ if "【风格锁定】" in raw or "【人物锁定】" in raw:
+ kept: list[str] = []
+ for part in re.split(r"[,,\n]", raw):
+ p = part.strip()
+ if not p:
+ continue
+ if p.startswith(("【风格锁定】", "【人物锁定】", "【约束】", "人物设定", "角色设定")):
+ continue
+ if p.startswith(("同一画风", "全片必须保持", "凡出现人物", "禁止写实", "禁止换脸", "画面干净无文字")):
+ continue
+ # Drop mid-lock fragments
+ if "禁止镜头间切换" in p or "必须严格沿用以上外形" in p:
+ continue
+ kept.append(p)
+ out = ",".join(kept)
+ out = re.sub(r"[,,]{2,}", ",", out)
+ out = re.sub(r"\s{2,}", " ", out)
+ return out.strip(",,。;; \n\t")
+
+
+def build_locked_image_prompt(
+ style_prefix: str,
+ img_prompt: str,
+ character_bible: str = "",
+) -> str:
+ """Canonical prompt sent to Seedream — style + cast locked every shot."""
+ body = strip_lock_blocks(strip_style_drift(img_prompt))
+ if style_prefix and style_prefix in body:
+ body = body.replace(style_prefix, "", 1).strip(",, ")
+ parts: list[str] = []
+ if style_prefix:
+ parts.append(
+ f"【风格锁定】{style_prefix}。全片统一此画风,禁止写实摄影与风格跳变"
+ )
+ if (character_bible or "").strip():
+ parts.append(
+ f"【人物锁定】{(character_bible or '').strip()}。人物外形全片一致,禁止换脸换装"
+ )
+ if body:
+ parts.append(f"【场景】{body}")
+ parts.append("【约束】同一画风同一人物,画面干净无文字")
+ return "\n".join(parts)
+
+
+def merge_negative(template_negative: str, *, image_text: bool = False) -> str:
+ base = (template_negative or "").strip(",, ")
+ parts = [p for p in (base, _EXTRA_NEGATIVE) if p]
+ merged = ",".join(parts)
+ if image_text and "文字" not in merged:
+ merged = f"{merged},画面文字,字幕,水印,标题字"
+ return merged
+
+
+def seedream_ref_urls(*candidates: str | None) -> list[str]:
+ """Normalize refs for Seedream — **public https only**.
+
+ Skip data: URIs (multi‑MB base64 often hangs Seedream) and LAN/localhost URLs
+ (Ark cloud cannot fetch them). Prefer prior shot `image_ark_url` CDN links.
+ """
+ out: list[str] = []
+ seen: set[str] = set()
+ for raw in candidates:
+ if not raw:
+ continue
+ u = raw.strip()
+ if not u or u in seen:
+ continue
+ if not (u.startswith("https://") or u.startswith("http://")):
+ continue
+ host = (urlparse(u).hostname or "").lower()
+ if not host or host in {"localhost", "127.0.0.1", "::1"}:
+ continue
+ if host.startswith("192.168.") or host.startswith("10."):
+ continue
+ if re.match(r"^172\.(1[6-9]|2\d|3[0-1])\.", host):
+ continue
+ out.append(u)
+ seen.add(u)
+ return out[:2]
diff --git a/backend/app/services/templates_seed.py b/backend/app/services/templates_seed.py
new file mode 100644
index 0000000..1d5b050
--- /dev/null
+++ b/backend/app/services/templates_seed.py
@@ -0,0 +1,207 @@
+"""内置风格模板 — 提示词与风格描述统一中文。"""
+
+TEMPLATES: list[dict] = [
+ {
+ "id": "vox_papercut",
+ "name": "Vox剪纸科普",
+ "description": "低饱和扁平剪纸,适合硬核科普与纪录片节奏。",
+ "category": ["科普", "剪纸"],
+ "preview_cover": "/static/templates/vox_papercut.svg",
+ "style_prefix": "Vox剪纸扁平插画,层叠剪纸边缘,低饱和,干净剪影,科普解说片气质",
+ "negative_prompt": "写实照片,真人,真实人脸,三维渲染,日系动漫,模糊,噪点,水印,画面文字",
+ "default_ratio": "16:9",
+ "shot_duration_min": 4,
+ "shot_duration_max": 15,
+ "llm_system_addon": "按科普讲解节奏拆镜,台词口语化、信息密度适中,每镜一个清晰视觉焦点。全片保持同一剪纸画风与角色外形。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.7,
+ "pipeline_mode": "full",
+ "character_prompt": "符号化科普角色或简洁人形剪影,低细节面部,服装色块固定,全片外形一致",
+ "extra_prompt": "层叠纸片边缘清晰,低饱和,单镜一个视觉焦点,避免写实皮肤与复杂纹理",
+ },
+ "seedance_config": {
+ "motion_bias": "缓慢横移,轻推镜头,纸层轻微错动",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "narrator_calm", "bgm_mood": "好奇纪录片"},
+ "subtitle_config": {"font": "SourceHanSans", "position": "bottom"},
+ "sort_order": 10,
+ "is_active": True,
+ "is_premium": False,
+ },
+ {
+ "id": "kids_flat",
+ "name": "儿童绘本扁平",
+ "description": "柔和配色与圆润造型,适合儿童科普与故事。",
+ "category": ["儿童", "绘本"],
+ "preview_cover": "/static/templates/kids_flat.svg",
+ "style_prefix": "儿童绘本扁平插画,柔和粉彩,圆润造型,友好角色,简洁背景",
+ "negative_prompt": "恐怖,阴暗,写实照片,复杂纹理,血腥",
+ "default_ratio": "16:9",
+ "shot_duration_min": 3,
+ "shot_duration_max": 12,
+ "llm_system_addon": "用孩子听得懂的短句,每镜突出一个可爱视觉元素,节奏轻快。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.65,
+ "pipeline_mode": "full",
+ "character_prompt": "圆润可爱卡通角色,大眼睛简化五官,柔和配色服装,友好表情,全片同一角色外形",
+ "extra_prompt": "粉彩柔光,背景简洁,造型圆润,适合儿童观看",
+ },
+ "seedance_config": {
+ "motion_bias": "轻微弹跳感,柔和镜头漂移",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "warm_storyteller", "bgm_mood": "俏皮轻快"},
+ "subtitle_config": {"font": "RoundedSans", "position": "bottom"},
+ "sort_order": 20,
+ "is_active": True,
+ "is_premium": False,
+ },
+ {
+ "id": "chalk_whiteboard",
+ "name": "粉笔白板手绘",
+ "description": "黑板粉笔与白板简笔画,适合课堂讲解风。",
+ "category": ["科普", "手绘"],
+ "preview_cover": "/static/templates/chalk_whiteboard.svg",
+ "style_prefix": "黑板粉笔与白板手绘讲解风,粉笔笔触,示意图箭头,素描线条",
+ "negative_prompt": "写实照片,光滑三维,杂乱界面",
+ "default_ratio": "16:9",
+ "shot_duration_min": 4,
+ "shot_duration_max": 15,
+ "llm_system_addon": "偏讲解结构:定义→例子→对比,画面多用示意图与箭头。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.6,
+ "pipeline_mode": "full",
+ "character_prompt": "粉笔简笔人物或火柴人讲解者,线条简洁,特征固定,可重复识别",
+ "extra_prompt": "黑板/白板底,箭头与示意图清晰,教学感构图",
+ },
+ "seedance_config": {
+ "motion_bias": "线条逐步显现,镜头基本固定",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "teacher_clear", "bgm_mood": "专注氛围"},
+ "subtitle_config": {"font": "SourceHanSans", "position": "bottom"},
+ "sort_order": 30,
+ "is_active": True,
+ "is_premium": False,
+ },
+ {
+ "id": "magazine_collage",
+ "name": "杂志拼贴",
+ "description": "剪报拼贴与印刷纹理,适合文化话题与品牌故事。",
+ "category": ["拼贴", "杂志"],
+ "preview_cover": "/static/templates/magazine_collage.svg",
+ "style_prefix": "杂志纸质拼贴,撕边,网纹印刷质感,层叠剪贴,大胆平面构图",
+ "negative_prompt": "纯净矢量,写实皮肤,脏污发灰的色彩",
+ "default_ratio": "9:16",
+ "shot_duration_min": 4,
+ "shot_duration_max": 12,
+ "llm_system_addon": "视觉冲击优先,每镜一个强构图,文案短而有力。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.75,
+ "pipeline_mode": "image_text",
+ "character_prompt": "杂志剪贴人像剪影或印刷半调人物,外形与配色全片统一",
+ "extra_prompt": "撕边纸质、网纹印刷、大胆色块,竖屏强构图",
+ },
+ "seedance_config": {
+ "motion_bias": "图层轻微滑动旋转,纸张沙沙感",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "urban_editorial", "bgm_mood": "时髦轻电子"},
+ "subtitle_config": {"font": "DisplaySans", "position": "center"},
+ "sort_order": 40,
+ "is_active": True,
+ "is_premium": False,
+ },
+ {
+ "id": "pixel_retro",
+ "name": "像素复古科普",
+ "description": "8-bit/16-bit 像素风,适合科技史与游戏化讲解。",
+ "category": ["像素", "复古"],
+ "preview_cover": "/static/templates/pixel_retro.svg",
+ "style_prefix": "复古像素画,16位有限色板,清晰像素块,简单游戏场景,无抗锯齿",
+ "negative_prompt": "平滑渐变,写实照片,模糊像素",
+ "default_ratio": "16:9",
+ "shot_duration_min": 3,
+ "shot_duration_max": 12,
+ "llm_system_addon": "节奏偏游戏关卡感,信息点做成可辨识像素图标。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.7,
+ "pipeline_mode": "full",
+ "character_prompt": "16位像素小人角色,有限色板,外形与调色全片不变",
+ "extra_prompt": "清晰像素块,无抗锯齿,游戏关卡式场景",
+ },
+ "seedance_config": {
+ "motion_bias": "逐帧步进运动,轻微视差滚动",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "retro_host", "bgm_mood": "8位好奇"},
+ "subtitle_config": {"font": "PixelFont", "position": "bottom"},
+ "sort_order": 50,
+ "is_active": True,
+ "is_premium": False,
+ },
+ {
+ "id": "ink_guofeng",
+ "name": "水墨国风",
+ "description": "水墨留白与写意笔触,适合历史与文化短故事。",
+ "category": ["国风", "水墨"],
+ "preview_cover": "/static/templates/ink_guofeng.svg",
+ "style_prefix": "中国水墨写意插画,富有表现力的笔触,大量留白,诗意氛围,淡雅墨色,非写实摄影",
+ "negative_prompt": "写实照片,真人,真实人脸,霓虹,赛博朋克,日系动漫,欧美卡通,画面文字,字幕,水印",
+ "default_ratio": "9:16",
+ "shot_duration_min": 4,
+ "shot_duration_max": 12,
+ "llm_system_addon": "叙事偏意境与转折,台词可略文言白话混用,留白节奏。适合竖屏图文:每镜短标题+诗意副标题叠字,并写可朗读的旁白。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.7,
+ "pipeline_mode": "image_text",
+ "character_prompt": "水墨写意人物,简笔眉眼,宽袍或古装轮廓固定,墨色淡雅,全片同一人设",
+ "extra_prompt": "大量留白,淡墨渲染,诗意意境,竖屏顶部可叠字",
+ },
+ "seedance_config": {
+ "motion_bias": "墨晕渗开与消散,缓慢升降镜头,薄雾飘动",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "guqin_narrator", "bgm_mood": "古筝氛围"},
+ "subtitle_config": {"font": "KaiTi", "position": "top"},
+ "sort_order": 60,
+ "is_active": True,
+ "is_premium": False,
+ },
+ {
+ "id": "portrait_story",
+ "name": "竖屏图文故事",
+ "description": "竖屏插画叙事,适合历史人文短片。",
+ "category": ["图文", "竖屏", "故事"],
+ "preview_cover": "/static/templates/ink_guofeng.svg",
+ "style_prefix": "统一二维概念插画,细腻光影与电影感构图,非写实摄影、非日系赛璐璐动漫,竖屏主体偏中下,顶部留白便于叠字,画面干净无文字",
+ "negative_prompt": "写实照片,真人,真实人脸,摄影棚,电影真人剧照,日系动漫赛璐璐,画面文字,字幕,水印,标题字,logo,模糊",
+ "default_ratio": "9:16",
+ "shot_duration_min": 4,
+ "shot_duration_max": 12,
+ "llm_system_addon": "按故事节拍拆镜:起承转合。每镜 title 短标题、subtitle 叠字副标题、text 为可朗读旁白。画面必须全片统一插画风与人物外形,禁止某镜突然变成真人照片或另一套动漫风。",
+ "seedream_config": {
+ "ref_images": [],
+ "strength": 0.7,
+ "pipeline_mode": "image_text",
+ "character_prompt": "故事主角外形固定:年龄感、发型发色、服装配色与辨识物全片一致,细腻插画五官,非真人照片",
+ "extra_prompt": "竖屏构图,主体偏中下,顶部约1/4留白,电影感光影,画面内无文字",
+ },
+ "seedance_config": {
+ "motion_bias": "缓慢推近或轻拉远",
+ "character_consistency": True,
+ },
+ "audio_config": {"voice_preset": "narrator_calm", "bgm_mood": "叙事氛围"},
+ "subtitle_config": {"font": "SourceHanSans", "position": "top"},
+ "sort_order": 5,
+ "is_active": True,
+ "is_premium": False,
+ },
+]
diff --git a/backend/app/services/voices.py b/backend/app/services/voices.py
new file mode 100644
index 0000000..b69e95d
--- /dev/null
+++ b/backend/app/services/voices.py
@@ -0,0 +1,67 @@
+"""Selectable TTS voice presets (豆包 openspeech + template aliases)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+# id used in API / project.voice_id; speaker is openspeech speaker id
+VOICE_PRESETS: list[dict[str, Any]] = [
+ {
+ "id": "zh_female_cancan_uranus_bigtts",
+ "label": "灿灿 · 女声旁白",
+ "gender": "female",
+ "speaker": "zh_female_cancan_uranus_bigtts",
+ },
+ {
+ "id": "zh_female_tianmeixiaoyuan_uranus_bigtts",
+ "label": "甜美女声 · 故事",
+ "gender": "female",
+ "speaker": "zh_female_tianmeixiaoyuan_uranus_bigtts",
+ },
+ {
+ "id": "zh_female_shuangkuaisisi_uranus_bigtts",
+ "label": "爽快女声 · 都市",
+ "gender": "female",
+ "speaker": "zh_female_shuangkuaisisi_uranus_bigtts",
+ },
+ {
+ "id": "zh_female_vv_uranus_bigtts",
+ "label": "Vivi · 国风女声",
+ "gender": "female",
+ "speaker": "zh_female_vv_uranus_bigtts",
+ },
+ {
+ "id": "zh_male_shaonianzixin_uranus_bigtts",
+ "label": "少年梓辛 · 男声",
+ "gender": "male",
+ "speaker": "zh_male_shaonianzixin_uranus_bigtts",
+ },
+]
+
+# Template audio_config.voice_preset aliases → speaker
+VOICE_ALIASES: dict[str, str] = {
+ "narrator_calm": "zh_female_cancan_uranus_bigtts",
+ "warm_storyteller": "zh_female_tianmeixiaoyuan_uranus_bigtts",
+ "teacher_clear": "zh_male_shaonianzixin_uranus_bigtts",
+ "urban_editorial": "zh_female_shuangkuaisisi_uranus_bigtts",
+ "retro_host": "zh_male_shaonianzixin_uranus_bigtts",
+ "guqin_narrator": "zh_female_vv_uranus_bigtts",
+}
+
+
+def list_voices() -> list[dict[str, Any]]:
+ return list(VOICE_PRESETS)
+
+
+def resolve_speaker(voice_id: str | None, *, template_preset: str | None = None) -> str:
+ """Map UI voice id / template alias to openspeech speaker."""
+ raw = (voice_id or "").strip() or (template_preset or "").strip()
+ if not raw:
+ return "zh_female_cancan_uranus_bigtts"
+ if raw in VOICE_ALIASES:
+ return VOICE_ALIASES[raw]
+ for preset in VOICE_PRESETS:
+ if preset["id"] == raw or preset["speaker"] == raw:
+ return str(preset["speaker"])
+ # Pass-through custom speaker ids
+ return raw
diff --git a/backend/app/workers/__init__.py b/backend/app/workers/__init__.py
new file mode 100644
index 0000000..f091f19
--- /dev/null
+++ b/backend/app/workers/__init__.py
@@ -0,0 +1 @@
+"""Celery worker package."""
diff --git a/backend/app/workers/autoscale.py b/backend/app/workers/autoscale.py
new file mode 100644
index 0000000..3c0bcc2
--- /dev/null
+++ b/backend/app/workers/autoscale.py
@@ -0,0 +1,327 @@
+"""Dynamic Celery worker autoscaler (Windows-friendly solo pool).
+
+Monitors Redis queue depth + unacked tasks, then spawns/kills
+`--pool=solo --concurrency=1` workers within [min, max].
+
+Run:
+ cd backend
+ .\\.venv\\Scripts\\python -m app.workers.autoscale
+"""
+
+from __future__ import annotations
+
+import atexit
+import logging
+import os
+import signal
+import socket
+import subprocess
+import sys
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import redis
+
+from app.config import get_settings, reload_settings
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s [%(levelname)s] autoscale: %(message)s",
+ datefmt="%H:%M:%S",
+)
+logger = logging.getLogger("autoscale")
+
+BACKEND_ROOT = Path(__file__).resolve().parents[2]
+STATE_DIR = BACKEND_ROOT / ".celery_autoscale"
+QUEUE_NAME = "pipeline"
+
+
+@dataclass
+class WorkerProc:
+ name: str
+ index: int
+ process: subprocess.Popen
+ started_at: float = field(default_factory=time.time)
+
+
+class CeleryAutoscaler:
+ def __init__(self) -> None:
+ self.settings = reload_settings()
+ self.min_workers = max(0, int(self.settings.celery_autoscale_min))
+ self.max_workers = max(self.min_workers, int(self.settings.celery_autoscale_max))
+ self.poll_sec = max(2.0, float(self.settings.celery_autoscale_poll_sec))
+ self.scale_down_sec = max(5.0, float(self.settings.celery_autoscale_idle_sec))
+ self.queue = (self.settings.celery_autoscale_queue or QUEUE_NAME).strip() or QUEUE_NAME
+ self.host = socket.gethostname().split(".")[0]
+ self.workers: dict[int, WorkerProc] = {}
+ self._idle_since: float | None = None
+ self._stop = False
+ self._redis = redis.Redis.from_url(
+ self.settings.redis_url,
+ decode_responses=False,
+ socket_connect_timeout=3,
+ socket_timeout=3,
+ )
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
+
+ def _celery_exe(self) -> Path:
+ win = BACKEND_ROOT / ".venv" / "Scripts" / "celery.exe"
+ nix = BACKEND_ROOT / ".venv" / "bin" / "celery"
+ if win.exists():
+ return win
+ if nix.exists():
+ return nix
+ return Path(sys.executable).with_name("celery.exe" if os.name == "nt" else "celery")
+
+ def _worker_name(self, index: int) -> str:
+ return f"auto-{index}@{self.host}"
+
+ def queue_load(self) -> tuple[int, int, int]:
+ """Return (pending, unacked, load)."""
+ pending = int(self._redis.llen(self.queue) or 0)
+ try:
+ unacked = int(self._redis.hlen("unacked") or 0)
+ except Exception: # noqa: BLE001
+ unacked = 0
+ load = pending + unacked
+ return pending, unacked, load
+
+ def desired_count(self, load: int) -> int:
+ if load <= 0:
+ return self.min_workers
+ return max(self.min_workers, min(self.max_workers, load))
+
+ def _spawn(self, index: int) -> WorkerProc:
+ name = self._worker_name(index)
+ celery = str(self._celery_exe())
+ cmd = [
+ celery,
+ "-A",
+ "app.workers.celery_app.celery_app",
+ "worker",
+ "-Q",
+ self.queue,
+ "-l",
+ "info",
+ "--concurrency=1",
+ "--pool=solo",
+ "-n",
+ name,
+ "--without-gossip",
+ "--without-mingle",
+ "--without-heartbeat",
+ ]
+ log_path = STATE_DIR / f"worker-{index}.log"
+ log_f = open(log_path, "a", encoding="utf-8", errors="replace") # noqa: SIM115
+ creationflags = 0
+ if os.name == "nt":
+ creationflags = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
+ proc = subprocess.Popen(
+ cmd,
+ cwd=str(BACKEND_ROOT),
+ stdout=log_f,
+ stderr=subprocess.STDOUT,
+ creationflags=creationflags,
+ env={**os.environ, "PYTHONUNBUFFERED": "1"},
+ )
+ (STATE_DIR / f"worker-{index}.pid").write_text(str(proc.pid), encoding="utf-8")
+ wp = WorkerProc(name=name, index=index, process=proc)
+ self.workers[index] = wp
+ logger.info("scale-up %s pid=%s (workers=%s)", name, proc.pid, len(self.workers))
+ return wp
+
+ def _terminate(self, wp: WorkerProc, *, reason: str) -> None:
+ pid = wp.process.pid
+ logger.info("scale-down %s pid=%s (%s)", wp.name, pid, reason)
+ try:
+ if os.name == "nt":
+ # CTRL_BREAK for process group; fall back to terminate
+ try:
+ wp.process.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]
+ wp.process.wait(timeout=8)
+ except Exception: # noqa: BLE001
+ wp.process.terminate()
+ try:
+ wp.process.wait(timeout=5)
+ except Exception: # noqa: BLE001
+ wp.process.kill()
+ else:
+ wp.process.terminate()
+ try:
+ wp.process.wait(timeout=8)
+ except Exception: # noqa: BLE001
+ wp.process.kill()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("failed stopping %s: %s", wp.name, exc)
+ self.workers.pop(wp.index, None)
+ pid_file = STATE_DIR / f"worker-{wp.index}.pid"
+ if pid_file.exists():
+ pid_file.unlink(missing_ok=True)
+
+ def _reap_dead(self) -> None:
+ dead = [idx for idx, wp in self.workers.items() if wp.process.poll() is not None]
+ for idx in dead:
+ wp = self.workers.pop(idx)
+ logger.warning("worker died %s exit=%s", wp.name, wp.process.returncode)
+
+ def _next_index(self) -> int:
+ used = set(self.workers)
+ for i in range(1, self.max_workers + 8):
+ if i not in used:
+ return i
+ return max(used, default=0) + 1
+
+ def reconcile(self) -> None:
+ self._reap_dead()
+ pending, unacked, load = self.queue_load()
+ desired = self.desired_count(load)
+ alive = len(self.workers)
+
+ if load > 0:
+ self._idle_since = None
+ elif self._idle_since is None:
+ self._idle_since = time.time()
+
+ # Scale up immediately
+ while len(self.workers) < desired:
+ self._spawn(self._next_index())
+
+ # Scale down only after idle cooldown (avoid killing mid-task when queue briefly empty)
+ if desired < len(self.workers):
+ idle_for = (time.time() - self._idle_since) if self._idle_since else 0.0
+ if load == 0 and idle_for >= self.scale_down_sec:
+ extras = sorted(self.workers.values(), key=lambda w: w.started_at, reverse=True)
+ while len(self.workers) > desired and extras:
+ self._terminate(extras.pop(0), reason=f"idle {idle_for:.0f}s")
+ elif load > 0 and alive > desired:
+ # More workers than load but work still present — keep until unfinished
+ pass
+
+ logger.info(
+ "load pending=%s unacked=%s → desired=%s alive=%s",
+ pending,
+ unacked,
+ desired,
+ len(self.workers),
+ )
+
+ def ensure_minimum(self) -> None:
+ while len(self.workers) < self.min_workers:
+ self._spawn(self._next_index())
+
+ def shutdown(self) -> None:
+ self._stop = True
+ for wp in list(sorted(self.workers.values(), key=lambda w: w.index)):
+ self._terminate(wp, reason="shutdown")
+
+ def run_forever(self) -> None:
+ logger.info(
+ "start queue=%s min=%s max=%s poll=%.1fs idle_down=%.1fs redis=%s",
+ self.queue,
+ self.min_workers,
+ self.max_workers,
+ self.poll_sec,
+ self.scale_down_sec,
+ self.settings.redis_url,
+ )
+ # Cold start: drop orphan unacked left by killed Windows workers
+ try:
+ from app.workers.recover import reclaim_unacked, redispatch_stale_projects
+
+ reclaim_unacked(self.settings.redis_url)
+ import asyncio
+
+ asyncio.run(redispatch_stale_projects(older_than_sec=120))
+ except Exception: # noqa: BLE001
+ logger.exception("startup recover failed")
+
+ self.ensure_minimum()
+ loops = 0
+ while not self._stop:
+ try:
+ self.settings = get_settings()
+ # Hot-read bounds each loop (env reload optional)
+ self.min_workers = max(0, int(self.settings.celery_autoscale_min))
+ self.max_workers = max(self.min_workers, int(self.settings.celery_autoscale_max))
+ self.poll_sec = max(2.0, float(self.settings.celery_autoscale_poll_sec))
+ self.scale_down_sec = max(5.0, float(self.settings.celery_autoscale_idle_sec))
+ self.reconcile()
+ loops += 1
+ # Every ~2 min: redispatch projects with no progress
+ if loops % max(1, int(120 / self.poll_sec)) == 0:
+ from app.workers.recover import redispatch_stale_projects
+ import asyncio
+
+ asyncio.run(redispatch_stale_projects())
+ except redis.RedisError as exc:
+ logger.error("redis error: %s", exc)
+ except Exception: # noqa: BLE001
+ logger.exception("reconcile failed")
+ time.sleep(self.poll_sec)
+
+
+def _pid_alive(pid: int) -> bool:
+ if pid <= 0:
+ return False
+ if os.name == "nt":
+ try:
+ import ctypes
+
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+ handle = kernel32.OpenProcess(0x1000, False, pid)
+ if handle:
+ kernel32.CloseHandle(handle)
+ return True
+ return False
+ except Exception: # noqa: BLE001
+ return False
+ try:
+ os.kill(pid, 0)
+ return True
+ except OSError:
+ return False
+
+
+def main() -> None:
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
+ lock_path = STATE_DIR / "autoscale.pid"
+ if lock_path.exists():
+ try:
+ old = int(lock_path.read_text(encoding="utf-8").strip())
+ if _pid_alive(old):
+ logger.error("another autoscale already running pid=%s", old)
+ sys.exit(1)
+ except Exception: # noqa: BLE001
+ pass
+
+ scaler = CeleryAutoscaler()
+ lock_path.write_text(str(os.getpid()), encoding="utf-8")
+
+ def _cleanup() -> None:
+ scaler.shutdown()
+ try:
+ if lock_path.exists() and lock_path.read_text(encoding="utf-8").strip() == str(os.getpid()):
+ lock_path.unlink(missing_ok=True)
+ except Exception: # noqa: BLE001
+ pass
+
+ def _sig(_signum, _frame) -> None: # noqa: ANN001
+ logger.info("signal received, shutting down…")
+ _cleanup()
+ sys.exit(0)
+
+ for sig in (signal.SIGINT, signal.SIGTERM):
+ try:
+ signal.signal(sig, _sig)
+ except Exception: # noqa: BLE001
+ pass
+ atexit.register(_cleanup)
+ try:
+ scaler.run_forever()
+ finally:
+ _cleanup()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py
new file mode 100644
index 0000000..3a54834
--- /dev/null
+++ b/backend/app/workers/celery_app.py
@@ -0,0 +1,37 @@
+from celery import Celery
+
+from app.config import reload_settings
+
+settings = reload_settings()
+
+celery_app = Celery(
+ "framecut",
+ broker=settings.redis_url,
+ backend=settings.redis_url,
+ include=["app.workers.tasks"],
+)
+
+celery_app.conf.update(
+ task_track_started=True,
+ task_serializer="json",
+ accept_content=["json"],
+ result_serializer="json",
+ timezone="Asia/Shanghai",
+ enable_utc=True,
+ worker_prefetch_multiplier=1,
+ # Late ack + kill/hang on Windows leaves Redis "unacked" orphans unless visibility expires
+ task_acks_late=True,
+ task_reject_on_worker_lost=True,
+ task_acks_on_failure_or_timeout=True,
+ task_soft_time_limit=int(settings.celery_task_soft_time_limit),
+ task_time_limit=int(settings.celery_task_time_limit),
+ broker_transport_options={
+ "visibility_timeout": int(settings.celery_visibility_timeout),
+ },
+ worker_cancel_long_running_tasks_on_connection_loss=True,
+ task_routes={
+ "app.workers.tasks.run_pipeline_task": {"queue": "pipeline"},
+ "app.workers.tasks.regen_image_task": {"queue": "pipeline"},
+ "app.workers.tasks.regen_video_task": {"queue": "pipeline"},
+ },
+)
diff --git a/backend/app/workers/recover.py b/backend/app/workers/recover.py
new file mode 100644
index 0000000..20adf5b
--- /dev/null
+++ b/backend/app/workers/recover.py
@@ -0,0 +1,75 @@
+"""Recover orphaned Celery unacked messages and stale RUNNING projects."""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timedelta, timezone
+
+import redis
+from sqlalchemy import select
+
+from app.config import get_settings
+from app.database import AsyncSessionLocal
+from app.models import Project, ProjectStatus
+
+logger = logging.getLogger("autoscale.recover")
+
+_RUNNING = {
+ ProjectStatus.SCRIPTING,
+ ProjectStatus.IMAGING,
+ ProjectStatus.VIDEOING,
+ ProjectStatus.AUDIOING,
+ ProjectStatus.COMPOSING,
+ ProjectStatus.AUDITING,
+}
+
+
+def reclaim_unacked(redis_url: str | None = None) -> int:
+ """Drop Redis unacked hash so late-acked tasks can be redelivered / redispatched.
+
+ Safe when no healthy workers hold live tasks (e.g. autoscale cold start).
+ """
+ settings = get_settings()
+ r = redis.Redis.from_url(redis_url or settings.redis_url, decode_responses=False)
+ n = int(r.hlen("unacked") or 0)
+ if n:
+ r.delete("unacked")
+ r.delete("unacked_mutex")
+ logger.warning("reclaimed %s orphaned unacked celery messages", n)
+ return n
+
+
+async def redispatch_stale_projects(*, older_than_sec: int | None = None) -> list[int]:
+ """Restart pipeline for projects stuck in RUNNING with stale updated_at."""
+ settings = get_settings()
+ stale_sec = older_than_sec if older_than_sec is not None else int(settings.celery_stale_project_sec)
+ cutoff = datetime.now(timezone.utc) - timedelta(seconds=max(60, stale_sec))
+
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(select(Project).where(Project.status.in_(_RUNNING)))
+ projects = list(result.scalars().all())
+
+ stale_ids: list[int] = []
+ for p in projects:
+ updated = p.updated_at
+ if updated is None:
+ stale_ids.append(p.id)
+ continue
+ # SQLite may return naive datetimes
+ if updated.tzinfo is None:
+ updated = updated.replace(tzinfo=timezone.utc)
+ if updated < cutoff:
+ stale_ids.append(p.id)
+
+ if not stale_ids:
+ return []
+
+ from app.services.pipeline import start_pipeline
+
+ for pid in stale_ids:
+ try:
+ tid = start_pipeline(pid)
+ logger.warning("redispatched stale project=%s task=%s", pid, tid)
+ except Exception: # noqa: BLE001
+ logger.exception("failed to redispatch project=%s", pid)
+ return stale_ids
diff --git a/backend/app/workers/tasks.py b/backend/app/workers/tasks.py
new file mode 100644
index 0000000..09e680a
--- /dev/null
+++ b/backend/app/workers/tasks.py
@@ -0,0 +1,89 @@
+"""Celery tasks wrapping async pipeline stages."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+
+from app.workers.celery_app import celery_app
+
+logger = logging.getLogger(__name__)
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+@celery_app.task(
+ name="app.workers.tasks.run_pipeline_task",
+ bind=True,
+ max_retries=1,
+ soft_time_limit=None, # use app conf
+ time_limit=None,
+)
+def run_pipeline_task(self, project_id: int) -> dict:
+ from celery.exceptions import SoftTimeLimitExceeded
+
+ from app.config import reload_settings
+ from app.services.ark import reset_ark
+ from app.services.pipeline import PipelineCancelled, is_cancelled, run_pipeline
+
+ reload_settings()
+ reset_ark()
+ try:
+ _run(run_pipeline(project_id))
+ return {"ok": True, "project_id": project_id}
+ except SoftTimeLimitExceeded:
+ logger.error("pipeline soft time limit project=%s", project_id)
+ try:
+ from app.database import AsyncSessionLocal
+ from app.models import Project, ProjectStatus
+
+ async def _mark_timeout() -> None:
+ async with AsyncSessionLocal() as db:
+ p = await db.get(Project, project_id)
+ if p and p.status not in {ProjectStatus.DONE, ProjectStatus.CANCELLED}:
+ p.status = ProjectStatus.FAILED
+ p.error_msg = "任务超时(可能卡在出图/合成),请重新生成"
+ await db.commit()
+
+ _run(_mark_timeout())
+ except Exception: # noqa: BLE001
+ logger.exception("failed to mark timeout project=%s", project_id)
+ return {"ok": False, "project_id": project_id, "error": "task_timeout"}
+ except PipelineCancelled:
+ return {"ok": False, "cancelled": True, "project_id": project_id}
+ except Exception as exc: # noqa: BLE001
+ if is_cancelled(project_id):
+ return {"ok": False, "cancelled": True, "project_id": project_id}
+ msg = str(exc)
+ # Permanent policy / client errors — do not retry
+ if any(
+ x in msg
+ for x in (
+ "PolicyViolation",
+ "SensitiveContent",
+ "InputTextSensitive",
+ "400",
+ )
+ ) and "Seedream" in msg:
+ logger.error("permanent seedream failure project=%s: %s", project_id, msg[:400])
+ return {"ok": False, "project_id": project_id, "error": msg[:500]}
+ logger.exception("celery pipeline failed project=%s", project_id)
+ raise self.retry(exc=exc, countdown=10)
+
+
+@celery_app.task(name="app.workers.tasks.regen_image_task")
+def regen_image_task(project_id: int, shot_id: int) -> dict:
+ from app.services.pipeline import regen_shot_image
+
+ _run(regen_shot_image(project_id, shot_id))
+ return {"ok": True}
+
+
+@celery_app.task(name="app.workers.tasks.regen_video_task")
+def regen_video_task(project_id: int, shot_id: int) -> dict:
+ from app.services.pipeline import regen_shot_video
+
+ _run(regen_shot_video(project_id, shot_id))
+ return {"ok": True}
diff --git a/backend/requirements.txt b/backend/requirements.txt
new file mode 100644
index 0000000..bec8e09
--- /dev/null
+++ b/backend/requirements.txt
@@ -0,0 +1,18 @@
+fastapi==0.115.12
+uvicorn[standard]==0.34.2
+sqlalchemy==2.0.40
+aiosqlite==0.21.0
+pydantic==2.11.3
+pydantic-settings==2.9.1
+python-jose[cryptography]==3.4.0
+passlib[bcrypt]==1.7.4
+bcrypt==4.3.0
+python-multipart==0.0.20
+celery==5.5.1
+redis==5.2.1
+httpx==0.28.1
+sse-starlette==2.2.1
+python-dotenv==1.1.0
+email-validator==2.2.0
+edge-tts==7.2.3
+# Optional: pip install "volcengine-python-sdk[ark]" if you prefer official SDK
diff --git a/backend/scripts/start_autoscale.ps1 b/backend/scripts/start_autoscale.ps1
new file mode 100644
index 0000000..d2a049b
--- /dev/null
+++ b/backend/scripts/start_autoscale.ps1
@@ -0,0 +1,26 @@
+# Start Celery autoscaler (dynamic worker pool).
+# Usage: from repo powershell -File backend/scripts/start_autoscale.ps1
+
+$ErrorActionPreference = "Stop"
+$Backend = Split-Path -Parent $PSScriptRoot
+Set-Location $Backend
+
+Get-CimInstance Win32_Process |
+ Where-Object {
+ $_.CommandLine -and (
+ $_.CommandLine -match 'celery.*celery_app.*worker' -or
+ $_.CommandLine -match 'app\.workers\.autoscale'
+ )
+ } |
+ ForEach-Object {
+ Write-Host "stop pid=$($_.ProcessId)"
+ Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
+ }
+
+Start-Sleep -Seconds 2
+$py = Join-Path $Backend ".venv\Scripts\python.exe"
+if (-not (Test-Path $py)) { throw "venv python not found: $py" }
+
+Write-Host "starting autoscale..."
+Start-Process -WindowStyle Hidden -FilePath $py -ArgumentList "-m","app.workers.autoscale" -WorkingDirectory $Backend
+Write-Host "ok - logs under .celery_autoscale/worker-*.log"
diff --git a/backend/static/templates/chalk_whiteboard.svg b/backend/static/templates/chalk_whiteboard.svg
new file mode 100644
index 0000000..79571f3
--- /dev/null
+++ b/backend/static/templates/chalk_whiteboard.svg
@@ -0,0 +1,7 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='640' height='360' viewBox='0 0 640 360'>
+ <rect width='640' height='360' fill='#1a2332'/>
+ <circle cx='480' cy='120' r='90' fill='#e8eef5' opacity='0.25'/>
+ <rect x='48' y='48' width='220' height='140' rx='8' fill='#e8eef5' opacity='0.85'/>
+ <text x='48' y='280' font-family='Georgia, serif' font-size='42' fill='#e8eef5'>Chalk</text>
+ <text x='48' y='320' font-family='sans-serif' font-size='18' fill='#e8eef5' opacity='0.7'>FrameCut Template</text>
+</svg>
diff --git a/backend/static/templates/ink_guofeng.svg b/backend/static/templates/ink_guofeng.svg
new file mode 100644
index 0000000..7dfd4e9
--- /dev/null
+++ b/backend/static/templates/ink_guofeng.svg
@@ -0,0 +1,7 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='640' height='360' viewBox='0 0 640 360'>
+ <rect width='640' height='360' fill='#f3efe6'/>
+ <circle cx='480' cy='120' r='90' fill='#2c2c2c' opacity='0.25'/>
+ <rect x='48' y='48' width='220' height='140' rx='8' fill='#2c2c2c' opacity='0.85'/>
+ <text x='48' y='280' font-family='Georgia, serif' font-size='42' fill='#2c2c2c'>Ink</text>
+ <text x='48' y='320' font-family='sans-serif' font-size='18' fill='#2c2c2c' opacity='0.7'>FrameCut Template</text>
+</svg>
diff --git a/backend/static/templates/kids_flat.svg b/backend/static/templates/kids_flat.svg
new file mode 100644
index 0000000..f334874
--- /dev/null
+++ b/backend/static/templates/kids_flat.svg
@@ -0,0 +1,7 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='640' height='360' viewBox='0 0 640 360'>
+ <rect width='640' height='360' fill='#f7e8d0'/>
+ <circle cx='480' cy='120' r='90' fill='#e07a5f' opacity='0.25'/>
+ <rect x='48' y='48' width='220' height='140' rx='8' fill='#e07a5f' opacity='0.85'/>
+ <text x='48' y='280' font-family='Georgia, serif' font-size='42' fill='#e07a5f'>Kids</text>
+ <text x='48' y='320' font-family='sans-serif' font-size='18' fill='#e07a5f' opacity='0.7'>FrameCut Template</text>
+</svg>
diff --git a/backend/static/templates/magazine_collage.svg b/backend/static/templates/magazine_collage.svg
new file mode 100644
index 0000000..04f4047
--- /dev/null
+++ b/backend/static/templates/magazine_collage.svg
@@ -0,0 +1,7 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='640' height='360' viewBox='0 0 640 360'>
+ <rect width='640' height='360' fill='#1f1a17'/>
+ <circle cx='480' cy='120' r='90' fill='#f0c75e' opacity='0.25'/>
+ <rect x='48' y='48' width='220' height='140' rx='8' fill='#f0c75e' opacity='0.85'/>
+ <text x='48' y='280' font-family='Georgia, serif' font-size='42' fill='#f0c75e'>Collage</text>
+ <text x='48' y='320' font-family='sans-serif' font-size='18' fill='#f0c75e' opacity='0.7'>FrameCut Template</text>
+</svg>
diff --git a/backend/static/templates/pixel_retro.svg b/backend/static/templates/pixel_retro.svg
new file mode 100644
index 0000000..9df2753
--- /dev/null
+++ b/backend/static/templates/pixel_retro.svg
@@ -0,0 +1,7 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='640' height='360' viewBox='0 0 640 360'>
+ <rect width='640' height='360' fill='#0f1a12'/>
+ <circle cx='480' cy='120' r='90' fill='#5dffa8' opacity='0.25'/>
+ <rect x='48' y='48' width='220' height='140' rx='8' fill='#5dffa8' opacity='0.85'/>
+ <text x='48' y='280' font-family='Georgia, serif' font-size='42' fill='#5dffa8'>Pixel</text>
+ <text x='48' y='320' font-family='sans-serif' font-size='18' fill='#5dffa8' opacity='0.7'>FrameCut Template</text>
+</svg>
diff --git a/backend/static/templates/vox_papercut.svg b/backend/static/templates/vox_papercut.svg
new file mode 100644
index 0000000..4e15b61
--- /dev/null
+++ b/backend/static/templates/vox_papercut.svg
@@ -0,0 +1,7 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='640' height='360' viewBox='0 0 640 360'>
+ <rect width='640' height='360' fill='#2a2a2a'/>
+ <circle cx='480' cy='120' r='90' fill='#c4b5a0' opacity='0.25'/>
+ <rect x='48' y='48' width='220' height='140' rx='8' fill='#c4b5a0' opacity='0.85'/>
+ <text x='48' y='280' font-family='Georgia, serif' font-size='42' fill='#c4b5a0'>Vox</text>
+ <text x='48' y='320' font-family='sans-serif' font-size='18' fill='#c4b5a0' opacity='0.7'>FrameCut Template</text>
+</svg>
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
new file mode 100644
index 0000000..8d844e8
--- /dev/null
+++ b/deploy/docker-compose.yml
@@ -0,0 +1,43 @@
+services:
+ redis:
+ image: redis:7-alpine
+ ports:
+ - "6379:6379"
+
+ api:
+ build: ./backend
+ ports:
+ - "8000:8000"
+ env_file:
+ - ../backend/.env
+ 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
+ volumes:
+ - ../backend:/app
+ - api-data:/app/data
+ depends_on:
+ - redis
+ command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
+
+ 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
+ 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
+
+volumes:
+ api-data:
diff --git a/frontend/.gitignore b/frontend/.gitignore
new file mode 100644
index 0000000..875727f
--- /dev/null
+++ b/frontend/.gitignore
@@ -0,0 +1,4 @@
+node_modules/
+dist/
+.env.local
+*.local
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json
new file mode 100644
index 0000000..6fa991d
--- /dev/null
+++ b/frontend/.oxlintrc.json
@@ -0,0 +1,8 @@
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "plugins": ["react", "typescript", "oxc"],
+ "rules": {
+ "react/rules-of-hooks": "error",
+ "react/only-export-components": ["warn", { "allowConstantExport": true }]
+ }
+}
diff --git a/frontend/README.md b/frontend/README.md
new file mode 100644
index 0000000..d6af7e3
--- /dev/null
+++ b/frontend/README.md
@@ -0,0 +1,32 @@
+# React + TypeScript + Vite
+
+This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
+
+Currently, two official plugins are available:
+
+- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
+- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
+
+## React Compiler
+
+The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
+
+## Expanding the Oxlint configuration
+
+If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
+
+```json
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "plugins": ["react", "typescript", "oxc"],
+ "options": {
+ "typeAware": true
+ },
+ "rules": {
+ "react/rules-of-hooks": "error",
+ "react/only-export-components": ["warn", { "allowConstantExport": true }]
+ }
+}
+```
+
+See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
diff --git a/frontend/index.html b/frontend/index.html
new file mode 100644
index 0000000..e1a05bb
--- /dev/null
+++ b/frontend/index.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="UTF-8" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>纸戏 FrameCut</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&family=Syne:wght@500;700&family=ZCOOL+XiaoWei&display=swap"
+ rel="stylesheet"
+ />
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
new file mode 100644
index 0000000..b89ae97
--- /dev/null
+++ b/frontend/package-lock.json
@@ -0,0 +1,1385 @@
+{
+ "name": "frontend",
+ "version": "0.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "frontend",
+ "version": "0.0.0",
+ "dependencies": {
+ "react": "^19.2.8",
+ "react-dom": "^19.2.8",
+ "react-router-dom": "^7.18.2"
+ },
+ "devDependencies": {
+ "@types/node": "^24.13.3",
+ "@types/react": "^19.2.17",
+ "@types/react-dom": "^19.2.3",
+ "@vitejs/plugin-react": "^6.0.4",
+ "oxlint": "^1.75.0",
+ "typescript": "~6.0.2",
+ "vite": "^8.2.0"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.142.0",
+ "resolved": "https://registry.npmmirror.com/@oxc-project/types/-/types-0.142.0.tgz",
+ "integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm-eabi": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.77.0.tgz",
+ "integrity": "sha512-E06sKWS6PiI6HRxS1wyQg22HvApt01hI7fV+T3wUk3OSbaaP4a3hYGY/MIQDmASqCiRjBdpRQYkgMkqH82cWmQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm64": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm64/-/binding-android-arm64-1.77.0.tgz",
+ "integrity": "sha512-NvsKz0KZxTp9cYWPLf+FXaSZwB3oO3peAjtukpOMBgse2vhQSoIIVqeO1yR0lEo/UcdZIDL18uq+kL0LzQ0ytA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-arm64": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.77.0.tgz",
+ "integrity": "sha512-bgjTn6nW4bQCFBvSvuHCpDD+sONvmpo4lGI4PxzMt1quBA+xYxhczk6RiCn3GZ9gY8uhaBbwhj9MdKGfu6T9DA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-x64": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.77.0.tgz",
+ "integrity": "sha512-aotaIttH1R6j1Rwhx0M0htgeZyGtVQqYNTVEYMN/UcgHPquGA6kmk9OyuDc3a2GKUQBC+3C3GVQCcrRPMYqAFA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-freebsd-x64": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.77.0.tgz",
+ "integrity": "sha512-nNx/wta7ksRAdYvq+l4AWjXkLxEXHALhENxjj2cYbQAIR4ybaA5L+hCbE63HOmft5czQ6ks+hb8vmEAnn7YGPg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-gnueabihf": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.77.0.tgz",
+ "integrity": "sha512-tMLLjM7xXtzXisVCzkOTXNCy9bZVId2wteNwjohlFDR/jY6WagpEDA1c1wu4xRc20Hojaxj+V6DSR7gbKxijWA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-musleabihf": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.77.0.tgz",
+ "integrity": "sha512-MiAFDFaqR0tmHTAyo0YDcZ5hyLREdYw/RQhc2R3cbT+8O3tB+zqPM2th9TTQ+Uo3jn/embS+DO+HyX9ztCPkOQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-gnu": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.77.0.tgz",
+ "integrity": "sha512-/xqQ3B16i1T4cyt/9Mn+4CpzhUXoBXp7kVpIwzOXNFLj5JmK1bIjsbSnX296Gg8A/o7oDtKWikFgBx0SLwztkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-musl": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.77.0.tgz",
+ "integrity": "sha512-LSbwuRKiNCenPDcbARqAZ5RfBy7gmj7vOvfJRLeCDU3gFtSxWbhv/+VTlaUqzUhNj1gFLHB8h7ALnxa/Az6z6g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-ppc64-gnu": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.77.0.tgz",
+ "integrity": "sha512-QWdcH31mXEUe5Nq1s0CfCpceaKjIo9uZtwDjAuL681g1axf+5x8xrg/eXWaw//4NCxYZ4V4e5Hu5tvdR+pTBlg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-gnu": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.77.0.tgz",
+ "integrity": "sha512-GnOfYgJxbcElOiPZaDFDl406ONddwvOWk2jvAAAEjwAl4GofNoHF+/HHUIBYa6bFCArlcGPi0XjC4cU1pkgF/Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-musl": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.77.0.tgz",
+ "integrity": "sha512-AyEMTUCf0xY+hHF+IxqXFQIX0yQOIR8ykpY0lJNOw9xYqOzUX8dyZfRvlG0RfXwuQn2eonf/8NrMmDSZJjdqsA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-s390x-gnu": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.77.0.tgz",
+ "integrity": "sha512-sPLzEcNvxd/oyVQ5oZo92CiHkFkpBeRop13E/P3TPY+hZfXHKCOWKI70TE2RYwMKFJDc20EMjH16L7NZICtKTw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-gnu": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.77.0.tgz",
+ "integrity": "sha512-1Oh2ssH2L7lwyvkdSqaMUfsGfwU2Wfvew+obBUYjRVqhpBcUpwnsPSEr1IzVi9XqkuY10geiLsNKecqaZC34Dw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-musl": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.77.0.tgz",
+ "integrity": "sha512-0j/2wRgNGO+Qj/M1uu/p57h/hFTTWWcfie0ufkbabeus2s5+/QqkCflnMOwLLN5m2GsNeWp4xdl4cPa4n7QCOQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-openharmony-arm64": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.77.0.tgz",
+ "integrity": "sha512-BJ/j54qS0usEnyDkLYURMj2iiD9h5Cyy+ppzeMSXBGRXaGRNWnj1Mw14NqWMR5E/PzdgB30OOCCzLzbRoduafw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-arm64-msvc": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.77.0.tgz",
+ "integrity": "sha512-Yh8w+g2Lpx7StrvtYkoz9JJvXjB9wxgFChFNb85nrXm/wj/XTwGWS1hve9+900HL7llrntYB3YP+y32E3tRqzA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-ia32-msvc": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.77.0.tgz",
+ "integrity": "sha512-zja5b7+6a7UsRFgAQSrnax5vrzliEyNPLCjfXONu/vTWswaIVZGFajJZptaeRvPE4LghtFdAzVFlexTm7MVTGA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-x64-msvc": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.77.0.tgz",
+ "integrity": "sha512-+teyvPDZ2RjUvo+SuCqS/UhaJl1QtdW5fWT5NJTV61V5MIuIS90Db9LixmtEGvXixyttiK62P96MSu3UlpviBw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.2.tgz",
+ "integrity": "sha512-l7x215OGvo1s52JWmR8U/DAVzEDWBCIbTm28aeJV/WDTSHgcKXaZTuBT0hJMs5NggilfJTW3clZVvd24yfKJxA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.2.tgz",
+ "integrity": "sha512-9u9Xv6c1AJZT0FfwH5vrMG5Jjcwhc1MlyrPu0XfTqkzsmqfks2M6W/o5XwAJgVVN/jHpqqngC1WevHKKTIUtIA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.2.tgz",
+ "integrity": "sha512-9W1mbGZAfW3oqd85bhBkmpyHCCzL1TeG/zFFP3vg7b0rlly8cxOcre5nXwz+LHazCwac2MNWgPdPCHndABjpWQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.2.tgz",
+ "integrity": "sha512-0p1lhiCSCyaerFwtrdZQUx7NqGk6LQnaRKWX7tFQqwQgvX0rjM15cIkm3pax1UpEakK14C4mOxx/jSqCBdBRqQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.2.tgz",
+ "integrity": "sha512-e+cOJXrJ2L3zx6YzqPg+f6Wbk3V1cKB8bOhbaYdVYN3DdquzNdRAmrbETz1qnt5yp/c7JNlNjmITiA2cVneQ7w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.2.tgz",
+ "integrity": "sha512-JsSMsj6sNat/MuhG5fnBD7QgbtpHKVe30x5/bAVirDHdhoQRXJkF6xc0Jqk8O4fiCUQAzMOoH9wZi3m60c8wtg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.2.tgz",
+ "integrity": "sha512-B5G/zJdHaoJn9vD50eGHWkiWfmq8Uhi3IiLPJTzmZTrAalk1bztUikSXo0qga18ibE0IXboyeMUnhPjhAJ45wQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.2.tgz",
+ "integrity": "sha512-6mC/awzKka8W6EoekjegpfGkjz8jXWDX63pqu/HYVpyKtZfu65Jsh4QAH3Kej3CAv/c1oGX7psTmFEbr0mDxLA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.2.tgz",
+ "integrity": "sha512-412MX9fJLdA1IK28EZnc8jYv2HRTleOZgfLQumJ5zy7OeJLZlg/CETwFaXjNmGVxG51cFHpKLqb5LKvBC+HsHA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.2.tgz",
+ "integrity": "sha512-Q/+HI/ToJafZ1iCqGgVQXUEkIjufHCTF0gBQ2a5o3cg7GJ2h0qyq3nvvSmU+bGda2/7ygXpTY4TM6gO9OhQ0ZA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.2.tgz",
+ "integrity": "sha512-ZKp/w41n6wCvxzxQHtQSbuphfX3Y4cCvbjkKHusrLx4lh+JWLTU7StSltO/DKARISzbj368d+qUaCjI8K2wzXw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.2.tgz",
+ "integrity": "sha512-pxE6xD4KS3eAROkKK5yrhB9/3+vhlhVGMvlQLbdpzrBGDbKrnzx3RLwPaHvasLo6jgaiBLn7e04Df9C4tYhjmA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.2.tgz",
+ "integrity": "sha512-4MqEue5re+xIZzAWsB8sj0P1kqZySWqIuN4t6QaIO/YA6SFwySOLruvWQFzfmqk8LBK2P30KCSJwf6mJCZZ5/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.2.tgz",
+ "integrity": "sha512-NweNxxD0Nf9t8v7kodun45Ijp3EIwYY+uydPP6qBEYvfBqhIjN6dZMzlQja3tqX/aLs3F3Uz+AxDpKgRhpOZQg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "24.13.3",
+ "resolved": "https://registry.npmmirror.com/@types/node/-/node-24.13.3.tgz",
+ "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.18.0"
+ }
+ },
+ "node_modules/@types/react": {
+ "version": "19.2.18",
+ "resolved": "https://registry.npmmirror.com/@types/react/-/react-19.2.18.tgz",
+ "integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "csstype": "^3.2.2"
+ }
+ },
+ "node_modules/@types/react-dom": {
+ "version": "19.2.4",
+ "resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-19.2.4.tgz",
+ "integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^19.2.0"
+ }
+ },
+ "node_modules/@vitejs/plugin-react": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-6.0.5.tgz",
+ "integrity": "sha512-BOVzne/NL162sMdResB25mUv+vWMF5NoAjNf09TeGlE7ZpszZWSD3winycicLJw72yeVsoCn/2kOhEuCvEShMA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rolldown/pluginutils": "^1.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "peerDependencies": {
+ "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
+ "babel-plugin-react-compiler": "^1.0.0",
+ "vite": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@rolldown/plugin-babel": {
+ "optional": true
+ },
+ "babel-plugin-react-compiler": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/cookie": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/cookie/-/cookie-1.1.1.tgz",
+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.17",
+ "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.17.tgz",
+ "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/oxlint": {
+ "version": "1.77.0",
+ "resolved": "https://registry.npmmirror.com/oxlint/-/oxlint-1.77.0.tgz",
+ "integrity": "sha512-qnGh8XJHaQ0dprrDXNQZgS0FgjI6v+V3+X8DwmaV++5Aamy6jGKfDdQ1TUvhUxtmKFAbEf4/WeO5QZX+5WSngg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "oxlint": "bin/oxlint"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxlint/binding-android-arm-eabi": "1.77.0",
+ "@oxlint/binding-android-arm64": "1.77.0",
+ "@oxlint/binding-darwin-arm64": "1.77.0",
+ "@oxlint/binding-darwin-x64": "1.77.0",
+ "@oxlint/binding-freebsd-x64": "1.77.0",
+ "@oxlint/binding-linux-arm-gnueabihf": "1.77.0",
+ "@oxlint/binding-linux-arm-musleabihf": "1.77.0",
+ "@oxlint/binding-linux-arm64-gnu": "1.77.0",
+ "@oxlint/binding-linux-arm64-musl": "1.77.0",
+ "@oxlint/binding-linux-ppc64-gnu": "1.77.0",
+ "@oxlint/binding-linux-riscv64-gnu": "1.77.0",
+ "@oxlint/binding-linux-riscv64-musl": "1.77.0",
+ "@oxlint/binding-linux-s390x-gnu": "1.77.0",
+ "@oxlint/binding-linux-x64-gnu": "1.77.0",
+ "@oxlint/binding-linux-x64-musl": "1.77.0",
+ "@oxlint/binding-openharmony-arm64": "1.77.0",
+ "@oxlint/binding-win32-arm64-msvc": "1.77.0",
+ "@oxlint/binding-win32-ia32-msvc": "1.77.0",
+ "@oxlint/binding-win32-x64-msvc": "1.77.0"
+ },
+ "peerDependencies": {
+ "oxlint-tsgolint": ">=7.0.2001",
+ "vite-plus": "*"
+ },
+ "peerDependenciesMeta": {
+ "oxlint-tsgolint": {
+ "optional": true
+ },
+ "vite-plus": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz",
+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.25",
+ "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.25.tgz",
+ "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.16",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/react": {
+ "version": "19.2.8",
+ "resolved": "https://registry.npmmirror.com/react/-/react-19.2.8.tgz",
+ "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.2.8",
+ "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-19.2.8.tgz",
+ "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.27.0"
+ },
+ "peerDependencies": {
+ "react": "^19.2.8"
+ }
+ },
+ "node_modules/react-router": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmmirror.com/react-router/-/react-router-7.18.2.tgz",
+ "integrity": "sha512-aUVMjFm3GAPTTZL7oYr5E7ETiqfQCHRLH+B+5afnICvf0r7kkK4eR6SMuwbSTJw/7t+12khT/Kahij49fqOCIg==",
+ "license": "MIT",
+ "dependencies": {
+ "cookie": "^1.0.1",
+ "set-cookie-parser": "^2.6.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "react-dom": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/react-router-dom": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmmirror.com/react-router-dom/-/react-router-dom-7.18.2.tgz",
+ "integrity": "sha512-AIKJ/jgGlFb3EbfCXk5Gzshiwt+l3mqbCrNjmEWMMjqQxNJ3svBa6bgzFyCC2Sw3RA0VWF1kg3uQf2OFhxb8hw==",
+ "license": "MIT",
+ "dependencies": {
+ "react-router": "7.18.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "react-dom": ">=18"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.2.tgz",
+ "integrity": "sha512-opwpo1tQBAcpSUJDt94B7hhLNGOKjCdE//XXjeLrnx9b83bjnw45tXdg1b09yEw/VLFBJGZpwRULMmOZo7ol+A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.142.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm64": "1.2.2",
+ "@rolldown/binding-darwin-arm64": "1.2.2",
+ "@rolldown/binding-darwin-x64": "1.2.2",
+ "@rolldown/binding-freebsd-x64": "1.2.2",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.2",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.2",
+ "@rolldown/binding-linux-arm64-musl": "1.2.2",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.2",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.2",
+ "@rolldown/binding-linux-x64-gnu": "1.2.2",
+ "@rolldown/binding-linux-x64-musl": "1.2.2",
+ "@rolldown/binding-openharmony-arm64": "1.2.2",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.2",
+ "@rolldown/binding-win32-x64-msvc": "1.2.2"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.27.0",
+ "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.27.0.tgz",
+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
+ "license": "MIT"
+ },
+ "node_modules/set-cookie-parser": {
+ "version": "2.7.2",
+ "resolved": "https://registry.npmmirror.com/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
+ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
+ "license": "MIT"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmmirror.com/typescript/-/typescript-6.0.3.tgz",
+ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.18.2.tgz",
+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmmirror.com/vite/-/vite-8.2.0.tgz",
+ "integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.5",
+ "postcss": "^8.5.23",
+ "rolldown": "~1.2.0",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.4.0",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/frontend/package.json b/frontend/package.json
new file mode 100644
index 0000000..21f1141
--- /dev/null
+++ b/frontend/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "frontend",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "tsc -b && vite build",
+ "lint": "oxlint",
+ "preview": "vite preview"
+ },
+ "dependencies": {
+ "react": "^19.2.8",
+ "react-dom": "^19.2.8",
+ "react-router-dom": "^7.18.2"
+ },
+ "devDependencies": {
+ "@types/node": "^24.13.3",
+ "@types/react": "^19.2.17",
+ "@types/react-dom": "^19.2.3",
+ "@vitejs/plugin-react": "^6.0.4",
+ "oxlint": "^1.75.0",
+ "typescript": "~6.0.2",
+ "vite": "^8.2.0"
+ }
+}
diff --git a/frontend/public/favicon.svg b/frontend/public/favicon.svg
new file mode 100644
index 0000000..6893eb1
--- /dev/null
+++ b/frontend/public/favicon.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-49.64" y="2.03" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-45.045" y="20.029" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-43.513" y="21.178" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="15.756" y="-17.901" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="23.548" y="2.284" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="23.548" y="2.284" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-27.636" y="-22.853" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="20.116" y="-38.415" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="24.641" y="-11.323" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-29.286" y="6.009" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-29.286" y="6.009" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="8.244" y="-2.416" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="18.713" y="10.588" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="4.596"/></filter></defs></svg>
\ No newline at end of file
diff --git a/frontend/public/icons.svg b/frontend/public/icons.svg
new file mode 100644
index 0000000..e952219
--- /dev/null
+++ b/frontend/public/icons.svg
@@ -0,0 +1,24 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+ <symbol id="bluesky-icon" viewBox="0 0 16 17">
+ <g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
+ <defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
+ </symbol>
+ <symbol id="discord-icon" viewBox="0 0 20 19">
+ <path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
+ </symbol>
+ <symbol id="documentation-icon" viewBox="0 0 21 20">
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
+ </symbol>
+ <symbol id="github-icon" viewBox="0 0 19 19">
+ <path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
+ </symbol>
+ <symbol id="social-icon" viewBox="0 0 20 20">
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
+ </symbol>
+ <symbol id="x-icon" viewBox="0 0 19 19">
+ <path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
+ </symbol>
+</svg>
diff --git a/frontend/src/App.css b/frontend/src/App.css
new file mode 100644
index 0000000..150b386
--- /dev/null
+++ b/frontend/src/App.css
@@ -0,0 +1,752 @@
+.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 {
+ font-family: 'ZCOOL XiaoWei', 'Noto Serif SC', serif;
+ font-size: 1.45rem;
+ letter-spacing: 0.04em;
+}
+
+.brand-mark span {
+ margin-left: 0.35rem;
+ font-family: 'Syne', 'Noto Sans SC', sans-serif;
+ font-size: 0.78rem;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: var(--muted);
+}
+
+.hero-band {
+ padding: 3.5rem 0 2.5rem;
+ border-bottom: 1px solid var(--line);
+ margin-bottom: 2.5rem;
+}
+
+.eyebrow {
+ color: var(--crimson);
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ font-size: 0.75rem;
+ margin: 0 0 0.75rem;
+}
+
+.brand-hero {
+ font-family: 'ZCOOL XiaoWei', 'Noto Serif SC', serif;
+ font-size: clamp(3.5rem, 10vw, 6.5rem);
+ line-height: 0.95;
+ margin: 0 0 0.75rem;
+ letter-spacing: 0.08em;
+}
+
+.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.ghost {
+ background: transparent;
+}
+
+.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: 'ZCOOL XiaoWei', serif;
+ font-size: 1.8rem;
+ margin: 0 0 0.35rem;
+}
+
+.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, 252, 246, 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(180, 35, 24, 0.35);
+}
+
+.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(--moss);
+}
+
+.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;
+}
+
+.auth-shell {
+ min-height: 100vh;
+ display: grid;
+ grid-template-columns: 1.1fr 0.9fr;
+}
+
+.auth-panel {
+ padding: 3rem 2.5rem;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: 0.75rem;
+}
+
+.auth-panel h1 {
+ font-family: 'ZCOOL XiaoWei', serif;
+ font-size: 2.4rem;
+ margin: 0.5rem 0 0;
+}
+
+.auth-visual {
+ position: relative;
+ overflow: hidden;
+ background: #1c1916;
+}
+
+.ink-wash {
+ position: absolute;
+ inset: -20%;
+ background:
+ radial-gradient(circle at 30% 40%, rgba(180, 35, 24, 0.45), transparent 40%),
+ radial-gradient(circle at 70% 60%, rgba(242, 235, 224, 0.2), transparent 35%),
+ repeating-linear-gradient(
+ -12deg,
+ transparent,
+ transparent 18px,
+ rgba(242, 235, 224, 0.04) 18px,
+ rgba(242, 235, 224, 0.04) 19px
+ );
+ animation: drift 14s ease-in-out infinite alternate;
+}
+
+@keyframes drift {
+ from {
+ transform: translate3d(-2%, -1%, 0) scale(1.02);
+ }
+ to {
+ transform: translate3d(2%, 2%, 0) scale(1.08);
+ }
+}
+
+.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, 252, 246, 0.9);
+ 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, 252, 246, 0.78);
+ border: 1px solid var(--line);
+ box-shadow: var(--shadow);
+}
+
+.studio-input,
+.studio-main {
+ padding: 1.25rem;
+}
+
+.studio-input h1 {
+ font-family: 'ZCOOL XiaoWei', serif;
+ font-size: 1.6rem;
+ margin: 0 0 1rem;
+}
+
+.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(--moss), var(--crimson));
+ 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);
+ 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: 'ZCOOL XiaoWei', 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, 252, 246, 0.78);
+ box-shadow: var(--shadow);
+ overflow: hidden;
+ transition: transform 0.2s ease, border-color 0.2s ease;
+}
+
+.history-card.selected {
+ border-color: rgba(180, 35, 24, 0.45);
+ background: rgba(255, 248, 240, 0.95);
+}
+
+.history-card:hover {
+ transform: translateY(-2px);
+ border-color: rgba(180, 35, 24, 0.35);
+}
+
+.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: #b42318;
+ cursor: pointer;
+}
+
+.history-select input:disabled {
+ cursor: not-allowed;
+ opacity: 0.35;
+}
+
+.history-cover {
+ border: 0;
+ 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 {
+ 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 (max-width: 900px) {
+ .auth-shell {
+ grid-template-columns: 1fr;
+ }
+
+ .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;
+ }
+
+ .history-body {
+ grid-column: 2;
+ }
+}
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
new file mode 100644
index 0000000..20bb399
--- /dev/null
+++ b/frontend/src/App.tsx
@@ -0,0 +1,20 @@
+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 StudioPage from './pages/StudioPage'
+import './App.css'
+
+export default function App() {
+ return (
+ <BrowserRouter>
+ <Routes>
+ <Route path="/" element={<HomePage />} />
+ <Route path="/auth" element={<AuthPage />} />
+ <Route path="/studio" element={<StudioPage />} />
+ <Route path="/history" element={<HistoryPage />} />
+ <Route path="*" element={<Navigate to="/" replace />} />
+ </Routes>
+ </BrowserRouter>
+ )
+}
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
new file mode 100644
index 0000000..3d5587c
--- /dev/null
+++ b/frontend/src/api.ts
@@ -0,0 +1,317 @@
+function defaultApiBase() {
+ if (typeof window !== 'undefined' && window.location?.hostname) {
+ const { protocol, hostname } = window.location
+ // Same host as Vite; API listens on 8000 for LAN + local
+ return `${protocol}//${hostname}:8000`
+ }
+ return 'http://127.0.0.1:8000'
+}
+
+const API_BASE = import.meta.env.VITE_API_BASE || defaultApiBase()
+
+function authHeaders(): HeadersInit {
+ const token = localStorage.getItem('token')
+ return token
+ ? { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
+ : { 'Content-Type': 'application/json' }
+}
+
+async function request<T>(path: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(`${API_BASE}${path}`, {
+ ...init,
+ headers: { ...authHeaders(), ...(init?.headers || {}) },
+ })
+ 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()
+}
+
+export type PipelineMode = 'full' | 'image_text'
+
+export type Template = {
+ id: string
+ name: string
+ description: string
+ category: string[]
+ preview_cover: string
+ default_ratio: string
+ shot_duration_min: number
+ shot_duration_max: number
+ is_premium: boolean
+ sort_order: number
+ style_prefix?: string
+ negative_prompt?: string
+ llm_system_addon?: string
+ seedream_config?: {
+ ref_images?: string[]
+ strength?: number
+ pipeline_mode?: PipelineMode
+ character_prompt?: string
+ extra_prompt?: string
+ }
+ audio_config?: {
+ voice_preset?: string
+ bgm_mood?: string
+ }
+}
+
+/** Template voice_preset alias → openspeech speaker id */
+export const VOICE_PRESET_ALIASES: Record<string, string> = {
+ narrator_calm: 'zh_female_cancan_uranus_bigtts',
+ warm_storyteller: 'zh_female_tianmeixiaoyuan_uranus_bigtts',
+ teacher_clear: 'zh_male_shaonianzixin_uranus_bigtts',
+ urban_editorial: 'zh_female_shuangkuaisisi_uranus_bigtts',
+ retro_host: 'zh_male_shaonianzixin_uranus_bigtts',
+ guqin_narrator: 'zh_female_vv_uranus_bigtts',
+}
+
+export function defaultsFromTemplate(t: Template): {
+ style_prompt: string
+ character_prompt: string
+ extra_prompt: string
+ voice_id: string
+ pipeline_mode: PipelineMode
+} {
+ 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',
+ }
+}
+
+export type Shot = {
+ id: number
+ shot_no: number
+ duration: number
+ narration: string
+ overlay_title?: string
+ overlay_subtitle?: string
+ img_prompt: string
+ video_prompt: string
+ camera: string
+ bgm_mood: string
+ image_url: string | null
+ video_url: string | null
+ audio_url: string | null
+ status: string
+ version: number
+}
+
+export type VoicePreset = {
+ id: string
+ label: string
+ gender: string
+ speaker: string
+}
+
+export type Project = {
+ id: number
+ template_id: string
+ title: string
+ source_type: string
+ source_text: string
+ status: string
+ progress: number
+ error_msg: string | null
+ cover_url: string | null
+ final_video_url: string | null
+ resolution_mode: string
+ pipeline_mode?: PipelineMode
+ voice_id?: string
+ character_bible?: string
+ style_prompt?: string
+ character_prompt?: string
+ extra_prompt?: string
+ ref_image_url: string | null
+ created_at: string
+ updated_at: string
+ shots: Shot[]
+}
+
+export type User = {
+ id: number
+ email: string
+ nickname: string
+ quota_left: number
+}
+
+export type Work = {
+ id: number
+ project_id: number
+ user_id: number
+ title: string
+ cover_url: string | null
+ video_url: string
+ visibility: string
+ published_at: string
+}
+
+export const api = {
+ assetUrl(path: string | null | undefined, cacheBust?: string | number) {
+ if (!path) return ''
+ if (path.startsWith('http')) return path
+ // Only bust when caller passes a stable version (e.g. updated_at) — never Date.now()
+ const q = cacheBust != null && cacheBust !== '' ? `?v=${encodeURIComponent(String(cacheBust))}` : ''
+ return `${API_BASE}${path}${q}`
+ },
+ register(email: string, password: string, nickname: string) {
+ return request<{ access_token: string }>('/api/auth/register', {
+ method: 'POST',
+ body: JSON.stringify({ email, password, nickname }),
+ })
+ },
+ login(email: string, password: string) {
+ return request<{ access_token: string }>('/api/auth/login', {
+ method: 'POST',
+ body: JSON.stringify({ email, password }),
+ })
+ },
+ me() {
+ return request<User>('/api/auth/me')
+ },
+ templates() {
+ return request<Template[]>('/api/templates')
+ },
+ createProject(body: {
+ template_id: string
+ title: string
+ source_type: 'theme' | 'script'
+ source_text: string
+ resolution_mode?: 'preview' | 'hd'
+ pipeline_mode?: PipelineMode
+ voice_id?: string
+ style_prompt?: string
+ character_prompt?: string
+ extra_prompt?: string
+ }) {
+ return request<Project>('/api/projects', { method: 'POST', body: JSON.stringify(body) })
+ },
+ updateProject(
+ id: number,
+ body: {
+ title?: string
+ source_type?: 'theme' | 'script'
+ source_text?: string
+ template_id?: string
+ pipeline_mode?: PipelineMode
+ resolution_mode?: 'preview' | 'hd'
+ voice_id?: string
+ style_prompt?: string
+ character_prompt?: string
+ extra_prompt?: string
+ },
+ ) {
+ return request<Project>(`/api/projects/${id}`, {
+ method: 'PATCH',
+ body: JSON.stringify(body),
+ })
+ },
+ voices() {
+ return request<VoicePreset[]>('/api/voices')
+ },
+ listProjects() {
+ return request<
+ Array<{
+ id: number
+ title: string
+ template_id: string
+ status: string
+ progress: number
+ cover_url: string | null
+ final_video_url?: string | null
+ error_msg?: string | null
+ pipeline_mode?: PipelineMode
+ created_at: string
+ updated_at?: string
+ }>
+ >('/api/projects')
+ },
+ async downloadZip(ids: number[]) {
+ const res = await fetch(`${API_BASE}/api/projects/download-zip`, {
+ method: 'POST',
+ headers: authHeaders(),
+ body: JSON.stringify({ ids }),
+ })
+ 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 || '打包下载失败')
+ }
+ const blob = await res.blob()
+ const cd = res.headers.get('Content-Disposition') || ''
+ const m = cd.match(/filename="?([^"]+)"?/)
+ const filename = m?.[1] || `framecut_videos_${Date.now()}.zip`
+ return { blob, filename }
+ },
+ getProject(id: number) {
+ return request<Project>(`/api/projects/${id}`)
+ },
+ generate(id: number) {
+ return request<Project>(`/api/projects/${id}/generate`, { method: 'POST' })
+ },
+ cancelProject(id: number) {
+ return request<Project>(`/api/projects/${id}/cancel`, { method: 'POST' })
+ },
+ deleteProject(id: number) {
+ return request<{ ok: boolean; id: number }>(`/api/projects/${id}`, { method: 'DELETE' })
+ },
+ updateShot(projectId: number, shotId: number, body: Partial<Shot>) {
+ return request<Shot>(`/api/projects/${projectId}/shots/${shotId}`, {
+ method: 'PATCH',
+ body: JSON.stringify(body),
+ })
+ },
+ regenImage(projectId: number, shotId: number) {
+ return request<Shot>(`/api/projects/${projectId}/shots/${shotId}/regen-image`, {
+ method: 'POST',
+ })
+ },
+ regenVideo(projectId: number, shotId: number) {
+ return request<Shot>(`/api/projects/${projectId}/shots/${shotId}/regen-video`, {
+ method: 'POST',
+ })
+ },
+ regenAudio(projectId: number, shotId: number) {
+ return request<Shot>(`/api/projects/${projectId}/shots/${shotId}/regen-audio`, {
+ method: 'POST',
+ })
+ },
+ regenAllAudio(projectId: number) {
+ return request<Project>(`/api/projects/${projectId}/regen-audio`, { method: 'POST' })
+ },
+ compose(projectId: number) {
+ return request<Project>(`/api/projects/${projectId}/compose`, { method: 'POST' })
+ },
+ publish(projectId: number) {
+ return request<Work>(`/api/projects/${projectId}/publish`, { method: 'POST' })
+ },
+ works() {
+ return request<Work[]>('/api/works')
+ },
+ eventsUrl(projectId: number) {
+ return `${API_BASE}/api/projects/${projectId}/events`
+ },
+}
diff --git a/frontend/src/assets/hero.png b/frontend/src/assets/hero.png
new file mode 100644
index 0000000..02251f4
Binary files /dev/null and b/frontend/src/assets/hero.png differ
diff --git a/frontend/src/assets/react.svg b/frontend/src/assets/react.svg
new file mode 100644
index 0000000..6c87de9
--- /dev/null
+++ b/frontend/src/assets/react.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
\ No newline at end of file
diff --git a/frontend/src/assets/vite.svg b/frontend/src/assets/vite.svg
new file mode 100644
index 0000000..5101b67
--- /dev/null
+++ b/frontend/src/assets/vite.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="g" width="74.749" height="58.852" x="29.961" y="-17.13" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="h" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="i" width="61.377" height="25.362" x="37.754" y="3.055" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="j" width="56.045" height="63.649" x="-13.43" y="-22.082" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="k" width="54.814" height="64.646" x="34.321" y="-37.644" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="l" width="33.541" height="35.313" x="38.847" y="-10.552" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="m" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="n" width="54.814" height="64.646" x="-15.081" y="6.78" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="o" width="54.814" height="64.646" x="22.45" y="-1.645" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="p" width="39.409" height="43.623" x="32.919" y="11.36" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter></defs></svg>
diff --git a/frontend/src/index.css b/frontend/src/index.css
new file mode 100644
index 0000000..2d9be8b
--- /dev/null
+++ b/frontend/src/index.css
@@ -0,0 +1,53 @@
+:root {
+ --ink: #1a1714;
+ --paper: #f2ebe0;
+ --paper-deep: #e6dccb;
+ --crimson: #b42318;
+ --moss: #3d5a45;
+ --muted: #6b6258;
+ --line: rgba(26, 23, 20, 0.12);
+ --shadow: 0 18px 50px rgba(26, 23, 20, 0.08);
+ font-family: 'Noto Sans SC', 'Source Han Sans SC', 'PingFang SC', sans-serif;
+ color: var(--ink);
+ background: var(--paper);
+ line-height: 1.5;
+ font-weight: 400;
+ font-synthesis: none;
+ text-rendering: optimizeLegibility;
+ -webkit-font-smoothing: antialiased;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+html,
+body,
+#root {
+ margin: 0;
+ min-height: 100%;
+}
+
+body {
+ background:
+ radial-gradient(1200px 600px at 10% -10%, rgba(180, 35, 24, 0.08), transparent 55%),
+ radial-gradient(900px 500px at 100% 0%, rgba(61, 90, 69, 0.1), transparent 50%),
+ linear-gradient(180deg, #f7f1e7 0%, var(--paper) 40%, #ebe2d4 100%);
+ background-attachment: fixed;
+}
+
+a {
+ color: inherit;
+ text-decoration: none;
+}
+
+button,
+input,
+textarea,
+select {
+ font: inherit;
+}
+
+button {
+ cursor: pointer;
+}
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
new file mode 100644
index 0000000..fab1219
--- /dev/null
+++ b/frontend/src/main.tsx
@@ -0,0 +1,10 @@
+import { StrictMode } from 'react'
+import { createRoot } from 'react-dom/client'
+import App from './App'
+import './index.css'
+
+createRoot(document.getElementById('root')!).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+)
diff --git a/frontend/src/pages/AuthPage.tsx b/frontend/src/pages/AuthPage.tsx
new file mode 100644
index 0000000..2d6702b
--- /dev/null
+++ b/frontend/src/pages/AuthPage.tsx
@@ -0,0 +1,85 @@
+import { useState } from 'react'
+import type { FormEvent } from 'react'
+import { Link, useNavigate } from 'react-router-dom'
+import { api } from '../api'
+
+export default function AuthPage() {
+ const nav = useNavigate()
+ const [mode, setMode] = useState<'login' | 'register'>('login')
+ const [email, setEmail] = useState('[email protected]')
+ const [password, setPassword] = useState('demo1234')
+ const [nickname, setNickname] = useState('创作者')
+ const [error, setError] = useState('')
+ const [loading, setLoading] = useState(false)
+
+ async function onSubmit(e: FormEvent) {
+ e.preventDefault()
+ setError('')
+ setLoading(true)
+ try {
+ const res =
+ mode === 'login'
+ ? await api.login(email, password)
+ : await api.register(email, password, nickname)
+ localStorage.setItem('token', res.access_token)
+ nav('/')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '失败')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ return (
+ <div className="auth-shell">
+ <div className="auth-panel">
+ <Link to="/" className="brand-mark">
+ 纸戏 <span>FrameCut</span>
+ </Link>
+ <h1>{mode === 'login' ? '回到工作台' : '创建创作者账号'}</h1>
+ <p className="lede">多风格模板驱动的 AI 短视频流水线</p>
+ <form onSubmit={onSubmit} className="stack">
+ {mode === 'register' && (
+ <label>
+ 昵称
+ <input value={nickname} onChange={(e) => setNickname(e.target.value)} required />
+ </label>
+ )}
+ <label>
+ 邮箱
+ <input
+ type="email"
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ required
+ />
+ </label>
+ <label>
+ 密码
+ <input
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ minLength={6}
+ required
+ />
+ </label>
+ {error && <p className="error">{error}</p>}
+ <button className="btn primary" disabled={loading}>
+ {loading ? '处理中…' : mode === 'login' ? '登录' : '注册'}
+ </button>
+ </form>
+ <button
+ type="button"
+ className="linkish"
+ onClick={() => setMode(mode === 'login' ? 'register' : 'login')}
+ >
+ {mode === 'login' ? '没有账号?注册' : '已有账号?登录'}
+ </button>
+ </div>
+ <div className="auth-visual" aria-hidden>
+ <div className="ink-wash" />
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
new file mode 100644
index 0000000..6c8136c
--- /dev/null
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -0,0 +1,382 @@
+import { useEffect, useMemo, useState } from 'react'
+import { Link, useNavigate } from 'react-router-dom'
+import { api } from '../api'
+import type { Project } from '../api'
+
+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'
+}
+
+function canDownload(p: HistoryItem) {
+ return p.status === 'DONE' && Boolean(p.final_video_url)
+}
+
+function triggerBlobDownload(blob: Blob, filename: string) {
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ a.remove()
+ URL.revokeObjectURL(url)
+}
+
+export default function HistoryPage() {
+ const nav = useNavigate()
+ const [items, setItems] = useState<HistoryItem[]>([])
+ 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 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()
+ setItems(list as HistoryItem[])
+ setError('')
+ setSelected((prev) => {
+ const ids = new Set(list.map((x) => x.id))
+ return new Set([...prev].filter((id) => ids.has(id)))
+ })
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '加载失败')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ if (!localStorage.getItem('token')) {
+ nav('/auth')
+ return
+ }
+ load()
+ }, [nav])
+
+ useEffect(() => {
+ if (!hasRunning) return
+ const timer = setInterval(load, 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
+ })
+ }
+
+ function toggleAllDownloadable() {
+ if (allDownloadableSelected) {
+ setSelected((prev) => {
+ const next = new Set(prev)
+ downloadable.forEach((p) => next.delete(p.id))
+ return next
+ })
+ return
+ }
+ setSelected((prev) => {
+ const next = new Set(prev)
+ downloadable.forEach((p) => next.add(p.id))
+ return next
+ })
+ }
+
+ async function onBatchDownload() {
+ const ids = selectedDownloadable.map((p) => p.id)
+ if (!ids.length) {
+ setError('请先勾选已完成的作品')
+ return
+ }
+ setPacking(true)
+ setError('')
+ try {
+ const { blob, filename } = await api.downloadZip(ids)
+ triggerBlobDownload(blob, filename)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '打包下载失败')
+ } finally {
+ setPacking(false)
+ }
+ }
+
+ async function onCancel(p: HistoryItem) {
+ if (!window.confirm(`取消「${p.title || '未命名作品'}」的生成任务?`)) return
+ setBusyId(p.id)
+ try {
+ await api.cancelProject(p.id)
+ await load()
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '取消失败')
+ } finally {
+ setBusyId(null)
+ }
+ }
+
+ 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)
+ }
+ }
+
+ return (
+ <div className="page">
+ <header className="topbar">
+ <Link to="/" className="brand-mark">
+ 纸戏 <span>FrameCut</span>
+ </Link>
+ <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>
+ </div>
+
+ {loading && <p className="muted">加载中…</p>}
+ {error && <p className="error">{error}</p>}
+
+ {!loading && items.length === 0 && (
+ <div className="empty-state">
+ <p>还没有创作记录。</p>
+ <button type="button" className="btn primary" onClick={() => nav('/studio')}>
+ 去创作
+ </button>
+ </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>}
+ </div>
+ <div className="history-actions">
+ <button
+ type="button"
+ className="btn ghost"
+ onClick={() => nav(`/studio?project=${p.id}`)}
+ >
+ 打开
+ </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)}
+ >
+ 删除
+ </button>
+ </div>
+ </div>
+ </article>
+ )
+ })}
+ </div>
+ </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)}>
+ 关闭
+ </button>
+ </header>
+ <video
+ key={`${preview.url}:${preview.bust || ''}`}
+ className="preview-media"
+ src={api.assetUrl(preview.url, preview.bust)}
+ controls
+ autoPlay
+ playsInline
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/pages/HomePage.tsx b/frontend/src/pages/HomePage.tsx
new file mode 100644
index 0000000..d27f588
--- /dev/null
+++ b/frontend/src/pages/HomePage.tsx
@@ -0,0 +1,124 @@
+import { useEffect, useState } from 'react'
+import { Link, useNavigate } from 'react-router-dom'
+import { api } from '../api'
+import type { Template, User, Work } from '../api'
+
+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('')
+
+ useEffect(() => {
+ api
+ .templates()
+ .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'))
+ }
+ }, [])
+
+ function logout() {
+ localStorage.removeItem('token')
+ setUser(null)
+ }
+
+ return (
+ <div className="page">
+ <header className="topbar">
+ <Link to="/" className="brand-mark">
+ 纸戏 <span>FrameCut</span>
+ </Link>
+ <nav>
+ <Link to="/studio">创作</Link>
+ {user ? <Link to="/history">历史</Link> : null}
+ {user ? (
+ <>
+ <span className="quota">额度不限</span>
+ <button type="button" className="linkish" onClick={logout}>
+ {user.nickname} · 退出
+ </button>
+ </>
+ ) : (
+ <Link to="/auth">登录</Link>
+ )}
+ </nav>
+ </header>
+
+ <section className="hero-band">
+ <p className="eyebrow">模板驱动 · 全链路字节模型</p>
+ <h1 className="brand-hero">纸戏</h1>
+ <p className="lede">选风格模板,输入主题,生成分镜到成片。</p>
+ <div className="cta-row">
+ <button
+ className="btn primary"
+ type="button"
+ onClick={() => nav(user ? '/studio' : '/auth')}
+ >
+ 开始创作
+ </button>
+ <a className="btn ghost" href="#templates">
+ 浏览模板
+ </a>
+ </div>
+ </section>
+
+ {error && <p className="error pad">{error}</p>}
+
+ <section id="templates" className="section">
+ <h2>风格模板</h2>
+ <p className="lede">同一条流水线,不同视觉语言。</p>
+ <div className="template-grid">
+ {templates.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ className="template-card"
+ onClick={() => {
+ if (!user) {
+ nav('/auth')
+ return
+ }
+ nav(
+ `/studio?template=${t.id}${
+ t.id === 'portrait_story' || t.id === 'ink_guofeng' ? '&mode=image_text' : ''
+ }`,
+ )
+ }}
+ >
+ <img src={api.assetUrl(t.preview_cover)} alt="" />
+ <div>
+ <h3>{t.name}</h3>
+ <p>{t.description}</p>
+ <div className="tags">
+ {t.category.map((c) => (
+ <span key={c}>{c}</span>
+ ))}
+ </div>
+ </div>
+ </button>
+ ))}
+ </div>
+ </section>
+
+ <section className="section">
+ <h2>公开作品</h2>
+ {works.length === 0 ? (
+ <p className="muted">还没有发布作品,去创作一条吧。</p>
+ ) : (
+ <div className="works-row">
+ {works.map((w) => (
+ <article key={w.id} className="work-item">
+ <img src={api.assetUrl(w.cover_url)} alt="" />
+ <h3>{w.title}</h3>
+ </article>
+ ))}
+ </div>
+ )}
+ </section>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/StudioPage.tsx b/frontend/src/pages/StudioPage.tsx
new file mode 100644
index 0000000..4e47659
--- /dev/null
+++ b/frontend/src/pages/StudioPage.tsx
@@ -0,0 +1,892 @@
+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 { 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
+ })
+}
+
+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,
+ })
+ }
+
+ 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)
+ }
+ }
+
+ 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 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">
+ <Link to="/" className="brand-mark">
+ 纸戏 <span>FrameCut</span>
+ </Link>
+ <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}
+ >
+ {templates.map((t) => (
+ <option key={t.id} value={t.id}>
+ {t.name}
+ </option>
+ ))}
+ </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 && 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>
+ )}
+ {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>
+ )
+}
diff --git a/frontend/src/promptDisplay.ts b/frontend/src/promptDisplay.ts
new file mode 100644
index 0000000..02f5cc4
--- /dev/null
+++ b/frontend/src/promptDisplay.ts
@@ -0,0 +1,33 @@
+/** Strip internal Seedream lock wrappers from prompts shown in UI. */
+export function scenePromptForDisplay(raw: string | null | undefined): string {
+ if (!raw) return ''
+ const scene = raw.match(/【场景】\s*([\s\S]+?)(?=\n【|$)/)
+ if (scene?.[1]) {
+ return scene[1].replace(/^[,,。\s]+|[,,。\s]+$/g, '').trim()
+ }
+ const boilerplate = [
+ '同一画风',
+ '全片必须保持',
+ '凡出现人物',
+ '禁止写实',
+ '禁止换脸',
+ '禁止镜头间切换',
+ '必须严格沿用',
+ '画面干净无文字',
+ ]
+ return raw
+ .split(/[,,\n]/)
+ .map((p) => p.trim())
+ .filter((p) => {
+ if (!p) return false
+ if (/^【(?:风格锁定|人物锁定|约束)】/.test(p)) return false
+ if (p.startsWith('人物设定') || p.startsWith('角色设定')) return false
+ if (boilerplate.some((b) => p.includes(b) || p.startsWith(b))) return false
+ return true
+ })
+ .join(',')
+ .replace(/【(?:风格锁定|人物锁定|约束|场景)】/g, '')
+ .replace(/[,,]{2,}/g, ',')
+ .replace(/^[,,。;;\s]+|[,,。;;\s]+$/g, '')
+ .trim()
+}
diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts
new file mode 100644
index 0000000..7019602
--- /dev/null
+++ b/frontend/src/vite-env.d.ts
@@ -0,0 +1,9 @@
+/// <reference types="vite/client" />
+
+interface ImportMetaEnv {
+ readonly VITE_API_BASE: string
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv
+}
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
new file mode 100644
index 0000000..6830b6f
--- /dev/null
+++ b/frontend/tsconfig.app.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "es2023",
+ "lib": ["ES2023", "DOM"],
+ "module": "esnext",
+ "types": ["vite/client"],
+ "allowArbitraryExtensions": true,
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+
+ /* Linting */
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "erasableSyntaxOnly": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
new file mode 100644
index 0000000..1ffef60
--- /dev/null
+++ b/frontend/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "files": [],
+ "references": [
+ { "path": "./tsconfig.app.json" },
+ { "path": "./tsconfig.node.json" }
+ ]
+}
diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json
new file mode 100644
index 0000000..8455dcb
--- /dev/null
+++ b/frontend/tsconfig.node.json
@@ -0,0 +1,23 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
+ "target": "es2023",
+ "lib": ["ES2023"],
+ "types": ["node"],
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "module": "nodenext",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+
+ /* Linting */
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "erasableSyntaxOnly": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
new file mode 100644
index 0000000..8b0f57b
--- /dev/null
+++ b/frontend/vite.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+
+// https://vite.dev/config/
+export default defineConfig({
+ plugins: [react()],
+})