File size: 15,209 Bytes
a430f34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
diff --git a/dataloader/registry.py b/dataloader/registry.py
index f3de37d..c9cba24 100644
--- a/dataloader/registry.py
+++ b/dataloader/registry.py
@@ -6,8 +6,10 @@ from .front3d import Front3DLoader
 from .ycb import YCBVLoader
 from .messykitchen import MessyKitchenLoader
 from .picasso import PicassoLoader
+from .frozen import FrozenEvaluationLoader
 
 DATASETS = {
+    "frozen": FrozenEvaluationLoader,
     "capture": CaptureLoader,
     "combined": CombinedLoader,
     "extent": ExtentLoader,
diff --git a/dataloader/frozen.py b/dataloader/frozen.py
new file mode 100644
index 0000000..2a43518
--- /dev/null
+++ b/dataloader/frozen.py
@@ -0,0 +1,74 @@
+"""Read portable RGB, masks, and shared GT meshes from frozen evaluation data."""
+from collections import defaultdict
+import json
+
+import numpy as np
+from PIL import Image
+import trimesh
+
+from .base import BaseDataLoader, EvaluationSample
+from .geometry import artifact_path, checked_digest
+from utils.hashing import input_hashes, sha256
+
+
+SCHEMA = 'partprobe3d.frozen-evaluation.v1'
+
+
+class FrozenEvaluationLoader(BaseDataLoader):
+    """Load saved evaluation inputs without the original source datasets."""
+    name = 'frozen'
+
+    def __init__(self, root):
+        super().__init__(root)
+        self.manifest_path = self.root / 'manifest.json'
+        self.manifest = json.loads(self.manifest_path.read_text())
+        if self.manifest.get('schema') != SCHEMA or not self.manifest.get('complete'):
+            raise ValueError('A complete frozen evaluation dataset is required')
+        self.rows = self.manifest['frames']
+        if not self.rows or len({row['key'] for row in self.rows}) != len(self.rows):
+            raise ValueError('Frozen evaluation sample keys must be nonempty and unique')
+
+    def __len__(self):
+        return len(self.rows)
+
+    def _load_sample(self, index):
+        row = self.rows[index]
+        paths = {key: artifact_path(self.root, row[key]) for key in ('rgb', 'masks', 'ground_truth')}
+        for relative in (row[key] for key in paths):
+            if checked_digest(artifact_path(self.root, relative)) != self.manifest['files'][relative]:
+                raise ValueError(f'Frozen evaluation file checksum differs: {relative}')
+        with Image.open(paths['rgb']) as image:
+            rgb = np.array(image.convert('RGB'))
+        with Image.open(paths['masks']) as image:
+            masks = np.array(image).astype(np.int32)
+        if input_hashes(rgb, masks) != {key: row[key] for key in ('rgb_sha256', 'masks_sha256')}:
+            raise ValueError('Frozen RGB pixels or mask labels differ from the source selection')
+        scene = trimesh.load(paths['ground_truth'], force='scene', process=False)
+        metadata = scene.metadata.get('partprobe3d', {})
+        if (metadata.get('schema') != 'partprobe3d.object-meshes.v1' or metadata.get('units') != 'm'
+                or metadata.get('coordinate_frame') != row['gt_coordinate_frame']
+                or metadata.get('identity_mode') != row['dataset_metadata'].get('input_mask_identity', 'mask')):
+            raise ValueError('Frozen GT mesh metadata differs from the selection')
+        pieces = defaultdict(list)
+        for node in scene.graph.nodes_geometry:
+            transform, geometry = scene.graph[node]
+            mesh = scene.geometry[geometry].copy().apply_transform(transform)
+            pieces[int(mesh.metadata['object_index'])].append(mesh)
+        meshes = {index: trimesh.util.concatenate(parts) for index, parts in pieces.items()}
+        if (set(meshes) != {int(obj['object_index']) for obj in metadata['objects']}
+                or len(meshes) != row['target_objects']):
+            raise ValueError('Frozen GT objects differ from the selection')
+        return EvaluationSample(key=row['key'], rgb=rgb, masks=masks, gt_meshes=meshes,
+            gt_coordinate_frame=row['gt_coordinate_frame'], metadata=row['dataset_metadata'],
+            visibility=row.get('visibility', {}), mask_overlap_pixels=row.get('mask_overlap_pixels', 0),
+            discarded_mask_pixels=row.get('discarded_mask_pixels', {}))
+
+    def sample_records(self):
+        return [{'index': i, 'key': row['key'], 'group': row['dataset_metadata'].get('scene', row['key']),
+                 'order': row['dataset_metadata'].get('source_view', row['key'])}
+                for i, row in enumerate(self.rows)]
+
+    def provenance(self):
+        return {**super().provenance(), 'manifest_sha256': sha256(self.manifest_path),
+                'source_selection_sha256': self.manifest['source_selection_sha256'],
+                'source_dataset': self.manifest['source_dataset'], 'gt_representation': 'exported GLB float32'}
diff --git a/preprocess/evaluation.py b/preprocess/evaluation.py
new file mode 100644
index 0000000..8f6dd03
--- /dev/null
+++ b/preprocess/evaluation.py
@@ -0,0 +1,171 @@
+"""Store and publish frozen evaluation images with one copy of each GT export."""
+import argparse
+from collections import defaultdict
+from concurrent.futures import ThreadPoolExecutor
+from copy import deepcopy
+import json
+from pathlib import Path
+from threading import Lock
+
+import numpy as np
+from PIL import Image
+
+from dataloader.frozen import SCHEMA
+from dataloader.geometry import artifact_path
+from preprocess.reproduction import DEFAULT_REPO, Publisher, package
+from preprocess.storage import atomic_json, link_artifact
+from utils.hashing import input_hashes, sha256
+from utils.paths import path_under
+
+
+def stage_selection(source, destination, *, workers=4):
+    """Verify and retain original image bytes and shared GT in a portable dataset."""
+    source, destination = Path(source).resolve(), Path(destination).resolve()
+    selection_path = source / 'selection.json'
+    original_digest = sha256(selection_path)
+    original = json.loads(selection_path.read_text())
+    if not original['frames'] or workers < 1:
+        raise ValueError('A nonempty selection and positive worker count are required')
+    if len({row['key'] for row in original['frames']}) != len(original['frames']):
+        raise ValueError('Selection sample keys must be unique')
+    destination.mkdir(parents=True, exist_ok=True)
+    saved = destination / 'manifest.json'
+    if saved.exists() and json.loads(saved.read_text()).get('source_selection_sha256') != original_digest:
+        raise ValueError('The destination contains a different frozen selection')
+    meshes, files, lock = {}, {}, Lock()
+
+    def view(frame):
+        folder = artifact_path(source, f"inputs/{frame['key']}")
+        with Image.open(folder / 'rgb.png') as image:
+            rgb = np.array(image.convert('RGB'))
+        with Image.open(folder / 'masks.png') as image:
+            masks = np.array(image)
+        if input_hashes(rgb, masks) != {key: frame[key] for key in ('rgb_sha256', 'masks_sha256')}:
+            raise ValueError(f"Saved evaluation RGB or masks changed: {frame['key']}")
+        row = deepcopy(frame)
+        row['source_sample_index'] = row.pop('sample_index')
+        row['source_gt_sha256'] = row.pop('gt_sha256')
+        view_files = {}
+        for key, filename in (('rgb', 'rgb.png'), ('masks', 'masks.png'), ('mask_preview', 'mask_preview.png')):
+            relative = f"views/{frame['key']}/{filename}"
+            path = folder / filename
+            digest = sha256(path)
+            link_artifact(path, artifact_path(destination, relative))
+            row[key] = relative
+            view_files[relative] = digest
+        mesh_source = (folder / 'ground_truth.glb').resolve()
+        with lock:
+            if mesh_source not in meshes:
+                digest = sha256(mesh_source)
+                relative = f'ground_truth/{digest}.glb'
+                link_artifact(mesh_source, destination / relative)
+                meshes[mesh_source] = relative
+                files[relative] = digest
+            row['ground_truth'] = meshes[mesh_source]
+            files.update(view_files)
+        return row
+
+    with ThreadPoolExecutor(max_workers=workers) as pool:
+        frames = []
+        for number, row in enumerate(pool.map(view, original['frames']), 1):
+            frames.append(row)
+            if number % 100 == 0:
+                print(f'VERIFIED {destination.name}: {number}/{len(original["frames"])} images', flush=True)
+    if sha256(selection_path) != original_digest:
+        raise ValueError('Source selection changed during dataset storage')
+    link_artifact(selection_path, destination / 'source_selection.json')
+    files['source_selection.json'] = original_digest
+    manifest = {'schema': SCHEMA, 'complete': True, 'source_dataset': original['dataset'],
+                'source_selection_sha256': original_digest, 'selection_seed': original['selection_seed'],
+                'source_provenance': original['dataset_provenance'], 'frames': frames,
+                'gt_representation': 'Original exported GLB bytes; vertices use float32',
+                'unique_gt_meshes': len(set(meshes.values())), 'files': dict(sorted(files.items()))}
+    atomic_json(saved, manifest)
+    print(f'READY {destination}: {len(frames)} images, {manifest["unique_gt_meshes"]} GT exports', flush=True)
+    return manifest
+
+
+def stage_cohort(source, destination, *, workers=4):
+    source, destination = Path(source).resolve(), Path(destination).resolve()
+    cohort = json.loads((source / 'benchmark_manifest.json').read_text())
+    if cohort.get('status') != 'ready':
+        raise ValueError('The complete evaluation cohort must pass preparation first')
+    result = {'schema': 'partprobe3d.frozen-evaluation-cohort.v1', 'complete': False, 'datasets': {}}
+    for name, item in cohort['datasets'].items():
+        part = artifact_path(destination, name)
+        selection = source / name / 'selection.json'
+        if sha256(selection) != item['selection_sha256']:
+            raise ValueError(f'Frozen selection checksum differs: {name}')
+        manifest = stage_selection(selection.parent, part, workers=workers)
+        if len(manifest['frames']) != item['requested_views']:
+            raise ValueError(f'Frozen selection count differs: {name}')
+        result['datasets'][name] = {'manifest': f'{name}/manifest.json', 'sha256': sha256(part / 'manifest.json'),
+            'views': len(manifest['frames']), 'unique_gt_meshes': manifest['unique_gt_meshes']}
+    result.update(complete=True, total_views=sum(row['views'] for row in result['datasets'].values()))
+    atomic_json(destination / 'index.json', result)
+    return result
+
+
+def publish(source, output, repo=DEFAULT_REPO, *, workers=4, shard_bytes=1024**3):
+    """Publish optional evaluation archives through the verified project uploader."""
+    source, output = Path(source).resolve(), Path(output).resolve()
+    cohort = json.loads((source / 'index.json').read_text())
+    if not cohort.get('complete'):
+        raise ValueError('A complete portable cohort is required')
+    output.mkdir(parents=True, exist_ok=True)
+    publisher = Publisher(repo, workers=workers)
+    result = {'repo': repo, 'complete': False, 'total_views': cohort['total_views'],
+              'component': 'optional/evaluation/indoor', 'datasets': cohort['datasets']}
+    atomic_json(output / 'status.json', result)
+    metadata = [source / 'index.json', *sorted(source.glob('*.md'))]
+    groups, checksums = [], {}
+    for name, record in cohort['datasets'].items():
+        root = artifact_path(source, name)
+        if sha256(root / 'manifest.json') != record['sha256']:
+            raise ValueError(f'Portable manifest changed: {name}')
+        manifest = json.loads((root / 'manifest.json').read_text())
+        scenes = defaultdict(set)
+        counts = defaultdict(int)
+        for row in manifest['frames']:
+            scene = row['dataset_metadata'].get('scene', row['key'])
+            scenes[scene].update(artifact_path(root, row[key])
+                                 for key in ('rgb', 'masks', 'mask_preview', 'ground_truth'))
+            counts[scene] += 1
+        metadata.extend([root / 'manifest.json', root / 'source_selection.json', *sorted(root.glob('*.md'))])
+        groups.extend((name, sorted(paths), counts[scene]) for scene, paths in sorted(scenes.items()))
+        checksums.update({artifact_path(root, key): value for key, value in manifest['files'].items()})
+    index = package(source, output, 'optional/evaluation', 'indoor',
+        destination=Path('datasets/evaluation/indoor'), kind='frozen-evaluation',
+        metadata=metadata, groups=groups, checksums=checksums,
+        details={'source_manifest_sha256': sha256(source / 'index.json'), 'views': cohort['total_views'],
+                 'datasets': cohort['datasets'], 'evaluation_only': True},
+        shard_bytes=shard_bytes, publisher=publisher)
+    result.update(complete=True, bytes=index['bytes'], archives=len(index['archives']),
+                  revision=publisher.api.dataset_info(repo).sha)
+    atomic_json(output / 'status.json', result)
+    return result
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    commands = parser.add_subparsers(dest='command', required=True)
+    staging = commands.add_parser('store')
+    staging.add_argument('--source', type=Path, required=True)
+    staging.add_argument('--destination', type=Path, default=Path('datasets/evaluation/indoor'))
+    staging.add_argument('--workers', type=int, default=4)
+    publishing = commands.add_parser('publish')
+    publishing.add_argument('--source', type=Path, default=Path('datasets/evaluation/indoor'))
+    publishing.add_argument('--output', type=Path, default=Path('outputs/huggingface/evaluation'))
+    publishing.add_argument('--repo', default=DEFAULT_REPO)
+    publishing.add_argument('--workers', type=int, default=4)
+    args = parser.parse_args()
+    if args.workers < 1:
+        parser.error('--workers must be positive')
+    if args.command == 'store':
+        stage_cohort(path_under(args.source, 'outputs'), path_under(args.destination, 'datasets'), workers=args.workers)
+    else:
+        publish(path_under(args.source, 'datasets'), path_under(args.output, 'outputs'), args.repo, workers=args.workers)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/evaluation/configs/picasso_frozen.json b/evaluation/configs/picasso_frozen.json
new file mode 100644
index 0000000..5c472dc
--- /dev/null
+++ b/evaluation/configs/picasso_frozen.json
@@ -0,0 +1,3 @@
+{
+  "root": "datasets/evaluation/indoor/picasso"
+}
diff --git a/evaluation/configs/messykitchen_frozen.json b/evaluation/configs/messykitchen_frozen.json
new file mode 100644
index 0000000..0191781
--- /dev/null
+++ b/evaluation/configs/messykitchen_frozen.json
@@ -0,0 +1,3 @@
+{
+  "root": "datasets/evaluation/indoor/messykitchen"
+}
diff --git a/evaluation/configs/front3d_frozen.json b/evaluation/configs/front3d_frozen.json
new file mode 100644
index 0000000..6087592
--- /dev/null
+++ b/evaluation/configs/front3d_frozen.json
@@ -0,0 +1,3 @@
+{
+  "root": "datasets/evaluation/indoor/3dfront"
+}