cmvr-visual/inference/llm_services/video_edit/protocol.py

133 lines
4.6 KiB
Python
Raw Normal View History

"""Strict remote wire protocol and immutable analysis bindings."""
import hashlib
import json
import re
from pathlib import Path
PROFILE = "wan-animate-replace-v1"
TASKS = {"video.people.analyze", "video.replace"}
def sha256(path):
digest = hashlib.sha256()
with Path(path).open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def verify_binding(binding, *, principal, source_sha256, manifest_sha256):
expected = {
"principal": principal,
"source_sha256": source_sha256,
"profile": PROFILE,
"manifest_sha256": manifest_sha256,
}
if any(binding.get(k) != v for k, v in expected.items()):
raise ValueError(
"Analysis binding does not match principal, source, profile or manifest"
)
def token(binding):
# Manifest is private and the queue checks analysis success; this digest is not authorization.
return hashlib.sha256(
json.dumps(binding, sort_keys=True, separators=(",", ":")).encode()
).hexdigest()
def validate(task, inputs, parameters, workspace):
from ..runner import _integer, _number, confined_path
allowed = {"video_path"}
if task == "video.replace":
allowed |= {
"analysis_id",
"analysis_token",
"prompt",
"negative_prompt",
"replacements",
}
if set(inputs) - allowed:
raise ValueError("Unknown video input field")
result = dict(inputs)
result["video_path"] = str(
confined_path(inputs.get("video_path"), workspace, exists=True)
)
p = {"profile": PROFILE, "fps": 24, "max_pixels": 399360}
if task == "video.replace":
p.update(
num_inference_steps=20,
guidance_scale=1.0,
seed=42,
preserve_audio=True,
mask_expand_pixels=8,
mask_feather_pixels=4,
)
for name in ("analysis_id", "analysis_token"):
if not isinstance(inputs.get(name), str) or not re.fullmatch(
r"[a-zA-Z0-9_-]{1,128}", inputs[name]
):
raise ValueError("Invalid " + name)
for name in ("prompt", "negative_prompt"):
value = inputs.get(name, "")
if (
not isinstance(value, str)
or len(value) > 8000
or (name == "prompt" and not value.strip())
):
raise ValueError("Invalid " + name)
result[name] = value
replacements = inputs.get("replacements")
if not isinstance(replacements, list) or not replacements:
raise ValueError("At least one replacement is required")
seen = set()
result["replacements"] = []
for item in replacements:
if not isinstance(item, dict) or set(item) - {
"person_id",
"image_path",
"prompt",
}:
raise ValueError("Invalid replacement")
person = item.get("person_id")
if not isinstance(person, str) or not re.fullmatch(
r"person_\d{4,}", person
):
raise ValueError("Invalid person_id")
if person in seen:
raise ValueError("Duplicate person_id")
seen.add(person)
prompt = item.get("prompt", "")
if not isinstance(prompt, str) or len(prompt) > 8000:
raise ValueError("Invalid actor prompt")
result["replacements"].append(
{
"person_id": person,
"prompt": prompt,
"image_path": str(
confined_path(item.get("image_path"), workspace, exists=True)
),
}
)
if set(parameters) - set(p):
raise ValueError("Unknown video parameter")
p.update(parameters)
if (
p["profile"] != PROFILE
or type(p["fps"]) is not int
or p["fps"] != 24
or p["max_pixels"] not in (399360, 921600)
):
raise ValueError("Unsupported video profile, fps or pixel budget")
if task == "video.replace":
_integer(p["num_inference_steps"], "steps", 1, 100)
_integer(p["seed"], "seed", 0, 2**32 - 1)
p["guidance_scale"] = _number(p["guidance_scale"], "guidance", 1, 20)
for name in ("mask_expand_pixels", "mask_feather_pixels"):
_integer(p[name], name, 0, 64)
if type(p["preserve_audio"]) is not bool:
raise ValueError("preserve_audio must be boolean")
return result, p