730 lines
37 KiB
Python
730 lines
37 KiB
Python
|
|
"""项目与资产库接口(图1 模块①:人物与声音资产库 + 项目数据库)。"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
|
|||
|
|
from sqlalchemy import func, or_, select
|
|||
|
|
from sqlalchemy.orm import Session
|
|||
|
|
|
|||
|
|
from app import schemas
|
|||
|
|
from app.api import deps
|
|||
|
|
from app.constants import AssetKind, TaskKind
|
|||
|
|
from app.db import get_db
|
|||
|
|
from app.api.auth import require_user
|
|||
|
|
from app.models import Asset, Character, Project, Scene, Shot, Task, User, VoiceAsset, now_utc
|
|||
|
|
from app.providers import registry as model_registry
|
|||
|
|
from app.providers.base import AssetGenRequest
|
|||
|
|
from app.services import (costing, daemon, dispatch, events, prompt as prompt_service, storage, status,
|
|||
|
|
timbre, versions)
|
|||
|
|
|
|||
|
|
router = APIRouter(tags=["library"])
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------------------------------------------------------------- 项目
|
|||
|
|
# 总览封面优先用首镜关键帧:一眼能看出「这个项目长什么样」;
|
|||
|
|
# 还没出关键帧的项目退回场景图 / 定妆图,全都没有才让前端显示占位。
|
|||
|
|
COVER_KINDS = (AssetKind.KEYFRAME, AssetKind.LAST_FRAME, AssetKind.SCENE_IMAGE, AssetKind.PORTRAIT)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def project_covers(db: Session, project_ids: list[int]) -> dict[int, dict]:
|
|||
|
|
"""批量取项目封面,避免总览页逐项目查素材(N+1)。"""
|
|||
|
|
if not project_ids:
|
|||
|
|
return {}
|
|||
|
|
rows = db.execute(
|
|||
|
|
select(Asset.project_id, Asset.kind, Asset.path)
|
|||
|
|
.where(Asset.project_id.in_(project_ids), Asset.kind.in_(COVER_KINDS))
|
|||
|
|
.order_by(Asset.project_id, Asset.id)
|
|||
|
|
).all()
|
|||
|
|
preferred = {kind: rank for rank, kind in enumerate(COVER_KINDS)}
|
|||
|
|
best: dict[int, dict] = {}
|
|||
|
|
for project_id, kind, path in rows:
|
|||
|
|
rank = preferred.get(str(kind), 99)
|
|||
|
|
current = best.get(int(project_id))
|
|||
|
|
if current is not None and current["rank"] <= rank:
|
|||
|
|
continue
|
|||
|
|
if not storage.exists(path):
|
|||
|
|
continue
|
|||
|
|
best[int(project_id)] = {"url": storage.url_for(path), "kind": str(kind), "rank": rank}
|
|||
|
|
return best
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects")
|
|||
|
|
def list_projects(status_filter: str = Query("", alias="status"), q: str = "",
|
|||
|
|
brief: bool = Query(False), db: Session = Depends(get_db)):
|
|||
|
|
"""项目列表。
|
|||
|
|
|
|||
|
|
`brief=1` 只回选择器需要的字段(id / 名称 / 阶段 / 封面 / 镜头数):
|
|||
|
|
全量列表每个项目都带 characters + scenes + voices + 素材版本 + stats,
|
|||
|
|
6 个项目就有 170KB+,而「引入到哪个项目」这类下拉只需要 id 和名字。
|
|||
|
|
"""
|
|||
|
|
stmt = select(Project).order_by(Project.id.desc())
|
|||
|
|
if status_filter:
|
|||
|
|
stmt = stmt.where(Project.status == status_filter)
|
|||
|
|
rows = db.scalars(stmt).all()
|
|||
|
|
if q:
|
|||
|
|
rows = [p for p in rows if q.lower() in f"{p.name}{p.description}{p.genre}".lower()]
|
|||
|
|
ids = [int(p.id) for p in rows]
|
|||
|
|
covers = project_covers(db, ids)
|
|||
|
|
if brief:
|
|||
|
|
shot_counts = dict(db.execute(
|
|||
|
|
select(Shot.project_id, func.count(Shot.id)).where(Shot.project_id.in_(ids or [-1]))
|
|||
|
|
.group_by(Shot.project_id)).all())
|
|||
|
|
payload = [{
|
|||
|
|
"id": int(p.id), "name": p.name, "status": p.status, "current_stage": p.current_stage,
|
|||
|
|
"stage_label": status.STAGE_LABELS.get(p.current_stage, ""), "genre": p.genre,
|
|||
|
|
"aspect_ratio": p.aspect_ratio, "updated_at": p.updated_at,
|
|||
|
|
"cover_url": (covers.get(int(p.id)) or {}).get("url", ""),
|
|||
|
|
"cover_kind": (covers.get(int(p.id)) or {}).get("kind", ""),
|
|||
|
|
"shot_count": int(shot_counts.get(int(p.id)) or 0),
|
|||
|
|
} for p in rows]
|
|||
|
|
return {"projects": payload, "count": len(payload), "brief": True}
|
|||
|
|
asset_map = status.preload_assets(db, ids)
|
|||
|
|
payload = []
|
|||
|
|
for project in rows:
|
|||
|
|
item = status.project_dict(db, project, asset_map=asset_map)
|
|||
|
|
cover = covers.get(int(project.id)) or {}
|
|||
|
|
item["cover_url"] = cover.get("url", "")
|
|||
|
|
item["cover_kind"] = cover.get("kind", "")
|
|||
|
|
item["shot_count"] = int((item.get("stats") or {}).get("shots") or 0)
|
|||
|
|
payload.append(item)
|
|||
|
|
return {"projects": payload, "count": len(payload)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def import_platform_assets(db: Session, project: Project,
|
|||
|
|
refs: list[schemas.PlatformRef]) -> tuple[list[dict], list[dict]]:
|
|||
|
|
"""建项目时顺带把平台资源库的母版引进来(人物会连默认声线与母版素材一起复制)。
|
|||
|
|
|
|||
|
|
逐条独立提交:一个母版坏了(素材文件被删、母版不存在)不能连累整批,
|
|||
|
|
失败原因回吐给前端显示,用户仍然拿到一个建好的项目。
|
|||
|
|
"""
|
|||
|
|
from app.api import platform as platform_api # 局部导入,避免 api 包内的加载顺序耦合
|
|||
|
|
|
|||
|
|
imported: list[dict] = []
|
|||
|
|
failures: list[dict] = []
|
|||
|
|
seen: set[tuple[str, int]] = set()
|
|||
|
|
for ref in refs:
|
|||
|
|
key = (str(ref.owner_type), int(ref.asset_id))
|
|||
|
|
if key in seen:
|
|||
|
|
continue
|
|||
|
|
seen.add(key)
|
|||
|
|
try:
|
|||
|
|
result = platform_api.import_into_project(schemas.PlatformImport(
|
|||
|
|
project_id=int(project.id), asset_type=key[0], asset_id=key[1]), db=db)
|
|||
|
|
imported.append(result.get("result") or {})
|
|||
|
|
except HTTPException as exc:
|
|||
|
|
failures.append({"owner_type": key[0], "asset_id": key[1], "detail": exc.detail})
|
|||
|
|
except Exception as exc: # noqa: BLE001 - 建项目不该被引入拖垮
|
|||
|
|
db.rollback()
|
|||
|
|
failures.append({"owner_type": key[0], "asset_id": key[1],
|
|||
|
|
"detail": f"{type(exc).__name__}: {exc}"})
|
|||
|
|
if imported or failures:
|
|||
|
|
events.log_event(db, "project.assets_imported", project_id=project.id,
|
|||
|
|
message=f"创建项目时引入资源库母版 {len(imported)} 个"
|
|||
|
|
+ (f",失败 {len(failures)} 个" if failures else ""),
|
|||
|
|
entity_type="project", entity_id=project.id,
|
|||
|
|
data={"imported": imported, "failures": failures})
|
|||
|
|
db.commit()
|
|||
|
|
return imported, failures
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects")
|
|||
|
|
def create_project(data: schemas.ProjectCreate, db: Session = Depends(get_db),
|
|||
|
|
actor: User = Depends(require_user)):
|
|||
|
|
project = Project(**data.model_dump(exclude={"settings", "platform_assets"}),
|
|||
|
|
settings_json=data.settings or {})
|
|||
|
|
project.current_stage = "create_project"
|
|||
|
|
if actor.id: # AUTH_ENABLED=false 的虚拟账号不落库,不占外键
|
|||
|
|
project.created_by_id, project.created_by = actor.id, actor.username
|
|||
|
|
project.updated_by_id, project.updated_by = actor.id, actor.username
|
|||
|
|
db.add(project)
|
|||
|
|
db.flush()
|
|||
|
|
events.log_event(db, "project.created", project_id=project.id, message=f"创建项目《{project.name}》",
|
|||
|
|
entity_type="project", entity_id=project.id,
|
|||
|
|
data={"resolution": project.resolution, "aspect_ratio": project.aspect_ratio,
|
|||
|
|
"fps": project.fps, "provider": project.default_provider})
|
|||
|
|
db.commit()
|
|||
|
|
imported, failures = import_platform_assets(db, project, data.platform_assets)
|
|||
|
|
payload = status.project_dict(db, project)
|
|||
|
|
payload["imported_assets"], payload["import_failures"] = imported, failures
|
|||
|
|
return {"ok": True, "result": payload, "summary": deps.summary(db, project)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects/{project_id}")
|
|||
|
|
def get_project(project_id: int, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
return {"ok": True, "result": status.project_dict(db, project), "summary": deps.summary(db, project)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects/{project_id}/summary")
|
|||
|
|
def project_summary(project_id: int, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
return {"ok": True, "result": {"workflow": status.workflow_of(db, project),
|
|||
|
|
"stats": status.stats_of(db, project)},
|
|||
|
|
"summary": deps.summary(db, project)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.patch("/api/projects/{project_id}")
|
|||
|
|
def update_project(project_id: int, data: schemas.ProjectUpdate, db: Session = Depends(get_db),
|
|||
|
|
actor: User = Depends(require_user)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
patch = data.model_dump(exclude_unset=True)
|
|||
|
|
if actor.id:
|
|||
|
|
project.updated_by_id, project.updated_by = actor.id, actor.username
|
|||
|
|
if not (project.created_by_id or 0): # 补上用户体系之前建的项目
|
|||
|
|
project.created_by_id, project.created_by = actor.id, actor.username
|
|||
|
|
settings_patch = patch.pop("settings", None)
|
|||
|
|
if settings_patch is not None:
|
|||
|
|
project.settings_json = {**(project.settings_json or {}), **settings_patch}
|
|||
|
|
for key, value in patch.items():
|
|||
|
|
setattr(project, key, value)
|
|||
|
|
db.flush()
|
|||
|
|
if {"style_guide", "global_negative_prompt"} & set(patch):
|
|||
|
|
# 项目级提示词会参与每个镜头的组装;只改项目行会让已有分镜继续使用旧文本。
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
prompt_service.sync_prompt(
|
|||
|
|
db, project, shot,
|
|||
|
|
reason="项目风格或负面提示词更新后重算分镜提示词",
|
|||
|
|
actor="studio",
|
|||
|
|
)
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
events.log_event(db, "project.updated", project_id=project.id, message="更新项目设定",
|
|||
|
|
entity_type="project", entity_id=project.id, data=patch)
|
|||
|
|
return deps.done(db, project, {"project_id": project.id})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.delete("/api/projects/{project_id}")
|
|||
|
|
def delete_project(project_id: int, purge_files: bool = False, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
active = db.query(Task).filter(Task.project_id == project_id,
|
|||
|
|
Task.status.in_(["queued", "running", "retrying"])).count()
|
|||
|
|
if active:
|
|||
|
|
raise HTTPException(409, f"仍有 {active} 个任务在执行,请先取消任务")
|
|||
|
|
name = project.name
|
|||
|
|
db.delete(project)
|
|||
|
|
db.commit()
|
|||
|
|
if purge_files:
|
|||
|
|
storage.cleanup_project_files(project_id)
|
|||
|
|
events.log_event(db, "project.deleted", message=f"删除项目《{name}》", data={"project_id": project_id})
|
|||
|
|
return {"ok": True, "deleted": project_id}
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------------------------------------------------------------- 角色
|
|||
|
|
@router.post("/api/projects/{project_id}/characters")
|
|||
|
|
def create_character(project_id: int, data: schemas.CharacterCreate, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
char = Character(project_id=project.id, **data.model_dump())
|
|||
|
|
db.add(char)
|
|||
|
|
db.flush()
|
|||
|
|
events.log_event(db, "character.created", project_id=project.id, message=f"新增角色「{char.name}」",
|
|||
|
|
entity_type="character", entity_id=char.id)
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"id": char.id, "name": char.name})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.patch("/api/projects/{project_id}/characters/{character_id}")
|
|||
|
|
def update_character(project_id: int, character_id: int, data: schemas.CharacterUpdate,
|
|||
|
|
db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
char = deps.get_character(db, project_id, character_id)
|
|||
|
|
patch = data.model_dump(exclude_unset=True)
|
|||
|
|
for key, value in patch.items():
|
|||
|
|
setattr(char, key, value)
|
|||
|
|
db.flush()
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
if char in (shot.characters or []) or shot.speaker_character_id == char.id:
|
|||
|
|
from app.services import prompt as prompt_service
|
|||
|
|
|
|||
|
|
prompt_service.sync_prompt(db, project, shot, reason=f"角色「{char.name}」设定更新后重算提示词",
|
|||
|
|
record=True)
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"id": char.id, **patch})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.delete("/api/projects/{project_id}/characters/{character_id}")
|
|||
|
|
def delete_character(project_id: int, character_id: int, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
char = deps.get_character(db, project_id, character_id)
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
if char in (shot.characters or []):
|
|||
|
|
shot.characters = [c for c in shot.characters if c.id != char.id]
|
|||
|
|
if shot.speaker_character_id == char.id:
|
|||
|
|
shot.speaker_character_id = None
|
|||
|
|
storage.purge_owner_assets(db, "human", character_id)
|
|||
|
|
db.delete(char)
|
|||
|
|
db.flush()
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"deleted": character_id})
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------------------------------------------------------------- 场景
|
|||
|
|
@router.post("/api/projects/{project_id}/scenes")
|
|||
|
|
def create_scene(project_id: int, data: schemas.SceneCreate, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
scene = Scene(project_id=project.id, **data.model_dump())
|
|||
|
|
db.add(scene)
|
|||
|
|
db.flush()
|
|||
|
|
events.log_event(db, "scene.created", project_id=project.id, message=f"新增场景「{scene.name}」",
|
|||
|
|
entity_type="scene", entity_id=scene.id)
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"id": scene.id, "name": scene.name})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.patch("/api/projects/{project_id}/scenes/{scene_id}")
|
|||
|
|
def update_scene(project_id: int, scene_id: int, data: schemas.SceneUpdate, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
scene = deps.get_scene(db, project_id, scene_id)
|
|||
|
|
patch = data.model_dump(exclude_unset=True)
|
|||
|
|
for key, value in patch.items():
|
|||
|
|
setattr(scene, key, value)
|
|||
|
|
db.flush()
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"id": scene.id, **patch})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.delete("/api/projects/{project_id}/scenes/{scene_id}")
|
|||
|
|
def delete_scene(project_id: int, scene_id: int, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
scene = deps.get_scene(db, project_id, scene_id)
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
if scene in (shot.scenes or []):
|
|||
|
|
shot.scenes = [s for s in shot.scenes if s.id != scene.id]
|
|||
|
|
storage.purge_owner_assets(db, "scene", scene_id)
|
|||
|
|
db.delete(scene)
|
|||
|
|
db.flush()
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"deleted": scene_id})
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------------------------------------------------------------- 声线
|
|||
|
|
@router.post("/api/projects/{project_id}/voices")
|
|||
|
|
def create_voice(project_id: int, data: schemas.VoiceCreate, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
if data.is_default:
|
|||
|
|
db.query(VoiceAsset).filter(VoiceAsset.project_id == project.id,
|
|||
|
|
VoiceAsset.is_default.is_(True)).update({"is_default": False})
|
|||
|
|
voice = VoiceAsset(project_id=project.id, **data.model_dump())
|
|||
|
|
db.add(voice)
|
|||
|
|
db.flush()
|
|||
|
|
events.log_event(db, "voice.created", project_id=project.id, message=f"新增声线「{voice.name}」",
|
|||
|
|
entity_type="voice", entity_id=voice.id)
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"id": voice.id, "name": voice.name})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.patch("/api/projects/{project_id}/voices/{voice_id}")
|
|||
|
|
def update_voice(project_id: int, voice_id: int, data: schemas.VoiceUpdate, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
voice = deps.get_voice(db, project_id, voice_id)
|
|||
|
|
patch = data.model_dump(exclude_unset=True)
|
|||
|
|
if patch.get("is_default"):
|
|||
|
|
db.query(VoiceAsset).filter(VoiceAsset.project_id == project.id, VoiceAsset.id != voice_id,
|
|||
|
|
VoiceAsset.is_default.is_(True)).update({"is_default": False})
|
|||
|
|
for key, value in patch.items():
|
|||
|
|
setattr(voice, key, value)
|
|||
|
|
db.flush()
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"id": voice.id, **patch})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects/{project_id}/voices/{voice_id}/reference-status")
|
|||
|
|
def voice_reference_status(project_id: int, voice_id: int, db: Session = Depends(get_db)):
|
|||
|
|
"""打开项目侧「生成试听」前先预告:这次会拿到谁的嗓子。
|
|||
|
|
|
|||
|
|
和平台侧同一个理由——音色由参考音频决定,声线表单里的性别对 zero-shot
|
|||
|
|
克隆模型只是元数据,所以「会不会男声出成女声」必须在点生成之前说清楚。
|
|||
|
|
"""
|
|||
|
|
deps.get_project(db, project_id)
|
|||
|
|
voice = deps.get_voice(db, project_id, voice_id)
|
|||
|
|
spec, _adapter = model_registry.resolve_voice(db, None, None)
|
|||
|
|
return {"ok": True, "result": timbre.reference_status(db, voice, clone=timbre.clone_model(spec))}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.delete("/api/projects/{project_id}/voices/{voice_id}")
|
|||
|
|
def delete_voice(project_id: int, voice_id: int, db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
voice = deps.get_voice(db, project_id, voice_id)
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
if shot.voice_asset_id == voice_id:
|
|||
|
|
shot.voice_asset_id = None
|
|||
|
|
for char in project.characters or []:
|
|||
|
|
if char.default_voice_id == voice_id:
|
|||
|
|
char.default_voice_id = None
|
|||
|
|
storage.purge_owner_assets(db, "voice", voice_id)
|
|||
|
|
db.delete(voice)
|
|||
|
|
db.flush()
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, {"deleted": voice_id})
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------------------------------------------------------------- 资产
|
|||
|
|
@router.get("/api/projects/{project_id}/assets")
|
|||
|
|
def list_assets(project_id: int, owner_type: str = "", owner_id: int | None = None, kind: str = "",
|
|||
|
|
db: Session = Depends(get_db)):
|
|||
|
|
deps.get_project(db, project_id)
|
|||
|
|
stmt = db.query(Asset).filter(Asset.project_id == project_id)
|
|||
|
|
if owner_type:
|
|||
|
|
stmt = stmt.filter(Asset.owner_type == owner_type)
|
|||
|
|
if owner_id is not None:
|
|||
|
|
stmt = stmt.filter(Asset.owner_id == owner_id)
|
|||
|
|
if kind:
|
|||
|
|
stmt = stmt.filter(Asset.kind == kind)
|
|||
|
|
rows = [row for row in stmt.order_by(Asset.id).all()
|
|||
|
|
if storage.belongs_to_owner(db, row.owner_type, row.owner_id, row)]
|
|||
|
|
return {"assets": [storage.asset_dict(a) for a in rows], "count": len(rows)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects/{project_id}/assets/usage")
|
|||
|
|
def asset_usage(project_id: int, db: Session = Depends(get_db)):
|
|||
|
|
"""返回人物 / 场景 / 声线分别被哪些镜头使用,支持资产页直达分镜。"""
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
usage: dict[str, dict[str, dict]] = {"human": {}, "scene": {}, "voice": {}}
|
|||
|
|
|
|||
|
|
def add(owner_type: str, owner_id: int, shot) -> None:
|
|||
|
|
bucket = usage[owner_type].setdefault(str(owner_id), {"target_type": owner_type, "target_id": owner_id,
|
|||
|
|
"count": 0, "shots": []})
|
|||
|
|
if any(row["id"] == shot.id for row in bucket["shots"]):
|
|||
|
|
return
|
|||
|
|
bucket["count"] += 1
|
|||
|
|
bucket["shots"].append({"id": shot.id, "order_index": shot.order_index,
|
|||
|
|
"title": shot.title or f"镜头 {shot.order_index}"})
|
|||
|
|
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
seen_humans: set[int] = set()
|
|||
|
|
for character in shot.characters or []:
|
|||
|
|
seen_humans.add(character.id)
|
|||
|
|
add("human", character.id, shot)
|
|||
|
|
if shot.speaker_character_id and shot.speaker_character_id not in seen_humans:
|
|||
|
|
add("human", shot.speaker_character_id, shot)
|
|||
|
|
|
|||
|
|
for scene in shot.scenes or []:
|
|||
|
|
add("scene", scene.id, shot)
|
|||
|
|
|
|||
|
|
voices: set[int] = set()
|
|||
|
|
if shot.voice_asset_id:
|
|||
|
|
voices.add(shot.voice_asset_id)
|
|||
|
|
if shot.speaker_character_id:
|
|||
|
|
speaker = db.get(Character, shot.speaker_character_id)
|
|||
|
|
if speaker and speaker.default_voice_id:
|
|||
|
|
voices.add(speaker.default_voice_id)
|
|||
|
|
for character in shot.characters or []:
|
|||
|
|
if character.default_voice_id:
|
|||
|
|
voices.add(character.default_voice_id)
|
|||
|
|
for voice_id in voices:
|
|||
|
|
add("voice", voice_id, shot)
|
|||
|
|
|
|||
|
|
items = [row for group in usage.values() for row in group.values()]
|
|||
|
|
items.sort(key=lambda row: (row["target_type"], row["target_id"]))
|
|||
|
|
return {"usage": usage, "items": items, "count": len(items)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _generation_references(db: Session, project_id: int, target_type: str, target_id: int,
|
|||
|
|
ids: list[int], *, media_type: str) -> list[Asset]:
|
|||
|
|
rows: list[Asset] = []
|
|||
|
|
seen: set[int] = set()
|
|||
|
|
image_suffixes = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}
|
|||
|
|
audio_suffixes = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg", ".opus"}
|
|||
|
|
for asset_id in ids:
|
|||
|
|
if asset_id in seen:
|
|||
|
|
continue
|
|||
|
|
seen.add(asset_id)
|
|||
|
|
row = db.get(Asset, asset_id)
|
|||
|
|
if row is None or row.project_id != project_id:
|
|||
|
|
raise HTTPException(400, "参考素材不属于当前项目资产")
|
|||
|
|
# 图像生成需要跨资产组合参考图,例如「场景母图 + 人物定妆图」。
|
|||
|
|
# 音色克隆仍必须来自当前声线,避免把别的角色声音静默克隆进来。
|
|||
|
|
if media_type != "image" and (row.owner_type != target_type or row.owner_id != target_id):
|
|||
|
|
raise HTTPException(400, "声音参考素材不属于当前声线资产")
|
|||
|
|
if not storage.exists(row.path):
|
|||
|
|
raise HTTPException(400, "参考素材文件不存在,请重新上传")
|
|||
|
|
suffix = Path(row.path).suffix.lower()
|
|||
|
|
if media_type == "image" and suffix not in image_suffixes:
|
|||
|
|
raise HTTPException(400, "图像参考素材必须是图片文件")
|
|||
|
|
if media_type == "tts" and suffix not in audio_suffixes:
|
|||
|
|
raise HTTPException(400, "音色参考素材必须是音频文件")
|
|||
|
|
rows.append(row)
|
|||
|
|
return rows
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects/{project_id}/assets/generate")
|
|||
|
|
def generate_asset(project_id: int, data: schemas.AssetGenerate, db: Session = Depends(get_db)):
|
|||
|
|
"""调用已配置图像/TTS 模型生成角色、场景、分镜关键帧或声线资产。"""
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
target_type = data.target_type
|
|||
|
|
if target_type == "human":
|
|||
|
|
owner = deps.get_character(db, project_id, data.target_id)
|
|||
|
|
allowed = {AssetKind.PORTRAIT, AssetKind.TURNAROUND, AssetKind.COSTUME, AssetKind.EXPRESSION}
|
|||
|
|
media_type, operation = "image", "generate_image"
|
|||
|
|
elif target_type == "scene":
|
|||
|
|
owner = deps.get_scene(db, project_id, data.target_id)
|
|||
|
|
allowed = {AssetKind.SCENE_IMAGE}
|
|||
|
|
media_type, operation = "image", "generate_image"
|
|||
|
|
elif target_type == "voice":
|
|||
|
|
owner = deps.get_voice(db, project_id, data.target_id)
|
|||
|
|
allowed = {AssetKind.VOICE_SAMPLE}
|
|||
|
|
media_type, operation = "tts", "generate_voice_sample"
|
|||
|
|
else:
|
|||
|
|
owner = deps.get_shot(db, project_id, data.target_id)
|
|||
|
|
allowed = {AssetKind.KEYFRAME, AssetKind.LAST_FRAME, AssetKind.REFERENCE_IMAGE}
|
|||
|
|
media_type, operation = "image", "generate_image"
|
|||
|
|
|
|||
|
|
if data.kind not in allowed:
|
|||
|
|
raise HTTPException(400, f"{target_type} 不支持资产生成类型 {data.kind};"
|
|||
|
|
f"可用:{', '.join(sorted(allowed))}")
|
|||
|
|
if media_type == "tts":
|
|||
|
|
spec, adapter = model_registry.resolve_voice(db, data.provider or owner.provider or None,
|
|||
|
|
data.model or None)
|
|||
|
|
else:
|
|||
|
|
spec, adapter = model_registry.resolve_asset(db, media_type, data.provider or None,
|
|||
|
|
data.model or None)
|
|||
|
|
if not spec.enabled:
|
|||
|
|
raise HTTPException(409, f"模型 {spec.provider}/{spec.model} 已停用")
|
|||
|
|
references = _generation_references(
|
|||
|
|
db, project.id, target_type, owner.id, data.reference_asset_ids, media_type=media_type,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
owner_name = ((owner.title or owner.code or f"镜头 {owner.order_index:02d}")
|
|||
|
|
if isinstance(owner, Shot) else owner.name)
|
|||
|
|
generated_name = f"{owner_name} · AI {AssetKind.LABELS.get(data.kind, data.kind)}"
|
|||
|
|
if isinstance(owner, Shot):
|
|||
|
|
existing = storage.assets_of(db, "shot", owner.id, data.kind)
|
|||
|
|
# 关键帧/尾帧是镜头上的单值槽位。沿用已有素材名可原地递增版本,
|
|||
|
|
# 确保 first_asset_path 立即命中新图,而不是继续使用旧的关键帧。
|
|||
|
|
if existing:
|
|||
|
|
generated_name = existing[-1].name
|
|||
|
|
payload = data.model_dump(exclude={"drain"})
|
|||
|
|
if isinstance(owner, Shot) and not payload.get("prompt"):
|
|||
|
|
# 关键帧与镜头提示词共用同一份版本化文本。生成前先同步,避免页面
|
|||
|
|
# 刚改完景别/运镜却仍用上一次缓存的提示词出图。
|
|||
|
|
prompt_service.sync_prompt(db, project, owner, reason="生成分镜关键帧前同步提示词",
|
|||
|
|
actor="studio", record=True)
|
|||
|
|
payload["prompt"] = owner.prompt or owner.description
|
|||
|
|
payload["negative_prompt"] = payload.get("negative_prompt") or owner.negative_prompt
|
|||
|
|
payload.update({"operation": operation, "name": generated_name,
|
|||
|
|
"reference_paths": [str(storage.to_absolute(row.path)) for row in references]})
|
|||
|
|
task = Task(project_id=project.id, kind=TaskKind.ASSET,
|
|||
|
|
name=f"资产生成:{payload['name']}", stage="asset", status="queued",
|
|||
|
|
priority=3, provider=spec.provider, model=spec.model,
|
|||
|
|
mode=media_type, max_attempts=2,
|
|||
|
|
idempotency_key=f"asset-gen:{target_type}:{owner.id}:{data.kind}:{int(now_utc().timestamp())}",
|
|||
|
|
payload_json=payload, cost_currency=spec.currency, queued_at=now_utc())
|
|||
|
|
db.add(task)
|
|||
|
|
db.flush()
|
|||
|
|
events.log_event(db, "asset.queued", project_id=project.id, task_id=task.id,
|
|||
|
|
message=f"{payload['name']} 已进入资产任务队列({spec.provider}/{spec.model})",
|
|||
|
|
entity_type="asset", entity_id=None,
|
|||
|
|
data={"target_type": target_type, "target_id": owner.id,
|
|||
|
|
"kind": data.kind, "provider": spec.provider, "model": spec.model})
|
|||
|
|
db.commit()
|
|||
|
|
|
|||
|
|
drained = None
|
|||
|
|
if data.drain:
|
|||
|
|
dispatch.dispatch_due(db, limit=1, project_id=project.id)
|
|||
|
|
drained = daemon.drain_queue(db, project_id=project.id, timeout=300)
|
|||
|
|
db.expire_all()
|
|||
|
|
task = db.get(Task, task.id)
|
|||
|
|
return {"ok": True, "result": {"task": status.task_dict(task), "drained": drained},
|
|||
|
|
"summary": deps.summary(db, project)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects/{project_id}/assets/text-assist")
|
|||
|
|
def text_assist(project_id: int, data: schemas.TextAssist, db: Session = Depends(get_db)):
|
|||
|
|
"""调用大模型补全角色/场景一致性提示词,并把建议返回给资产编辑器。"""
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
if data.target_type == "character":
|
|||
|
|
if data.target_id is None:
|
|||
|
|
raise HTTPException(400, "角色文本补全缺少 target_id")
|
|||
|
|
owner = deps.get_character(db, project_id, data.target_id)
|
|||
|
|
subject = ",".join(part for part in [
|
|||
|
|
owner.name, owner.role, owner.appearance, owner.personality, project.style_guide
|
|||
|
|
] if part)
|
|||
|
|
asset_type = "character"
|
|||
|
|
elif data.target_type == "scene":
|
|||
|
|
if data.target_id is None:
|
|||
|
|
raise HTTPException(400, "场景文本补全缺少 target_id")
|
|||
|
|
owner = deps.get_scene(db, project_id, data.target_id)
|
|||
|
|
subject = ",".join(part for part in [
|
|||
|
|
owner.name, owner.description, owner.prompt, owner.lighting,
|
|||
|
|
owner.time_of_day, owner.palette, project.style_guide
|
|||
|
|
] if part)
|
|||
|
|
asset_type = "scene"
|
|||
|
|
else:
|
|||
|
|
owner = deps.get_shot(db, project_id, data.target_id) if data.target_id else None
|
|||
|
|
if owner is None:
|
|||
|
|
raise HTTPException(400, "分镜文本补全缺少 target_id")
|
|||
|
|
subject = ",".join(part for part in [
|
|||
|
|
owner.title, owner.description, owner.prompt, project.style_guide
|
|||
|
|
] if part)
|
|||
|
|
asset_type = "storyboard"
|
|||
|
|
|
|||
|
|
spec, _adapter = model_registry.resolve_llm(db, data.provider or None, data.model or None)
|
|||
|
|
if not spec.enabled:
|
|||
|
|
raise HTTPException(409, f"大模型 {spec.provider}/{spec.model} 已停用")
|
|||
|
|
prompt = (
|
|||
|
|
f"请补全以下{asset_type}的一致性提示词。保留已有事实,不新增与设定冲突的内容。"
|
|||
|
|
f"输出一段可直接送入图像/视频模型的中文提示词。\n"
|
|||
|
|
f"当前设定:{subject or '尚未填写'}\n"
|
|||
|
|
f"补充要求:{data.instruction or '强化外观、材质、光线和跨镜头一致性'}"
|
|||
|
|
)
|
|||
|
|
request = AssetGenRequest(kind="text", prompt=prompt, seed=None,
|
|||
|
|
params={"subject": subject, "asset_type": asset_type,
|
|||
|
|
"model": spec.model},
|
|||
|
|
idempotency_key=f"text-assist:{data.target_type}:{data.target_id}",
|
|||
|
|
label=f"TEXT-{data.target_type.upper()}-{data.target_id}")
|
|||
|
|
result = model_registry.generate_asset(db, request, "llm", spec.provider, spec.model)
|
|||
|
|
if not result.text.strip():
|
|||
|
|
raise HTTPException(502, "大模型未返回有效内容")
|
|||
|
|
cost = float(result.cost or 0.0)
|
|||
|
|
if not cost:
|
|||
|
|
cost = len(prompt) / 1000.0 * float(spec.price_per_1k_chars or 0.0)
|
|||
|
|
if cost:
|
|||
|
|
costing.record_cost(db, project_id=project.id, kind="text_assist",
|
|||
|
|
provider=spec.provider, model=spec.model, quantity=len(prompt) / 1000.0,
|
|||
|
|
unit="1k_chars", unit_price=float(spec.price_per_1k_chars or 0.0),
|
|||
|
|
cost=cost, currency=spec.currency, note="一致性提示词补全")
|
|||
|
|
costing.record_generation(db, project_id=project.id, provider=spec.provider, model=spec.model,
|
|||
|
|
kind="asset_text", prompt=prompt,
|
|||
|
|
output_path="", cost=cost, currency=spec.currency,
|
|||
|
|
metadata_json={"target_type": data.target_type,
|
|||
|
|
"target_id": data.target_id})
|
|||
|
|
events.log_event(db, "asset.text_assist", project_id=project.id,
|
|||
|
|
message=f"使用 {spec.provider}/{spec.model} 补全了 {asset_type} 一致性提示词",
|
|||
|
|
entity_type=data.target_type, entity_id=data.target_id,
|
|||
|
|
data={"chars": len(result.text), "cost": round(cost, 6)})
|
|||
|
|
db.commit()
|
|||
|
|
return {"ok": True, "result": {"text": result.text.strip(), "provider": spec.provider,
|
|||
|
|
"model": spec.model, "cost": round(cost, 6),
|
|||
|
|
"currency": spec.currency}}
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def _upload(db: Session, project: Project, file: UploadFile, *, owner_type: str, owner_id: int,
|
|||
|
|
kind: str, name: str, note: str, stem: str) -> Asset:
|
|||
|
|
return await deps.save_asset_file(db, file, project=project, owner_type=owner_type, owner_id=owner_id,
|
|||
|
|
kind=kind, name=name, note=note, stem=stem)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects/{project_id}/characters/{character_id}/assets")
|
|||
|
|
async def upload_character_asset(project_id: int, character_id: int, kind: str = Form(...),
|
|||
|
|
name: str = Form(""), note: str = Form(""),
|
|||
|
|
file: UploadFile = File(...), db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
char = deps.get_character(db, project_id, character_id)
|
|||
|
|
asset = await _upload(db, project, file, owner_type="human", owner_id=char.id, kind=kind, name=name,
|
|||
|
|
note=note, stem=f"char-{char.id}-{kind}")
|
|||
|
|
for shot in project.shots or []:
|
|||
|
|
if char in (shot.characters or []):
|
|||
|
|
from app.services import prompt as prompt_service
|
|||
|
|
|
|||
|
|
prompt_service.sync_prompt(db, project, shot, reason="角色资产更新后重算提示词", record=False)
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, storage.asset_dict(asset))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects/{project_id}/scenes/{scene_id}/assets")
|
|||
|
|
async def upload_scene_asset(project_id: int, scene_id: int, kind: str = Form("scene_image"),
|
|||
|
|
name: str = Form(""), note: str = Form(""),
|
|||
|
|
file: UploadFile = File(...), db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
scene = deps.get_scene(db, project_id, scene_id)
|
|||
|
|
asset = await _upload(db, project, file, owner_type="scene", owner_id=scene.id, kind=kind, name=name,
|
|||
|
|
note=note, stem=f"scene-{scene.id}-{kind}")
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, storage.asset_dict(asset))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects/{project_id}/voices/{voice_id}/assets")
|
|||
|
|
async def upload_voice_asset_file(project_id: int, voice_id: int, kind: str = Form("voice_sample"),
|
|||
|
|
name: str = Form(""), note: str = Form(""),
|
|||
|
|
file: UploadFile = File(...), db: Session = Depends(get_db)):
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
voice = deps.get_voice(db, project_id, voice_id)
|
|||
|
|
asset = await _upload(db, project, file, owner_type="voice", owner_id=voice.id, kind=kind, name=name,
|
|||
|
|
note=note, stem=f"voice-{voice.id}-{kind}")
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
return deps.done(db, project, storage.asset_dict(asset))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/projects/{project_id}/assets")
|
|||
|
|
async def upload_project_asset(project_id: int, kind: str = Form(...), name: str = Form(""),
|
|||
|
|
note: str = Form(""), file: UploadFile = File(...),
|
|||
|
|
db: Session = Depends(get_db)):
|
|||
|
|
"""项目级素材:配乐 / 音效 / 通用参考。"""
|
|||
|
|
project = deps.get_project(db, project_id)
|
|||
|
|
asset = await _upload(db, project, file, owner_type="project", owner_id=project.id, kind=kind, name=name,
|
|||
|
|
note=note, stem=f"project-{kind}")
|
|||
|
|
return deps.done(db, project, storage.asset_dict(asset))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/assets/{asset_id}/refresh")
|
|||
|
|
def refresh_asset(asset_id: int, db: Session = Depends(get_db)):
|
|||
|
|
asset = db.get(Asset, asset_id)
|
|||
|
|
if asset is None:
|
|||
|
|
raise HTTPException(404, "资产不存在")
|
|||
|
|
task = Task(project_id=asset.project_id, kind=TaskKind.ASSET, name=f"资产校验:{asset.name}",
|
|||
|
|
stage="asset", status="queued", max_attempts=1,
|
|||
|
|
idempotency_key=f"asset:{asset.id}:{asset.checksum}",
|
|||
|
|
payload_json={"asset_id": asset.id}, queued_at=now_utc())
|
|||
|
|
db.add(task)
|
|||
|
|
db.commit()
|
|||
|
|
return {"ok": True, "task_id": task.id}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.delete("/api/assets/{asset_id}")
|
|||
|
|
def delete_asset(asset_id: int, db: Session = Depends(get_db)):
|
|||
|
|
asset = db.get(Asset, asset_id)
|
|||
|
|
if asset is None:
|
|||
|
|
raise HTTPException(404, "资产不存在")
|
|||
|
|
project = deps.get_project(db, asset.project_id)
|
|||
|
|
owner_type, owner_id, kind = asset.owner_type, asset.owner_id, asset.kind
|
|||
|
|
db.delete(asset)
|
|||
|
|
db.flush()
|
|||
|
|
deps.recheck(db, project)
|
|||
|
|
events.log_event(db, "asset.deleted", project_id=project.id, message=f"删除资产:{asset.name}",
|
|||
|
|
data={"kind": kind, "owner_type": owner_type, "owner_id": owner_id})
|
|||
|
|
return deps.done(db, project, {"deleted": asset_id})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/api/assets/{asset_id}/versions/{version_no}/current")
|
|||
|
|
def set_asset_current_version(asset_id: int, version_no: int, data: schemas.VersionAction | None = None,
|
|||
|
|
db: Session = Depends(get_db)):
|
|||
|
|
"""把项目资产的某个历史版本设为当前版本。"""
|
|||
|
|
try:
|
|||
|
|
result = versions.set_current(db, versions.PROJECT_ASSET, asset_id, version_no,
|
|||
|
|
actor=(data.actor if data else "ui"))
|
|||
|
|
except versions.VersionError as exc:
|
|||
|
|
raise HTTPException(exc.status_code, exc.detail)
|
|||
|
|
return {"ok": True, "result": result}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.delete("/api/assets/{asset_id}/versions/{version_no}")
|
|||
|
|
def delete_asset_version(asset_id: int, version_no: int, data: schemas.VersionAction | None = None,
|
|||
|
|
db: Session = Depends(get_db)):
|
|||
|
|
"""删除项目资产的某个版本;删的正是当前版本时自动回落到剩余最新版本。"""
|
|||
|
|
try:
|
|||
|
|
result = versions.delete_version(db, versions.PROJECT_ASSET, asset_id, version_no,
|
|||
|
|
actor=(data.actor if data else "ui"))
|
|||
|
|
except versions.VersionError as exc:
|
|||
|
|
raise HTTPException(exc.status_code, exc.detail)
|
|||
|
|
return {"ok": True, "result": result}
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------------------------------------------------------------- 观测
|
|||
|
|
@router.get("/api/projects/{project_id}/events")
|
|||
|
|
def project_events(project_id: int, limit: int = 120, level: str = "", db: Session = Depends(get_db)):
|
|||
|
|
deps.get_project(db, project_id)
|
|||
|
|
return {"events": events.recent_events(db, project_id=project_id, limit=min(500, max(1, limit)),
|
|||
|
|
level=level or None)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects/{project_id}/costs")
|
|||
|
|
def project_costs(project_id: int, db: Session = Depends(get_db)):
|
|||
|
|
deps.get_project(db, project_id)
|
|||
|
|
return {"cost": costing.summarize(db, project_id), "items": costing.detailed_costs(db, project_id)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/api/projects/{project_id}/generations")
|
|||
|
|
def project_generations(project_id: int, limit: int = 200, db: Session = Depends(get_db)):
|
|||
|
|
deps.get_project(db, project_id)
|
|||
|
|
rows = costing.generation_records(db, project_id, limit=min(500, max(1, limit)))
|
|||
|
|
return {"generations": rows, "count": len(rows)}
|