File size: 7,218 Bytes
94a4005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""One small runnable end-to-end check; fixtures are synthetic, not real validation."""
import json
import pickle
import subprocess
import sys
import tempfile
from pathlib import Path

import numpy as np
from PIL import Image

from acquire import sha, safe_path
from media import mask, decode
from preprocess import se3
from validate import pt, check_inventory

HERE = Path(__file__).resolve().parent


def command(*args, succeeds=True):
    p = subprocess.run([sys.executable, str(HERE / 'preprocess.py'), *map(str, args)], capture_output=True, text=True)
    if (p.returncode == 0) != succeeds:
        raise AssertionError(p.stdout + p.stderr)
    return p


def provenance(root):
    entries = [{'path': p.relative_to(root).as_posix(), 'sha256': sha(p),
                'source_locator': {'file': 'SYNTHETIC_TEST_FIXTURE', 'member': p.relative_to(root).as_posix()}}
               for p in sorted(root.rglob('*')) if p.is_file() and p.name != 'sources.jsonl']
    (root / 'sources.jsonl').write_text(''.join(json.dumps(r) + '\n' for r in entries))


def save_pickle(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('wb') as f:
        pickle.dump(value, f)


def main():
    rng = np.random.default_rng(17)
    with tempfile.TemporaryDirectory() as directory:
        temp = Path(directory)
        ego = temp / 'ego'
        for split in ('train', 'val', 'test_indomain', 'test_outdomain'):
            for folder in ('image', 'label'):
                (ego / split / folder).mkdir(parents=True)
            for i in range(2):
                # One JPEG stratum and one PNG stratum exercise copy and both lossless encoders.
                ext = '.jpg' if split != 'val' else '.png'
                Image.fromarray(rng.integers(0, 256, (24, 32, 3), dtype=np.uint8)).save(ego / split / 'image' / f'{i}{ext}')
                Image.fromarray(np.tile(np.arange(32, dtype=np.uint8) % 9, (24, 1))).save(ego / split / 'label' / f'{i}.png')
        provenance(ego)
        output = temp / 'ego-pilot'
        command('build', '--dataset', 'EgoHOS', '--input', ego, '--out', output, '--chunk', 8)
        report = json.loads((output / 'doc/validation/report.json').read_text())
        assert report['all_frames_checked'] == 8
        check_inventory(output, report['file_hashes'])
        encoded = next((output / 'data').glob('train*/*/annotation/segment/mask.mkv'))
        assert np.array_equal(next(decode(encoded, True)), mask(ego / 'train/label/0.png'))
        assert (next(decode(encoded, True)) == 9).any()
        # Missing human review must block full and upload before any remote call.
        command('build', '--dataset', 'EgoHOS', '--input', ego, '--out', temp / 'badfull', '--phase', 'full', '--pilot', output, '--chunk', 8, succeeds=False)
        command('upload', '--release', output, succeeds=False)
        # A modified release fails its file inventory.
        (output / 'data/unexpected.txt').write_text('modified')
        try:
            check_inventory(output, report['file_hashes'])
        except ValueError:
            pass
        else:
            raise AssertionError('Mutation accepted')

        oak = temp / 'oak'
        seq = 'A00001_0004_0001_0002/2021-01-01-00-00-00'
        image = oak / 'image/stream_release_v2' / seq / 'north_east_color_10.png'
        image.parent.mkdir(parents=True)
        Image.fromarray(rng.integers(0, 256, (24, 32, 3), dtype=np.uint8)).save(image)
        anno = oak / 'image/anno'
        anno.mkdir()
        info = [[seq, person, 10, 0] for person in (0, 1)]
        (anno / 'seq_all.json').write_text(json.dumps(info))
        for rel, value in [('split_train_val/split0/example_split_train.json', info),
                           ('split_train_val/split0/example_split_val.json', []), ('split/split0/seq_test.json', [])]:
            p = anno / rel
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(json.dumps(value))
        k = np.array([[20, 0, 16], [0, 20, 12], [0, 0, 1]], np.float32)
        xyz = np.column_stack((np.linspace(-.1, .1, 21), np.zeros(21), np.ones(21))).astype(np.float32)
        pose = np.eye(4, dtype=np.float32)
        pose[2, 3] = 1
        for x in info:
            key = '__'.join(map(str, x)).replace('/', '__') + '.pkl'
            for folder, value in [('cam_intr', k), ('hand_j', xyz), ('obj_transf', pose), ('general_info', {'cam_extr': np.eye(4, dtype=np.float32)})]:
                save_pickle(anno / folder / key, value)
        obj = oak / 'image/obj/A00001.obj'
        obj.parent.mkdir()
        obj.write_text('mtllib absent.mtl\nv 0 0 0\nv .2 0 0\nv 0 .2 0\nusemtl default\nf 1 2 3\n')
        (oak / 'acquisition.json').write_text(json.dumps({'command': 'extract', 'dataset': 'OakInk-v1', 'note': 'SYNTHETIC TEST ONLY'}))
        provenance(oak)
        command('build', '--dataset', 'OakInk-v1', '--input', oak, '--out', temp / 'oak-blocked', succeeds=False)
        command('build', '--dataset', 'OakInk-v1', '--input', oak, '--out', temp / 'oak-rgb', '--allow-rgb-only')
        out = temp / 'oak-geo'
        command('build', '--dataset', 'OakInk-v1', '--input', oak, '--out', out,
                '--annotations', anno, '--trust-pickle')
        views = list((out / 'data').glob('*/*/metainfo.json'))
        assert len(views) == 2 and any('person0' in str(p) for p in views) and any('person1' in str(p) for p in views)
        for m in views:
            v = m.parent
            points = pt(v / 'annotation/keypoints/xyz.pt')
            assert np.isnan(points[:, 0]).all() and np.array_equal(points[0, 1], xyz)
            uv = pt(v / 'annotation/keypoints/uv.pt')
            assert np.allclose(uv[0, 1, 0], [14, 12])
            text = (v / 'annotation/object/A00001/assets/A00001.obj').read_text()
            assert 'v -0.1 -0.1 0' in text
            assert 'mtllib ' not in text and 'usemtl ' not in text
            metadata = json.loads(m.read_text())
            assert metadata['components']['object_mesh']['provenance']['source_missing_materials'] == ['absent.mtl']
        # Test review records apply only to these temporary synthetic fixtures.
        command('approve', '--release', out, '--reviewer', 'SYNTHETIC_TEST_ONLY')
        command('upload', '--release', out, succeeds=False)  # Reviewed pilot still cannot publish.
        command('build', '--dataset', 'OakInk-v1', '--input', oak, '--out', temp / 'oak-full',
                '--annotations', anno, '--trust-pickle', '--phase', 'full', '--pilot', out)
        for bad in ('../escape', '/absolute', 'a/../../escape'):
            try:
                safe_path(temp, bad)
            except ValueError:
                pass
            else:
                raise AssertionError('Unsafe path accepted')
        bad = np.eye(4)
        bad[0, 0] = 2
        try:
            se3(bad, 'bad')
        except ValueError:
            pass
        else:
            raise AssertionError('Invalid SE3 accepted')
    print('PASS: JPEG copy, FFV1/x264 RGB, labels, provenance, review gates, RGB-only, synthetic OakInk geometry, NaN slots, projection, mesh centering, mutation/path/SE3 rejection')


if __name__ == '__main__':
    main()