Spaces:
Running on Zero
Running on Zero
File size: 8,757 Bytes
1b2e96f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | """Publish generated videos and their camera metadata."""
from __future__ import annotations
import json
import platform
import shutil
import sys
import time
from pathlib import Path
from typing import TYPE_CHECKING
from fdanyone.config import INFERENCE, ModeSettings
from fdanyone.errors import FourDAnyoneError
from fdanyone.io import write_json
if TYPE_CHECKING:
from fdanyone.model.inference import GeneratedViews
from fdanyone.motion.result import MotionResult
from fdanyone.skeleton.pipeline import Conditioning
from fdanyone.video import CanonicalClip
def _copy_file(source: Path, destination: Path) -> Path:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
return destination
def _runtime_metadata(device: str) -> dict:
import torch
cuda = {
"available": torch.cuda.is_available(),
"torch_cuda": torch.version.cuda,
"cudnn": torch.backends.cudnn.version(),
}
if torch.cuda.is_available():
torch_device = torch.device(device)
properties = torch.cuda.get_device_properties(torch_device)
cuda.update(
{
"device": device,
"device_name": torch.cuda.get_device_name(torch_device),
"device_capability": list(torch.cuda.get_device_capability(torch_device)),
"device_total_memory_bytes": properties.total_memory,
}
)
return {
"python": sys.version.split()[0],
"platform": platform.platform(),
"torch": torch.__version__,
"cuda": cuda,
}
def _camera_rig_payload(payload: dict, cameras: list[dict]) -> dict:
"""Keep the final OpenCV camera rig needed by downstream tools."""
records = []
for camera in cameras:
camera_id = int(camera["camera_id"])
records.append(
{
"camera_id": camera_id,
"layer_index": int(camera["layer_index"]),
"pitch": int(camera["pitch_degrees"]),
"yaw": float(camera["yaw_degrees"]),
"K": camera["K"],
"camera_to_world": camera["camera_to_world"],
"image_width": int(camera["image_width"]),
"image_height": int(camera["image_height"]),
"video": f"videos/dense/{camera_id:02d}.mp4",
"skeleton_video": f"skeletons/{camera_id:02d}.mp4",
}
)
return {
"camera_model": "OPENCV",
"world_frame": payload["world_frame"],
"camera_frame": payload["camera_frame"],
"front_camera_ids": payload["front_camera_ids"],
"framing": payload["framing"],
"cameras": records,
}
def _target_cameras(payload: object, expected_count: int) -> list[dict]:
"""Read the camera records produced by the conditioning stage."""
if not isinstance(payload, dict) or payload.get("camera_model") != "OPENCV":
raise FourDAnyoneError("Conditioning did not produce an OpenCV camera rig.")
cameras = payload.get("cameras")
if not isinstance(cameras, list) or len(cameras) != expected_count:
raise FourDAnyoneError(f"Conditioning must contain {expected_count} target cameras.")
if [camera.get("camera_id") for camera in cameras if isinstance(camera, dict)] != list(range(expected_count)):
raise FourDAnyoneError("Target cameras are not in canonical order.")
return cameras
def export_result(
*,
clip: CanonicalClip,
conditioning: Conditioning,
generated: GeneratedViews,
destination: str | Path,
motion: MotionResult,
model_identity: dict,
pipeline_started: float,
settings: ModeSettings,
) -> dict:
"""Publish proposal, target, skeleton, camera, and metadata artifacts."""
root = Path(destination).expanduser().resolve()
attention_backend = "sdpa" if settings.exact_attention else "sageattention"
view_plan = generated.view_plan
if conditioning.view_plan != view_plan:
raise FourDAnyoneError("Conditioning and generation resolved different view plans.")
if len(generated.rcp_videos) != len(view_plan.rcp_camera_ids):
raise FourDAnyoneError(
f"Generation returned {len(generated.rcp_videos)} RCP videos, expected {len(view_plan.rcp_camera_ids)}."
)
if len(generated.target_videos) != view_plan.num_target_views:
raise FourDAnyoneError(
f"Generation returned {len(generated.target_videos)} target videos, expected {view_plan.num_target_views}."
)
if len(conditioning.target_skeletons) != view_plan.num_target_views:
raise FourDAnyoneError(
f"Conditioning returned {len(conditioning.target_skeletons)} target skeletons, "
f"expected {view_plan.num_target_views}."
)
sparse_root = root / "videos" / "sparse"
dense_root = root / "videos" / "dense"
skeletons_root = root / "skeletons"
dense_root.mkdir(parents=True, exist_ok=False)
skeletons_root.mkdir(exist_ok=False)
if generated.rcp_videos:
sparse_root.mkdir(exist_ok=False)
output_sparse = tuple(
_copy_file(source, sparse_root / f"{camera_id:02d}.mp4")
for camera_id, source in zip(view_plan.rcp_camera_ids, generated.rcp_videos, strict=True)
)
output_dense = tuple(
_copy_file(source, dense_root / f"{camera_id:02d}.mp4")
for camera_id, source in enumerate(generated.target_videos)
)
for camera_id, skeleton in enumerate(conditioning.target_skeletons):
_copy_file(skeleton.path, skeletons_root / f"{camera_id:02d}.mp4")
camera_payload = json.loads((conditioning.root / "cameras.json").read_text())
conditioning_metadata = json.loads((conditioning.root / "metadata.json").read_text())
camera_records = _target_cameras(camera_payload, view_plan.num_target_views)
total_elapsed = time.monotonic() - pipeline_started
metadata = {
"input": {
"filename": clip.source_path.name,
"fps": f"{clip.fps_num}/{clip.fps_den}",
"start_time_seconds": float(clip.start_time),
"num_frames": len(clip.frames),
"width": clip.width,
"height": clip.height,
},
"motion": {
"method": "GVHMR",
"revision": motion.gvhmr_revision,
},
"preprocessing": {
"source_crop_policy": conditioning_metadata["source_crop_policy"],
"foreground_model": conditioning_metadata["foreground_model"],
"framing": conditioning_metadata["framing"],
"skeleton_draw_scale": conditioning_metadata["skeleton_draw_scale"],
"target_render_deferred": bool(
conditioning_metadata.get("target_render_deferred", False)
),
"target_render_overlap": conditioning_metadata.get("target_render_overlap"),
},
"model": dict(model_identity),
"generation": {
"mode": settings.mode,
"seed": generated.seed,
"view_plan": {
**view_plan.to_dict(),
"num_layers": view_plan.num_layers,
"num_target_views": view_plan.num_target_views,
"groups_per_layer": view_plan.groups_per_layer,
"tcr_active": view_plan.tcr_active,
"routing_topology": "circular" if view_plan.closed_yaw else "open",
},
"attention_backend": attention_backend,
"inference_steps": settings.num_inference_steps,
"elapsed_seconds": generated.elapsed_seconds,
"total_elapsed_seconds": total_elapsed,
"peak_vram_allocated_bytes": generated.peak_vram_allocated_bytes,
"peak_vram_reserved_bytes": generated.peak_vram_reserved_bytes,
},
"output": {
"rcp_views": len(output_sparse),
"target_views": len(output_dense),
"frames_per_video": INFERENCE.num_frames,
"width": INFERENCE.width,
"height": INFERENCE.height,
"fps": f"{clip.fps_num}/{clip.fps_den}",
},
"runtime": _runtime_metadata(generated.device),
}
write_json(root / "cameras.json", _camera_rig_payload(camera_payload, camera_records))
write_json(root / "metadata.json", metadata)
return {
"attention_backend": attention_backend,
"num_rcp_videos": len(output_sparse),
"num_target_videos": len(output_dense),
"fps": f"{clip.fps_num}/{clip.fps_den}",
"peak_vram_allocated_bytes": generated.peak_vram_allocated_bytes,
"peak_vram_reserved_bytes": generated.peak_vram_reserved_bytes,
"total_pipeline_elapsed_seconds": total_elapsed,
}
|