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" +}