Restructure backend and frontend modules; add story, library, and editor schema migrations. Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews. Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
189 lines
7.4 KiB
Python
189 lines
7.4 KiB
Python
"""视频编辑的纯参数与公开分析合同;不接受客户端路径或遮罩。"""
|
||
|
||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
||
from app.domain.errors import MediaError
|
||
|
||
PROFILE = "wan-animate-replace-v1"
|
||
TASKS = {"video.people.analyze", "video.replace"}
|
||
|
||
|
||
def video_capability(settings):
|
||
available = bool(getattr(settings, "video_edit_enabled", False) and settings.inference_base_url)
|
||
return {
|
||
"available": available,
|
||
"profile": getattr(settings, "video_edit_profile", PROFILE),
|
||
"model": "Wan2.2-Animate-14B",
|
||
"max_seconds": getattr(settings, "video_edit_max_seconds", 120),
|
||
"max_people": getattr(settings, "video_edit_max_people", 12),
|
||
"max_pixels": getattr(settings, "video_edit_max_pixels", 399360),
|
||
"fps": 24,
|
||
"reason": None if available else "视频编辑尚未启用或未完成模型认证。",
|
||
}
|
||
|
||
|
||
def video_defaults(task, settings):
|
||
value = {
|
||
"profile": getattr(settings, "video_edit_profile", PROFILE),
|
||
"max_pixels": 399360,
|
||
"fps": 24,
|
||
}
|
||
if task == "video.replace":
|
||
value.update(
|
||
num_inference_steps=20,
|
||
guidance_scale=1.0,
|
||
seed=42,
|
||
preserve_audio=True,
|
||
mask_expand_pixels=8,
|
||
mask_feather_pixels=4,
|
||
)
|
||
return value
|
||
|
||
|
||
def invalid(message="视频编辑输入或参数无效。"):
|
||
return MediaError("invalid_input", message)
|
||
|
||
|
||
def validate_video_arguments(task, inputs, parameters, settings):
|
||
# 参数校验也用于Provider;服务器绑定通过单独参数传递,不能混入浏览器input。
|
||
if not video_capability(settings)["available"]:
|
||
raise MediaError("capability_unavailable", "视频编辑尚未启用或未认证。")
|
||
allowed = {"video_asset_id"}
|
||
if task == "video.replace":
|
||
allowed |= {"analysis_job_id", "prompt", "negative_prompt", "replacements"}
|
||
if not isinstance(inputs, dict) or set(inputs) - allowed:
|
||
raise invalid()
|
||
for key in ("video_asset_id", "analysis_job_id"):
|
||
if (key == "video_asset_id" or task == "video.replace") and (
|
||
not isinstance(inputs.get(key), str) or not 1 <= len(inputs[key]) <= 64
|
||
):
|
||
raise invalid()
|
||
defaults = video_defaults(task, settings)
|
||
if not isinstance(parameters, dict) or set(parameters) - set(defaults):
|
||
raise invalid()
|
||
p = defaults | parameters
|
||
if (
|
||
p["profile"] != getattr(settings, "video_edit_profile", PROFILE)
|
||
or type(p["fps"]) is not int
|
||
or p["fps"] != 24
|
||
or type(p["max_pixels"]) is not int
|
||
or p["max_pixels"] not in {399360, 921600}
|
||
or p["max_pixels"] > video_capability(settings)["max_pixels"]
|
||
):
|
||
raise invalid()
|
||
if task == "video.people.analyze":
|
||
return p
|
||
for key in ("prompt", "negative_prompt"):
|
||
if not isinstance(inputs.get(key, ""), str) or len(inputs.get(key, "")) > 8000:
|
||
raise invalid()
|
||
if not inputs.get("prompt", "").strip():
|
||
raise invalid("请输入全局提示词。")
|
||
rows = inputs.get("replacements")
|
||
if not isinstance(rows, list) or not 1 <= len(rows) <= getattr(
|
||
settings, "video_edit_max_people", 12
|
||
):
|
||
raise invalid("请选择预算范围内的人物。")
|
||
seen = set()
|
||
for row in rows:
|
||
if not isinstance(row, dict) or set(row) - {"person_id", "reference_asset_id", "prompt"}:
|
||
raise invalid()
|
||
for key in ("person_id", "reference_asset_id"):
|
||
if not isinstance(row.get(key), str) or not 1 <= len(row[key]) <= 64:
|
||
raise invalid()
|
||
if row["person_id"] in seen:
|
||
raise invalid("同一人物不能重复替换。")
|
||
seen.add(row["person_id"])
|
||
if not isinstance(row.get("prompt", ""), str) or len(row.get("prompt", "")) > 8000:
|
||
raise invalid()
|
||
for key, low, high in (
|
||
("num_inference_steps", 1, 100),
|
||
("seed", 0, 2**32 - 1),
|
||
("mask_expand_pixels", 0, 64),
|
||
("mask_feather_pixels", 0, 64),
|
||
):
|
||
if type(p[key]) is not int or not low <= p[key] <= high:
|
||
raise invalid()
|
||
if (
|
||
type(p["preserve_audio"]) is not bool
|
||
or type(p["guidance_scale"]) not in {int, float}
|
||
or not 1 <= p["guidance_scale"] <= 20
|
||
):
|
||
raise invalid()
|
||
return p
|
||
|
||
|
||
class SafeModel(BaseModel):
|
||
model_config = ConfigDict(extra="ignore", strict=True, allow_inf_nan=False)
|
||
|
||
|
||
class Video(SafeModel):
|
||
width: int = Field(gt=0, le=16384)
|
||
height: int = Field(gt=0, le=16384)
|
||
fps: int = Field(ge=24, le=24)
|
||
frames: int = Field(gt=0)
|
||
duration_seconds: float = Field(gt=0)
|
||
|
||
|
||
class Sample(SafeModel):
|
||
frame: int = Field(ge=0)
|
||
bbox: list[float] = Field(min_length=4, max_length=4)
|
||
|
||
@model_validator(mode="after")
|
||
def valid_box(self):
|
||
x1, y1, x2, y2 = self.bbox
|
||
if not 0 <= x1 < x2 <= 1 or not 0 <= y1 < y2 <= 1:
|
||
raise ValueError("Invalid normalized bbox")
|
||
return self
|
||
|
||
|
||
class Person(SafeModel):
|
||
id: str = Field(pattern=r"^person_[0-9]{4,}$", max_length=64)
|
||
label: str = Field(min_length=1, max_length=128)
|
||
thumbnail_output_index: int = Field(ge=0)
|
||
first_frame: int = Field(ge=0)
|
||
last_frame: int = Field(ge=0)
|
||
confidence: float = Field(ge=0, le=1)
|
||
samples: list[Sample] = Field(min_length=1, max_length=128)
|
||
|
||
|
||
class Analysis(SafeModel):
|
||
profile: str
|
||
analysis_token: str = Field(min_length=1, max_length=512)
|
||
source_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||
video: Video
|
||
poster_output_index: int = Field(ge=0)
|
||
people: list[Person] = Field(max_length=1000)
|
||
warnings: list[str] = Field(max_length=128)
|
||
|
||
|
||
def safe_analysis(value, settings, *, output_count=None):
|
||
try:
|
||
data = Analysis.model_validate(value)
|
||
if (
|
||
data.profile != getattr(settings, "video_edit_profile", PROFILE)
|
||
or data.video.duration_seconds > getattr(settings, "video_edit_max_seconds", 120)
|
||
or len(data.people) > getattr(settings, "video_edit_max_people", 12)
|
||
):
|
||
raise ValueError("Analysis exceeds profile limits")
|
||
indexes = [data.poster_output_index] + [p.thumbnail_output_index for p in data.people]
|
||
if len(set(indexes)) != len(indexes) or len({p.id for p in data.people}) != len(
|
||
data.people
|
||
):
|
||
raise ValueError("Duplicate analysis index or person")
|
||
if output_count is not None and any(i >= output_count for i in indexes):
|
||
raise ValueError("Missing preview output")
|
||
if abs(data.video.frames - round(data.video.duration_seconds * 24)) > 1:
|
||
raise ValueError("Analysis timeline duration differs")
|
||
for p in data.people:
|
||
frames = {s.frame for s in p.samples}
|
||
if not {p.first_frame, p.last_frame} <= frames or len(frames) < min(
|
||
3, p.last_frame - p.first_frame + 1
|
||
):
|
||
raise ValueError("Analysis needs visible start/middle/end samples")
|
||
if not p.first_frame <= p.last_frame < data.video.frames or any(
|
||
not p.first_frame <= s.frame <= p.last_frame for s in p.samples
|
||
):
|
||
raise ValueError("Invalid person timing")
|
||
return data.model_dump()
|
||
except (ValidationError, ValueError, TypeError):
|
||
raise MediaError("invalid_analysis", "人物分析结果无效或已过期。") from None
|