"""Entrypoint executed only inside the worker-owned GPU process tree.""" import json import os from pathlib import Path from .media import decode, mux from .profiles import deployment from .protocol import PROFILE, sha256, token, verify_binding def run(request): from PIL import Image from ..store import Settings, atomic_json, confined_path, open_confined_file settings = Settings.from_env() receipt = deployment(settings, verify=True) output = Path(request["output_dir"]) inputs = request["input"] parameters = request["parameters"] identity = os.environ.get("VIDEO_EDIT_PRINCIPAL") if not identity: raise ValueError("Missing trusted worker principal") digest = sha256(inputs["video_path"]) if request["task_type"] == "video.people.analyze": from .preprocess import analyze_frames private = output / ".private" private.mkdir(mode=0o700) video = decode( inputs["video_path"], private / "frames", parameters["max_pixels"], settings.video_edit_max_seconds, ) people = analyze_frames( private / "frames", private, video, receipt, settings.video_edit_max_people ) manifest = { "profile": PROFILE, "source_sha256": digest, "video": video, "people": people, "parameters": parameters, } # 每个派生文件均进入不可变哈希清单,拒绝mask/pose在分析后被替换。 manifest["files"] = { p.relative_to(private).as_posix(): sha256(p) for p in private.rglob("*") if p.is_file() } if sha256(inputs["video_path"]) != digest: raise ValueError("Source video changed during analysis") atomic_json(private / "manifest.json", manifest) binding = { "principal": identity, "source_sha256": digest, "profile": PROFILE, "manifest_sha256": sha256(private / "manifest.json"), } atomic_json(private / "binding.json", binding) poster = output / "poster.png" Image.open(private / "frames" / "000000.png").save(poster) outputs = [poster] previews = [] for person, track in people.items(): boxes = track["boxes"] positions = sorted({0, len(boxes) // 2, len(boxes) - 1}) samples = [ { "frame": boxes[pos][0], "bbox": [ max( 0, min( 1, v / ( video["width"] if axis % 2 == 0 else video["height"] ), ), ) for axis, v in enumerate(boxes[pos][1]) ], } for pos in positions ] index, box = boxes[len(boxes) // 2] thumbnail = output / f"{person}.png" Image.open(private / "frames" / f"{index:06d}.png").crop( tuple(map(int, box)) ).save(thumbnail) outputs.append(thumbnail) previews.append( { "id": person, "label": f"人物{len(previews) + 1}", "thumbnail_output_index": len(outputs) - 1, "first_frame": track["first_frame"], "last_frame": track["last_frame"], "confidence": track["confidence"], "samples": samples, } ) return outputs, { "profile": PROFILE, "analysis_token": token(binding), "source_sha256": digest, "video": {k: v for k, v in video.items() if k != "source_has_audio"}, "poster_output_index": 0, "people": previews, "warnings": [], } from .replace import replace_people manifest_path = confined_path( os.environ.get("VIDEO_EDIT_MANIFEST", ""), settings.workspace_root, must_exist=True, file_only=True, ) private = manifest_path.parent with open_confined_file(manifest_path, settings.workspace_root) as stream: manifest = json.load(stream) with open_confined_file( private / "binding.json", settings.workspace_root ) as stream: binding = json.load(stream) verify_binding( binding, principal=identity, source_sha256=digest, manifest_sha256=sha256(manifest_path), ) if ( token(binding) != inputs["analysis_token"] or manifest["parameters"]["max_pixels"] != parameters["max_pixels"] ): raise ValueError("Analysis token or parameters changed") for name, expected in manifest["files"].items(): file = confined_path(private / name, private, must_exist=True, file_only=True) if sha256(file) != expected: raise ValueError("Private analysis artifact integrity mismatch") if any( actor["person_id"] not in manifest["people"] for actor in inputs["replacements"] ): raise ValueError("Unknown selected person") frames = output / ".frames" mapping = replace_people( inputs, parameters, manifest, private, frames, receipt["model_dir"] ) target = output / "replacement.mp4" mux( frames, inputs["video_path"], target, manifest["video"], parameters["preserve_audio"], ) video = manifest["video"] if sha256(inputs["video_path"]) != digest: raise ValueError("Source video changed during replacement") return [target], { "profile": PROFILE, "person_ids": [a["person_id"] for a in mapping], "actor_mapping": mapping, "source_sha256": digest, "source_frames": video["frames"], "output_frames": video["frames"], "fps": 24, "width": video["width"], "height": video["height"], "duration_seconds": video["duration_seconds"], "preserve_audio": parameters["preserve_audio"], "parameters": parameters, "warnings": [], "final_output_indices": [0], }