diff --git a/README.md b/README.md index 6411a113e1235c39e1c4ab33fe8e291856851de4..a0c74cd8e02d5a7e8256a738ce29e12b35469ac4 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ pass, and generates only what no frame observes. | File | Content | Size | |---|---|---| | `agt_reconstruction.safetensors` | feed-forward reconstruction model | 4.9 GB | -| `agt_completion_lora.safetensors` | LoRA for FLUX.1-Fill-dev used in the frame-0 completion | 0.7 GB | +| `agt_completion_lora.safetensors` | LoRA of FLUX.1 Fill used in the generative completion | 0.7 GB | | `code/` | inference, evaluation and benchmark rebuild code | | ## Usage @@ -38,7 +38,6 @@ pass, and generates only what no frame observes. hf download MRBSTUDIO/AGT --local-dir AGT-release cd AGT-release/code mkdir -p checkpoints && mv ../*.safetensors checkpoints/ -# then follow code/README.md: installation, the TAPIP3D checkpoint, and the demo ``` FLUX.1-Fill-dev, SegFormer-B5, TAPIP3D, SAM 3 and Qwen3.5 are loaded from their official sources, see diff --git a/code/README.md b/code/README.md index 1d51a078cb9631e286604b88554e2a2567f64145..5145e781052fc8de7b17c93c584cfc00213be2f0 100644 --- a/code/README.md +++ b/code/README.md @@ -29,12 +29,12 @@ AGT reconstructs a complete 4D Gaussian scene from a driving video whose every frame is partly hidden by the hood, the dashboard, windshield reflections or watermarks. -- **Reconstruct what is observed.** As the camera moves, other frames observe part of each occluded region. A - feed-forward model reconstructs these parts from the input frames in a single pass, with the occluded pixels - excluded from its cross-frame attention. -- **Generate only what is never observed.** The region that no input frame observes is completed once, in the first - frame, by an image generation model, and the completed content is fused into the 4D scene by a short per-scene - refinement. +- **Amodal geometry recovery.** The occluder mask masks the occluder tokens in the attention layers, so that the + feed-forward model recovers cameras, depth and motion from the obstructed frames in a single pass. +- **Observed appearance reconstruction.** The observability of every pixel is computed from this geometry, and + appearance is reconstructed only in the observed regions. +- **Generative completion.** The unobserved regions are filled by an image diffusion model and optimized into the + Gaussian scene. - **AmodalDrive.** The model is trained on AmodalDrive, a paired dataset that composites occluder layers separated from in-the-wild dashcam videos onto clean driving scenes. @@ -44,17 +44,12 @@ the dashboard, windshield reflections or watermarks. ## Installation -Tested on Linux with CUDA 12 and one NVIDIA H200. The full chain peaks at about 36 GB of GPU memory in the -completion step. Reconstruction alone needs about 8 GB with 4 input frames and 17 GB with 20. - ```bash git clone https://github.com/MRBXCD/AGT.git cd AGT ``` -The frame-0 completion runs in its own environment. - -**Main environment** (reconstruction, refinement, evaluation): +**Main environment** (reconstruction, scene optimization, evaluation): ```bash conda create -n agt python=3.10 -y @@ -65,7 +60,7 @@ pip install --no-build-isolation --no-binary gsplat gsplat==1.5.3 pip install --no-build-isolation third_party/dggt/third_party/pointops2 ``` -**Completion environment** (frame-0 completion with FLUX.1-Fill): +**Completion environment** (generative completion): ```bash conda create -n agt-completion python=3.12 -y @@ -79,7 +74,7 @@ pip install -r requirements-completion.txt - **Mask generation for your own clips**: SAM 3 and the Qwen3.5 verifier each run in their own environment. Install SAM 3 by following its repository, and install `requirements-masks.txt` for the verifier. The verifier runs - `Qwen/Qwen3.5-35B-A3B` locally with vLLM on one GPU with about 80 GB of memory. + `Qwen/Qwen3.5-35B-A3B` locally with vLLM. - **Benchmark rebuild**: `requirements-rebuild.txt` and a static build of ffmpeg 7.0.2. @@ -97,20 +92,10 @@ mv checkpoints/tapip3d_final.pth checkpoints/tracking_model.pth | File | Content | Size | |---|---|---| | `agt_reconstruction.safetensors` | feed-forward reconstruction model | 4.9 GB | -| `agt_completion_lora.safetensors` | LoRA for FLUX.1-Fill-dev used in the frame-0 completion | 0.7 GB | +| `agt_completion_lora.safetensors` | LoRA of FLUX.1 Fill used in the generative completion | 0.7 GB | FLUX.1-Fill-dev and SegFormer are loaded from the Hugging Face Hub, or from local copies given with `--flux` and -`--segformer`. FLUX.1-Fill-dev is gated: accept its license on the Hub and log in with `hf auth login`. The first run -downloads the CoTracker3 feature encoder used inside TAPIP3D through `torch.hub` and the LPIPS network weights -through torchvision, both cached under `$TORCH_HOME`. - -| Model | Used for | Source | -|---|---|---| -| FLUX.1-Fill-dev | frame-0 completion | [black-forest-labs/FLUX.1-Fill-dev](https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev) | -| SegFormer-B5 Cityscapes | sky masks | [nvidia/segformer-b5-finetuned-cityscapes-1024-1024](https://huggingface.co/nvidia/segformer-b5-finetuned-cityscapes-1024-1024) | -| TAPIP3D | tracking of dynamic objects | [zbww/tapip3d](https://huggingface.co/zbww/tapip3d) | -| SAM 3 | occluder proposals for new clips | [facebookresearch/sam3](https://github.com/facebookresearch/sam3) | -| Qwen3.5 | occluder verification for new clips | [Qwen/Qwen3.5-35B-A3B](https://huggingface.co/Qwen/Qwen3.5-35B-A3B) | +`--segformer`. ## Demo @@ -126,33 +111,40 @@ python inference.py \ --completion-python "$(conda run -n agt-completion which python)" ``` -Add `--reconstruction-only` to stop after the feed-forward reconstruction; this needs only the main environment. +Add `--reconstruction-only` to run AGT without generative completion; this needs only the main environment. Outputs are rendered at 518x294. ## Inference on your own video +Cut a 20-frame clip from the video: + ```bash -# 1. Cut a 20-frame clip from the video. python tools/prepare_clip.py --video drive.mp4 --start 12 --out work/export +``` -# 2. Generate the occluder mask: SAM 3 proposes regions, Qwen3.5 verifies them, the frames vote. -python tools/make_masks.py --export work/export --out work/masks --stage propose # SAM 3 environment -python tools/make_masks.py --export work/export --out work/masks --stage verify # verifier environment (requirements-masks.txt) -python tools/make_masks.py --export work/export --out work/masks --stage finish # main environment (CPU) +Generate its occluder mask. SAM 3 proposes regions in the SAM 3 environment, Qwen3.5 verifies them in the verifier +environment, and the frames vote in the main environment: -# 3. Run the chain. +```bash +python tools/make_masks.py --export work/export --out work/masks --stage propose +python tools/make_masks.py --export work/export --out work/masks --stage verify +python tools/make_masks.py --export work/export --out work/masks --stage finish +``` + +Run AGT: + +```bash python inference.py --export work/export --mask-dir work/masks --out outputs/my_clip \ --completion-python "$(conda run -n agt-completion which python)" ``` -The output directory holds the rendered frames, depth and opacity of every clip, the completed first frame, and the -intermediate reliability maps. +The output directory holds the rendered frames, depth and opacity of every clip. ## Evaluation Build the benchmark first, see [Dataset](#dataset). Both commands use the precomputed occluder masks of AmodalDrive. -**Feed-forward reconstruction** (colour, depth and region metrics): +**AGT without completion** (colour, depth and region metrics): ```bash python -m agt.recon.reconstruct render --inputs AmodalDrive/exports/test --out outputs/test_feedforward \ @@ -161,7 +153,7 @@ python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDri --export AmodalDrive/exports/test --method outputs/test_feedforward --out scores/test_feedforward ``` -**Full method** (the method directory is `/final`): +**AGT** (the method directory is `/final`): ```bash python inference.py --export AmodalDrive/exports/test --masks dataset --data-root AmodalDrive \ @@ -170,8 +162,8 @@ python eval/score.py --config configs/eval/test_waymo.json --data-root AmodalDri --export AmodalDrive/exports/test --method outputs/test_full/final --out scores/test_full --tables A1 A2 B ``` -`--clips ID ...` restricts `inference.py` to a subset of the export. The full method is scored on the colour and -region tables (`--tables A1 A2 B`). `configs/eval/val_waymo.json` scores the validation export (`--split val`). +`--clips ID ...` restricts `inference.py` to a subset of the export. AGT is scored on the colour and region tables +(`--tables A1 A2 B`). `configs/eval/val_waymo.json` scores the validation export (`--split val`). ## Dataset @@ -183,20 +175,16 @@ hf download MRBSTUDIO/AmodalDrive --repo-type dataset --local-dir AmodalDrive ``` Download the [Waymo Open Dataset](https://waymo.com/open/) v2.0.1, then run the scripts below to build the composed -validation and test data: +validation and test data. They preprocess the scenes, compute the labels used by the scorer, and compose and export +the clips. ```bash -# Scene preprocessing. python tools/build_waymo_scenes.py --data-root AmodalDrive --waymo-root WAYMO --split val --split test \ --ffmpeg /path/to/ffmpeg --ffprobe /path/to/ffprobe - -# Labels used by the scorer. python tools/make_labels.py depth --data-root AmodalDrive --waymo-root WAYMO --split val --split test python tools/make_labels.py sky --data-root AmodalDrive --waymo-root WAYMO --split val --split test python tools/make_labels.py visibility --data-root AmodalDrive --dggt-checkpoint checkpoints/model_latest_waymo.pt \ --split val --split test - -# Composition and clip export. python tools/export_clips.py --data-root AmodalDrive --split val --out AmodalDrive/exports/val python tools/export_clips.py --data-root AmodalDrive --split test --protocol full --out AmodalDrive/exports/test ``` @@ -209,20 +197,20 @@ python tools/export_clips.py --data-root AmodalDrive --split test --protocol ful ```text AGT/ -├── inference.py runs the whole chain on an example case or a new clip +├── inference.py runs AGT on an example case, a new clip or a benchmark export ├── agt/ │ ├── masks/ occluder mask generation with a pluggable verifier │ ├── prepare/ clip export from a video -│ ├── model/ model construction and the occluder attention mask +│ ├── model/ model construction, masked attention and observability │ ├── recon/ feed-forward reconstruction and rendering -│ ├── completion/ reliability maps and frame-0 completion -│ ├── refine/ per-scene refinement +│ ├── completion/ render completion +│ ├── refine/ scene optimization │ ├── data/ AmodalDrive reader with on-the-fly composition │ ├── dataset/ scene preprocessing and label generation │ └── eval/ scorer ├── eval/score.py scoring entry ├── tools/ clip preparation, mask generation, benchmark rebuild -├── configs/ model, completion, refinement, mask, dataset and evaluation settings +├── configs/ model, completion, scene optimization, mask, dataset and evaluation settings └── third_party/dggt/ the DGGT files used by this code ``` diff --git a/code/agt/completion/flux_fill.py b/code/agt/completion/flux_fill.py index 0e34538a64ea0a165a0649f08c22d791b0baa2cd..34b6786571a8e02e3907e8b8a233df85cbed6eb2 100644 --- a/code/agt/completion/flux_fill.py +++ b/code/agt/completion/flux_fill.py @@ -1,21 +1,3 @@ -"""Frame-0 completion: FLUX.1 Fill [dev] with the AGT LoRA fills the repair mask of the first rendered frame. - -Inputs per clip: the first-pass render of frame 0 (frames.npz 'rgb'[0]) and the repair mask of frame 0 at tau -(agt.completion.reliability). No ground truth is read. -- resolution (no stretching): 294x518 -> PIL LANCZOS x2 to 588x1036 -> edge padding right / bottom to 592x1040 - (FLUX needs multiples of 16: VAE x8 and 2x2 packing); the mask goes x2 nearest (pixel repeat) + the same padding. - The output is cropped back to 588x1036 and resized to 294x518 with PIL LANCZOS. -- the image and mask go to diffusers FluxFillPipeline as PIL images (mask 255 = fill); the pipeline's own - preprocessing, masked-image latents and channel concatenation are used unchanged. -- sampling: the FluxFillPipeline defaults (strength 1.0, 50 steps, guidance scale 30, max_sequence_length 512), - fixed seed on a CPU generator, the fixed prompt of configs/completion.json encoded once per run. -- LoRA: rank / alpha / target modules from the safetensors metadata, attached with peft LoraConfig - (init 'gaussian') + transformer.add_adapter, then the tensors are copied in. -Output /.npz (agt.completion.handoff, positions [0]): rgb = the whole generated frame, mask = the repair mask. - - python -m agt.completion.flux_fill --pass1 --rel --out \\ - --base --lora checkpoints/agt_completion_lora.safetensors -""" from __future__ import annotations import argparse @@ -31,8 +13,8 @@ from .reliability import load_repair_mask CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json' GRID_HW = (294, 518) SCALE = 2 -UP_HW = (GRID_HW[0] * SCALE, GRID_HW[1] * SCALE) # 588 x 1036 -MODEL_HW = (592, 1040) # padded to multiples of 16 +UP_HW = (GRID_HW[0] * SCALE, GRID_HW[1] * SCALE) +MODEL_HW = (592, 1040) def to_u8(rgb01): @@ -40,7 +22,6 @@ def to_u8(rgb01): def up2_rgb(frame_u8): - """uint8 [294,518,3] -> uint8 [588,1036,3], PIL LANCZOS x2.""" from PIL import Image f = np.asarray(frame_u8) assert f.dtype == np.uint8 and f.shape[:2] == GRID_HW, f.shape @@ -48,14 +29,12 @@ def up2_rgb(frame_u8): def up2_mask(mask): - """bool [294,518] -> bool [588,1036], x2 nearest (pixel repeat).""" m = np.asarray(mask, bool) assert m.shape == GRID_HW, m.shape return np.repeat(np.repeat(m, SCALE, 0), SCALE, 1) def pad_edge(a, hw=MODEL_HW): - """Edge padding right / bottom to hw.""" a = np.asarray(a) ph, pw = hw[0] - a.shape[0], hw[1] - a.shape[1] assert ph >= 0 and pw >= 0, (a.shape, hw) @@ -63,14 +42,12 @@ def pad_edge(a, hw=MODEL_HW): def crop_pad(a, hw=UP_HW): - """Inverse of pad_edge.""" a = np.asarray(a) assert a.shape[:2] == MODEL_HW, a.shape return a[:hw[0], :hw[1]] def to_model(frame_u8, mask=None): - """Frame u8 + repair mask -> model input (uint8 [592,1040,3], bool [592,1040] | None).""" img = pad_edge(up2_rgb(frame_u8)) m = None if mask is None else pad_edge(up2_mask(mask)) assert img.shape == (*MODEL_HW, 3) and (m is None or m.shape == MODEL_HW) @@ -78,7 +55,6 @@ def to_model(frame_u8, mask=None): def from_model(gen_u8): - """Generated uint8 [592,1040,3] -> crop the padding -> LANCZOS to uint8 [294,518,3].""" from PIL import Image g = crop_pad(np.asarray(gen_u8)) assert g.dtype == np.uint8 and g.shape == (*UP_HW, 3), g.shape @@ -88,7 +64,6 @@ def from_model(gen_u8): def to_pil(img_u8, mask=None): - """FluxFillPipeline image / mask_image: PIL RGB and PIL L (255 = fill); already at the model size.""" from PIL import Image im = Image.fromarray(np.asarray(img_u8, np.uint8)) return im if mask is None else (im, Image.fromarray(np.where(np.asarray(mask, bool), 255, 0).astype(np.uint8), mode='L')) @@ -102,7 +77,6 @@ def attach_lora(transformer, rank, alpha, targets, init='gaussian', dropout=0.0) def load_lora(transformer, path): - """LoRA safetensors (keys = transformer parameter names, float32) -> attached and copied in (same key set).""" from safetensors import safe_open from safetensors.torch import load_file with safe_open(str(path), 'pt') as f: @@ -129,7 +103,6 @@ def load_pipeline(base, device, dtype_name='bfloat16', lora=None, revision=None) def encode_prompt(pipe, prompt, device, max_sequence_length=512): - """FluxFillPipeline.encode_prompt (CLIP pooled + T5, prompt_2 = None) -> (prompt_embeds, pooled_prompt_embeds).""" import torch with torch.no_grad(): pe, ppe, _ = pipe.encode_prompt(prompt=prompt, prompt_2=None, device=device, num_images_per_prompt=1, @@ -138,7 +111,6 @@ def encode_prompt(pipe, prompt, device, max_sequence_length=512): def generate(pipe, img_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling): - """Model-size input (uint8 [H,W,3] + bool [H,W]) -> generated uint8 [H,W,3].""" import torch im, m = to_pil(img_u8, mask) h, w = np.asarray(img_u8).shape[:2] @@ -152,14 +124,13 @@ def generate(pipe, img_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling): def fix_frame(pipe, frame_u8, mask, prompt_embeds, pooled_prompt_embeds, sampling): - """294x518 frame + mask -> generated whole frame uint8 [294,518,3].""" img, m = to_model(frame_u8, mask) return from_model(generate(pipe, img, m, prompt_embeds, pooled_prompt_embeds, sampling)) def main(argv=None): import torch - p = argparse.ArgumentParser(prog='agt.completion.flux_fill', description=__doc__.split('\n')[0]) + p = argparse.ArgumentParser(prog='agt.completion.flux_fill') p.add_argument('--pass1', required=True, help='first-pass output directory') p.add_argument('--rel', required=True, help='reliability maps (agt.completion.reliability)') p.add_argument('--out', required=True) diff --git a/code/agt/completion/handoff.py b/code/agt/completion/handoff.py index 25b7b7aa23ba9e1c981b2333b6f5278b1496f01c..9d68b88c4e8793c8e683f9c7bedab37559b6ce81 100644 --- a/code/agt/completion/handoff.py +++ b/code/agt/completion/handoff.py @@ -1,10 +1,3 @@ -"""Hand-off files between the completion and refinement steps. - -/.npz: rgb float32 (n,294,518,3) in [0, 1], mask bool (n,294,518) = repair mask of each frame, -positions int64 (n,), meta = JSON string. The frame-0 completion writes positions [0] (rgb = the whole generated -frame, not pasted back into the mask); the refinement writes its renders of the input frames (positions = the input -frames of the first pass). -""" from __future__ import annotations import json @@ -28,7 +21,6 @@ def write_handoff(path, rgb, mask, positions, meta): def load_handoff(path, positions): - """-> (rgb (n,H,W,3) float32, mask (n,H,W) bool, meta); positions must match.""" with np.load(path, allow_pickle=False) as h: rgb, mask, pos = h['rgb'].astype(np.float32), h['mask'].astype(bool), h['positions'].tolist() meta = json.loads(str(h['meta'])) diff --git a/code/agt/completion/reliability.py b/code/agt/completion/reliability.py index 1fcc7f4f83b39875ff093ca4f18b6d63f8039c48..85fca91275d03cac66e0295a58f0e3168e4c43ea 100644 --- a/code/agt/completion/reliability.py +++ b/code/agt/completion/reliability.py @@ -1,23 +1,3 @@ -"""Reliability map of a first-pass render: the pixels of the rendered frames that no input frame supports. - -Per clip, from the first-pass outputs of agt.recon.reconstruct (depth.npz, render_cameras.npz and render_sky.npz, -written with --export-render-cameras --export-render-sky) and the occluder mask of that pass: -- observation count n: every pixel of every rendered frame is unprojected with its rendered depth and projected into - each input frame; it counts once when it lands inside the image and outside that frame's occluder mask - (agt.model.visibility.visibility_camera on the full frame; a frame is never its own source). Input frames add a - self term of 1 outside their mask. With more than 8 input frames the sources go in groups of 8 and the counts add. -- U = (n == 0) and not (rendered sky outside the occluder mask): the sky is rendered by the sky model and has no - geometry; inside the occluder mask a "sky" label is the segmentation mistaking the smooth rendered occluder. -- holes: accumulated opacity alpha < tau and not sky (DGGT trains alpha towards 1 - sky, train.py:199). -- repair mask (per tau) = U or holes; ledger 0 = kept, 1 = unobserved (U), 2 = hole observed at least once. -Coordinates as in visibility_camera: depth = camera z, pixel i at the continuous coordinate i. - -Output //reliability.npz: n, alpha, sky, depth_valid, U, holes, repair_mask, ledger (per tau), taus, -positions, context_positions. - - python -m agt.completion.reliability --pass1 --inputs --out \\ - --masks dataset --data-root # the mask options of the first pass -""" from __future__ import annotations import argparse @@ -27,21 +7,17 @@ from pathlib import Path import numpy as np EXPORT_CONTEXT = [0, 5, 10, 15] -MAX_SOURCES = 8 # visibility_camera: one bit of a uint8 per source +MAX_SOURCES = 8 LEDGER = {'S': 0, 'G': 1, 'R': 2} CONFIG = Path(__file__).resolve().parents[2] / 'configs' / 'completion.json' def source_chunks(sources): - """Sources in groups of at most 8 (one group = a single call).""" sources = list(sources) return [sources[i:i + MAX_SOURCES] for i in range(0, len(sources), MAX_SOURCES)] def observation_count(depth, K, c2w, mask, context_positions, *, device='cpu'): - """depth (T,H,W) camera z; K (T,3,3); c2w (T,4,4); mask (T,H,W) bool occluder mask (source alpha). - - Returns n uint8 (T,H,W) = count over the other input frames + self term; valid bool (T,H,W) (finite depth > 0).""" import torch from ..model.visibility import visibility_camera depth = torch.as_tensor(np.asarray(depth), dtype=torch.float64, device=device) @@ -63,8 +39,6 @@ def observation_count(depth, K, c2w, mask, context_positions, *, device='cpu'): def compose(n, alpha, sky, taus, mask): - """n (T,H,W); alpha (T,H,W) accumulated opacity; sky (T,H,W) bool; mask (H,W) occluder mask. - Returns U and holes / repair_mask / ledger of shape (len(taus),T,H,W).""" n, alpha, sky = np.asarray(n), np.asarray(alpha, np.float32), np.asarray(sky, bool) U = (n == 0) & ~(sky & ~np.broadcast_to(np.asarray(mask, bool), sky.shape)) holes = np.stack([(alpha < tau) & ~sky for tau in taus]) @@ -76,7 +50,6 @@ def compose(n, alpha, sky, taus, mask): def load_pass1(pass1, cid): - """First-pass exports of one clip: depth / alpha, render cameras, rendered sky.""" d = Path(pass1) / cid with np.load(d / 'depth.npz') as f: depth, alpha = f['depth'].astype(np.float32), f['alpha'].astype(np.float32) @@ -113,7 +86,6 @@ def write_clip(out, cid, arrays): def load_repair_mask(rel, cid, tau): - """repair_mask (T,H,W) bool of one clip at tau.""" with np.load(Path(rel) / cid / 'reliability.npz', allow_pickle=False) as h: taus = [round(float(x), 6) for x in h['taus']] return h['repair_mask'][taus.index(round(float(tau), 6))].astype(bool) @@ -121,7 +93,7 @@ def load_repair_mask(rel, cid, tau): def main(argv=None): from ..recon.reconstruct import open_masks - p = argparse.ArgumentParser(prog='agt.completion.reliability', description=__doc__.split('\n')[0]) + p = argparse.ArgumentParser(prog='agt.completion.reliability') p.add_argument('--pass1', required=True, help='first-pass output directory (reconstruct with ' '--export-render-cameras --export-render-sky)') p.add_argument('--inputs', required=True, help='clip export of the first pass') diff --git a/code/agt/data/__init__.py b/code/agt/data/__init__.py index e9cfff52af1e5433f2ffffee43dda87d140afc3d..a31b3d03d3b65543a439c06c66741a069cb04ee2 100644 --- a/code/agt/data/__init__.py +++ b/code/agt/data/__init__.py @@ -1,4 +1,3 @@ -"""Data access: clip protocol, scene index over a data root, clip reader with read-time occluder composition.""" from .protocol import ClipProtocol from .reader import ClipReader, open_reader diff --git a/code/agt/data/camera.py b/code/agt/data/camera.py index e4734c55145f924885363197e28922e05a130ca3..1f34e9fa59fb4a51e3b8455ac1b82e03862a6fc9 100644 --- a/code/agt/data/camera.py +++ b/code/agt/data/camera.py @@ -1,4 +1,3 @@ -"""Pinhole geometry in integer pixel coordinates; arrays use column-vector poses.""" from dataclasses import dataclass import numpy as np @@ -29,7 +28,6 @@ class PinholeCamera: if calibration_profile == NUREC_PINHOLE_PROFILE: if value.get('camera_id') != 'pinhole_front_v1': raise ValueError('NuRec pinhole profile requires pinhole_front_v1') - # NuRec render samples are at x+0.5, y+0.5: convert once to integer pixel centres. principal = principal - .5 elif calibration_profile != DECLARED_INTEGER_PROFILE: raise ValueError(f'Unsupported calibration profile: {calibration_profile}') @@ -55,7 +53,6 @@ class PinholeCamera: def exposure_midpoint(frame): - """Camera-to-world pose at the exposure midpoint: translation mean, rotation Slerp at 0.5.""" poses = np.asarray([frame['pose_start_camera_to_world'], frame['pose_end_camera_to_world']], dtype=np.float64) if poses.shape != (2, 4, 4) or not np.isfinite(poses).all(): raise ValueError('Invalid camera poses') diff --git a/code/agt/data/clips.py b/code/agt/data/clips.py index a1bd00a7a1c761124f483aff424681a5b9e1f782..8ff38130056a0bd6099cb54d431f18e5d6fd6637 100644 --- a/code/agt/data/clips.py +++ b/code/agt/data/clips.py @@ -1,12 +1,3 @@ -"""(protocol, scene record) -> clip records: frame numbers derived from timestamps, roles, times. - -Frame selection: every sample time takes the frame whose exposure midpoint is nearest (a tie goes to the earlier -frame). The selection tolerance is half the scene's mean frame period unless the data declares a tolerance for the -scene's source (eval_sets/.frame_selection.json; nuScenes 50 ms). The tolerance only decides whether a -window is accepted; it never changes which frame a sample takes. A window is unusable when a sample has no frame -within the tolerance or when two samples take the same frame; such a window is dropped (never repaired) and -recorded. -""" from __future__ import annotations import numpy as np @@ -18,8 +9,6 @@ RULE_SAME_FRAME = 'same_frame_picked_twice' class FrameSelectionError(ValueError): - """A window's samples cannot be mapped to frames; `rules` names every violated rule.""" - def __init__(self, message, *, rules=(), max_error_us=float('nan'), tolerance_us=float('nan')): super().__init__(message) self.rules, self.max_error_us, self.tolerance_us = tuple(rules), float(max_error_us), float(tolerance_us) @@ -38,7 +27,6 @@ def frame_times(frames_meta) -> dict: def nearest_frames(tau_us: np.ndarray, targets_us) -> tuple: - """(pick, error_us): the nearest exposure midpoint per target, ties to the earlier frame; no checks.""" targets = np.asarray(targets_us, dtype=np.float64) right = np.clip(np.searchsorted(tau_us, targets), 1, len(tau_us) - 1) left = right - 1 @@ -47,13 +35,10 @@ def nearest_frames(tau_us: np.ndarray, targets_us) -> tuple: def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float: - """The data's declared tolerance, else half the scene's mean frame period.""" return float(period_us) / 2 if tolerance_us is None else float(tolerance_us) def select_frames(tau_us: np.ndarray, targets_us, period_us: float, tolerance_us: float | None = None) -> tuple: - """Nearest exposure midpoint per target; every target must be within the tolerance and no two targets may take - the same frame. Raises FrameSelectionError naming every violation.""" tol = selection_tolerance_us(period_us, tolerance_us) targets = np.asarray(targets_us, dtype=np.float64) pick, error = nearest_frames(tau_us, targets) @@ -73,11 +58,6 @@ def select_frames(tau_us: np.ndarray, targets_us, period_us: float, tolerance_us def build_clips(protocol: ClipProtocol, record, frames_meta, *, sample_id: str | None = None, skipped: list | None = None, tolerance_us: float | None = None) -> list: - """`record` is a SceneRecord; `sample_id` defaults to its scene_id. - - tolerance_us: the selection tolerance the data declares for the record's source (None: half the scene's mean - frame period). skipped=None: an unusable window raises; with a list, such a window is left out and recorded - there: {sample_id, scene_id, source_id, window_start_s, reason, rules, max_error_us, tolerance_us}.""" T = int(record.frame_count) if len(frames_meta) != T: raise ValueError(f'{record.scene_id}: frames.jsonl has {len(frames_meta)} rows, record says {T}') diff --git a/code/agt/data/compose.py b/code/agt/data/compose.py index cf3f18663899467d6f2da7e16484bbb28ce938eb..1975e70a535e436fcd1394f1366d43881a4f7f89 100644 --- a/code/agt/data/compose.py +++ b/code/agt/data/compose.py @@ -1,10 +1,3 @@ -"""Read-time composition of an occluder layer onto clean frames (float32 display space). - -Day (lighting profile adaptation 'none'): compose_batch(clean, idx, layers, lighting=None). -Night ('night_appearance_v1'): adapt_layers(layers, roles, scene_stats, profile) once per scene re-exposes the -static layers to the scene (configs/dataset/lighting/.yaml), then compose_batch(clean, idx, adapted, lighting). -All maths of the adaptation in approximately linear light (display^2.2). -""" from __future__ import annotations import math @@ -21,9 +14,7 @@ GAMMA = 2.2 LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32) -# ---- composition -------------------------------------------------------------------------- def to_uint8(image: np.ndarray) -> np.ndarray: - """floor(clip(x, 0, 1) * 255 + 0.5).""" return np.ascontiguousarray( np.floor(np.clip(image, 0.0, 1.0) * 255.0 + 0.5), dtype=np.uint8 ) @@ -45,8 +36,6 @@ def compose_hybrid(clean: np.ndarray, alpha: np.ndarray, obs: np.ndarray, solid_ def compose_batch(clean_frames: np.ndarray, frame_indices: np.ndarray, layers: dict[str, np.ndarray], lighting: dict | None = None) -> np.ndarray: - """Compose a batch of clean frames [T,H,W,3] with prepared layers. `lighting` is the parameters block of an - adapting profile (night_appearance_v1) or None for the day chain.""" if clean_frames.ndim != 4 or clean_frames.shape[0] != len(frame_indices): raise ValueError('clean_frames must be [T,H,W,3] with one index per frame') if clean_frames.shape[1:] != layers['solid_rgb'].shape: @@ -66,7 +55,6 @@ def compose_batch(clean_frames: np.ndarray, frame_indices: np.ndarray, layers: d return np.stack([night_frame(frames[i], int(frame_indices[i]), layers, lighting) for i in range(len(frame_indices))]) -# ---- lighting profiles -------------------------------------------------------------------- def _number(value: Any, field: str, low: float, high: float) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not low <= value <= high: raise ValueError(f'{field}: expected a finite number in [{low}, {high}]') @@ -74,7 +62,6 @@ def _number(value: Any, field: str, low: float, high: float) -> float: def load_lighting_profile(profile_id: str, directory=LIGHTING_DIR) -> dict[str, Any]: - """Strictly validated lighting profile /.yaml.""" import yaml if not isinstance(profile_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', profile_id): raise ValueError('lighting profile_id: expected a safe, nonempty identifier') @@ -138,7 +125,6 @@ def luminance(x: np.ndarray) -> np.ndarray: def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray], scene_stats: dict[str, Any], profile: dict[str, Any]) -> tuple[dict[str, np.ndarray], dict[str, Any]]: - """Night re-exposure of the static layers to the target scene (scene_stats.json of the clean scene).""" if is_identity(profile): raise ValueError('adapt_layers is only defined for adapting profiles') solid_cfg = profile['solid'] @@ -150,7 +136,7 @@ def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray assigned = np.zeros(solid_mask.shape, bool) gains: dict[str, Any] = {} low, high = solid_cfg['gain_clip'] - for role in ROLES: # fixed order: pixels claimed by an earlier role are not re-assigned + for role in ROLES: mask = role_masks.get(role) if mask is None: continue @@ -162,7 +148,7 @@ def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray gains[role] = {'pixels': int(selected.sum()), 'day_mean_luminance': day_mean, 'gain': gain} gain_map[selected] = gain assigned |= selected - rest = solid_mask & ~assigned # edge fill / bottom band pixels without a role follow the dashboard + rest = solid_mask & ~assigned if rest.any(): day_mean = float(max(lum[rest].mean(), 1e-6)) gain = float(np.clip(solid_cfg['target_over_scene_mean']['dashboard'] * scene_mean / day_mean, low, high)) @@ -186,14 +172,12 @@ def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray def frame_noise(shape: tuple[int, ...], sigma: float, seed: int, frame_index: int) -> np.ndarray: - """Zero-mean Gaussian noise that depends only on (seed, frame index).""" if sigma <= 0: return np.zeros(shape, np.float32) return np.random.default_rng([int(seed), int(frame_index)]).normal(0.0, sigma, shape).astype(np.float32) def night_frame(clean: np.ndarray, frame_index: int, layers: dict[str, np.ndarray], parameters: dict[str, Any]) -> np.ndarray: - """One frame with the per-frame terms of night_appearance_v1 (clean and layers in display domain).""" from scipy.ndimage import gaussian_filter clean_lin = lin(clean) reflection = parameters['hood_reflection'] diff --git a/code/agt/data/grid.py b/code/agt/data/grid.py index 943ec2333797c2a24cca449c69868694bb3bb904..0aea261959b2d4db0e17fd250cb6e2cc4a6a8bf4 100644 --- a/code/agt/data/grid.py +++ b/code/agt/data/grid.py @@ -1,11 +1,3 @@ -"""Scoring grid and the one resampling function. - -``resize_float`` is the single resampler for GT frames, labels and method outputs: torch -``F.interpolate(mode='bilinear', antialias=True, align_corners=False)`` on CPU float32. RGB is u8/255 -> resize -> -floor(clip(x, 0, 1) * 255 + 0.5); binary masks are resized as float32 and thresholded at >= 0.5; continuous layers -are resized as is. The output is bitwise stable across thread counts and batch sizes within one torch build, but -not across torch builds (last ulp). Data stored on the grid (518x294) is never resampled. -""" from __future__ import annotations import numpy as np @@ -18,7 +10,6 @@ DIRECT = 'direct_anisotropic_full_frame' def resize_float(values: np.ndarray, width: int, height: int, *, batched: bool = False) -> np.ndarray: - """Resampler on CPU float32. Layouts: HxW, HxWxC (batched=False); NxHxW, NxHxWxC (batched=True).""" import torch import torch.nn.functional as F x = np.asarray(values) @@ -40,8 +31,6 @@ def resize_float(values: np.ndarray, width: int, height: int, *, batched: bool = class ScoringGrid: - """Grid spec from the protocol -> camera + array resampling for that grid.""" - def __init__(self, spec: dict | None = None): self.spec = dict(spec or GRID_518x294) self.width, self.height = int(self.spec['width']), int(self.spec['height']) @@ -55,25 +44,21 @@ class ScoringGrid: return f'g{self.height}' def camera(self, native: PinholeCamera) -> PinholeCamera: - """fx' = fx*sx, cx' = (cx + 0.5) * sx - 0.5 (pixel centres at integers), same in y.""" sx, sy = self.width / native.width, self.height / native.height return PinholeCamera(self.width, self.height, native.fx * sx, native.fy * sy, (native.cx + .5) * sx - .5, (native.cy + .5) * sy - .5) def continuous(self, layer: np.ndarray, *, batched: bool = False) -> np.ndarray: - """HxW / HxWxC (or NxHxW / NxHxWxC with batched=True) float layer -> grid float32.""" layer = np.asarray(layer, dtype=np.float32) return resize_float(layer, self.width, self.height, batched=batched) def rgb(self, frames_u8: np.ndarray) -> np.ndarray: - """(N,)H,W,3 uint8 native RGB -> grid uint8 RGB.""" frames = np.asarray(frames_u8) if frames.dtype != np.uint8 or frames.shape[-1] != 3 or frames.ndim not in (3, 4): raise ValueError('Expected uint8 RGB (N,)HxWx3') return to_uint8(self.continuous(frames.astype(np.float32) / 255, batched=frames.ndim == 4)) def mask(self, mask: np.ndarray) -> np.ndarray: - """(N,)HxW binary -> grid uint8 {0,1} (resize as float32, >= threshold).""" mask = np.asarray(mask) if mask.ndim not in (2, 3) or not np.isin(mask, (0, 1)).all(): raise ValueError('Expected a binary (N,)HxW mask') diff --git a/code/agt/data/labels.py b/code/agt/data/labels.py index 159032beaf05fa507aa0b02ec56d5b4444c92fc4..d3b09773aa3aad7ed636b5f356ab2f415fe536ef 100644 --- a/code/agt/data/labels.py +++ b/code/agt/data/labels.py @@ -1,5 +1,3 @@ -"""Per-frame clean-scene label stores (labels////.h5), read by frame number with -frame / time alignment checks. Labels are validated, never rescaled.""" from __future__ import annotations import numpy as np @@ -20,7 +18,7 @@ class FrameLabels: def read(self, scene_id: str, indices, frame_count: int, timestamps_start_us=None) -> dict: import h5py - self.labels.require(scene_id) # listed in unavailable.json: LabelsUnavailable + self.labels.require(scene_id) path = self.labels.path(scene_id) if not path.is_file(): raise FileNotFoundError(f'{self.labels.name} labels missing for {scene_id}: {path}') @@ -52,15 +50,11 @@ class FrameLabels: class MotionStore(FrameLabels): - """labels/motion_v2///masks.h5 `motion_mask`.""" - def __init__(self, root): super().__init__(root, name='motion', layers=('motion_mask',)) class CleanSkyStore(FrameLabels): - """labels/sky_v1///sky.h5 `sky`: uint8 sky probability of the clean frames (>= 128 is sky).""" - def __init__(self, root): super().__init__(root, name='sky', layers=('sky',)) if self.labels.version != 1: diff --git a/code/agt/data/protocol.py b/code/agt/data/protocol.py index b0f860137e0ef221ce6b5328eb17c3f456bdf51d..d7d586d44442a7caafa2cebe3742527246f3cc75 100644 --- a/code/agt/data/protocol.py +++ b/code/agt/data/protocol.py @@ -1,13 +1,3 @@ -"""Clip protocol: which instants of a scene form a clip, and what each one is for. - -Everything is written in seconds and Hz; frame numbers are derived per scene from its timestamps (nearest exposure -midpoint) and stored in the clip record. On 30 fps data this gives 60-frame windows, sample stride 3 and context -offsets 0/15/30/45. The selection tolerance is a data-side parameter (eval_sets/.frame_selection.json, -see agt.data.store.frame_selection); the protocol JSON is unchanged by it. - -The protocol is a small JSON object. ``protocol_id`` = sha256 of its canonical JSON (sorted keys, no whitespace, -UTF-8). -""" from __future__ import annotations from dataclasses import dataclass, field, fields @@ -18,8 +8,6 @@ from pathlib import Path SCHEMA = 'clip_protocol_v1' PROTOCOL_DIR = Path(__file__).resolve().parent / 'protocols' -# The scoring grid is the native frame resized as a whole (anisotropic, no crop), with one resampling function for -# GT, labels and method outputs. GRID_518x294 = { 'width': 518, 'height': 294, @@ -47,24 +35,20 @@ class ClipProtocol: name: str = 'clips' version: str = '1' schema: str = SCHEMA - # ---- frame protocol ---- window_s: float = 2.0 sample_hz: float = 10.0 context_s: tuple = (0.0, 0.5, 1.0, 1.5) - # ---- windows ---- window_mode: str = 'full' - window_starts_s: tuple | None = None # list mode only - full_first_s: float = 0.0 # full: first_s, first_s + window_s, ... while the window fits - partial_starts_s: tuple = (0.0, 9.0) # partial: these, then min(partial_last_s, T - window_s) + window_starts_s: tuple | None = None + full_first_s: float = 0.0 + partial_starts_s: tuple = (0.0, 9.0) partial_last_s: float = 17.97 duration_rule: str = 'T = frame_count * mean_frame_period; window fits if start + window_s <= T + period/2' frame_selection: str = 'nearest_exposure_midpoint_within_half_mean_frame_period' - # ---- time, pose, normalisation ---- - frame_time: str = 'exposure_midpoint' # (timestamp_start_us + timestamp_end_us) / 2 - pose_time: str = 'exposure_midpoint' # translation mean, rotation Slerp at 0.5 - pose_reference: str = 'first_context_frame' # c2w[first context] = I + frame_time: str = 'exposure_midpoint' + pose_time: str = 'exposure_midpoint' + pose_reference: str = 'first_context_frame' t_norm: str = '(t - t_context_first) / (t_context_last - t_context_first)' - # ---- scoring grid ---- grid: dict = field(default_factory=lambda: dict(GRID_518x294)) def __post_init__(self): @@ -98,7 +82,6 @@ class ClipProtocol: if key not in self.grid: raise ValueError('grid needs ' + key) - # ---- sampling lattice ---------------------------------------------- def n_samples(self) -> int: return int(round(self.window_s * self.sample_hz)) @@ -109,7 +92,6 @@ class ClipProtocol: return tuple(_us(c) for c in self.context_s) def roles(self) -> tuple: - """Role of each sample, in sample order.""" ctx = self.context_us() first, last = ctx[0], ctx[-1] out = [] @@ -125,15 +107,12 @@ class ClipProtocol: return tuple(out) def frame_set_positions(self, which: str) -> list: - """Sample positions of a frame set: heldout = interp + extrap, recon = context.""" roles = self.roles() wanted = {'heldout': (ROLE_INTERP, ROLE_EXTRAP), 'interp': (ROLE_INTERP,), 'extrap': (ROLE_EXTRAP,), 'recon': (ROLE_CONTEXT,)}[which] return [i for i, r in enumerate(roles) if r in wanted] - # ---- windows --------------------------------------------------------- def window_starts_us(self, duration_us: float, period_us: float) -> list: - """Window start times (us, scene time with frame 0 at 0) for a scene of the given duration.""" W = _us(self.window_s) tol = period_us / 2 @@ -157,7 +136,6 @@ class ClipProtocol: raise ValueError(f'windows {bad or "none"} do not fit a {duration_us/US:.4f} s scene') return starts - # ---- identity -------------------------------------------------------- def to_dict(self) -> dict: d = {f.name: getattr(self, f.name) for f in fields(self)} for key in ('context_s', 'partial_starts_s', 'window_starts_s'): @@ -191,7 +169,6 @@ class ClipProtocol: @classmethod def load(cls, name_or_path='partial') -> 'ClipProtocol': - """A protocol by name ('partial': 3 windows per scene; 'full': consecutive windows) or a JSON file.""" path = Path(name_or_path) if not str(name_or_path).endswith('.json'): path = PROTOCOL_DIR / f'{name_or_path}.json' diff --git a/code/agt/data/reader.py b/code/agt/data/reader.py index ba6355433098b027cf5e0c2c9b610be28a9b3ae1..d5e55a18ce260ef3ea8b30c34b585859fe16a6b5 100644 --- a/code/agt/data/reader.py +++ b/code/agt/data/reader.py @@ -1,4 +1,3 @@ -"""ClipReader: protocol x scene index -> clip list, and clip -> the arrays the scorer and the export read.""" from __future__ import annotations from collections import OrderedDict @@ -45,19 +44,15 @@ class ClipReader: return clips def skipped_windows(self) -> list: - """Windows left out (never repaired) because a sample had no frame within the source's selection tolerance or - two samples took the same frame.""" self.clips() return [w for sample_id in sorted(self._skipped) for w in self._skipped[sample_id]] def clips(self) -> list: - """Deterministic enumeration: samples in sample-key order, windows in time order.""" if self._clips is None: self._clips = [c for record in self.index for c in self.clips_for(self.index.sample_id(record))] return list(self._clips) def load(self, clip: dict, *, rgb=RGB_KINDS) -> dict: - """Arrays in protocol sample order: rgb_clean / rgb_dirty (uint8 on the grid), poses, times, roles, cameras.""" src = self.source(clip['sample_id']) idx = [int(i) for i in clip['frame_indices']] out = {'frame_indices': np.asarray(idx, dtype=np.int64), @@ -92,6 +87,5 @@ class ClipReader: def open_reader(data_root, split: str, protocol: ClipProtocol, *, map_version: str = 'v2', sources=None, time_of_day: str = 'both', **kwargs) -> ClipReader: - """ClipReader of one split of a data root (scene store rebuilt locally + the released metadata).""" index = SceneIndex.from_data_root(data_root, split, map_version=map_version, sources=sources, time_of_day=time_of_day) return ClipReader(index, protocol, **kwargs) diff --git a/code/agt/data/scene.py b/code/agt/data/scene.py index 2baac5ef9f5d754b66f5f1dcd8f49d8a6ac2d09c..6147414275baea9a81ba276f7f50f785a5a34005 100644 --- a/code/agt/data/scene.py +++ b/code/agt/data/scene.py @@ -1,5 +1,3 @@ -"""Scene records (where things are), scene index (which samples), label sets and scene sources (how to read one -sample on the protocol's grid).""" from __future__ import annotations from dataclasses import dataclass, field @@ -22,18 +20,14 @@ def read_jsonl(path): def native_camera(camera_json: dict, dataset_id: str) -> tuple: - """Principal point as declared (NuRec cameras: pixel-edge convention converted to integer centres).""" profile = DATASET_CAMERA_PROFILES.get(dataset_id, DECLARED_INTEGER_PROFILE) return PinholeCamera.from_json(camera_json, calibration_profile=profile), profile -# ---- label sets ------------------------------------------------------------------------------ LABEL_MANIFEST = 'label_manifest.json' class LabelSet: - """Per-scene label files under one root, described by its label_manifest.json (name, version, grid, layers).""" - def __init__(self, root, manifest: dict): self.root, self.manifest = Path(root), manifest self.name, self.version = manifest['name'], int(manifest['version']) @@ -57,21 +51,18 @@ class LabelSet: @property def unavailable(self) -> dict: - """{scene_id: entry} of the root's unavailable.json (scenes this label set cannot have; {} without one).""" if self._unavailable is None: from .store import read_unavailable self._unavailable = read_unavailable(self.root) return self._unavailable def require(self, scene_id: str): - """Raise store.LabelsUnavailable when the root lists the scene as unavailable (no labels, never zeros).""" if scene_id in self.unavailable: from .store import unavailable_error source = self.manifest.get('source_id', self.root.name) raise unavailable_error(self.name, self.root.parent.name, source, [scene_id], self.unavailable, self.root) -# ---- records and index ----------------------------------------------------------------------- @dataclass class SceneRecord: dataset_id: str @@ -79,13 +70,13 @@ class SceneRecord: camera_id: str variant_id: str frame_count: int - files: dict # clean, camera, frames, scene_stats[, template_layers] + files: dict time_of_day: str = 'unknown' group: str = 'unknown' template_id: str = '' source_id: str | None = None fps: float | None = None - resolution: tuple | None = None # stored video (width, height) + resolution: tuple | None = None split: str | None = None official_split: str | None = None map_version: str | None = None @@ -104,8 +95,6 @@ class SceneRecord: @classmethod def from_rows(cls, scene_row: dict, eval_row: dict, map_row: dict, data_root, template_file: str) -> 'SceneRecord': - """One sample: scene-store row (where the clean scene is) + split row + map row (which layer, which lighting - profile, which noise seed). The obstructed frames are composed at read time.""" root = Path(data_root) files = {'clean': str(root / scene_row['files']['rgb']['relative_path'])} for key in ('camera', 'frames', 'scene_stats'): @@ -125,8 +114,6 @@ class SceneRecord: class SceneIndex: - """Ordered samples of one split (one sample per scene).""" - def __init__(self, records, *, eval_set_id: str, info: dict | None = None): self.records = sorted(records, key=lambda r: r.sample_key) keys = [r.sample_key for r in self.records] @@ -149,8 +136,6 @@ class SceneIndex: return '__'.join(record.sample_key[1:]) def selection_tolerance_us(self, record: SceneRecord) -> float | None: - """Frame-selection tolerance the data declares for the record's source; None = half the scene's mean frame - period.""" block = self.info.get('frame_selection') if block is None: return None @@ -165,23 +150,17 @@ class SceneIndex: @classmethod def from_data_root(cls, root, split: str, *, map_version: str = 'v2', sources=None, time_of_day: str = 'both') -> 'SceneIndex': - """scenes/manifest.jsonl x eval_sets//.jsonl x maps//.jsonl; sources: subset - of the map's enabled sources (None = all); time_of_day: 'day' (= day + dawn) | 'night' | 'both'.""" from .store import build_records records, info = build_records(root, split, map_version=map_version, sources=sources, time_of_day=time_of_day) return cls(records, eval_set_id=f"amodaldrive_map_{map_version}_{split}", info=info) -# ---- one sample ------------------------------------------------------------------------------ class SceneSource: - """One sample, opened once: camera, timing, poses, RGB on demand.""" - def __init__(self, record: SceneRecord, grid: ScoringGrid, *, thread_count=2, thread_type=None): self.record, self.grid = record, grid self.thread_count, self.thread_type = thread_count, thread_type clean_dir = record.clean_dir self.camera, self.calibration_profile = native_camera(read_json(clean_dir / 'camera.json'), record.dataset_id) - # The stored video is on the grid (518x294); a camera.json at another resolution is mapped to the grid. self.stored_size = tuple(int(v) for v in record.resolution) same = (self.camera.width, self.camera.height) == (grid.width, grid.height) self.grid_camera = self.camera if same else grid.camera(self.camera) @@ -206,7 +185,6 @@ class SceneSource: return self._video def rgb(self, kind: str, indices) -> np.ndarray: - """(N, 294, 518, 3) uint8 in the order of `indices`; 'dirty' = compose(clean) with the map row's layer.""" indices = [int(i) for i in indices] if kind == 'dirty': return self.compose(self.rgb('clean', indices), indices) @@ -220,19 +198,16 @@ class SceneSource: return out def template(self): - """store.PreparedTemplate of this scene's map row (day layers, or night-adapted layers + parameters).""" if self._template is None: from .store import prepared_template self._template = prepared_template(self.record) return self._template def compose(self, clean_u8, indices) -> np.ndarray: - """uint8 obstructed frames from uint8 clean frames at absolute `indices`.""" from .store import compose return compose(clean_u8, indices, self.template()) def poses(self, indices, *, reference: int) -> np.ndarray: - """Exposure-midpoint camera-to-world poses relative to frame `reference`.""" indices = [int(i) for i in indices] poses = np.stack([exposure_midpoint(self.frames_meta[i]) for i in indices]) if int(reference) == indices[0]: diff --git a/code/agt/data/store.py b/code/agt/data/store.py index 8294ac4362b5eb71a415bbf7a916f8bec9211fb9..4a411cd6a66ab7ad7060b98f147fdcbdf978fa06 100644 --- a/code/agt/data/store.py +++ b/code/agt/data/store.py @@ -1,26 +1,3 @@ -"""Data root: scene store + occluder-layer pool + pairing map, joined into SceneRecords; layer loading and the -read-time composition used by SceneSource. - -Layout (all paths relative to the data root): - scenes/manifest.jsonl one row per rebuilt scene (source_id, dataset_id, fps, frame_count, ...) - scenes///{rgb.mp4 518x294, frames.jsonl, camera.json, scene_stats.json} - eval_sets//.jsonl the split rows (scene_id, source_id, split, ...) - eval_sets/.frame_selection.json frame-selection tolerance per source - maps//{.jsonl, map.json} one row per (source, scene): template_id, lighting_profile, noise_seed - templates/pool.json template_id -> layer file (data-root relative) + partition - templates/layers//layers_518x294.h5 8 static layers + roles/ masks - masks/ground_truth|predicted///mask.h5 occluder masks - labels/