cmvr-visual/backend/app/services/assets.py

482 lines
18 KiB
Python
Raw Normal View History

import asyncio
import hashlib
from pathlib import Path
import re
import shutil
from sqlalchemy import delete, func, select, update
from app.core.security import Actor
from app.services.snapshots import asset_dto
from app.core.errors import fail
from app.services.events import emit_asset, emit_job
from app.models import Asset, Job, User, new_id
from app.schemas.assets import AssetPatch
from app.adapters.storage import confined, file_thread, safe_file
from app.domain.video_generation import (
H3_PROFILES,
defaults as video_defaults,
required_output_frames,
)
async def owned_asset(session, asset_id, owner_id, *, include_deleted=False):
query = select(Asset).where(
Asset.id == asset_id,
Asset.owner_id == owner_id,
Asset.library_scope == "private",
Asset.ready.is_(True),
)
if not include_deleted:
query = query.where(Asset.deleted_at.is_(None))
asset = await session.scalar(query.with_for_update())
if asset is None:
fail(404, "asset_not_found", "素材不存在")
return asset
async def touch_source_job(session, asset):
if asset.source_job_id:
source = await session.scalar(
select(Job).where(
Job.id == asset.source_job_id,
Job.owner_id == asset.owner_id,
Job.deleted_at.is_(None),
)
)
if source is not None:
await emit_job(session, source)
async def build_asset(settings, owner_id, asset_id, path, name, **fields):
from app.adapters.media import inspect_media, make_thumbnail
path = confined(settings.asset_root, path, exists=True)
metadata = await inspect_media(path, settings)
def hash_file():
digest = hashlib.sha256()
with safe_file(settings.asset_root, path) as source:
while chunk := source.read(1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
digest = await asyncio.to_thread(hash_file)
thumbnail = await make_thumbnail(path, path.with_name("thumbnail.jpg"), settings)
return Asset(
id=asset_id,
owner_id=owner_id,
name=name[:255],
storage_key=path.relative_to(settings.asset_root).as_posix(),
thumbnail_key=Path(thumbnail).relative_to(settings.asset_root).as_posix()
if thumbnail
else None,
kind=metadata["kind"],
mime_type=metadata["mime_type"],
size_bytes=path.stat().st_size,
sha256=digest,
width=metadata.get("width"),
height=metadata.get("height"),
duration_seconds=metadata.get("duration_seconds"),
tags=[],
favorite=False,
**fields,
)
async def validate_workflow_output(job, source, settings, *, run_kind="legacy", output_index=None):
if job.task_type == "video.generate" and job.parameters.get("profile") in H3_PROFILES:
from app.adapters.media import inspect_video_track
# H3公开帧数就是裁剪后的真实输出,普通单任务也必须复核,不能把native多余帧入库。
p = video_defaults(job.parameters["profile"]) | job.parameters
if output_index is not None and output_index not in ({0, 1} if p["upscale"] else {0}):
raise ValueError("H3 output index differs from frozen generation stages")
raw = p["upscale"] and output_index == 0
dims = (
(p["width"], p["height"])
if raw or not p["upscale"]
else (p["upscale_width"], p["upscale_height"])
)
track = await inspect_video_track(source, settings)
if (
track["frames"] != p["num_frames"]
or track["fps"] != 24
or (track["width"], track["height"]) != dims
):
raise ValueError("H3 output differs from frozen actual frame count or video dimensions")
return
if job.task_type == "video.replace":
from app.services.video_editing import validate_video_output
await validate_video_output(job, source, settings)
candidate = (job.request_key or "").startswith("candidate:")
if candidate and job.task_type == "video.generate":
from app.adapters.media import inspect_video_track
track = await inspect_video_track(source, settings)
p = job.parameters
dims = (
(p["upscale_width"], p["upscale_height"])
if p.get("upscale")
else (p["width"], p["height"])
)
if (
track["frames"] < required_output_frames(p)
or track["fps"] != 24
or (track["width"], track["height"]) != dims
):
raise ValueError("Candidate video does not meet frozen decoded video specification")
if job.run_id and job.step_key != "compose" and (job.task_type == "video.generate"):
from app.adapters.media import inspect_video_track
source_frames = job.parameters.get("num_frames", 121)
if not isinstance(source_frames, int) or isinstance(source_frames, bool):
raise ValueError("Workflow shot does not meet frozen decoded video specification")
auto = run_kind in {"story_auto", "workflow_auto"}
required = (
required_output_frames(job.parameters)
if auto
else max(120, required_output_frames(job.parameters))
)
if auto and (source_frames < 2 or job.parameters.get("fps", 24) != 24):
raise ValueError("Workflow shot does not meet frozen decoded video specification")
# 自动编排按该 Job 冻结的 native/upscale 输出验证;旧运行保留120帧兼容下限。
dims = (job.parameters.get("upscale_width"), job.parameters.get("upscale_height"))
if auto and not job.parameters.get("upscale"):
dims = (job.parameters.get("width"), job.parameters.get("height"))
track = await inspect_video_track(source, settings)
if (
track["frames"] < required
or track["fps"] != 24
or (track["width"], track["height"]) != dims
):
raise ValueError("Workflow shot does not meet frozen decoded video specification")
async def import_output(db, settings, job, source, index, *, execution_fence=None):
async with db.session() as session:
current = await session.scalar(
select(Job).where(
Job.id == job.id, Job.owner_id == job.owner_id, Job.deleted_at.is_(None)
)
)
if current is None:
raise ValueError("Archived job cannot import output")
job = current
run_kind = "legacy"
if job.run_id:
from app.models import WorkflowRun
run_kind = (
await session.scalar(
select(WorkflowRun.run_kind).where(
WorkflowRun.id == job.run_id, WorkflowRun.owner_id == job.owner_id
)
)
or "legacy"
)
existing = await session.scalar(
select(Asset).where(Asset.source_job_id == job.id, Asset.source_output_index == index)
)
if existing:
if execution_fence:
from app.models import AssetReference
binding = await session.scalar(
select(AssetReference.id).where(
AssetReference.asset_id == existing.id,
AssetReference.ref_kind == "execution",
AssetReference.ref_id == execution_fence["execution_id"],
)
)
if not binding:
raise ValueError("Output belongs to a different execution")
if existing:
from app.services.artifacts import digest_file
path = confined(settings.asset_root, existing.storage_key, exists=True)
with safe_file(settings.asset_root, path):
pass
if path.stat().st_size != existing.size_bytes or digest_file(path) != existing.sha256:
raise ValueError("Imported artifact is missing or corrupt")
await validate_workflow_output(job, path, settings, run_kind=run_kind, output_index=index)
return existing
asset_id = new_id()
source = confined(settings.job_work_root, source, exists=True)
if source.stat().st_size > settings.max_output_bytes:
raise ValueError(
"Output exceeds reserved asset limit; retained for operator reconciliation"
)
await validate_workflow_output(job, source, settings, run_kind=run_kind, output_index=index)
directory = confined(settings.asset_root, Path(job.owner_id) / asset_id)
directory.mkdir(parents=True)
suffix = (
source.suffix.lower()
if re.fullmatch("\\.[a-z0-9]{1,10}", source.suffix.lower())
else ".bin"
)
destination = directory / ("original" + suffix)
def copy():
with safe_file(settings.job_work_root, source) as src, destination.open("xb") as dst:
shutil.copyfileobj(src, dst, 1024 * 1024)
try:
await file_thread(copy)
asset = await build_asset(
settings,
job.owner_id,
asset_id,
destination,
source.name,
origin="generated",
source_job_id=job.id,
source_upstream_id=job.upstream_id,
source_output_index=index,
ready=False,
)
async with db.session() as session:
current = await session.scalar(
select(Job).where(
Job.id == job.id, Job.owner_id == job.owner_id, Job.deleted_at.is_(None)
)
)
if current is None:
raise ValueError("Archived job cannot import output")
if execution_fence:
from app.services.orchestration.executions import gpu_publication_matches
current = await session.get(Job, job.id)
if not await gpu_publication_matches(session, current, execution_fence):
raise ValueError("Stale GPU result import")
from app.services.quotas import enforce_owner_asset_budget
await enforce_owner_asset_budget(session, settings, job.owner_id, asset.size_bytes)
session.add(asset)
await session.flush()
from app.services.folders import add_asset_folder
await add_asset_folder(session, asset, current.output_folder_id, allow_missing=True)
if execution_fence:
from app.models import AssetReference
session.add(
AssetReference(
owner_id=job.owner_id,
asset_id=asset.id,
ref_kind="execution",
ref_id=execution_fence["execution_id"],
)
)
await session.commit()
return asset
except BaseException:
raise
async def upload(
runtime,
file=None,
name: str | None = None,
actor: Actor = None,
content_length="0",
folder_id=None,
):
from app.services.user_deletion import owner_upload
try:
async with owner_upload(runtime, actor.id):
return await _upload(runtime, file, name, actor, content_length, folder_id)
finally:
await file.close()
async def _upload(
runtime,
file=None,
name: str | None = None,
actor: Actor = None,
content_length="0",
folder_id=None,
):
settings = runtime.settings
from app.core.maintenance import require_writable
from app.services.quotas import check_storage_budget
require_writable(settings)
async with runtime.db.session() as session:
from app.services.folders import owned_folder
if folder_id:
await owned_folder(session, folder_id, actor.id, lock=True)
await check_storage_budget(
session,
settings,
actor.id,
min(
max(0, int(content_length))
if content_length.isdigit()
else settings.max_upload_bytes,
settings.max_upload_bytes,
),
)
asset_id = new_id()
directory = confined(settings.asset_root, Path(actor.id) / asset_id)
directory.mkdir(parents=True)
original_name = (file.filename or "素材").replace("\\", "/").rsplit("/", 1)[-1]
suffix = Path(original_name).suffix.lower()
if not re.fullmatch("\\.[a-z0-9]{1,10}", suffix):
suffix = ".bin"
path, size = (directory / ("original" + suffix), 0)
commit_started = False
try:
with path.open("xb") as output:
while chunk := (await file.read(1024 * 1024)):
size += len(chunk)
if size > settings.max_upload_bytes:
fail(413, "upload_too_large", "文件超过上传大小限制")
output.write(chunk)
if not size:
fail(422, "empty_upload", "文件不能为空")
asset = await build_asset(
settings, actor.id, asset_id, path, name or original_name or "素材", origin="upload"
)
if asset.kind not in {"image", "video", "audio"}:
fail(422, "unsupported_upload", "上传仅支持图片、视频或音频")
async with runtime.db.session() as session:
from app.services.quotas import enforce_owner_asset_budget
owner = await session.scalar(select(User).where(User.id == actor.id).with_for_update())
if owner is None or owner.disabled:
fail(403, "owner_disabled", "账号已停用,上传未保存")
await enforce_owner_asset_budget(session, settings, actor.id, asset.size_bytes)
session.add(asset)
await session.flush()
from app.services.folders import assign_asset_folders
await assign_asset_folders(session, asset, [folder_id] if folder_id else [])
commit_started = True
emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)})
await session.commit()
return asset_dto(asset)
except BaseException as exc:
if not commit_started:
shutil.rmtree(directory, ignore_errors=True)
if hasattr(exc, "code") and hasattr(exc, "message"):
fail(422, exc.code, exc.message)
raise
finally:
await file.close()
async def list_assets(
runtime,
page: int = 1,
page_size: int = 24,
kind: str = "",
q: str = "",
tag: str = "",
favorite: bool | None = None,
origin: str = "",
actor: Actor = None,
folder_id: str = "",
):
if page < 1 or not 1 <= page_size <= 100:
fail(422, "invalid_page", "分页参数无效")
async with runtime.db.session() as session:
query = select(Asset).where(
Asset.owner_id == actor.id,
Asset.library_scope == "private",
Asset.origin != "normalized",
Asset.deleted_at.is_(None),
Asset.ready.is_(True),
)
from app.services.folders import folder_filter
query = query.where(await folder_filter(session, Asset, actor.id, folder_id))
if kind:
query = query.where(Asset.kind == kind)
if q:
query = query.where(Asset.name.contains(q[:255], autoescape=True))
from app.models import AssetTag
if favorite is not None:
query = query.where(Asset.favorite == favorite)
if origin:
query = query.where(Asset.origin == origin)
if tag:
query = query.where(
Asset.id.in_(
select(AssetTag.asset_id).where(
AssetTag.owner_id == actor.id, AssetTag.tag == tag
)
)
)
total = await session.scalar(select(func.count()).select_from(query.subquery()))
rows = (
await session.scalars(
query.order_by(Asset.created_at.desc(), Asset.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
).all()
return {
"items": [asset_dto(a) for a in rows],
"total": total,
"page": page,
"page_size": page_size,
}
async def get_asset(asset_id: str, runtime, actor: Actor = None):
async with runtime.db.session() as session:
return asset_dto(await owned_asset(session, asset_id, actor.id))
async def patch_asset(asset_id: str, body: AssetPatch, runtime, actor: Actor = None):
async with runtime.db.session() as session:
asset = await owned_asset(session, asset_id, actor.id)
if body.folder_ids is not None:
from app.services.folders import assign_asset_folders
await assign_asset_folders(session, asset, body.folder_ids)
if body.name is not None:
asset.name = body.name.strip() or asset.name
if body.tags is not None:
if any((not tag.strip() or len(tag) > 64 for tag in body.tags)):
fail(422, "invalid_tag", "标签须为 1–64 个字符")
asset.tags = list(dict.fromkeys((tag.strip() for tag in body.tags)))
from app.models import AssetTag
await session.execute(delete(AssetTag).where(AssetTag.asset_id == asset.id))
session.add_all(
(AssetTag(owner_id=actor.id, asset_id=asset.id, tag=tag) for tag in asset.tags)
)
if body.favorite is not None:
asset.favorite = body.favorite
emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)})
await touch_source_job(session, asset)
await session.commit()
return asset_dto(asset)
async def delete_asset(asset_id: str, runtime, actor: Actor = None):
async with runtime.db.session() as session:
asset = await owned_asset(session, asset_id, actor.id, include_deleted=True)
from app.services.asset_deletion import remove_asset
from app.models import Submission
await remove_asset(session, runtime.settings, asset)
await session.execute(
update(Submission)
.where(
Submission.owner_id == actor.id,
Submission.status != "purged",
Submission.resource_json["asset_id"].as_string() == asset.id,
)
.values(status="purged")
)
emit_asset(session, actor.id, "asset.deleted", {"id": asset.id})
await touch_source_job(session, asset)
await session.commit()
return None