File size: 12,518 Bytes
f41f1f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read the HandDiffuse relative-path episode layout without modifying data.

NumPy is needed only for load_motion(). No MANO models, renderer, video decoder,
or machine-specific paths are required. See README.md for the draft's limits.
"""
from __future__ import annotations

import csv
import json
from dataclasses import dataclass
from fractions import Fraction
from pathlib import Path, PurePosixPath
from typing import Callable, Iterator


@dataclass(frozen=True)
class Frame:
    motion_index: int
    video_index: int | None
    video_pts: int | None
    video_time_base: Fraction | None
    video_timestamp_seconds: str | None
    quality_flags: tuple[str, ...] = ()
    alignment_certainty: str = 'SUPPORTED_BY_RECORDED_EVIDENCE'
    alternative_video_index: int | None = None
    alternative_video_pts: int | None = None
    alternative_video_timestamp_seconds: str | None = None

    @property
    def has_approximate_timing(self) -> bool:
        return self.alignment_certainty == 'APPROXIMATE_ADJACENT_FRAME_SELECTION'

    @property
    def available(self) -> bool:
        return self.video_index is not None

    @property
    def passes_recorded_screens(self) -> bool:
        """Availability and recorded screens only; not an accuracy guarantee."""
        return self.available and not self.quality_flags


def _relative(value: str) -> PurePosixPath:
    path = PurePosixPath(value)
    if not value or path.is_absolute() or '..' in path.parts or '\\' in value:
        raise ValueError(f'Expected a confined relative package path: {value!r}')
    return path


class Episode:
    """One selected pair of hands and explicitly listed camera views.

    root is the package root containing episodes/. An optional resolver maps
    package-relative paths to existing read-only files for curation without
    staging media. Published datasets use the default relative-path resolver.
    """

    def __init__(self, root: str | Path, episode_id: str,
                 resolver: Callable[[str], Path] | None = None):
        if len(_relative(episode_id).parts) != 1 or episode_id in ('.', ''):
            raise ValueError('episode_id must be one directory name')
        self.root = Path(root).resolve()
        self.prefix = PurePosixPath('episodes') / episode_id
        self._resolver = resolver
        self.metadata = self._json(self.path('metadata.json'))
        if self.metadata['episode_id'] != episode_id:
            raise ValueError('Episode ID differs from metadata')
        self.frames = int(self.metadata['motion']['frames'])
        if self.frames < 0:
            raise ValueError('Negative motion length')
        self.cameras = {}
        for camera in self.metadata['cameras']:
            uid = camera['camera_uid']
            if uid in self.cameras:
                raise ValueError(f'Duplicate camera UID: {uid}')
            self.cameras[uid] = camera
        self.motion_files = {}
        for item in self.metadata['motion']['files']:
            side = item['side']
            if side in self.motion_files or side not in ('left', 'right'):
                raise ValueError('Expected one selected file per hand')
            self.motion_files[side] = item
        if set(self.motion_files) != {'left', 'right'}:
            raise ValueError('Episode requires both selected hand files')
        self._calibrations: dict[str, dict] = {}
        self._flags: dict[int, set[str]] | None = None

    @staticmethod
    def _json(path: Path):
        with path.open(encoding='utf-8') as handle:
            return json.load(handle)

    def path(self, episode_relative: str) -> Path:
        target = (self.prefix / _relative(episode_relative)).as_posix()
        if self._resolver is not None:
            return Path(self._resolver(target))
        result = (self.root / target).resolve()
        if not result.is_relative_to(self.root):
            raise ValueError('Resolved path escapes the package root')
        return result

    def load_motion(self, side: str):
        """Memory-map numeric source values read-only; never invent betas."""
        import numpy as np
        item = self.motion_files[side]
        array = np.load(self.path(item['file']), mmap_mode='r', allow_pickle=False)
        expected = (self.frames, int(item['parameter_columns']))
        if expected[1] not in (51, 61) or tuple(array.shape) != expected:
            raise ValueError(f'Unexpected {side} motion shape: {array.shape}')
        if tuple(item['shape']) != expected or str(array.dtype) != item['dtype']:
            raise ValueError(f'{side} shape/dtype differs from metadata')
        if bool(item['betas_present']) != (expected[1] == 61):
            raise ValueError(f'{side} beta declaration differs from shape')
        return array

    def calibration(self, camera_uid: str) -> dict:
        """Return the original parameter entry, without changing order or values."""
        camera = self.cameras[camera_uid]
        filename = camera['calibration_file']
        if filename not in self._calibrations:
            self._calibrations[filename] = self._json(self.path(filename))
        data = self._calibrations[filename]
        if data['episode_id'] != self.metadata['episode_id']:
            raise ValueError('Calibration belongs to a different episode')
        return data['namespaces'][camera['parameter_namespace']]['parameters'][str(camera['original_parameter_id'])]

    def _indices(self, values) -> set[int]:
        result = set()
        for index in values:
            if isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < self.frames:
                raise ValueError(f'Invalid motion quality index: {index!r}')
            result.add(index)
        return result

    def _quality(self) -> dict[int, set[str]]:
        if self._flags is not None:
            return self._flags
        flags: dict[int, set[str]] = {}
        boundary = self.metadata.get('boundary_quality_mask_file')
        if boundary:
            count = 0
            with self.path(boundary).open(newline='', encoding='utf-8') as handle:
                for count, row in enumerate(csv.DictReader(handle), start=1):
                    index = int(row['motion_frame_index'])
                    if index != count - 1 or index >= self.frames:
                        raise ValueError('Boundary mask must cover consecutive motion rows')
                    if row['boundary_usable'] not in ('0', '1'):
                        raise ValueError('Invalid boundary availability flag')
                    if row['boundary_usable'] == '0':
                        flags.setdefault(index, set()).add('boundary_screen')
            if count != self.frames:
                raise ValueError('Incomplete boundary mask')
        local = self._indices(self.metadata.get('locally_excluded_motion_indices', []))
        events_path = self.metadata.get('local_motion_quality_events_file')
        if events_path:
            events = self._json(self.path(events_path))
            if events['episode_id'] != self.metadata['episode_id'] or events['motion_frames'] != self.frames:
                raise ValueError('Local events belong to a different motion')
            if self._indices(events['strict_pair_excluded_motion_indices']) != local:
                raise ValueError('Local event indices differ from metadata')
            for side, item in self.motion_files.items():
                if events['motion_file_sha256_by_side'][side] != item['sha256']:
                    raise ValueError('Local events are bound to a different selected motion')
        elif local:
            raise ValueError('Local mask declared without event annotations')
        for index in local:
            flags.setdefault(index, set()).add('local_motion_screen')
        self._flags = flags
        return flags

    def quality_flags(self, motion_index: int) -> tuple[str, ...]:
        self._indices([motion_index])
        return tuple(sorted(self._quality().get(motion_index, ())))

    def iter_frame_map(self, camera_uid: str) -> Iterator[Frame]:
        """Yield every motion row, including explicit missing video frames.

        Consume the iterator to exhaustion to validate its complete row count.
        PTS/time_base remain exact; no fixed FPS or nearest-frame inference.
        """
        camera = self.cameras[camera_uid]
        certainty = camera.get('alignment_certainty', 'SUPPORTED_BY_RECORDED_EVIDENCE')
        approximate = certainty == 'APPROXIMATE_ADJACENT_FRAME_SELECTION'
        if approximate:
            if camera.get('exact_extraction_index_recovered') is not False:
                raise ValueError('Approximate timing cannot declare exact extraction recovery')
            if abs(camera['selected_fixed_offset'] - camera['alternative_fixed_offset']) != 1:
                raise ValueError('Expected adjacent alternative offsets')
        flags = self._quality()
        missing = []
        count = 0
        with self.path(camera['frame_map_file']).open(newline='', encoding='utf-8') as handle:
            for count, row in enumerate(csv.DictReader(handle), start=1):
                index = int(row['motion_frame_index'])
                if index != count - 1 or index >= self.frames:
                    raise ValueError('Frame map must cover consecutive motion rows')
                video = row['video_frame_index'].strip()
                available = bool(video)
                explicit = row.get('source_frame_available')
                if explicit is not None and explicit not in ('0', '1'):
                    raise ValueError('Invalid source_frame_available flag')
                if explicit is not None and (explicit == '1') != available:
                    raise ValueError('Availability flag contradicts source index')
                raw_pts = row['video_pts'].strip()
                raw_base = row['video_time_base'].strip()
                raw_seconds = row['video_timestamp_seconds'].strip()
                if not available:
                    if raw_pts or raw_base or raw_seconds:
                        raise ValueError('Missing video row contains a timestamp')
                    missing.append(index)
                    video_index = pts = base = seconds = None
                else:
                    if not raw_pts or not raw_base or not raw_seconds:
                        raise ValueError('Available video row has incomplete timing')
                    video_index, pts = int(video), int(raw_pts)
                    base, seconds = Fraction(raw_base), raw_seconds
                    if video_index < 0 or base <= 0:
                        raise ValueError('Invalid video index/time base')
                alternate_index = alternate_pts = alternate_seconds = None
                row_certainty = row.get('alignment_certainty', certainty)
                if row_certainty != certainty:
                    raise ValueError('Frame timing certainty differs from camera metadata')
                if approximate:
                    alternate = row.get('alternative_video_frame_index', '').strip()
                    alternate_tick = row.get('alternative_video_pts', '').strip()
                    alternate_seconds = row.get('alternative_video_timestamp_seconds', '').strip()
                    if not available or not alternate or not alternate_tick or not alternate_seconds:
                        raise ValueError('Approximate frame map requires both candidate timestamps')
                    alternate_index, alternate_pts = int(alternate), int(alternate_tick)
                    if (video_index != index + camera['selected_fixed_offset'] or
                            alternate_index != index + camera['alternative_fixed_offset'] or
                            alternate_index < 0):
                        raise ValueError('Approximate candidate indices differ from recorded offsets')
                yield Frame(index, video_index, pts, base, seconds,
                            tuple(sorted(flags.get(index, ()))), certainty,
                            alternate_index, alternate_pts, alternate_seconds)
        if count != self.frames:
            raise ValueError('Incomplete frame map')
        if missing != camera.get('unobserved_motion_indices', []):
            raise ValueError('Missing source rows differ from camera metadata')
        if self.frames - len(missing) != camera['source_video_observed_motion_frames']:
            raise ValueError('Observed row count differs from metadata')