cmvr-visual/inference/llm_services/video_edit/replace.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
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.
2026-11-14 14:07:26 +08:00

155 lines
5.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Temporal WanAnimate replacement, followed by exact visible-region protection."""
from .tracking import composite
def conditioning(inputs, actor):
return {
"prompt": "\n".join(
p for p in (inputs["prompt"], actor.get("prompt", "")) if p
),
"negative_prompt": inputs.get("negative_prompt", ""),
"reference_path": actor["image_path"],
}
def replace_people(inputs, parameters, manifest, private, target, model_dir):
import numpy as np
import torch
from PIL import Image, ImageFilter
from .protocol import sha256
from .temporal import generate_windows, pipeline_class
count = manifest["video"]["frames"]
width = manifest["video"]["width"]
height = manifest["video"]["height"]
source = private / "frames"
target.mkdir()
for index in range(count):
# 独立输出目录:后续人物基于上个人物合成结果,不能覆盖前一人物替换。
Image.open(source / f"{index:06d}.png").save(target / f"{index:06d}.png")
pipe = pipeline_class().from_pretrained(
model_dir, torch_dtype=torch.bfloat16, local_files_only=True
)
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()
mappings = []
for actor in inputs["replacements"]:
person = actor["person_id"]
spec = conditioning(inputs, actor)
folder = private / person
with Image.open(spec["reference_path"]) as ref:
reference = ref.convert("RGB").copy()
generator = torch.Generator(device="cpu").manual_seed(parameters["seed"])
def generate(
start,
end,
previous,
folder=folder,
reference=reference,
spec=spec,
generator=generator,
):
pose = []
face = []
masks = []
background = []
for index in range(start, end):
frame = Image.open(target / f"{index:06d}.png").convert("RGB")
mask_path = folder / "mask" / f"{index:06d}.png"
mask = (
Image.open(mask_path).convert("L")
if mask_path.exists()
else Image.new("L", (width, height))
)
if parameters["mask_expand_pixels"]:
mask = mask.filter(
ImageFilter.MaxFilter(parameters["mask_expand_pixels"] * 2 + 1)
)
# 模型可看扩展边缘,最终合成仍严格限制在原始可见mask内。
masks.append(mask)
background.append(
Image.fromarray(
np.where(
np.asarray(mask)[..., None] > 0, 0, np.asarray(frame)
).astype("uint8")
)
)
pose_path = folder / "pose" / f"{index:06d}.png"
face_path = folder / "face" / f"{index:06d}.png"
pose.append(
Image.open(pose_path).convert("RGB")
if pose_path.exists()
else Image.new("RGB", (width, height))
)
face.append(
Image.open(face_path).convert("RGB")
if face_path.exists()
else Image.new("RGB", (512, 512))
)
pipe.carried_frame = None
if previous is not None:
pixels = (
np.asarray(previous.convert("RGB"), dtype="float32") / 127.5 - 1
)
pipe.carried_frame = torch.from_numpy(pixels).permute(2, 0, 1)[
None, :, None
]
# Native Wan requires >=2 conditioning frames. Padding is removed
# before assembly; it never changes source duration/frame count.
if end - start == 1:
for sequence in (pose, face, masks, background):
sequence.append(sequence[-1])
generated = pipe(
image=reference,
pose_video=pose,
face_video=face,
background_video=background,
mask_video=masks,
mode="replace",
prompt=spec["prompt"],
negative_prompt=spec["negative_prompt"],
height=height,
width=width,
segment_frame_length=77,
motion_encode_batch_size=8,
num_inference_steps=parameters["num_inference_steps"],
guidance_scale=parameters["guidance_scale"],
generator=generator,
output_type="pil",
).frames[0]
pipe.carried_frame = None
return generated[: end - start]
for index, generated_frame in generate_windows(count, generate):
current = np.asarray(Image.open(target / f"{index:06d}.png").convert("RGB"))
mask_path = folder / "mask" / f"{index:06d}.png"
visible = (
np.asarray(Image.open(mask_path)) > 0
if mask_path.exists()
else np.zeros((height, width), bool)
)
protected = np.zeros_like(visible)
for other in manifest["people"]:
other_path = private / other / "mask" / f"{index:06d}.png"
if other != person and other_path.exists():
protected |= np.asarray(Image.open(other_path)) > 0
result = composite(
current,
np.asarray(generated_frame.convert("RGB")),
visible,
protected,
parameters["mask_feather_pixels"],
)
Image.fromarray(result).save(target / f"{index:06d}.png")
mappings.append(
{
"person_id": person,
"reference_sha256": sha256(spec["reference_path"]),
"prompt": spec["prompt"],
}
)
return mappings