File size: 16,728 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
 
 
 
 
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from __future__ import annotations

from collections import OrderedDict
from dataclasses import dataclass
import io
import json
import math
from pathlib import Path

import numpy as np

SCENE_MANIFEST = 'scenes/manifest.jsonl'
TEMPLATE_SIZE_WH = (518, 294)
ROLE_GROUP = 'roles'
LAYER_NAMES = {'dc_alpha', 'dc_observation_rgb', 'solid_rgb', 'solid_mask_hard', 'solid_mask_blend',
               'effective_alpha', 'bottom_forced_mask', 'hole_filled_mask'}
TIME_OF_DAY_FILTERS = ('day', 'night', 'both')
DAY_GROUP = ('day', 'dawn')


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 group_of(time_of_day: str) -> str:
    return 'day' if time_of_day in DAY_GROUP else 'night'


def _check(condition, message):
    if not condition:
        raise ValueError(message)


def load_template_layers(data: bytes, *, source: str = '<bytes>') -> tuple:
    import h5py
    width, height = TEMPLATE_SIZE_WH
    binary = {'solid_mask_hard', 'bottom_forced_mask', 'hole_filled_mask'}
    rgb = {'dc_observation_rgb', 'solid_rgb'}
    with h5py.File(io.BytesIO(data), 'r') as handle:
        datasets = {k for k, v in handle.items() if isinstance(v, h5py.Dataset)}
        groups = {k for k, v in handle.items() if isinstance(v, h5py.Group)}
        if datasets != LAYER_NAMES or not groups <= {ROLE_GROUP} or not handle.attrs.get('static_across_frames', False):
            raise ValueError(f'{source}: template layers have an invalid schema ({sorted(datasets)}, groups {sorted(groups)})')
        if 'lighting_adaptation' in handle.attrs:
            raise ValueError(f'{source}: template layers must be the day layers (adaptation happens at read time)')
        layers = {}
        for name in sorted(datasets):
            value = handle[name][:]
            shape = (height, width, 3) if name in rgb else (height, width)
            dtype = np.uint8 if name in binary else np.float32
            if value.shape != shape or value.dtype != dtype or not np.isfinite(value).all():
                raise ValueError(f'{source}: invalid template layer {name} {value.shape} {value.dtype}')
            if np.any(value < 0) or np.any(value > 1):
                raise ValueError(f'{source}: template layer outside [0, 1]: {name}')
            layers[name] = value
        roles = {}
        if ROLE_GROUP in handle:
            for role, dataset in handle[ROLE_GROUP].items():
                value = dataset[:]
                if value.shape != (height, width) or value.dtype != np.float32 or not np.isin(value, (0, 1)).all():
                    raise ValueError(f'{source}: invalid role mask {role}')
                roles[role] = value
        attrs = {k: (v.item() if hasattr(v, 'item') else v) for k, v in handle.attrs.items()}
    solid = layers['solid_mask_hard'].astype(bool)
    if not np.all(layers['solid_mask_blend'][solid] == 1):
        raise ValueError(f'{source}: solid pixels must remain fully opaque')
    expected = layers['solid_mask_blend'] + (1 - layers['solid_mask_blend']) * layers['dc_alpha']
    if not np.array_equal(expected, layers['effective_alpha']):
        raise ValueError(f'{source}: effective alpha is inconsistent with the template layers')
    if not np.all(solid[layers['bottom_forced_mask'].astype(bool)]):
        raise ValueError(f'{source}: bottom forced pixels are not solid opaque')
    for value in list(layers.values()) + list(roles.values()):
        value.setflags(write=False)
    return layers, roles, attrs


class LRU:
    def __init__(self, capacity: int):
        self.capacity = max(1, int(capacity))
        self.items = OrderedDict()

    def get(self, key, make):
        if key in self.items:
            self.items.move_to_end(key)
            return self.items[key]
        value = make()
        self.items[key] = value
        while len(self.items) > self.capacity:
            self.items.popitem(last=False)
        return value


TEMPLATES = LRU(8)
PREPARED = LRU(8)
_PROFILES = {}


def template_layers(path) -> tuple:
    return TEMPLATES.get(str(path), lambda: load_template_layers(Path(path).read_bytes(), source=str(path)))


def lighting_profile(profile_id: str) -> dict:
    if profile_id not in _PROFILES:
        from .compose import load_lighting_profile
        _PROFILES[profile_id] = load_lighting_profile(profile_id)
    return _PROFILES[profile_id]


def row_parameters(parameters: dict, noise_seed: int) -> dict:
    if isinstance(noise_seed, bool) or not isinstance(noise_seed, (int, np.integer)) or noise_seed < 0:
        raise ValueError(f'noise_seed must be a nonnegative integer, got {noise_seed!r}')
    return {**parameters, 'solid': {**parameters['solid'], 'noise_seed': int(noise_seed)}}


@dataclass(frozen=True)
class PreparedTemplate:
    layers: dict
    roles: dict
    parameters: dict | None


def prepared_template(record) -> PreparedTemplate:
    layers, roles, _ = template_layers(record.files['template_layers'])
    profile = lighting_profile(record.lighting_profile)
    expected = 'none' if record.group == 'day' else 'night_appearance_v1'
    if profile['adaptation'] != expected:
        raise ValueError(f'{record.scene_id}: group {record.group} needs adaptation {expected}, '
                         f'profile {record.lighting_profile} is {profile["adaptation"]}')
    if profile['adaptation'] == 'none':
        return PreparedTemplate(layers, roles, None)
    key = (str(record.files['template_layers']), record.scene_id, record.lighting_profile, int(record.noise_seed))

    def make():
        from .compose import adapt_layers
        stats = json.loads(Path(record.files['scene_stats']).read_bytes())
        adapted, metadata = adapt_layers(dict(layers), roles, stats, profile)
        for value in adapted.values():
            value.setflags(write=False)
        return PreparedTemplate(adapted, roles, row_parameters(metadata['parameters'], record.noise_seed))
    return PREPARED.get(key, make)


def compose(clean_u8: np.ndarray, indices, prepared: PreparedTemplate) -> np.ndarray:
    from .compose import compose_batch, to_uint8
    clean = np.asarray(clean_u8)
    if clean.dtype != np.uint8 or clean.ndim != 4 or clean.shape[0] != len(indices):
        raise ValueError('compose expects (N, H, W, 3) uint8 clean frames and one absolute index per frame')
    frames = clean.astype(np.float32) / 255
    return to_uint8(compose_batch(frames, np.asarray([int(i) for i in indices], np.int64), prepared.layers,
                                  lighting=prepared.parameters))


class MissingLabels(FileNotFoundError):
    pass


class LabelsUnavailable(MissingLabels):
    pass


UNAVAILABLE = 'unavailable.json'


def label_root(data_root, version: str, source_id: str) -> Path:
    return Path(data_root) / 'labels' / version / source_id


def read_unavailable(root) -> dict:
    path = Path(root) / UNAVAILABLE
    if not path.is_file():
        return {}
    out = {}
    for entry in read_json(path)['scenes']:
        _check(entry['scene'] not in out, f'{path}: scene {entry["scene"]} listed twice')
        out[entry['scene']] = entry
    return out


def unavailable_error(name: str, version: str, source: str, scenes, entries: dict, root) -> LabelsUnavailable:
    scenes = sorted(scenes)
    reasons = sorted({str(entries[s].get('reason', 'no reason given')) for s in scenes})
    return LabelsUnavailable(
        f'label set {version} ({name}) is unavailable for {len(scenes)} {source} scene(s) of this request (e.g. '
        f'{scenes[:5]}): {"; ".join(reasons)}; listed in {Path(root) / UNAVAILABLE}')


FRAME_SELECTION_SUFFIX = '.frame_selection.json'
SELECTION_SCENE_MEAN = 'half_scene_mean_frame_period'
SELECTION_LONGEST_REGULAR = 'half_longest_regular_interval'
FRAME_SELECTION_PARAMETERS = {
    'interval': 'exposure midpoint (timestamp_start_us + timestamp_end_us) / 2 of frame k+1 minus that of frame k',
    'bin_us': 10_000,
    'regular_share': 0.05,
    'dropout_periods': 1.5,
    'cadence_tolerance': 0.01,
    'long_interval_rounding_us': 1_000,
}


def selection_from_histogram(histogram: dict, medians: dict, means: dict, fps, parameters: dict) -> dict:
    total = sum(int(k) for k in histogram.values())
    _check(total > 0, 'empty interval histogram')
    _check(fps is not None and float(fps) > 0, f'nominal fps {fps!r} is not positive')
    nominal = 1e6 / float(fps)
    frequent = sorted(int(v) for v, k in histogram.items() if int(k) >= parameters['regular_share'] * total)
    regular = [v for v in frequent if float(medians[str(v)]) < parameters['dropout_periods'] * nominal]
    mean, matched = None, False
    if regular:
        weight = sum(int(histogram[str(v)]) for v in regular)
        mean = sum(int(histogram[str(v)]) * float(means[str(v)]) for v in regular) / weight
        matched = abs(mean - nominal) <= parameters['cadence_tolerance'] * nominal
    out = {'frequent_intervals_ms': frequent, 'dropout_intervals_ms': [v for v in frequent if v not in regular],
           'regular_intervals_ms': regular, 'regular_mean_us': mean, 'nominal_period_us': nominal,
           'cadence_matched': bool(matched)}
    if len(regular) < 2 or not matched:
        return {**out, 'selection': SELECTION_SCENE_MEAN, 'long_interval_us': None, 'tolerance_us': None}
    step = parameters['long_interval_rounding_us']
    long_us = int(math.floor(float(medians[str(regular[-1])]) / step + 0.5) * step)
    return {**out, 'selection': SELECTION_LONGEST_REGULAR, 'long_interval_us': long_us, 'tolerance_us': long_us / 2}


def frame_selection(root, eval_path: str, sources) -> dict:
    path = Path(root) / (str(eval_path).rstrip('/') + FRAME_SELECTION_SUFFIX)
    if not path.is_file():
        return {s: {'selection': SELECTION_SCENE_MEAN, 'tolerance_us': None} for s in sources}
    doc = read_json(path)
    _check({k: (doc.get('parameters') or {}).get(k) for k in FRAME_SELECTION_PARAMETERS} == FRAME_SELECTION_PARAMETERS,
           f'{path}: parameters {doc.get("parameters")} differ from this code ({FRAME_SELECTION_PARAMETERS})')
    out = {}
    for source in sorted(sources):
        entry = (doc.get('sources') or {}).get(source)
        _check(entry is not None, f'{path}: no frame-selection entry for source {source!r}')
        derived = selection_from_histogram(entry['histogram_ms'], entry['median_us_by_value'], entry['mean_us_by_value'],
                                           entry['fps'], doc['parameters'])
        stored = {k: entry.get(k) for k in derived}
        _check(stored == derived, f'{path}: {source} declares {stored}, its histogram gives {derived}')
        out[source] = {'selection': derived['selection'], 'tolerance_us': derived['tolerance_us']}
    return out


def manifest_records(root, source_id: str, scene_ids=None) -> list:
    from .scene import SceneRecord
    root = Path(root)
    rows = [r for r in read_jsonl(root / SCENE_MANIFEST) if r['source_id'] == source_id]
    ids = [r['scene_id'] for r in rows]
    _check(len(set(ids)) == len(ids), f'{SCENE_MANIFEST}: repeated {source_id} scene ids')
    if scene_ids is not None:
        wanted = set(scene_ids)
        unknown = sorted(wanted - set(ids))
        _check(not unknown, f'{source_id} scenes not in {SCENE_MANIFEST}: {unknown[:5]}')
        rows = [r for r in rows if r['scene_id'] in wanted]
    records = []
    for row in sorted(rows, key=lambda r: r['scene_id']):
        _check(row.get('resolution') == list(TEMPLATE_SIZE_WH), f"{row['scene_id']}: stored resolution {row.get('resolution')}")
        files = {'clean': str(root / row['files']['rgb']['relative_path'])}
        for key in ('camera', 'frames', 'scene_stats'):
            files[key] = str(root / row['files'][key]['relative_path'])
        _check(Path(files['clean']).parent == Path(files['camera']).parent, f"{row['scene_id']}: scene files are not in one directory")
        records.append(SceneRecord(dataset_id=row['dataset_id'], scene_id=row['scene_id'], camera_id=row['camera_id'],
                                   variant_id='clean', frame_count=int(row['frame_count']), files=files,
                                   time_of_day=row['time_of_day'], group=row['group'], source_id=source_id,
                                   fps=row['fps'], resolution=tuple(row['resolution']),
                                   official_split=row.get('official_split')))
    return records


def build_records(root, split: str, *, map_version: str = 'v2', sources=None, time_of_day: str = 'both') -> tuple:
    from .scene import SceneRecord
    root = Path(root)
    if time_of_day not in TIME_OF_DAY_FILTERS:
        raise ValueError(f'time_of_day must be one of {TIME_OF_DAY_FILTERS}, got {time_of_day!r}')
    map_dir = root / 'maps' / map_version
    map_json = read_json(map_dir / 'map.json')
    _check(map_json.get('version') == map_version, f'{map_dir}/map.json: version {map_json.get("version")!r} != {map_version!r}')
    _check(split in map_json.get('tables', {}), f'map {map_version} has no {split!r} table')
    eval_info = map_json['eval_sets']
    eval_path = root / eval_info['path'] / f'{split}.jsonl'
    map_path = map_dir / f'{split}.jsonl'
    pool_path = root / map_json['pool']['path']
    enabled = sorted(map_json.get('sources_enabled', []))
    wanted = enabled if sources is None else sorted(set(sources))
    unknown = sorted(set(wanted) - set(enabled))
    _check(not unknown and wanted, f'sources {unknown or wanted} not in map {map_version} (enabled: {enabled})')
    pool = read_json(pool_path)['templates']
    scenes = {}
    for r in read_jsonl(root / SCENE_MANIFEST):
        key = (r['source_id'], r['scene_id'])
        _check(key not in scenes, f'{SCENE_MANIFEST}: duplicate row {key}')
        scenes[key] = r
    selection = frame_selection(root, eval_info['path'], wanted)
    eval_rows = [r for r in read_jsonl(eval_path) if r['source_id'] in wanted]
    map_rows = {}
    for row in read_jsonl(map_path):
        if row['source_id'] in wanted:
            key = (row['source_id'], row['scene_id'])
            _check(key not in map_rows, f'map {map_version}/{split}: duplicate row {key}')
            map_rows[key] = row
    eval_keys = {(r['source_id'], r['scene_id']) for r in eval_rows}
    _check(len(eval_keys) == len(eval_rows), f'{eval_path}: duplicate scenes')
    missing = sorted(eval_keys - set(map_rows))
    _check(not missing, f'{len(missing)} scenes of {eval_path.name} have no row in maps/{map_version}/{split}.jsonl '
                        f'(e.g. {missing[:3]})')
    extra = sorted(set(map_rows) - eval_keys)
    _check(not extra, f'maps/{map_version}/{split}.jsonl has {len(extra)} rows for scenes not in the split (e.g. {extra[:3]})')
    records = []
    for erow in eval_rows:
        key = (erow['source_id'], erow['scene_id'])
        srow, mrow = scenes.get(key), map_rows[key]
        _check(srow is not None, f'{key} is not in {SCENE_MANIFEST} (rebuild the scene store first)')
        for field in ('dataset_id', 'fps', 'frame_count', 'time_of_day', 'group'):
            _check(erow.get(field) == srow.get(field), f'{key}: eval row {field}={erow.get(field)!r} != scene store {srow.get(field)!r}')
        for field in ('time_of_day', 'group'):
            _check(mrow.get(field) == srow.get(field), f'{key}: map row {field}={mrow.get(field)!r} != scene store {srow.get(field)!r}')
        _check(srow['group'] == group_of(srow['time_of_day']), f'{key}: group {srow["group"]} != group_of({srow["time_of_day"]})')
        _check(erow['split'] == split and mrow['split'] == split, f'{key}: split rows disagree with {split!r}')
        _check(mrow['partition'] == split, f'{key}: layer partition {mrow["partition"]} != split {split}')
        _check(mrow['map_version'] == map_version, f'{key}: map_version {mrow["map_version"]} != {map_version}')
        _check(srow.get('resolution') == list(TEMPLATE_SIZE_WH), f'{key}: stored resolution {srow.get("resolution")} != 518x294')
        entry = pool.get(mrow['template_id'])
        _check(entry is not None, f'{key}: layer {mrow["template_id"]} is not in the pool {pool_path.name}')
        _check(entry['partition'] == split, f'{key}: pool partition of {mrow["template_id"]} is {entry["partition"]}')
        records.append(SceneRecord.from_rows(srow, erow, mrow, root, entry['file']))
    if time_of_day != 'both':
        records = [r for r in records if r.group == time_of_day]
    info = {'split': split, 'map_version': map_version, 'eval_version': Path(eval_info['path']).name,
            'eval_path': eval_info['path'], 'sources': wanted, 'time_of_day': time_of_day,
            'frame_selection': selection}
    return records, info