Datasets:
File size: 9,624 Bytes
299146f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | 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()
|