File size: 4,262 Bytes
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
from __future__ import annotations

from collections import OrderedDict
from dataclasses import asdict

import numpy as np

from .clips import build_clips
from .grid import ScoringGrid
from .protocol import ClipProtocol
from .scene import SceneIndex, SceneSource


class ClipReader:
    RGB_KINDS = ('clean', 'dirty')

    def __init__(self, index: SceneIndex, protocol: ClipProtocol, *, thread_count=2, thread_type=None, cache_scenes=2):
        self.index, self.protocol = index, protocol
        self.grid = ScoringGrid(protocol.grid)
        self.thread_count, self.thread_type = thread_count, thread_type
        self._sources = OrderedDict()
        self._cache_scenes = max(1, int(cache_scenes))
        self._clips = None
        self._skipped = {}

    def source(self, sample_id: str) -> SceneSource:
        if sample_id in self._sources:
            self._sources.move_to_end(sample_id)
            return self._sources[sample_id]
        src = SceneSource(self.index.by_id[sample_id], self.grid, thread_count=self.thread_count,
                          thread_type=self.thread_type)
        self._sources[sample_id] = src
        while len(self._sources) > self._cache_scenes:
            _, old = self._sources.popitem(last=False)
            old.close()
        return src

    def clips_for(self, sample_id: str) -> list:
        record = self.index.by_id[sample_id]
        skipped = []
        clips = build_clips(self.protocol, record, self.source(sample_id).frames_meta, sample_id=sample_id,
                            skipped=skipped, tolerance_us=self.index.selection_tolerance_us(record))
        self._skipped[sample_id] = skipped
        return clips

    def skipped_windows(self) -> list:
        self.clips()
        return [w for sample_id in sorted(self._skipped) for w in self._skipped[sample_id]]

    def clips(self) -> list:
        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:
        src = self.source(clip['sample_id'])
        idx = [int(i) for i in clip['frame_indices']]
        out = {'frame_indices': np.asarray(idx, dtype=np.int64),
               'timestamps_us': src.timestamps_mid_us[idx].copy(),
               'timestamps_start_us': src.timestamps_start_us[idx].copy(),
               'is_keyframe': np.asarray(clip['is_keyframe'], dtype=np.uint8),
               'roles': np.asarray(clip['roles']),
               't_norm': np.asarray(clip['t_norm'], dtype=np.float64)}
        np.testing.assert_array_equal(out['timestamps_us'], np.asarray(clip['timestamps_us']))
        out['c2w'] = src.poses(idx, reference=clip['context_frames'][0])
        for kind in rgb:
            if kind not in self.RGB_KINDS:
                raise ValueError(kind)
            out['rgb_' + kind] = src.rgb(kind, idx)
        out['camera_params'] = asdict(src.grid_camera)
        out['native_camera'] = asdict(src.camera)
        record = src.record
        out['metadata'] = {'clip_id': clip['clip_id'], 'sample_id': clip['sample_id'], 'sample_key': clip['sample_key'],
                           'protocol_id': self.protocol.protocol_id, 'window_mode': self.protocol.window_mode,
                           'grid': self.grid.label, 'eval_set_id': self.index.eval_set_id,
                           'calibration_profile': src.calibration_profile, 'source_id': record.source_id,
                           'template_id': record.template_id, 'map_version': record.map_version,
                           'lighting_profile': record.lighting_profile, 'noise_seed': record.noise_seed,
                           'time_of_day': record.time_of_day, 'group': record.group}
        return out

    def close(self):
        for src in self._sources.values():
            src.close()
        self._sources.clear()


def open_reader(data_root, split: str, protocol: ClipProtocol, *, map_version: str = 'v2', sources=None,
                time_of_day: str = 'both', **kwargs) -> ClipReader:
    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)