""" OccuFly Dataset Builder for Hugging Face Datasets. Compatible with datasets>=2.0.0 Enables users to load the dataset with: from datasets import load_dataset dataset = load_dataset("username/occufly_test") """ import datasets from datasets import GeneratorBasedBuilder, BuilderConfig, Features, Image, Value, Array3D import zipfile import tempfile from pathlib import Path import numpy as np from typing import Optional from huggingface_hub import hf_hub_download from PIL import Image as PILImage logger = datasets.logging.get_logger(__name__) class OccuFlyConfig(BuilderConfig): """Builder config for OccuFly.""" def __init__(self, include_predictions=False, **kwargs): """ Args: include_predictions: If True, includes predicted depth maps """ super().__init__(**kwargs) self.include_predictions = include_predictions class OccuFly(GeneratorBasedBuilder): """OccuFly aerial dataset with depth, ground truth, and calibration.""" VERSION = datasets.Version("1.0.0") BUILDER_CONFIGS = [ OccuFlyConfig( name="default", version=VERSION, description="OccuFly dataset without depth predictions", include_predictions=False, ), OccuFlyConfig( name="with_predictions", version=VERSION, description="OccuFly dataset with predicted depth maps", include_predictions=True, ), ] DEFAULT_CONFIG_NAME = "default" SCENES = {1, 2, 3, 4, 5, 6, 7, 8, 9} ALTITUDES = {30, 40, 50} SPLITS = { "train": [1, 2, 3, 4, 5], "validation": [6, 7], "test": [8, 9] } def _info(self): """Define dataset schema.""" features = { "scene": Value("int32"), "altitude": Value("int32"), "frame_id": Value("int32"), "image": Image(), # Depth map from 3D reconstruction "depth_map": Array3D(dtype="float32", shape=(None, None)), # 3D Voxel grid ground truth (192, 128, 128) in camera coordinate system # Physical coverage: 96m (W) × 64m (H) × 64m (D) at 0.5m voxel size # Origin at camera position, Z pointing forward "voxel_grid": { # Semantic labels: uint8 (0=empty, 1-21=semantic classes, 255=invalid) "label": Array3D(dtype="uint8", shape=(192, 128, 128)), # Invalid mask: 1=invalid, 0=valid (outside frustum or no data) "invalid": Array3D(dtype="bool", shape=(192, 128, 128)), # Occlusion mask: 1=occluded from camera, 0=visible "occluded": Array3D(dtype="bool", shape=(192, 128, 128)), # Surface mask: 1=surface voxel, 0=interior/non-surface "surface": Array3D(dtype="bool", shape=(192, 128, 128)), }, # Camera calibration parameters "calibration": { "K": Array3D(dtype="float32", shape=(3, 3)), }, } if self.config.include_predictions: # Predicted depth from fine-tuned Depth Anything v2 features["predicted_depth"] = Array3D(dtype="float32", shape=(None, None)) return datasets.DatasetInfo( description=( "OccuFly: A 3D Vision Benchmark for Semantic Scene Completion from the Aerial Perspective. " "Contains RGB images, 3D semantic voxel grids, and metric depth maps captured from aerial perspectives " "at multiple altitudes (30m, 40m, 50m) across urban, industrial, and rural environments with 21 semantic classes." ), features=Features(features), supervised_keys=("image", "voxel_grid"), homepage="https://huggingface.co/datasets/BharadhwajSaiMatha/occufly_test", citation=( "@misc{gross2025occufly,\n" " title={{OccuFly}: A 3D Vision Benchmark for Semantic Scene Completion from the Aerial Perspective},\n" " author={Markus Gross and Sai B. Matha and Aya Fahmy and Rui Song and Daniel Cremers and Henri Meess},\n" " year={2025},\n" " eprint={2512.20770},\n" " archivePrefix={Accepted to CVPR 2026. arXiv},\n" " primaryClass={cs.CV},\n" " url={https://arxiv.org/abs/2512.20770}\n" "}" ), ) def _split_generators(self, dl_manager): """Download zips and return split generators.""" # Scene zip filenames scene_zips = { scene: f"OccuFly_Dataset/scene_{scene:02d}.zip" for scene in self.SCENES } # Download scene zips downloaded_paths = {} logger.info("Downloading scene zips...") for scene, filename in scene_zips.items(): try: path = hf_hub_download( repo_id="BharadhwajSaiMatha/occufly_test", filename=filename, repo_type="dataset", cache_dir=dl_manager.manual_dir, ) downloaded_paths[scene] = path except Exception as e: logger.warning(f"Could not download scene {scene}: {e}") # Download predictions if requested preds_path = None if self.config.include_predictions: try: logger.info("Downloading depth predictions...") preds_path = hf_hub_download( repo_id="BharadhwajSaiMatha/occufly_test", filename="OccuFly_Predicted_DepthMaps/OccuFly_Predicted_DepthMaps.zip", repo_type="dataset", cache_dir=dl_manager.manual_dir, ) except Exception as e: logger.warning(f"Could not download predictions: {e}") preds_path = None return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "scenes": self.SPLITS["train"], "downloaded_paths": downloaded_paths, "preds_path": preds_path, }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "scenes": self.SPLITS["validation"], "downloaded_paths": downloaded_paths, "preds_path": preds_path, }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "scenes": self.SPLITS["test"], "downloaded_paths": downloaded_paths, "preds_path": preds_path, }, ), ] def _generate_examples(self, scenes, downloaded_paths, preds_path): """Generate examples by extracting and iterating through frames.""" # Extract predictions if available preds_extract_dir = None if preds_path and self.config.include_predictions: preds_extract_dir = tempfile.mkdtemp() with zipfile.ZipFile(preds_path, 'r') as z: z.extractall(preds_extract_dir) example_id = 0 for scene_num in scenes: if scene_num not in downloaded_paths: logger.warning(f"Skipping scene {scene_num}: not downloaded") continue zip_path = downloaded_paths[scene_num] scene_name = f"scene_{scene_num:02d}" # Extract scene zip to temp directory with tempfile.TemporaryDirectory() as extract_dir: with zipfile.ZipFile(zip_path, 'r') as z: z.extractall(extract_dir) extract_path = Path(extract_dir) / scene_name # Iterate through altitudes for altitude in sorted(self.ALTITUDES): alt_dir = extract_path / str(altitude) if not alt_dir.exists(): logger.warning(f"Altitude {altitude} not found in scene {scene_num}") continue images_dir = alt_dir / "images" / "visual" depth_dir = alt_dir / "depth_maps" gt_dir = alt_dir / "ground_truth" # Iterate through frames if images_dir.exists(): for img_file in sorted(images_dir.glob("*.png")): try: frame_id = int(img_file.stem) except ValueError: logger.warning(f"Cannot parse frame ID from {img_file.name}") continue frame_str = f"{frame_id:06d}" try: # Load image image = PILImage.open(img_file) # Load depth map depth_path = depth_dir / f"{frame_str}.npy" if not depth_path.exists(): logger.warning(f"Missing depth for frame {frame_str}") continue depth_map = np.load(depth_path).astype(np.float32) # Load voxel grid ground truth gt_frame_dir = gt_dir / frame_str label_path = gt_frame_dir / f"{frame_str}.label" if not label_path.exists(): logger.warning(f"Missing label for {frame_str}") continue label = np.load(label_path) label = label.reshape(192, 128, 128) # Reshape from flattened # Load bitpacked boolean arrays and unpack invalid = self._unpack_bitpacked(gt_frame_dir / f"{frame_str}.invalid", (192, 128, 128)) occluded = self._unpack_bitpacked(gt_frame_dir / f"{frame_str}.occluded", (192, 128, 128)) surface = self._unpack_bitpacked(gt_frame_dir / f"{frame_str}.surface", (192, 128, 128)) voxel_grid = { "label": label, "invalid": invalid, "occluded": occluded, "surface": surface, } # Load calibration calib_path = extract_path / "calibration.txt" calibration = self._load_calibration(calib_path) example = { "scene": scene_num, "altitude": altitude, "frame_id": frame_id, "image": image, "depth_map": depth_map, "voxel_grid": voxel_grid, "calibration": calibration, } # Add predictions if available if self.config.include_predictions and preds_extract_dir: pred_path = ( Path(preds_extract_dir) / "OccuFly_Predicted_DepthMaps" / scene_name / str(altitude) / "depth_maps" / f"{frame_str}.npy" ) if pred_path.exists(): pred_depth = np.load(pred_path).astype(np.float32) example["predicted_depth"] = pred_depth yield example_id, example example_id += 1 except Exception as e: logger.warning(f"Error processing frame {frame_str}: {e}") continue @staticmethod def _unpack_bitpacked(bitfile_path, shape): """Unpack bitpacked boolean array to proper shape.""" with open(bitfile_path, 'rb') as f: bitpacked = np.frombuffer(f.read(), dtype=np.uint8) # Unpack bits to boolean array unpacked = np.unpackbits(bitpacked, bitorder='big') # Resize to exact size needed total_elements = np.prod(shape) unpacked = unpacked[:total_elements] # Reshape and convert to bool return unpacked.reshape(shape).astype(bool) @staticmethod def _load_calibration(calib_path): """Load camera calibration file.""" calib = { "K": np.eye(3, dtype=np.float32), } if calib_path.exists(): with open(calib_path) as f: for line in f: parts = line.strip().split() if not parts: continue key = parts[0].rstrip(':') vals = [float(v) for v in parts[1:]] if key == "K" and len(vals) == 9: calib["K"] = np.array(vals, dtype=np.float32).reshape(3, 3) return calib