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

214 lines
9.4 KiB
Python
Raw Normal View History

"""Per-detection ViTPose and temporal multi-object SAM2 (never single-person wrapper)."""
import os
import sys
from pathlib import Path
from types import SimpleNamespace
from .tracking import Tracker, iou
def prepare_detector_frame(detector, frame_rgb):
# 官方read_img将ndarray视为BGR并反转通道;PIL解码原图始终保持RGB
# 给ViTPose/人脸裁剪,只对检测入口提供BGR视图,避免红蓝互换。
return detector.preprocess(frame_rgb[..., ::-1])
def load_cpu_pose_models(checkpoint_dir):
"""Create both official ONNX wrappers with explicit per-job CPU pools."""
value = os.environ.get("OMP_NUM_THREADS", "2")
if not value.isascii() or not value.isdigit() or not 1 <= int(value) <= 64:
raise ValueError("OMP_NUM_THREADS must be an ASCII integer in [1, 64]")
threads = int(value)
import pose2d
original = pose2d.onnxruntime
def bounded_session(checkpoint, *, providers):
if providers != ["CPUExecutionProvider"]:
raise ValueError("Video preprocessing requires CPU ONNX sessions")
options = original.SessionOptions()
options.intra_op_num_threads = threads
options.inter_op_num_threads = 1
options.execution_mode = original.ExecutionMode.ORT_SEQUENTIAL
options.add_session_config_entry("session.intra_op.allow_spinning", "0")
options.add_session_config_entry("session.inter_op.allow_spinning", "0")
return original.InferenceSession(
checkpoint, sess_options=options, providers=providers
)
# 官方封装不传SessionOptions,ORT默认池不遵守OMP预算。只在本job
# 单线程初始化期间替换pose2d的模块局部引用;不改上游文件或全局ORT。
# 两个session停用空闲自旋,避免未运行的模型池占用当前模型CPU配额。
pose2d.onnxruntime = SimpleNamespace(InferenceSession=bounded_session)
try:
checkpoint_dir = Path(checkpoint_dir)
detector = pose2d.Yolo(
str(checkpoint_dir / "det/yolov10m.onnx"), device="cpu", threshold_conf=0.35
)
pose = pose2d.ViTPose(
str(checkpoint_dir / "pose2d/vitpose_h_wholebody.onnx/end2end.onnx"),
device="cpu",
)
return detector, pose
finally:
pose2d.onnxruntime = original
def analyze_frames(frames_dir, private, video, deployment, max_people):
import numpy as np
from PIL import Image
sys.path.insert(0, deployment["preprocess_dir"])
from human_visualization import draw_aapose_by_meta_new
from pose2d_utils import AAPoseMeta, load_pose_metas_from_kp2ds_seq
from sam2.build_sam import build_sam2_video_predictor
from utils import get_face_bboxes
ckpt = Path(deployment["checkpoint_dir"])
# ORT can allocate outside the PyTorch cap. CPU sessions keep the exact same
# detector/pose weights while reserving CUDA exclusively for supervised SAM.
detector, pose = load_cpu_pose_models(ckpt)
tracker = Tracker()
people = {}
tracks = []
for index in range(video["frames"]):
frame = np.asarray(Image.open(frames_dir / f"{index:06d}.png").convert("RGB"))
tensor, shape = prepare_detector_frame(detector, frame)
raw = detector.session.run(None, {detector.input_name: tensor[None]})[0]
detections = detector.postprocess(raw[0], shape)
boxes = [row[:4] for row in detections if int(row[-1]) == 0 and row[-2] >= 0.35]
tracked = tracker.update(boxes)
if len(tracked) > max_people:
raise ValueError("Detected people exceed configured budget")
tracks.append({p: list(map(float, b)) for p, b in tracked.items()})
for person, box in tracked.items():
directory = private / person
if person not in people:
directory.mkdir()
(directory / "pose").mkdir()
(directory / "face").mkdir()
(directory / "mask").mkdir()
people[person] = {
"first_frame": index,
"last_frame": index,
"boxes": [],
"confidence": 1.0,
}
people[person]["last_frame"] = index
score = max(
float(row[-2]) for row in detections if iou(row[:4], box) > 0.99
)
people[person]["confidence"] = min(people[person]["confidence"], score)
people[person]["boxes"].append([index, list(map(float, box))])
crop, center, scale = pose.preprocess(frame, np.array([*box, 1.0]))
kp = pose(crop[None], center[None], scale[None])
meta = load_pose_metas_from_kp2ds_seq(
kp, width=video["width"], height=video["height"]
)[0]
canvas = draw_aapose_by_meta_new(
np.zeros_like(frame), AAPoseMeta.from_humanapi_meta(meta)
)
Image.fromarray(canvas).save(directory / "pose" / f"{index:06d}.png")
x1, x2, y1, y2 = get_face_bboxes(
meta["keypoints_face"][:, :2], scale=1.3, image_shape=frame.shape[:2]
)
if x2 <= x1 or y2 <= y1:
raise ValueError("Person face conditioning cannot be located reliably")
Image.fromarray(frame[y1:y2, x1:x2]).resize((512, 512)).save(
directory / "face" / f"{index:06d}.png"
)
if not people:
raise ValueError("No people detected in source video")
del pose, detector
predictor = build_sam2_video_predictor(
"configs/sam2/sam2_hiera_l.yaml",
str(ckpt / "sam2/sam2_hiera_large.pt"),
device="cuda",
)
segment_people(predictor, frames_dir, private, video, tracks, people)
return people
def segment_people(predictor, frames_dir, private, video, tracks, people):
"""Run actual bounded SAM propagation; predictor is supplied by the GPU stage."""
import numpy as np
import torch
from PIL import Image
if not people or not any(tracks):
raise ValueError("No people detected in source video")
previous = {}
# 77-frame bounded windows avoid loading a 120-second clip into SAM GPU/RAM.
for start in range(0, video["frames"], 77):
end = min(start + 77, video["frames"])
if not any(tracks[start:end]):
# 无人窗口无需SAM提示/传播;原帧不改写,旧mask不能跨空段复用。
previous = {}
continue
segment = private / f"sam-{start}"
segment.mkdir()
for index in range(start, end):
Image.open(frames_dir / f"{index:06d}.png").convert("RGB").save(
segment / f"{index - start:06d}.jpg", quality=98
)
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
state = predictor.init_state(
str(segment), offload_video_to_cpu=True, offload_state_to_cpu=True
)
ids = {p: int(p.split("_")[1]) for p in people}
seeded = set()
next_previous = {}
for index in range(start, end):
for person, box in tracks[index].items():
if person in seeded:
continue
seeded.add(person)
if index == start and person in previous:
predictor.add_new_mask(
state,
frame_idx=0,
obj_id=ids[person],
mask=previous[person],
)
else:
# 本窗口首次可见时重新用当前框提示,不能借用非相邻帧mask。
predictor.add_new_points_or_box(
state,
frame_idx=index - start,
obj_id=ids[person],
box=np.array(box),
)
for local, object_ids, logits in predictor.propagate_in_video(state):
index = start + local
scores = logits[:, 0].float().cpu().numpy()
for position, object_id in enumerate(object_ids):
if f"person_{object_id:04d}" not in tracks[index]:
scores[position] = -float("inf")
winners = scores.argmax(axis=0)
for position, object_id in enumerate(object_ids):
person = f"person_{object_id:04d}"
mask = (scores[position] > 0) & (winners == position)
if person in tracks[index]:
yy, xx = np.nonzero(mask)
if (
not len(xx)
or iou(
(xx.min(), yy.min(), xx.max() + 1, yy.max() + 1),
tracks[index][person],
)
< 0.15
):
raise ValueError("SAM tracking ambiguous or lost person")
Image.fromarray(mask.astype("uint8") * 255).save(
private / person / "mask" / f"{index:06d}.png"
)
if index == end - 1 and person in tracks[index]:
next_previous[person] = mask
previous = next_previous
predictor.reset_state(state)
for file in segment.iterdir():
file.unlink()
segment.rmdir()
return people