| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import hashlib |
| import json |
| import os |
| import re |
| import shutil |
| from collections import Counter |
| from pathlib import Path |
| from typing import Any |
|
|
|
|
| IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} |
| VIDEO_EXTENSIONS = {".mp4", ".mov", ".avi", ".mkv"} |
| ATTRIBUTES = ("weave", "material", "usage", "features") |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Build the canonical VidTouch Hub release.") |
| parser.add_argument("--source", type=Path, required=True) |
| parser.add_argument("--output", type=Path, required=True) |
| return parser.parse_args() |
|
|
|
|
| def parse_labels(path: Path) -> dict[str, dict[str, Any]]: |
| labels: dict[str, dict[str, Any]] = {} |
| with path.open("r", encoding="utf-8") as handle: |
| for line_number, raw in enumerate(handle, 1): |
| line = raw.strip() |
| if not line or line.startswith("#"): |
| continue |
| parts = line.split() |
| if len(parts) < 4: |
| raise ValueError(f"Invalid label line {line_number}: {raw!r}") |
| fabric_id, weave, material, usage, *features = parts |
| if fabric_id in labels: |
| raise ValueError(f"Duplicate Fabric ID in labels: {fabric_id}") |
| labels[fabric_id] = { |
| "fabric_id": fabric_id, |
| "weave": weave, |
| "material": material, |
| "usage": usage, |
| "features": features, |
| } |
| return labels |
|
|
|
|
| def parse_fabric_id(path: Path) -> str: |
| match = re.match(r"^([A-Za-z0-9]+)", path.stem) |
| if not match: |
| raise ValueError(f"Cannot parse Fabric ID from {path.name}") |
| return match.group(1) |
|
|
|
|
| def sha256(path: Path) -> str: |
| digest = hashlib.sha256() |
| with path.open("rb") as handle: |
| for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): |
| digest.update(chunk) |
| return digest.hexdigest() |
|
|
|
|
| def link_or_copy(source: Path, destination: Path) -> None: |
| destination.parent.mkdir(parents=True, exist_ok=True) |
| if destination.exists(): |
| destination.unlink() |
| try: |
| os.link(source, destination) |
| except OSError: |
| shutil.copy2(source, destination) |
|
|
|
|
| def scan_media( |
| folder: Path, |
| extensions: set[str], |
| labels: dict[str, dict[str, Any]], |
| ) -> tuple[list[Path], list[str]]: |
| retained: list[Path] = [] |
| excluded: list[str] = [] |
| for path in sorted(folder.iterdir(), key=lambda item: item.name): |
| if not path.is_file() or path.suffix.lower() not in extensions: |
| continue |
| if parse_fabric_id(path) in labels: |
| retained.append(path) |
| else: |
| excluded.append(path.name) |
| return retained, excluded |
|
|
|
|
| def write_csv(path: Path, fieldnames: list[str], rows: list[dict[str, Any]]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with path.open("w", encoding="utf-8", newline="") as handle: |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(rows) |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| source = args.source.resolve() |
| output = args.output.resolve() |
|
|
| labels_path = source / "label.txt" |
| split_dir = source / "experiments" / "vidtouch_method" / "splits" |
| labels = parse_labels(labels_path) |
| split = json.loads((split_dir / "fabric_common_v2.json").read_text(encoding="utf-8")) |
|
|
| partition_by_id: dict[str, str] = {} |
| for partition, key in (("train", "train_ids"), ("validation", "val_ids"), ("test", "test_ids")): |
| for fabric_id in split[key]: |
| if fabric_id in partition_by_id: |
| raise ValueError(f"Fabric ID appears in multiple partitions: {fabric_id}") |
| partition_by_id[fabric_id] = partition |
| if set(partition_by_id) != set(labels): |
| raise ValueError("Frozen split does not cover exactly the canonical Fabric IDs.") |
|
|
| images, excluded_images = scan_media(source / "RGBs", IMAGE_EXTENSIONS, labels) |
| videos, excluded_videos = scan_media(source / "TACs", VIDEO_EXTENSIONS, labels) |
|
|
| image_counts = Counter(parse_fabric_id(path) for path in images) |
| video_counts = Counter(parse_fabric_id(path) for path in videos) |
| missing_images = sorted(set(labels) - set(image_counts)) |
| missing_videos = sorted(set(labels) - set(video_counts)) |
| if missing_images or missing_videos: |
| raise ValueError( |
| f"Missing media: RGB={missing_images}, tactile={missing_videos}" |
| ) |
|
|
| expected = { |
| "fabrics": 144, |
| "rgb_images": 435, |
| "tactile_videos": 432, |
| "partitions": {"train": 100, "validation": 22, "test": 22}, |
| "label_cardinality": {"weave": 39, "material": 60, "usage": 46, "features": 100}, |
| } |
| label_cardinality = { |
| "weave": len({row["weave"] for row in labels.values()}), |
| "material": len({row["material"] for row in labels.values()}), |
| "usage": len({row["usage"] for row in labels.values()}), |
| "features": len({feature for row in labels.values() for feature in row["features"]}), |
| } |
| actual = { |
| "fabrics": len(labels), |
| "rgb_images": len(images), |
| "tactile_videos": len(videos), |
| "partitions": dict(Counter(partition_by_id.values())), |
| "label_cardinality": label_cardinality, |
| } |
| if actual != expected: |
| raise ValueError(f"Release statistics differ from the frozen specification: {actual}") |
|
|
| for relative in ( |
| "RGBs", |
| "TACs", |
| "metadata", |
| "splits", |
| ): |
| (output / relative).mkdir(parents=True, exist_ok=True) |
|
|
| link_or_copy(labels_path, output / "label.txt") |
| for split_name in ( |
| "fabric_common_v2.json", |
| "fabric_common_v2_lowshot25.json", |
| "fabric_common_v2_lowshot50.json", |
| ): |
| link_or_copy(split_dir / split_name, output / "splits" / split_name) |
|
|
| fabric_rows: list[dict[str, Any]] = [] |
| for fabric_id in sorted(labels): |
| label = labels[fabric_id] |
| fabric_rows.append( |
| { |
| "fabric_id": fabric_id, |
| "split": partition_by_id[fabric_id], |
| "weave": label["weave"], |
| "material": label["material"], |
| "usage": label["usage"], |
| "features": json.dumps(label["features"], ensure_ascii=True), |
| "rgb_count": image_counts[fabric_id], |
| "tactile_count": video_counts[fabric_id], |
| } |
| ) |
| write_csv( |
| output / "metadata" / "fabrics.csv", |
| ["fabric_id", "split", "weave", "material", "usage", "features", "rgb_count", "tactile_count"], |
| fabric_rows, |
| ) |
|
|
| observation_rows: list[dict[str, Any]] = [] |
| for modality, paths, destination_name in ( |
| ("rgb", images, "RGBs"), |
| ("tactile", videos, "TACs"), |
| ): |
| modality_rows: list[dict[str, Any]] = [] |
| for path in paths: |
| fabric_id = parse_fabric_id(path) |
| label = labels[fabric_id] |
| link_or_copy(path, output / destination_name / path.name) |
| row = { |
| "file_name": path.name, |
| "fabric_id": fabric_id, |
| "split": partition_by_id[fabric_id], |
| "weave": label["weave"], |
| "material": label["material"], |
| "usage": label["usage"], |
| "features": json.dumps(label["features"], ensure_ascii=True), |
| } |
| modality_rows.append(row) |
| observation_rows.append( |
| { |
| "path": f"{destination_name}/{path.name}", |
| "modality": modality, |
| **{key: value for key, value in row.items() if key != "file_name"}, |
| } |
| ) |
| write_csv( |
| output / destination_name / "metadata.csv", |
| ["file_name", "fabric_id", "split", "weave", "material", "usage", "features"], |
| modality_rows, |
| ) |
|
|
| write_csv( |
| output / "metadata" / "observations.csv", |
| ["path", "modality", "fabric_id", "split", "weave", "material", "usage", "features"], |
| observation_rows, |
| ) |
|
|
| release_manifest = { |
| "release_name": "VidTouch canonical release", |
| "release_version": "1.0.0", |
| "statistics": actual, |
| "rgb_per_fabric_distribution": dict(sorted(Counter(image_counts.values()).items())), |
| "tactile_per_fabric_distribution": dict(sorted(Counter(video_counts.values()).items())), |
| "excluded_unannotated_source_media": { |
| "rgb": excluded_images, |
| "tactile": excluded_videos, |
| }, |
| "canonical_label_sha256": sha256(labels_path), |
| "frozen_split_sha256": sha256(split_dir / "fabric_common_v2.json"), |
| "assignment_sha256": split["metadata"]["assignment_sha256"], |
| "data_manifest_sha256": split["metadata"]["data_manifest_sha256"], |
| } |
| (output / "release_manifest.json").write_text( |
| json.dumps(release_manifest, indent=2, ensure_ascii=True) + "\n", |
| encoding="utf-8", |
| ) |
|
|
| checksum_paths = sorted( |
| path |
| for path in output.rglob("*") |
| if path.is_file() and path.name != "checksums.sha256" |
| ) |
| with (output / "checksums.sha256").open("w", encoding="utf-8", newline="\n") as handle: |
| for path in checksum_paths: |
| relative = path.relative_to(output).as_posix() |
| handle.write(f"{sha256(path)} {relative}\n") |
|
|
| print(json.dumps(release_manifest, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|