AGT / code /agt /data /scene.py
MRBSTUDIO's picture
Update code and model card
fb3460f verified
Raw History Blame Contribute Delete
9.69 kB
from __future__ import annotations
from dataclasses import dataclass, field
import json
from pathlib import Path
import numpy as np
from .camera import DATASET_CAMERA_PROFILES, DECLARED_INTEGER_PROFILE, PinholeCamera, exposure_midpoint
from .grid import ScoringGrid
from .video import VideoSource
def read_json(path):
return json.loads(Path(path).read_text())
def read_jsonl(path):
return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
def native_camera(camera_json: dict, dataset_id: str) -> tuple:
profile = DATASET_CAMERA_PROFILES.get(dataset_id, DECLARED_INTEGER_PROFILE)
return PinholeCamera.from_json(camera_json, calibration_profile=profile), profile
LABEL_MANIFEST = 'label_manifest.json'
class LabelSet:
def __init__(self, root, manifest: dict):
self.root, self.manifest = Path(root), manifest
self.name, self.version = manifest['name'], int(manifest['version'])
self.file = manifest.get('file', 'masks.h5')
self._unavailable = None
@classmethod
def open(cls, root, *, name='motion') -> 'LabelSet':
root = Path(root)
manifest = read_json(root / LABEL_MANIFEST)
if manifest['name'] != name:
raise ValueError(f'{root}: label set is {manifest["name"]!r}, expected {name!r}')
return cls(root, manifest)
@property
def grid(self) -> dict:
return self.manifest['grid']
def path(self, scene_id: str) -> Path:
return self.root / scene_id / self.file
@property
def unavailable(self) -> dict:
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):
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)
@dataclass
class SceneRecord:
dataset_id: str
scene_id: str
camera_id: str
variant_id: str
frame_count: int
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
split: str | None = None
official_split: str | None = None
map_version: str | None = None
lighting_profile: str | None = None
noise_seed: int | None = None
partition: str | None = None
source_group_id: str | None = None
@property
def sample_key(self) -> tuple:
return (self.dataset_id, self.scene_id, self.camera_id, self.variant_id)
@property
def clean_dir(self) -> Path:
return Path(self.files['clean']).parent
@classmethod
def from_rows(cls, scene_row: dict, eval_row: dict, map_row: dict, data_root, template_file: str) -> 'SceneRecord':
root = Path(data_root)
files = {'clean': str(root / scene_row['files']['rgb']['relative_path'])}
for key in ('camera', 'frames', 'scene_stats'):
files[key] = str(root / scene_row['files'][key]['relative_path'])
files['template_layers'] = str(root / template_file)
if Path(files['clean']).parent != Path(files['camera']).parent:
raise ValueError(f"{scene_row['scene_id']}: scene files are not in one directory")
return cls(dataset_id=scene_row['dataset_id'], scene_id=scene_row['scene_id'], camera_id=scene_row['camera_id'],
variant_id=f"map_{map_row['map_version']}_{map_row['template_id']}",
frame_count=int(scene_row['frame_count']), files=files, time_of_day=scene_row['time_of_day'],
group=scene_row['group'], template_id=map_row['template_id'],
source_id=scene_row['source_id'], fps=scene_row['fps'], resolution=tuple(scene_row['resolution']),
split=eval_row['split'], official_split=scene_row.get('official_split'),
map_version=map_row['map_version'], lighting_profile=map_row['lighting_profile'],
noise_seed=int(map_row['noise_seed']), partition=map_row['partition'],
source_group_id=map_row.get('source_group_id'))
class SceneIndex:
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]
if len(set(keys)) != len(keys):
raise ValueError('Duplicate sample keys')
scenes = [r.scene_id for r in self.records]
self._unique_scenes = len(set(scenes)) == len(scenes)
self.by_id = {self.sample_id(r): r for r in self.records}
self.eval_set_id = eval_set_id
self.info = dict(info or {})
per_source = {}
for r in self.records:
per_source.setdefault(r.source_id, set()).add((r.dataset_id, r.camera_id))
if any(len(v) > 1 for v in per_source.values()):
raise ValueError(f'One source must use one camera; found {per_source}')
def sample_id(self, record: SceneRecord) -> str:
if self._unique_scenes:
return record.scene_id
return '__'.join(record.sample_key[1:])
def selection_tolerance_us(self, record: SceneRecord) -> float | None:
block = self.info.get('frame_selection')
if block is None:
return None
return block[record.source_id]['tolerance_us']
def __len__(self):
return len(self.records)
def __iter__(self):
return iter(self.records)
@classmethod
def from_data_root(cls, root, split: str, *, map_version: str = 'v2', sources=None,
time_of_day: str = 'both') -> 'SceneIndex':
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)
class SceneSource:
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)
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)
if self.stored_size != (grid.width, grid.height):
raise ValueError(f'{record.scene_id}: stored video {self.stored_size} is not on the {grid.label} grid')
self.frames_meta = read_jsonl(clean_dir / 'frames.jsonl')
if len(self.frames_meta) != record.frame_count:
raise ValueError(f'{record.scene_id}: frames.jsonl rows {len(self.frames_meta)} != {record.frame_count}')
if [f['frame_index'] for f in self.frames_meta] != list(range(record.frame_count)):
raise ValueError(f'{record.scene_id}: frame_index column is not 0..N-1')
self.timestamps_start_us = np.asarray([f['timestamp_start_us'] for f in self.frames_meta], dtype=np.int64)
self.timestamps_end_us = np.asarray([f['timestamp_end_us'] for f in self.frames_meta], dtype=np.int64)
if np.any(np.diff(self.timestamps_start_us) <= 0) or np.any(self.timestamps_end_us < self.timestamps_start_us):
raise ValueError(f'{record.scene_id}: invalid frame timestamps')
self.timestamps_mid_us = (self.timestamps_start_us.astype(np.float64) + self.timestamps_end_us) / 2
self._video, self._template = None, None
def video(self) -> VideoSource:
if self._video is None:
self._video = VideoSource(self.record.files['clean'], thread_count=self.thread_count,
thread_type=self.thread_type, expected_frames=self.record.frame_count)
return self._video
def rgb(self, kind: str, indices) -> np.ndarray:
indices = [int(i) for i in indices]
if kind == 'dirty':
return self.compose(self.rgb('clean', indices), indices)
if kind != 'clean':
raise ValueError(kind)
frames = self.video().decode_native(indices)
out = np.stack([frames[i] for i in indices])
width, height = self.stored_size
if out.shape[1:] != (height, width, 3):
raise ValueError(f'{self.record.scene_id}: stored RGB {out.shape[1:]} != {width}x{height}')
return out
def template(self):
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:
from .store import compose
return compose(clean_u8, indices, self.template())
def poses(self, indices, *, reference: int) -> np.ndarray:
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]:
return np.linalg.inv(poses[0])[None] @ poses
return np.linalg.inv(exposure_midpoint(self.frames_meta[int(reference)]))[None] @ poses
def close(self):
if self._video is not None:
self._video.close()
self._video = None