Datasets:
Download install_annotations.py from ryo818/HOTC2026-Modal: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/datasets/ryo818/HOTC2026-Modal/resolve/main/install_annotations.py
- Command line
-
hf download hf://datasets/ryo818/HOTC2026-Modal/install_annotations.py
-
curl -L -o install_annotations.py https://huggingface.co/datasets/ryo818/HOTC2026-Modal/resolve/main/install_annotations.py
15.8 kB
| #!/usr/bin/env python3 | |
| """Install HOTC2026-Modal and optionally join it to the official HOTC 2026 data.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import os | |
| import shutil | |
| import struct | |
| import tempfile | |
| import zipfile | |
| from pathlib import Path | |
| RELEASE_FORMAT = "hotc2026-modal-release-manifest-v1" | |
| VIDEO_FORMAT = "hotc2026-modal-video-annotation-v1" | |
| INSTALLED_FORMAT = "hotc2026-modal-installed-v1" | |
| INTEGRATED_FORMAT = "hotc2026-modal-integrated-v1" | |
| FALSE_COLOR_DIRS = { | |
| "training": { | |
| "nir": "HSI-NIR-FalseColor", | |
| "rednir": "HSI-RedNIR-FalseColor", | |
| "vis": "HSI-VIS-FalseColor_25", | |
| }, | |
| "update": { | |
| "nir": "HSI-NIR-FalseColor", | |
| "rednir": "HSI-RedNIR-FalseColor", | |
| "vis": "HSI-VIS-FalseColor", | |
| }, | |
| "validation": { | |
| "nir": "HSI-NIR-FalseColor", | |
| "rednir": "HSI-RedNIR-FalseColor", | |
| "vis": "HSI-VIS-FalseColor", | |
| }, | |
| } | |
| HSI_DIRS = { | |
| "nir": "HSI-NIR", | |
| "rednir": "HSI-RedNIR", | |
| "vis": "HSI-VIS", | |
| } | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def atomic_write(path: Path, data: bytes) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| descriptor, temporary = tempfile.mkstemp(prefix=path.name, suffix=".tmp", dir=path.parent) | |
| try: | |
| with os.fdopen(descriptor, "wb") as handle: | |
| handle.write(data) | |
| os.replace(temporary, path) | |
| finally: | |
| if os.path.exists(temporary): | |
| os.unlink(temporary) | |
| def portable(path: Path, base: Path) -> str: | |
| try: | |
| return path.resolve().relative_to(base).as_posix() | |
| except ValueError: | |
| return str(path.resolve()) | |
| def parse_id(identifier: str) -> tuple[str, str, int]: | |
| sequence_id, separator, frame_text = identifier.rpartition("_") | |
| if not separator or not frame_text.isdigit(): | |
| raise ValueError(f"invalid HOTC ID: {identifier!r}") | |
| sensor, separator, sequence = sequence_id.partition("-") | |
| if not separator or sensor not in HSI_DIRS or not sequence: | |
| raise ValueError(f"invalid HOTC ID: {identifier!r}") | |
| return sensor, sequence, int(frame_text) | |
| def read_csv(path: Path, validation: bool) -> dict[tuple[str, str, str], list[dict]]: | |
| videos: dict[tuple[str, str, str], list[dict]] = {} | |
| collection = "validation" if validation else "training" | |
| previous_frame: int | None = None | |
| with path.open(newline="", encoding="utf-8-sig") as handle: | |
| reader = csv.DictReader(handle) | |
| if reader.fieldnames != ["ID", "x", "y", "width", "height"]: | |
| raise ValueError(f"unexpected columns in {path}: {reader.fieldnames}") | |
| for row in reader: | |
| sensor, sequence, frame_number = parse_id(row["ID"]) | |
| if not validation and previous_frame is not None and frame_number < previous_frame: | |
| if collection == "update": | |
| raise ValueError(f"multiple collection resets in {path}") | |
| collection = "update" | |
| previous_frame = frame_number | |
| bbox = None | |
| if not validation: | |
| bbox = [int(row[name]) for name in ("x", "y", "width", "height")] | |
| videos.setdefault((collection, sensor, sequence), []).append( | |
| { | |
| "frame_key": f"{collection}/{row['ID']}", | |
| "frame_number": frame_number, | |
| "official_amodal_bbox_xywh": bbox, | |
| } | |
| ) | |
| return videos | |
| def numbered_files(directory: Path, suffixes: set[str]) -> list[Path]: | |
| files = [ | |
| path for path in directory.iterdir() | |
| if path.is_file() and path.suffix.lower() in suffixes and path.stem.isdigit() | |
| ] | |
| return sorted(files, key=lambda path: int(path.stem)) | |
| def find_frame_directory( | |
| roots: list[Path], expected_count: int, suffixes: set[str] | |
| ) -> Path: | |
| matches = [] | |
| for root in roots: | |
| if not root.is_dir(): | |
| continue | |
| candidates = [root, *(path for path in root.rglob("*") if path.is_dir())] | |
| for candidate in candidates: | |
| if len(numbered_files(candidate, suffixes)) == expected_count: | |
| matches.append(candidate.resolve()) | |
| matches = sorted(set(matches)) | |
| if len(matches) != 1: | |
| raise FileNotFoundError( | |
| f"expected exactly one directory with {expected_count} frames under {roots}; " | |
| f"found {len(matches)}: {matches}" | |
| ) | |
| return matches[0] | |
| def sequence_roots( | |
| training_roots: list[Path], | |
| validation_roots: list[Path], | |
| collection: str, | |
| sensor: str, | |
| sequence: str, | |
| ) -> tuple[list[Path], list[Path]]: | |
| if collection == "validation": | |
| bases = validation_roots | |
| elif collection == "update": | |
| bases = [root / "update" for root in training_roots] | |
| elif collection == "training": | |
| bases = training_roots | |
| else: | |
| raise ValueError(f"unsupported collection: {collection!r}") | |
| return ( | |
| [base / FALSE_COLOR_DIRS[collection][sensor] / sequence for base in bases], | |
| [base / HSI_DIRS[sensor] / sequence for base in bases], | |
| ) | |
| def png_size(path: Path) -> tuple[int, int]: | |
| with path.open("rb") as handle: | |
| header = handle.read(24) | |
| if len(header) < 24 or header[:8] != b"\x89PNG\r\n\x1a\n" or header[12:16] != b"IHDR": | |
| raise ValueError(f"invalid PNG: {path}") | |
| return struct.unpack(">II", header[16:24]) | |
| def jpeg_size(path: Path) -> tuple[int, int]: | |
| with path.open("rb") as handle: | |
| if handle.read(2) != b"\xff\xd8": | |
| raise ValueError(f"invalid JPEG: {path}") | |
| while True: | |
| byte = handle.read(1) | |
| while byte == b"\xff": | |
| byte = handle.read(1) | |
| if not byte: | |
| break | |
| marker = byte[0] | |
| if marker in {0xD8, 0xD9} or 0xD0 <= marker <= 0xD7: | |
| continue | |
| length_data = handle.read(2) | |
| if len(length_data) != 2: | |
| break | |
| length = struct.unpack(">H", length_data)[0] | |
| if marker in { | |
| 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, | |
| 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF, | |
| }: | |
| dimensions = handle.read(5) | |
| if len(dimensions) != 5: | |
| break | |
| height, width = struct.unpack(">HH", dimensions[1:5]) | |
| return width, height | |
| handle.seek(length - 2, 1) | |
| raise ValueError(f"JPEG dimensions not found: {path}") | |
| def image_size(path: Path) -> tuple[int, int]: | |
| if path.suffix.lower() == ".png": | |
| return png_size(path) | |
| if path.suffix.lower() in {".jpg", ".jpeg"}: | |
| return jpeg_size(path) | |
| raise ValueError(f"unsupported image type: {path}") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("snapshot", type=Path, help="downloaded Hugging Face snapshot") | |
| parser.add_argument("--output", type=Path, default=Path("hotc2026-modal-v1")) | |
| parser.add_argument( | |
| "--training-root", type=Path, action="append", | |
| help="training directory; repeat if modalities are split across roots", | |
| ) | |
| parser.add_argument( | |
| "--validation-root", type=Path, action="append", | |
| help="validation directory; repeat if modalities are split across roots", | |
| ) | |
| parser.add_argument("--training-csv", type=Path) | |
| parser.add_argument("--sample-csv", type=Path) | |
| parser.add_argument( | |
| "--path-base", type=Path, default=Path.cwd(), | |
| help="make official-data paths relative to this directory when possible", | |
| ) | |
| args = parser.parse_args() | |
| integration_values = ( | |
| args.training_root, args.validation_root, args.training_csv, args.sample_csv | |
| ) | |
| if any(value is not None for value in integration_values) and not all( | |
| value is not None for value in integration_values | |
| ): | |
| parser.error( | |
| "--training-root, --validation-root, --training-csv, and --sample-csv " | |
| "must be supplied together" | |
| ) | |
| return args | |
| def main() -> None: | |
| args = parse_args() | |
| snapshot = args.snapshot.resolve() | |
| output = args.output.resolve() | |
| path_base = args.path_base.resolve() | |
| release = json.loads((snapshot / "release-manifest.json").read_text(encoding="utf-8")) | |
| if release.get("format") != RELEASE_FORMAT: | |
| raise ValueError("unsupported release manifest") | |
| integrate = args.training_root is not None | |
| official_rows: dict[tuple[str, str, str], list[dict]] = {} | |
| training_roots = validation_roots = None | |
| if integrate: | |
| training_roots = [path.resolve() for path in args.training_root] | |
| validation_roots = [path.resolve() for path in args.validation_root] | |
| official_rows.update(read_csv(args.training_csv.resolve(), validation=False)) | |
| official_rows.update(read_csv(args.sample_csv.resolve(), validation=True)) | |
| output.mkdir(parents=True, exist_ok=True) | |
| index_path = output / "frames.jsonl" | |
| index_handle = index_path.open("w", encoding="utf-8") if integrate else None | |
| videos = [] | |
| total_frames = 0 | |
| try: | |
| for video_index, video in enumerate(release["videos"], start=1): | |
| collection = video["collection"] | |
| sensor = video["sensor"] | |
| sequence = video["sequence_name"] | |
| identity = (collection, sensor, sequence) | |
| archive_path = snapshot / video["path"] | |
| if archive_path.stat().st_size != video["size_bytes"]: | |
| raise ValueError(f"archive size mismatch: {archive_path}") | |
| if sha256_file(archive_path) != video["sha256"]: | |
| raise ValueError(f"archive checksum mismatch: {archive_path}") | |
| video_root = output / collection / sensor / sequence | |
| with zipfile.ZipFile(archive_path) as archive: | |
| annotation = json.loads(archive.read("annotation.json")) | |
| if annotation.get("format") != VIDEO_FORMAT: | |
| raise ValueError(f"unsupported archive: {archive_path}") | |
| annotation_identity = tuple( | |
| annotation.get(name) for name in ("collection", "sensor", "sequence_name") | |
| ) | |
| if annotation_identity != identity: | |
| raise ValueError(f"archive identity mismatch: {archive_path}") | |
| frames = annotation["frames"] | |
| if len(frames) != video["frame_count"]: | |
| raise ValueError(f"archive frame count mismatch: {archive_path}") | |
| image_files = hsi_files = rows = None | |
| if integrate: | |
| rows = official_rows.get(identity) | |
| if rows is None or len(rows) != len(frames): | |
| raise ValueError( | |
| f"official CSV rows do not match {'/'.join(identity)}: " | |
| f"{0 if rows is None else len(rows)} != {len(frames)}" | |
| ) | |
| false_color_root, hsi_root = sequence_roots( | |
| training_roots, validation_roots, collection, sensor, sequence | |
| ) | |
| image_directory = find_frame_directory( | |
| false_color_root, len(frames), {".jpg", ".jpeg"} | |
| ) | |
| hsi_directory = find_frame_directory(hsi_root, len(frames), {".png"}) | |
| image_files = numbered_files(image_directory, {".jpg", ".jpeg"}) | |
| hsi_files = numbered_files(hsi_directory, {".png"}) | |
| for frame_offset, frame in enumerate(frames): | |
| mask_path = video_root / frame["mask_path"] | |
| mask_bytes = archive.read(frame["mask_path"]) | |
| if hashlib.sha256(mask_bytes).hexdigest() != frame["mask_sha256"]: | |
| raise ValueError(f"mask checksum mismatch: {frame['frame_key']}") | |
| if not mask_path.is_file() or sha256_file(mask_path) != frame["mask_sha256"]: | |
| atomic_write(mask_path, mask_bytes) | |
| if integrate: | |
| row = rows[frame_offset] | |
| if row["frame_key"] != frame["frame_key"]: | |
| raise ValueError( | |
| f"frame-key mismatch: {row['frame_key']} != {frame['frame_key']}" | |
| ) | |
| image_path = image_files[frame_offset] | |
| hsi_path = hsi_files[frame_offset] | |
| if image_size(mask_path) != image_size(image_path): | |
| raise ValueError( | |
| f"mask/image size mismatch for {frame['frame_key']}: " | |
| f"{image_size(mask_path)} != {image_size(image_path)}" | |
| ) | |
| record = { | |
| "frame_key": frame["frame_key"], | |
| "frame_number": frame["frame_number"], | |
| "collection": collection, | |
| "sensor": sensor, | |
| "sequence_name": sequence, | |
| "false_color_image": portable(image_path, path_base), | |
| "hsi_mosaic": portable(hsi_path, path_base), | |
| "mask": portable(mask_path, path_base), | |
| "official_amodal_bbox_xywh": row["official_amodal_bbox_xywh"], | |
| "modal_bbox_xywh": frame["modal_bbox_xywh"], | |
| } | |
| index_handle.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| annotation_path = video_root / "annotation.json" | |
| atomic_write( | |
| annotation_path, | |
| (json.dumps(annotation, ensure_ascii=False, indent=2) + "\n").encode(), | |
| ) | |
| total_frames += len(frames) | |
| video_record = { | |
| "collection": collection, | |
| "sensor": sensor, | |
| "sequence_name": sequence, | |
| "frame_count": len(frames), | |
| "annotation": portable(annotation_path, output), | |
| } | |
| if integrate: | |
| video_record["false_color_directory"] = portable(image_directory, path_base) | |
| video_record["hsi_directory"] = portable(hsi_directory, path_base) | |
| videos.append(video_record) | |
| if video_index % 25 == 0 or video_index == len(release["videos"]): | |
| print(f"processed {video_index}/{len(release['videos'])} videos", flush=True) | |
| finally: | |
| if index_handle is not None: | |
| index_handle.close() | |
| manifest = { | |
| "format": INTEGRATED_FORMAT if integrate else INSTALLED_FORMAT, | |
| "source": "ryo818/HOTC2026-Modal", | |
| "video_count": len(videos), | |
| "frame_count": total_frames, | |
| "collections": { | |
| name: sum(video["collection"] == name for video in videos) | |
| for name in ("training", "update", "validation") | |
| }, | |
| "frame_index": "frames.jsonl" if integrate else None, | |
| "official_data_linked": integrate, | |
| "videos": videos, | |
| } | |
| atomic_write( | |
| output / "manifest.json", | |
| (json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode(), | |
| ) | |
| print( | |
| f"installed {len(videos)} videos / {total_frames} frames under {output}; " | |
| f"official data linked: {integrate}", | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |