| 1 |
"""Build deterministic COLMAP benchmark shards from TartanAir V2.""" |
| 2 |
|
| 3 |
import argparse |
| 4 |
import concurrent.futures |
| 5 |
import dataclasses |
| 6 |
import hashlib |
| 7 |
import io |
| 8 |
import json |
| 9 |
import struct |
| 10 |
import tarfile |
| 11 |
import time |
| 12 |
import zlib |
| 13 |
from pathlib import Path |
| 14 |
from typing import TYPE_CHECKING |
| 15 |
from urllib.parse import quote |
| 16 |
|
| 17 |
import numpy as np |
| 18 |
import PIL.Image |
| 19 |
import requests |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from .tartanair_v2 import ( |
| 23 |
MANIFEST_PATH, |
| 24 |
SceneSelection, |
| 25 |
load_manifest, |
| 26 |
scene_shards, |
| 27 |
select_frame_window, |
| 28 |
shard_name, |
| 29 |
) |
| 30 |
else: |
| 31 |
try: |
| 32 |
from .tartanair_v2 import ( |
| 33 |
MANIFEST_PATH, |
| 34 |
SceneSelection, |
| 35 |
load_manifest, |
| 36 |
scene_shards, |
| 37 |
select_frame_window, |
| 38 |
shard_name, |
| 39 |
) |
| 40 |
except ImportError: # Support direct execution as a packaging script. |
| 41 |
from tartanair_v2 import ( |
| 42 |
MANIFEST_PATH, |
| 43 |
SceneSelection, |
| 44 |
load_manifest, |
| 45 |
scene_shards, |
| 46 |
select_frame_window, |
| 47 |
shard_name, |
| 48 |
) |
| 49 |
|
| 50 |
|
| 51 |
@dataclasses.dataclass(frozen=True) |
| 52 |
class ZipMember: |
| 53 |
name: str |
| 54 |
method: int |
| 55 |
crc32: int |
| 56 |
compressed_size: int |
| 57 |
uncompressed_size: int |
| 58 |
local_offset: int |
| 59 |
|
| 60 |
|
| 61 |
class RemoteZip: |
| 62 |
"""Read selected members of a remote ZIP using HTTP range requests.""" |
| 63 |
|
| 64 |
def __init__(self, url: str): |
| 65 |
self.url = url |
| 66 |
self.session = requests.Session() |
| 67 |
self.members = self._read_central_directory() |
| 68 |
|
| 69 |
def _range(self, byte_range: str) -> tuple[bytes, requests.Response]: |
| 70 |
for attempt in range(5): |
| 71 |
try: |
| 72 |
response = self.session.get( |
| 73 |
self.url, |
| 74 |
headers={"Range": f"bytes={byte_range}"}, |
| 75 |
timeout=180, |
| 76 |
) |
| 77 |
response.raise_for_status() |
| 78 |
if response.status_code != 206: |
| 79 |
raise RuntimeError( |
| 80 |
f"Server ignored byte range for {self.url}" |
| 81 |
) |
| 82 |
return response.content, response |
| 83 |
except requests.RequestException: |
| 84 |
if attempt == 4: |
| 85 |
raise |
| 86 |
time.sleep(2**attempt) |
| 87 |
raise AssertionError("unreachable") |
| 88 |
|
| 89 |
@staticmethod |
| 90 |
def _zip64_values( |
| 91 |
extra: bytes, uncompressed: int, compressed: int, offset: int |
| 92 |
) -> tuple[int, int, int]: |
| 93 |
position = 0 |
| 94 |
while position + 4 <= len(extra): |
| 95 |
tag, size = struct.unpack_from("<HH", extra, position) |
| 96 |
value = extra[position + 4 : position + 4 + size] |
| 97 |
position += 4 + size |
| 98 |
if tag != 1: |
| 99 |
continue |
| 100 |
value_position = 0 |
| 101 |
values = [] |
| 102 |
for old_value in (uncompressed, compressed, offset): |
| 103 |
if old_value == 0xFFFFFFFF: |
| 104 |
values.append( |
| 105 |
struct.unpack_from("<Q", value, value_position)[0] |
| 106 |
) |
| 107 |
value_position += 8 |
| 108 |
else: |
| 109 |
values.append(old_value) |
| 110 |
return tuple(values) |
| 111 |
return uncompressed, compressed, offset |
| 112 |
|
| 113 |
def _read_central_directory(self) -> dict[str, ZipMember]: |
| 114 |
tail, response = self._range("-262144") |
| 115 |
total_size = int(response.headers["Content-Range"].split("/")[-1]) |
| 116 |
eocd_offset = tail.rfind(b"PK\x05\x06") |
| 117 |
if eocd_offset < 0 or eocd_offset + 22 > len(tail): |
| 118 |
raise RuntimeError(f"Cannot locate ZIP directory for {self.url}") |
| 119 |
eocd = struct.unpack_from("<4s4H2LH", tail, eocd_offset) |
| 120 |
num_entries, directory_size, directory_offset = eocd[4:7] |
| 121 |
if ( |
| 122 |
num_entries == 0xFFFF |
| 123 |
or directory_size == 0xFFFFFFFF |
| 124 |
or directory_offset == 0xFFFFFFFF |
| 125 |
): |
| 126 |
locator_offset = tail.rfind( |
| 127 |
b"PK\x06\x07", max(0, eocd_offset - 64), eocd_offset |
| 128 |
) |
| 129 |
if locator_offset < 0: |
| 130 |
raise RuntimeError(f"Cannot locate ZIP64 directory: {self.url}") |
| 131 |
zip64_offset = struct.unpack_from("<4sLQL", tail, locator_offset)[2] |
| 132 |
zip64, _ = self._range(f"{zip64_offset}-{zip64_offset + 55}") |
| 133 |
values = struct.unpack_from("<4sQ2H2L4Q", zip64) |
| 134 |
num_entries, directory_size, directory_offset = values[7:10] |
| 135 |
if directory_offset + directory_size > total_size: |
| 136 |
raise RuntimeError(f"Invalid ZIP directory bounds: {self.url}") |
| 137 |
|
| 138 |
directory, _ = self._range( |
| 139 |
f"{directory_offset}-{directory_offset + directory_size - 1}" |
| 140 |
) |
| 141 |
members = {} |
| 142 |
position = 0 |
| 143 |
while ( |
| 144 |
position + 46 <= len(directory) |
| 145 |
and directory[position : position + 4] == b"PK\x01\x02" |
| 146 |
): |
| 147 |
values = struct.unpack_from("<4s6H3L5H2L", directory, position) |
| 148 |
method = values[4] |
| 149 |
crc32 = values[7] |
| 150 |
compressed = values[8] |
| 151 |
uncompressed = values[9] |
| 152 |
name_size, extra_size, comment_size = values[10:13] |
| 153 |
local_offset = values[16] |
| 154 |
name_start = position + 46 |
| 155 |
name = directory[name_start : name_start + name_size].decode() |
| 156 |
extra = directory[ |
| 157 |
name_start + name_size : name_start + name_size + extra_size |
| 158 |
] |
| 159 |
uncompressed, compressed, local_offset = self._zip64_values( |
| 160 |
extra, uncompressed, compressed, local_offset |
| 161 |
) |
| 162 |
members[name] = ZipMember( |
| 163 |
name=name, |
| 164 |
method=method, |
| 165 |
crc32=crc32, |
| 166 |
compressed_size=compressed, |
| 167 |
uncompressed_size=uncompressed, |
| 168 |
local_offset=local_offset, |
| 169 |
) |
| 170 |
position += 46 + name_size + extra_size + comment_size |
| 171 |
if len(members) != num_entries: |
| 172 |
raise RuntimeError( |
| 173 |
f"Expected {num_entries} ZIP members, parsed {len(members)}" |
| 174 |
) |
| 175 |
return members |
| 176 |
|
| 177 |
def read(self, name: str) -> tuple[bytes, ZipMember]: |
| 178 |
member = self.members[name] |
| 179 |
header, _ = self._range( |
| 180 |
f"{member.local_offset}-{member.local_offset + 29}" |
| 181 |
) |
| 182 |
values = struct.unpack_from("<4s5H3L2H", header) |
| 183 |
name_size, extra_size = values[9:11] |
| 184 |
data_offset = member.local_offset + 30 + name_size + extra_size |
| 185 |
compressed, _ = self._range( |
| 186 |
f"{data_offset}-{data_offset + member.compressed_size - 1}" |
| 187 |
) |
| 188 |
if member.method == 0: |
| 189 |
data = compressed |
| 190 |
elif member.method == 8: |
| 191 |
data = zlib.decompress(compressed, -15) |
| 192 |
else: |
| 193 |
raise RuntimeError(f"Unsupported ZIP method {member.method}") |
| 194 |
if len(data) != member.uncompressed_size: |
| 195 |
raise RuntimeError(f"Invalid size for ZIP member {name}") |
| 196 |
if zlib.crc32(data) != member.crc32: |
| 197 |
raise RuntimeError(f"Invalid CRC for ZIP member {name}") |
| 198 |
return data, member |
| 199 |
|
| 200 |
|
| 201 |
def add_bytes(archive: tarfile.TarFile, name: str, data: bytes) -> None: |
| 202 |
info = tarfile.TarInfo(name) |
| 203 |
info.size = len(data) |
| 204 |
info.mode = 0o644 |
| 205 |
info.mtime = 0 |
| 206 |
info.uid = 0 |
| 207 |
info.gid = 0 |
| 208 |
info.uname = "" |
| 209 |
info.gname = "" |
| 210 |
archive.addfile(info, io.BytesIO(data)) |
| 211 |
|
| 212 |
|
| 213 |
DEPTH_SIZE = (512, 256) |
| 214 |
DEPTH_SCALE = 8.0 |
| 215 |
DEPTH_INVALID_VALUE = 0 |
| 216 |
IMAGE_QUALITY = 97 |
| 217 |
IMAGE_SUBSAMPLING = 0 |
| 218 |
TARTANAIR_LICENSE_URL = ( |
| 219 |
"https://creativecommons.org/licenses/by/4.0/legalcode.txt" |
| 220 |
) |
| 221 |
TARTANAIR_LICENSE_SHA256 = ( |
| 222 |
"9ba9550ad48438d0836ddab3da480b3b69ffa0aac7b7878b5a0039e7ab429411" |
| 223 |
) |
| 224 |
|
| 225 |
|
| 226 |
def download_tartanair_license() -> bytes: |
| 227 |
response = requests.get(TARTANAIR_LICENSE_URL, timeout=60) |
| 228 |
response.raise_for_status() |
| 229 |
license_data = response.content |
| 230 |
digest = hashlib.sha256(license_data).hexdigest() |
| 231 |
if digest != TARTANAIR_LICENSE_SHA256: |
| 232 |
raise RuntimeError(f"Unexpected TartanAir license SHA-256: {digest}") |
| 233 |
return license_data |
| 234 |
|
| 235 |
|
| 236 |
def encode_image_jpeg(source_png: bytes) -> bytes: |
| 237 |
output = io.BytesIO() |
| 238 |
PIL.Image.open(io.BytesIO(source_png)).convert("RGB").save( |
| 239 |
output, |
| 240 |
format="JPEG", |
| 241 |
quality=IMAGE_QUALITY, |
| 242 |
subsampling=IMAGE_SUBSAMPLING, |
| 243 |
optimize=True, |
| 244 |
progressive=True, |
| 245 |
) |
| 246 |
return output.getvalue() |
| 247 |
|
| 248 |
|
| 249 |
def encode_depth_png(source_png: bytes) -> bytes: |
| 250 |
"""Convert packed float32 RGBA depth to min-pooled uint16 depth.""" |
| 251 |
rgba = np.asarray(PIL.Image.open(io.BytesIO(source_png))).copy() |
| 252 |
if rgba.dtype != np.uint8 or rgba.ndim != 3 or rgba.shape[2] != 4: |
| 253 |
raise ValueError("Expected an 8-bit RGBA depth image") |
| 254 |
source_height = int(rgba.shape[0]) |
| 255 |
source_width = int(rgba.shape[1]) |
| 256 |
depth = rgba.view("<f4").reshape(source_height, source_width) |
| 257 |
|
| 258 |
output_width, output_height = DEPTH_SIZE |
| 259 |
if source_width % output_width != 0 or source_height % output_height != 0: |
| 260 |
raise ValueError( |
| 261 |
f"Cannot downsample depth image of shape {depth.shape} " |
| 262 |
f"to {(output_height, output_width)}" |
| 263 |
) |
| 264 |
block_height = source_height // output_height |
| 265 |
block_width = source_width // output_width |
| 266 |
valid = np.isfinite(depth) & (depth > 0) |
| 267 |
depth = np.where(valid, depth, np.inf) |
| 268 |
depth = depth.reshape( |
| 269 |
output_height, block_height, output_width, block_width |
| 270 |
).min(axis=(1, 3)) |
| 271 |
|
| 272 |
quantized = np.zeros(depth.shape, dtype=np.uint16) |
| 273 |
valid = np.isfinite(depth) |
| 274 |
quantized[valid] = np.clip( |
| 275 |
np.rint(depth[valid] * DEPTH_SCALE), 1, np.iinfo(np.uint16).max |
| 276 |
).astype(np.uint16) |
| 277 |
|
| 278 |
output = io.BytesIO() |
| 279 |
PIL.Image.fromarray(quantized).save( |
| 280 |
output, format="PNG", compress_level=9, optimize=True |
| 281 |
) |
| 282 |
return output.getvalue() |
| 283 |
|
| 284 |
|
| 285 |
def source_url(manifest: dict, scene: SceneSelection) -> str: |
| 286 |
source = manifest["source"] |
| 287 |
path = quote(scene.source_archive) |
| 288 |
return ( |
| 289 |
f"https://huggingface.co/datasets/{source['repository']}/resolve/" |
| 290 |
f"{source['revision']}/{path}" |
| 291 |
) |
| 292 |
|
| 293 |
|
| 294 |
def package_scene( |
| 295 |
archive: tarfile.TarFile, |
| 296 |
manifest: dict, |
| 297 |
scene: SceneSelection, |
| 298 |
remote_zips: dict[str, RemoteZip], |
| 299 |
num_workers: int, |
| 300 |
) -> None: |
| 301 |
image_remote_zip = remote_zips.get(scene.source_archive) |
| 302 |
if image_remote_zip is None: |
| 303 |
image_remote_zip = RemoteZip(source_url(manifest, scene)) |
| 304 |
remote_zips[scene.source_archive] = image_remote_zip |
| 305 |
depth_remote_zip = remote_zips.get(scene.depth_source_archive) |
| 306 |
if depth_remote_zip is None: |
| 307 |
depth_url = source_url(manifest, scene).replace( |
| 308 |
"image_lcam_equirect.zip", "depth_lcam_equirect.zip" |
| 309 |
) |
| 310 |
depth_remote_zip = RemoteZip(depth_url) |
| 311 |
remote_zips[scene.depth_source_archive] = depth_remote_zip |
| 312 |
source_prefix = ( |
| 313 |
f"{scene.environment}/Data_{scene.difficulty}/{scene.trajectory}" |
| 314 |
) |
| 315 |
pose_name = f"{source_prefix}/pose_lcam_front.txt" |
| 316 |
pose_data, pose_member = image_remote_zip.read(pose_name) |
| 317 |
pose_lines = [line for line in pose_data.decode().splitlines() if line] |
| 318 |
poses = np.loadtxt(io.StringIO("\n".join(pose_lines))) |
| 319 |
options = manifest["frame_selection"] |
| 320 |
selected_window = select_frame_window( |
| 321 |
poses, |
| 322 |
num_frames=options["num_frames"], |
| 323 |
max_adjacent_translation_m=options["max_adjacent_translation_m"], |
| 324 |
max_adjacent_rotation_deg=options["max_adjacent_rotation_deg"], |
| 325 |
) |
| 326 |
selection_key = f"{scene.environment}:{scene.difficulty}:{scene.trajectory}" |
| 327 |
canonical_start = manifest["frame_starts"][selection_key] |
| 328 |
frame_ids = range(canonical_start, canonical_start + options["num_frames"]) |
| 329 |
if frame_ids != selected_window: |
| 330 |
raise RuntimeError( |
| 331 |
f"Canonical frame window changed for {selection_key}: " |
| 332 |
f"expected {frame_ids.start}, selected {selected_window.start}" |
| 333 |
) |
| 334 |
|
| 335 |
scene_root = f"{scene.category}/{scene.name}" |
| 336 |
selected_pose_lines = [] |
| 337 |
frames = [] |
| 338 |
source_names = [ |
| 339 |
( |
| 340 |
f"{source_prefix}/image_lcam_equirect/" |
| 341 |
f"{frame_id:06d}_lcam_equirect_image.png" |
| 342 |
) |
| 343 |
for frame_id in frame_ids |
| 344 |
] |
| 345 |
depth_source_names = [ |
| 346 |
( |
| 347 |
f"{source_prefix}/depth_lcam_equirect/" |
| 348 |
f"{frame_id:06d}_lcam_equirect_depth.png" |
| 349 |
) |
| 350 |
for frame_id in frame_ids |
| 351 |
] |
| 352 |
with concurrent.futures.ThreadPoolExecutor( |
| 353 |
max_workers=num_workers |
| 354 |
) as executor: |
| 355 |
image_members = list(executor.map(image_remote_zip.read, source_names)) |
| 356 |
depth_members = list( |
| 357 |
executor.map(depth_remote_zip.read, depth_source_names) |
| 358 |
) |
| 359 |
|
| 360 |
for frame_id, (image_data, image_member), (depth_data, depth_member) in zip( |
| 361 |
frame_ids, image_members, depth_members, strict=True |
| 362 |
): |
| 363 |
image_name = f"{frame_id:06d}.jpg" |
| 364 |
depth_name = f"{frame_id:06d}.png" |
| 365 |
add_bytes( |
| 366 |
archive, |
| 367 |
f"{scene_root}/images/{image_name}", |
| 368 |
encode_image_jpeg(image_data), |
| 369 |
) |
| 370 |
add_bytes( |
| 371 |
archive, |
| 372 |
f"{scene_root}/depth/{depth_name}", |
| 373 |
encode_depth_png(depth_data), |
| 374 |
) |
| 375 |
selected_pose_lines.append(f"{frame_id} {pose_lines[frame_id]}") |
| 376 |
frames.append( |
| 377 |
{ |
| 378 |
"source_frame": frame_id, |
| 379 |
"image_name": image_name, |
| 380 |
"depth_name": depth_name, |
| 381 |
"source_crc32": f"{image_member.crc32:08x}", |
| 382 |
"depth_source_crc32": f"{depth_member.crc32:08x}", |
| 383 |
} |
| 384 |
) |
| 385 |
|
| 386 |
metadata = { |
| 387 |
"manifest_version": manifest["version"], |
| 388 |
"category": scene.category, |
| 389 |
"environment": scene.environment, |
| 390 |
"difficulty": scene.difficulty, |
| 391 |
"trajectory": scene.trajectory, |
| 392 |
"source_archive": scene.source_archive, |
| 393 |
"depth_source_archive": scene.depth_source_archive, |
| 394 |
"pose_crc32": f"{pose_member.crc32:08x}", |
| 395 |
"image_size": manifest["source"]["image_size"], |
| 396 |
"image_encoding": { |
| 397 |
"format": "jpeg", |
| 398 |
"quality": IMAGE_QUALITY, |
| 399 |
"subsampling": "4:4:4", |
| 400 |
"progressive": True, |
| 401 |
}, |
| 402 |
"depth_size": list(DEPTH_SIZE), |
| 403 |
"depth_scale": DEPTH_SCALE, |
| 404 |
"depth_invalid_value": DEPTH_INVALID_VALUE, |
| 405 |
"depth_downsampling": "min_pool", |
| 406 |
"frames": frames, |
| 407 |
} |
| 408 |
add_bytes( |
| 409 |
archive, |
| 410 |
f"{scene_root}/poses.txt", |
| 411 |
("\n".join(selected_pose_lines) + "\n").encode(), |
| 412 |
) |
| 413 |
add_bytes( |
| 414 |
archive, |
| 415 |
f"{scene_root}/scene.json", |
| 416 |
(json.dumps(metadata, indent=2) + "\n").encode(), |
| 417 |
) |
| 418 |
|
| 419 |
|
| 420 |
def build_shard( |
| 421 |
output_path: Path, |
| 422 |
manifest: dict, |
| 423 |
shard_index: int, |
| 424 |
scenes: list[SceneSelection], |
| 425 |
overwrite: bool, |
| 426 |
num_workers: int, |
| 427 |
) -> tuple[str, str]: |
| 428 |
filename = shard_name(manifest, shard_index) |
| 429 |
target = output_path / filename |
| 430 |
if target.exists() and not overwrite: |
| 431 |
digest = sha256_file(target) |
| 432 |
return filename, digest |
| 433 |
|
| 434 |
temporary = target.with_suffix(target.suffix + ".part") |
| 435 |
remote_zips: dict[str, RemoteZip] = {} |
| 436 |
license_data = download_tartanair_license() |
| 437 |
with tarfile.open(temporary, "w", format=tarfile.PAX_FORMAT) as archive: |
| 438 |
root = Path(__file__).parent |
| 439 |
add_bytes(archive, "TARTANAIR_LICENSE", license_data) |
| 440 |
add_bytes( |
| 441 |
archive, |
| 442 |
"TARTANAIR_README.md", |
| 443 |
(root / "README.md").read_bytes(), |
| 444 |
) |
| 445 |
add_bytes(archive, MANIFEST_PATH.name, MANIFEST_PATH.read_bytes()) |
| 446 |
for scene in scenes: |
| 447 |
print(f"Packaging {scene.category}/{scene.name}") |
| 448 |
package_scene(archive, manifest, scene, remote_zips, num_workers) |
| 449 |
if temporary.stat().st_size >= 2 * 1024**3: |
| 450 |
raise RuntimeError(f"Release asset exceeds 2 GiB: {temporary}") |
| 451 |
temporary.replace(target) |
| 452 |
digest = sha256_file(target) |
| 453 |
return filename, digest |
| 454 |
|
| 455 |
|
| 456 |
def sha256_file(path: Path) -> str: |
| 457 |
digest = hashlib.sha256() |
| 458 |
with open(path, "rb") as fid: |
| 459 |
while chunk := fid.read(1024 * 1024): |
| 460 |
digest.update(chunk) |
| 461 |
return digest.hexdigest() |
| 462 |
|
| 463 |
|
| 464 |
def main() -> None: |
| 465 |
parser = argparse.ArgumentParser(description=__doc__) |
| 466 |
parser.add_argument("--output_path", type=Path, required=True) |
| 467 |
parser.add_argument("--shards", type=int, nargs="+", default=[]) |
| 468 |
parser.add_argument("--overwrite", action="store_true") |
| 469 |
parser.add_argument("--num_workers", type=int, default=8) |
| 470 |
args = parser.parse_args() |
| 471 |
|
| 472 |
manifest = load_manifest() |
| 473 |
shards = scene_shards(manifest) |
| 474 |
selected = args.shards or list(range(len(shards))) |
| 475 |
if any(index < 0 or index >= len(shards) for index in selected): |
| 476 |
raise ValueError(f"Shard index must be in [0, {len(shards) - 1}]") |
| 477 |
args.output_path.mkdir(parents=True, exist_ok=True) |
| 478 |
|
| 479 |
checksums = {} |
| 480 |
for index in selected: |
| 481 |
filename, digest = build_shard( |
| 482 |
args.output_path, |
| 483 |
manifest, |
| 484 |
index, |
| 485 |
shards[index], |
| 486 |
args.overwrite, |
| 487 |
args.num_workers, |
| 488 |
) |
| 489 |
checksums[filename] = digest |
| 490 |
checksum_path = args.output_path / "tartanair_v2_checksums.json" |
| 491 |
existing = ( |
| 492 |
json.loads(checksum_path.read_text()) if checksum_path.exists() else {} |
| 493 |
) |
| 494 |
existing.update(checksums) |
| 495 |
checksum_path.write_text(json.dumps(existing, indent=2) + "\n") |
| 496 |
print(f"Wrote {checksum_path}") |
| 497 |
|
| 498 |
|
| 499 |
if __name__ == "__main__": |
| 500 |
main() |