"""Extract raw KaoLRM labels on the 30 Hz Seamless Interaction body timeline.""" import argparse import os import json from pathlib import Path import sys import cv2 import numpy as np ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from preprocess.common import load_manifest, write_manifest FPS = 30.0 CROP_MARGIN = .35 MIN_CONFIDENCE = .05 CENTER_WINDOW = 15 SIZE_WINDOW = 21 COVER_MARGIN = .10 def smooth(values, window): if len(values) <= 2: return values.astype(np.float32, copy=True) padded = np.pad(values.astype(np.float32), window // 2, mode='edge') return np.convolve(padded, np.ones(window, np.float32) / window, mode='valid').astype(np.float32) def face_measurement(keypoints): face = keypoints[23:91] good = np.isfinite(face[:, :2]).all(1) & (face[:, 2] > MIN_CONFIDENCE) if good.sum() < 8: return None low, high = face[good, :2].min(0), face[good, :2].max(0) side = float((high - low).max()) if side < 8: return None center = (low.astype(np.float64) + high) * .5 return [center[0], center[1], side * (1 + CROP_MARGIN)] def face_crops(keypoints, body_valid, width, height): """Match the original crops, interpolating missing measurements on valid body frames.""" measured = np.zeros((len(keypoints), 3), np.float32) detected = np.zeros(len(keypoints), bool) for index in np.flatnonzero(body_valid): value = face_measurement(keypoints[index]) if value is not None: measured[index] = value detected[index] = True boxes = np.full((len(keypoints), 4), -1, np.int32) if not detected.any(): return boxes, detected time = np.arange(len(keypoints), dtype=np.float32) filled = np.stack([np.interp(time, time[detected], measured[detected, dim]) for dim in range(3)], axis=1).astype(np.float32) cx, cy = smooth(filled[:, 0], CENTER_WINDOW), smooth(filled[:, 1], CENTER_WINDOW) side = smooth(filled[:, 2], SIZE_WINDOW) cover = filled[:, 2] + 2 * np.maximum(np.abs(filled[:, 0] - cx), np.abs(filled[:, 1] - cy)) side = np.maximum(side, cover) * (1 + COVER_MARGIN) window = min(SIZE_WINDOW, 15) if len(side) > 2: padded = np.pad(side, window // 2, mode='edge') side = np.lib.stride_tricks.sliding_window_view(padded, window).max(-1) side = smooth(side, window) for index in np.flatnonzero(body_valid): radius = max(8., float(side[index])) * .5 x1, y1 = max(0, round(float(cx[index]) - radius)), max(0, round(float(cy[index]) - radius)) x2, y2 = min(width, round(float(cx[index]) + radius)), min(height, round(float(cy[index]) + radius)) if x2 > x1 and y2 > y1: boxes[index] = [x1, y1, x2, y2] return boxes, detected def prepare(video, pose, max_frames=None): capture = cv2.VideoCapture(str(video)) assert capture.isOpened(), f'Cannot open {video}' fps = capture.get(cv2.CAP_PROP_FPS) frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) capture.release() assert fps > 0 and frames > 0 and width > 0 and height > 0 with np.load(pose) as data: keypoints, valid = data['boxes_and_keypoints:keypoints'], data['smplh:is_valid'] assert valid.ndim == 1 and len(valid) == len(keypoints), 'Body/keypoint timelines differ' count = len(keypoints) if max_frames is None else min(len(keypoints), max_frames) indices = np.rint(np.arange(count, dtype=np.float64) / FPS * fps).astype(np.int64) indices = np.clip(indices, 0, frames - 1) # Smooth the complete trajectory before applying a smoke-test output cap. boxes, detected = face_crops(keypoints, valid, width, height) boxes, detected = boxes[:count], detected[:count] return dict(frame_indices=indices, pose_indices=np.arange(count, dtype=np.int64), crop_boxes=boxes, face_detected=detected, source_video_fps=np.float32(fps), source_num_frames=np.int64(frames), source_pose_num_frames=np.int64(len(keypoints)), source_pose_fps=np.float32(FPS), motion_fps=np.float32(FPS)) def read_crops(video, meta): # Decode each source frame once, including when multiple target frames map to it. needed = {} for index in np.flatnonzero(meta['crop_boxes'][:, 0] >= 0): needed.setdefault(int(meta['frame_indices'][index]), []).append(index) if not needed: return capture = cv2.VideoCapture(str(video)) assert capture.isOpened() try: first, last = min(needed), max(needed) assert capture.set(cv2.CAP_PROP_POS_FRAMES, first) for source in range(first, last + 1): ok, frame = capture.read() assert ok, f'Cannot decode {video.name} frame {source}' for index in needed.get(source, []): x1, y1, x2, y2 = meta['crop_boxes'][index] yield index, frame[y1:y2, x1:x2] finally: capture.release() def extract(item, output, model, max_frames=None): pose = Path(item['pose_file']) video = Path(item.get('video_file', pose.with_suffix('.mp4'))) meta = prepare(video, pose, max_frames) count = len(meta['frame_indices']) arrays = {key: np.zeros((count, size), np.float32) for key, size in [('expression50', 50), ('pose', 6), ('shape', 100)]} arrays['valid_mask'] = np.zeros(count, bool) for index, crop in read_crops(video, meta): # Preserve the original single-frame inference kernels and numerical results. values = model.predict(crop) for key, target in [('expression', 'expression50'), ('pose', 'pose'), ('shape', 'shape')]: value = values[key] assert value.shape == arrays[target].shape[1:] and np.isfinite(value).all() arrays[target][index] = value arrays['valid_mask'][index] = True assert arrays['valid_mask'].any(), f'No valid face crops: {video.name}' arrays['expression'] = np.pad(arrays['expression50'], ((0, 0), (0, 50))) # Preserve raw 112D FLAME. The training loader selects jaw-x and four eye axes -> 108D. arrays['motioncode'] = np.concatenate([arrays['expression'], arrays['pose'], np.zeros((count, 6), np.float32)], axis=1) output = Path(output) output.parent.mkdir(parents=True, exist_ok=True) temporary = output.with_suffix('.tmp.npz') np.savez_compressed(temporary, **arrays, **meta, extractor='KaoLRM', crop_policy='smoothed_per_frame_face_bbox', shape_policy='per_frame', param_smoothing='none', source_id=video.stem) temporary.replace(output) return dict(source_id=video.stem, frames=count, valid_frames=int(arrays['valid_mask'].sum())) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', required=True, help='Resolved manifest with pose_file and optional video_file') parser.add_argument('--kaolrm-repo', default=str(Path(__file__).resolve().parent / 'vendor/kaolrm'), help='Bundled parameter components; optional upstream checkout override') parser.add_argument('--checkpoint', default=str(Path(os.environ.get('ELLSA2_CHECKPOINT_ROOT', ROOT.parent / 'checkpoints')) / 'external_assets/kaolrm-mono'), help='KaoLRM mono weights (included in the checkpoint package)') parser.add_argument('--output-dir', required=True) parser.add_argument('--output-manifest', required=True) parser.add_argument('--device', default='cuda:0') parser.add_argument('--start-index', type=int, default=0) parser.add_argument('--max-videos', type=int) parser.add_argument('--max-frames', type=int, help='Smoke-test cap; omit for training data') parser.add_argument('--overwrite', action='store_true') args = parser.parse_args() assert args.start_index >= 0 assert args.max_videos is None or args.max_videos > 0 assert args.max_frames is None or args.max_frames > 0 rows, original = load_manifest(args.input) rows = rows[args.start_index:][:args.max_videos] assert rows, 'No selected recordings' paths = [Path(args.output_dir).resolve() / (Path(row['pose_file']).stem + '_flame.npz') for row in rows] assert len(set(paths)) == len(paths), 'Duplicate pose stems in input' assert args.overwrite or not any(path.exists() for path in paths), 'Output exists; select remaining rows or --overwrite' from preprocess.kaolrm import ParameterModel model = ParameterModel(args.kaolrm_repo, args.checkpoint).to(args.device) outputs = [] for row, path in zip(rows, paths): print(json.dumps(extract(row, path, model, args.max_frames)), flush=True) outputs.append(dict({key: value for key, value in row.items() if not key.startswith('flame_')}, flame_file=str(path))) write_manifest(args.output_manifest, outputs, original) if __name__ == '__main__': main()