File size: 10,517 Bytes
10ed3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Pinned OakInk-v1/v2 storage adapters; no annotation/geometry recomputation.

Only actual inventoried fields are supported. HOT3D's already-reviewed byte,
path and cached-leaf helpers are reused without modifying its frozen adapter.
"""
import copy
import json
import re
from pathlib import Path, PurePosixPath

import torch

from hot3d_bundle import (PROFILE, RELEASE, VERSION, Reader, at, check_field,
                         exact, safe_path)

DATASET_IDS = {'OakInk-v1': 'OakInk-v1', 'OakInk-v2': 'OakInk2'}
STORAGE_KEYS = {'data_ref', 'valid_ref', 'data_key', 'valid_key', 'storage', 'valid_storage'}


def fields(meta):
    if meta['dataset_id'] not in DATASET_IDS.values() or meta['hand_slots'] != ['left', 'right']:
        raise ValueError('Wrong OakInk dataset or hand-slot order')
    if meta['camera']['model'] != 'pinhole':
        raise ValueError('Unreviewed OakInk camera model')
    fixed = {
        'intrinsic': ('camera/pinhole/v1', 'camera/camera.pt', 'intrinsic', 'camera/intrinsic.pt'),
        'extrinsic': ('transform/se3/v1', 'camera/camera.pt', 'extrinsic', 'camera/extrinsic.pt'),
        'mano': ('mano/axis_angle61/v1', 'annotation/mano/mano.pt', 'motion', 'annotation/mano/motion.pt'),
        'keypoints_xyz': ('keypoints/xyz/v1', 'annotation/keypoints/keypoints.pt', 'xyz', 'annotation/keypoints/xyz.pt'),
        'keypoints_uv': ('keypoints/uv/v1', 'annotation/keypoints/keypoints.pt', 'uv', 'annotation/keypoints/uv.pt'),
    }
    result = []
    for name, c in meta['components'].items():
        if not c.get('available'):
            continue
        if c.get('attributes'):
            raise ValueError(f'Unreviewed attributes: {name}')
        if name == 'rgb' and c['schema_id'] == 'rgb/uint8/v1':
            continue
        if name == 'object_mesh' and c['schema_id'] == 'mesh/obj/v1':
            continue
        if name in fixed:
            schema, bundle, key, old = fixed[name]
        elif c['schema_id'] == 'object/rigid/v1':
            match = re.fullmatch(r'annotation/object/([^/]+)/(pose|object)\.pt', c['data_ref'])
            if not match:
                raise ValueError('Bad object pose path')
            oid = match.group(1)
            safe_path('/view', 'annotation/object/' + oid)
            if name not in {'object_pose', f'object_{oid}_pose'} or c.get('entity_id', oid) != oid:
                raise ValueError('Object component identity/path mismatch')
            schema, bundle, key, old = c['schema_id'], f'annotation/object/{oid}/object.pt', 'pose', f'annotation/object/{oid}/pose.pt'
        else:
            raise ValueError(f'Unreviewed OakInk component: {name}')
        if schema != c['schema_id']:
            raise ValueError(f'Unregistered schema for {name}')
        result.append({'locator': ['components', name], 'schema': schema,
                       'bundle': bundle, 'entry': key, 'old': old})
    pairs = [(f['bundle'], f['entry']) for f in result]
    if len(pairs) != len(set(pairs)):
        raise ValueError('Duplicate bundle entry')
    return result


def new_metadata(old):
    if old['schema_version'] != 'hand-warehouse/1.0' or old['release_id'] != 'shared-v1.0':
        raise ValueError('Source must be shared-v1.0')
    meta = copy.deepcopy(old)
    for f in fields(old):
        c = at(old, f['locator'])
        expected_valid = str(PurePosixPath(f['old']).with_stem(PurePosixPath(f['old']).stem + '_valid'))
        if c['data_ref'] != f['old'] or c.get('valid_ref') != expected_valid:
            raise ValueError('Unexpected source numerical reference')
        if 'data_key' in c or 'valid_key' in c:
            raise ValueError('Already bundled')
        at(meta, f['locator']).update(data_ref=f['bundle'], valid_ref=f['bundle'],
            data_key=[f['entry'], 'data'], valid_key=[f['entry'], 'valid'],
            storage={'profile': PROFILE}, valid_storage={'profile': PROFILE})
    meta.update(schema_version=VERSION, release_id=RELEASE)
    return meta


def validate_field(data, valid, field, component, total, registry):
    rule = registry['components'][field['schema']]
    required = set(rule.get('required_metadata', [])) - STORAGE_KEYS
    required |= {'axes', 'valid_axes', 'provenance', 'source_locator'}
    if not required.issubset(component):
        raise ValueError(f'Missing field metadata: {sorted(required-set(component))}')
    if field['schema'].startswith('keypoints/') and component['keypoint_schema'] != 'mano21/v1':
        raise ValueError('Unreviewed keypoint ordering')
    for key in ['unit', 'angle_unit', 'coordinate_frame']:
        if key in rule and component.get(key) != rule[key]:
            raise ValueError(f'Wrong {key} for {field["schema"]}')
    if field['entry'] == 'extrinsic' and component['convention'] != 'T_camera_from_world':
        raise ValueError('Wrong camera transform direction')
    if field['entry'] == 'pose' and component['convention'] != 'T_camera_from_object':
        raise ValueError('Wrong object transform direction')
    check_field(data, valid, field, component, total, registry)


def frame_audit(view, meta):
    count = 0; splits = {}
    with safe_path(view, meta['sampling']['frames_ref']).open() as handle:
        for line in handle:
            frame = json.loads(line)
            if frame['frame_index'] != count or not frame.get('source_locator'):
                raise ValueError('Broken frame mapping')
            member = frame['source_locator']['member']
            if meta['dataset_id'] == 'OakInk2':
                matches_camera = f'/{meta["camera_id"]}/' in member
            else:
                matches_camera = PurePosixPath(member).name.startswith(meta['camera_id'] + '_')
            if not matches_camera:
                raise ValueError('Frame belongs to another camera')
            split = frame.get('split', meta['split'])
            splits[split] = splits.get(split, 0) + 1
            count += 1
    if count != meta['num_frames']:
        raise ValueError('Frame count mismatch')
    return splits


def audit_view(view, registry, source=None, require_media=False, check_frames=True):
    reader = Reader(view); meta = reader.meta
    required = set(registry['view_metadata']['required_fields'])
    if not required.issubset(meta) or meta['view_type'] not in registry['view_metadata']['view_type_values']:
        raise ValueError('Incomplete view metadata')
    if source is not None:
        before = json.loads((Path(source)/'metainfo.json').read_text())
        if meta != new_metadata(before):
            raise ValueError('Metadata changed beyond version/storage')
    grouping, rows = {}, []
    for field in fields(meta):
        grouping.setdefault(field['bundle'], set()).add(field['entry'])
        data, valid = reader.numeric(field)
        validate_field(data, valid, field, at(meta, field['locator']), meta['num_frames'], registry)
        if source is not None:
            old = at(before, field['locator'])
            for key, tensor in [('data_ref', data), ('valid_ref', valid)]:
                original = torch.load(safe_path(source, old[key]), map_location='cpu', weights_only=True)
                if not exact(original, tensor):
                    raise ValueError(f'Changed tensor bytes: {field["locator"]}/{key}')
        rows.append({'field': '/'.join(field['locator']), 'bundle': field['bundle'],
                     'shape': list(data.shape), 'valid_shape': list(valid.shape),
                     'valid_true': int(valid.sum()), 'valid_total': valid.numel()})
    for ref, entries in grouping.items():
        if type(reader.cache[ref]) is not dict or set(reader.cache[ref]) != entries:
            raise ValueError('Extra/missing bundle fields')
    missing = []
    for name, c in meta['components'].items():
        if not c.get('available') or c['schema_id'] not in {'rgb/uint8/v1', 'mesh/obj/v1'}:
            continue
        if 'data_key' in c or 'valid_key' in c:
            raise ValueError('Media/mesh must not be bundled')
        if not safe_path(view, c['data_ref']).is_file():
            missing.append(c['data_ref'])
        if 'valid_ref' in c:
            tensor = reader.load(c['valid_ref'])
            shape = (meta['num_frames'],) if name == 'rgb' else ()
            if not isinstance(tensor, torch.Tensor) or tensor.dtype != torch.bool or tuple(tensor.shape) != shape:
                raise ValueError('Wrong standalone validity')
            if source is not None:
                old_valid = torch.load(safe_path(source, before['components'][name]['valid_ref']), map_location='cpu', weights_only=True)
                if not exact(old_valid, tensor):
                    raise ValueError('Standalone validity changed')
        elif type(c.get('valid')) is not bool:
            raise ValueError('Missing asset validity')
    # v2 assets are registered in object metainfo, not top-level components.
    for field in fields(meta):
        if field['entry'] != 'pose':
            continue
        object_dir = PurePosixPath(field['bundle']).parent
        object_meta = json.loads(safe_path(view, str(object_dir/'metainfo.json')).read_text())
        if source is not None:
            ref=str(object_dir/'metainfo.json')
            if safe_path(view,ref).read_bytes()!=safe_path(source,ref).read_bytes():
                raise ValueError('Object metadata changed')
        if object_meta.get('object_id', object_meta.get('entity_id')) != object_dir.name:
            raise ValueError('Object identity is not registered')
        for key in ['mesh_ref']:
            if key in object_meta and not safe_path(view, object_meta[key]).is_file():
                missing.append(object_meta[key])
    if require_media and missing:
        raise ValueError(f'Incomplete view: {len(set(missing))} missing media/asset references')
    if check_frames:
        if source is not None:
            if safe_path(view,meta['sampling']['frames_ref']).read_bytes()!=safe_path(source,before['sampling']['frames_ref']).read_bytes():
                raise ValueError('Frame mapping changed')
        frame_splits=frame_audit(view, meta)
    else:
        frame_splits=None
    return {'sequence': meta['sequence_id'], 'camera': meta['camera_id'], 'frames': meta['num_frames'],
            'split': meta['split'], 'view_type': meta['view_type'], 'fields': rows,
            'bundles': len(grouping), 'missing_media_asset_refs': sorted(set(missing)),
            'frame_splits':frame_splits,
            'numerical_bytes_exact': source is not None}