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_NATIVE_AV_PROFILES, H3_NATIVE_AV_TP2_PROFILE, 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, ) def native_av_output_indices(job, outputs=None): """原生音视频的两份最终产物缺一不可,不能套用旧静音/增强视频的索引规则。""" if ( job.task_type != "video.generate" or job.parameters.get("profile") not in H3_NATIVE_AV_PROFILES ): return None import math from app.services.orchestration.executions import gpu_result result = gpu_result(job) outputs = result.get("outputs") if outputs is None else outputs metadata = result.get("metadata", {}) if not isinstance(metadata, dict): raise ValueError("Native AV metadata is missing") p = video_defaults(job.parameters["profile"]) | job.parameters indices = metadata.get("final_output_indices") if "final_output_indices" not in metadata: from app.adapters.provider.native_av import TP2_RUNTIME_REVISION reported = metadata.get("parameters") parallelism = metadata.get("parallelism") # 已完成的旧TP2 runner漏写索引。只在已知引擎/固定版本/完整冻结参数均一致时推导; # 下方仍核对完整原声音频回执,每份文件仍实际解码,不改写历史结果或执行摘要。 if ( p["profile"] == metadata.get("profile") == H3_NATIVE_AV_TP2_PROFILE and metadata.get("engine") == "diffusers-modular-tp2" and metadata.get("diffusers_source_revision") == TP2_RUNTIME_REVISION and isinstance(parallelism, dict) and type(parallelism.get("tensor_parallel_degree")) is int and parallelism["tensor_parallel_degree"] == 2 and isinstance(reported, dict) and all( key in reported and type(reported[key]) is type(p[key]) and reported[key] == p[key] for key in ( "profile", "num_frames", "fps", "width", "height", "seed", "num_inference_steps", "upscale", "conditioning_mode", ) ) ): indices = [0, 1] if ( not isinstance(outputs, list) or len(outputs) != 2 or not isinstance(indices, list) or indices != [0, 1] or any(type(i) is not int for i in indices) ): raise ValueError("Native AV requires exactly the final MP4 and complete WAV at indices 0,1") paths = [item.get("path", "") if isinstance(item, dict) else item for item in outputs] if any(not isinstance(path, str) for path in paths) or [ Path(path).suffix.lower() for path in paths ] != [".mp4", ".wav"]: raise ValueError("Native AV final outputs must be MP4 followed by PCM WAV") if "profile" in metadata and metadata["profile"] != p["profile"]: raise ValueError("Native AV reported profile differs from frozen job") if "requested_frames" in metadata and ( type(metadata["requested_frames"]) is not int or metadata["requested_frames"] != p["num_frames"] ): raise ValueError("Native AV reported interval differs from frozen job") if "parameters" in metadata: reported = metadata["parameters"] if not isinstance(reported, dict) or any( key in reported and (type(reported[key]) is not type(p[key]) or reported[key] != p[key]) for key in ("profile", "num_frames", "fps", "width", "height", "seed", "upscale") ): raise ValueError("Native AV reported parameters differ from frozen job") maximum = 158 if p["profile"] == H3_NATIVE_AV_TP2_PROFILE else 345 report = metadata.get("native_av") if ( type(p["num_frames"]) is not int or p["num_frames"] not in range(124, maximum + 1, 17) or p["upscale"] is not False or not isinstance(report, dict) ): raise ValueError("Native AV frozen frame interval or audio receipt is invalid") integers = dict( sample_rate=32000, channels=2, video_frames=p["num_frames"], fps=24, start_sample=0 ) if any(type(report.get(k)) is not int or report[k] != v for k, v in integers.items()): raise ValueError("Native AV metadata differs from frozen full-native output") samples = report.get("audio_samples") if ( type(samples) is not int or samples <= 0 or type(report.get("end_sample")) is not int or report["end_sample"] != samples or report.get("output_policy") != "full_native" or report.get("audio_trimmed") is not False or report.get("audio_format") != "pcm_s16le" or abs(samples / 32000 - p["num_frames"] / 24) > 1 / 80 + 1 / 32000 ): raise ValueError("Native AV complete audio interval is missing or truncated") actual = dict( audio_duration=samples / 32000, video_duration=p["num_frames"] / 24, av_duration_delta=samples / 32000 - p["num_frames"] / 24, ) if any( type(report.get(k)) not in (int, float) or not math.isfinite(report[k]) or abs(report[k] - v) > 1e-8 for k, v in actual.items() ): raise ValueError("Native AV duration receipt does not match sample/frame counts") return [0, 1] async def validate_native_av_output(job, source, settings, output_index): import json import wave from app.adapters.media import input_options, inspect_video_track, run_process from app.services.orchestration.executions import gpu_result native_av_output_indices(job) p = video_defaults(job.parameters["profile"]) | job.parameters if type(output_index) is not int or output_index not in (0, 1): raise ValueError("Native AV output index must identify MP4 or complete PCM WAV") if output_index == 0: track = await inspect_video_track(source, settings) if (track["frames"], track["fps"], track["width"], track["height"]) != ( p["num_frames"], 24, p["width"], p["height"], ): raise ValueError("Native AV video differs from frozen frames, fps or canvas") raw = await run_process( [ settings.ffprobe_bin, "-v", "error", *input_options(), "-show_entries", "format=format_name:stream=codec_type,sample_rate,channels", "-of", "json", str(source), ], timeout=30, max_output=256 * 1024, ) try: data = json.loads(raw) audios = [s for s in data["streams"] if s.get("codec_type") == "audio"] videos = [s for s in data["streams"] if s.get("codec_type") == "video"] if ( "mov" not in data["format"]["format_name"].split(",") or len(audios) != 1 or len(videos) != 1 or int(audios[0]["sample_rate"]) != 32000 or audios[0]["channels"] != 2 ): raise ValueError() except (ValueError, TypeError, KeyError, IndexError): raise ValueError("Native AV MP4 must contain its original stereo audio track") from None return try: with wave.open(str(source), "rb") as wav: samples = wav.getnframes() if (wav.getframerate(), wav.getnchannels(), wav.getsampwidth(), wav.getcomptype()) != ( 32000, 2, 2, "NONE", ): raise ValueError() expected = gpu_result(job)["metadata"]["native_av"]["audio_samples"] if samples != expected or len(wav.readframes(samples)) != samples * 4: raise ValueError() except (OSError, wave.Error, EOFError, ValueError): raise ValueError( "Native AV sidecar must preserve every 32kHz stereo PCM16 sample" ) from None 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_NATIVE_AV_PROFILES: await validate_native_av_output(job, source, settings, output_index) return 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