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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import argparse
|
| 3 |
+
import ast
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import shutil
|
| 8 |
+
import ssl
|
| 9 |
+
import struct
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
EXCLUDED_DIRS = {
|
| 19 |
+
".agents",
|
| 20 |
+
".cache",
|
| 21 |
+
".codex",
|
| 22 |
+
".git",
|
| 23 |
+
".vscode",
|
| 24 |
+
"__pycache__",
|
| 25 |
+
"_hf_scene_archives",
|
| 26 |
+
"alignment_test_outputs",
|
| 27 |
+
"outputs",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
IMAGE_EXTENSIONS = {
|
| 31 |
+
".bmp",
|
| 32 |
+
".gif",
|
| 33 |
+
".jpeg",
|
| 34 |
+
".jpg",
|
| 35 |
+
".png",
|
| 36 |
+
".tif",
|
| 37 |
+
".tiff",
|
| 38 |
+
".webp",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
PNG_MODALITY_FILTERS = {
|
| 42 |
+
"image": "Lanczos",
|
| 43 |
+
"depth": "Triangle",
|
| 44 |
+
"flow": "Triangle",
|
| 45 |
+
"flow_scaled": "Triangle",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
DEFAULT_NUMPY_PYTHON = Path("/home/wangxy/miniconda3/envs/promptdepth/bin/python")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def log(message: str) -> None:
|
| 52 |
+
now = datetime.now().isoformat(timespec="seconds")
|
| 53 |
+
print(f"[{now}] {message}", flush=True)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def human_bytes(size: float) -> str:
|
| 57 |
+
units = ("B", "KiB", "MiB", "GiB", "TiB")
|
| 58 |
+
value = float(size)
|
| 59 |
+
for unit in units:
|
| 60 |
+
if abs(value) < 1024.0 or unit == units[-1]:
|
| 61 |
+
if unit == "B":
|
| 62 |
+
return f"{value:.0f} {unit}"
|
| 63 |
+
return f"{value:.1f} {unit}"
|
| 64 |
+
value /= 1024.0
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def parse_args() -> argparse.Namespace:
|
| 68 |
+
parser = argparse.ArgumentParser(
|
| 69 |
+
description="Pack each scene as a tar.zst archive and upload archives to Hugging Face."
|
| 70 |
+
)
|
| 71 |
+
parser.add_argument("repo_id", help="Dataset repo id, for example Yukki1011/PromptDepth")
|
| 72 |
+
parser.add_argument("--private", action="store_true", help="Create repo as private if needed")
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--archive-dir",
|
| 75 |
+
default="_hf_scene_archives",
|
| 76 |
+
help="Temporary directory for scene archives",
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--delete-after-upload",
|
| 80 |
+
action="store_true",
|
| 81 |
+
help="Delete each scene archive after it is uploaded successfully",
|
| 82 |
+
)
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--zstd-level",
|
| 85 |
+
type=int,
|
| 86 |
+
default=1,
|
| 87 |
+
help="zstd compression level. 1 is fastest and usually best for PNG-heavy data",
|
| 88 |
+
)
|
| 89 |
+
parser.add_argument(
|
| 90 |
+
"--rate-limit-sleep",
|
| 91 |
+
type=int,
|
| 92 |
+
default=5,
|
| 93 |
+
help="Seconds to sleep before retrying after a rate limit",
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--only",
|
| 97 |
+
nargs="*",
|
| 98 |
+
default=None,
|
| 99 |
+
help="Optional scene names to process. Default: all scenes",
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--workers",
|
| 103 |
+
type=int,
|
| 104 |
+
default=1,
|
| 105 |
+
help="Number of scenes to pack/upload in parallel. Use 1 for sequential processing",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--max-image-width",
|
| 109 |
+
type=int,
|
| 110 |
+
default=1280,
|
| 111 |
+
help="Resize uploaded image files to fit within this width. Default keeps 720p width",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--max-image-height",
|
| 115 |
+
type=int,
|
| 116 |
+
default=720,
|
| 117 |
+
help="Resize uploaded image files to fit within this height. Default keeps 720p height",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--staging-progress-every",
|
| 121 |
+
type=int,
|
| 122 |
+
default=10,
|
| 123 |
+
help="Seconds between staging progress log updates",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
"--progress-every",
|
| 127 |
+
type=int,
|
| 128 |
+
default=30,
|
| 129 |
+
help="Deprecated. Hugging Face/Xet progress output is used when available.",
|
| 130 |
+
)
|
| 131 |
+
return parser.parse_args()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def retry_delay_seconds(message: str, default_hourly_sleep: int) -> int | None:
|
| 135 |
+
lower = message.lower()
|
| 136 |
+
if "repository commits" in lower and "rate limit" in lower:
|
| 137 |
+
return default_hourly_sleep
|
| 138 |
+
if "too many requests" in lower or "429" in lower:
|
| 139 |
+
return default_hourly_sleep
|
| 140 |
+
retry_after = re.search(r"retry after\s+(\d+)\s+seconds", lower)
|
| 141 |
+
if retry_after:
|
| 142 |
+
return default_hourly_sleep
|
| 143 |
+
transient_network_markers = (
|
| 144 |
+
"broken pipe",
|
| 145 |
+
"connection error",
|
| 146 |
+
"unexpected_eof_while_reading",
|
| 147 |
+
"unexpected eof",
|
| 148 |
+
"connection reset",
|
| 149 |
+
"connection aborted",
|
| 150 |
+
"connecterror",
|
| 151 |
+
"connectionerror",
|
| 152 |
+
"connection timed out",
|
| 153 |
+
"connection timeout",
|
| 154 |
+
"connect timeout",
|
| 155 |
+
"http error",
|
| 156 |
+
"httperror",
|
| 157 |
+
"incomplete read",
|
| 158 |
+
"incompleteread",
|
| 159 |
+
"max retries exceeded",
|
| 160 |
+
"network is unreachable",
|
| 161 |
+
"no route to host",
|
| 162 |
+
"operation timed out",
|
| 163 |
+
"protocolerror",
|
| 164 |
+
"readtimeout",
|
| 165 |
+
"read timed out",
|
| 166 |
+
"request timeout",
|
| 167 |
+
"request timed out",
|
| 168 |
+
"temporarily unavailable",
|
| 169 |
+
"remote disconnected",
|
| 170 |
+
"remote end closed connection",
|
| 171 |
+
"protocol violation",
|
| 172 |
+
"tlsv1 alert",
|
| 173 |
+
"client has been closed",
|
| 174 |
+
"connection refused",
|
| 175 |
+
"name resolution",
|
| 176 |
+
"temporary failure in name resolution",
|
| 177 |
+
)
|
| 178 |
+
if any(marker in lower for marker in transient_network_markers):
|
| 179 |
+
return max(10, default_hourly_sleep)
|
| 180 |
+
return None
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def describe_proxy_environment() -> None:
|
| 184 |
+
proxy_vars = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy")
|
| 185 |
+
configured = [f"{name}={os.environ[name]}" for name in proxy_vars if os.environ.get(name)]
|
| 186 |
+
if configured:
|
| 187 |
+
log("Proxy environment detected: " + ", ".join(configured))
|
| 188 |
+
if any("127.0.0.1:" in value or "localhost:" in value for value in configured):
|
| 189 |
+
log("Localhost proxy detected; make sure the proxy is running on this server, not only on your laptop.")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def scene_dirs(root: Path, only: list[str] | None) -> list[Path]:
|
| 193 |
+
selected = set(only or [])
|
| 194 |
+
scenes = []
|
| 195 |
+
for child in sorted(root.iterdir()):
|
| 196 |
+
if not child.is_dir() or child.name in EXCLUDED_DIRS:
|
| 197 |
+
continue
|
| 198 |
+
if selected and child.name not in selected:
|
| 199 |
+
continue
|
| 200 |
+
scenes.append(child)
|
| 201 |
+
scenes.sort(key=lambda scene: (directory_size_bytes(scene), scene.name))
|
| 202 |
+
return scenes
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def directory_size_bytes(path: Path) -> int:
|
| 206 |
+
total = 0
|
| 207 |
+
stack = [path]
|
| 208 |
+
while stack:
|
| 209 |
+
current = stack.pop()
|
| 210 |
+
try:
|
| 211 |
+
with os.scandir(current) as entries:
|
| 212 |
+
for entry in entries:
|
| 213 |
+
try:
|
| 214 |
+
if entry.is_dir(follow_symlinks=False):
|
| 215 |
+
stack.append(Path(entry.path))
|
| 216 |
+
elif entry.is_file(follow_symlinks=False):
|
| 217 |
+
total += entry.stat(follow_symlinks=False).st_size
|
| 218 |
+
except OSError:
|
| 219 |
+
log(f"WARNING: cannot stat while sizing scene, skipping: {entry.path}")
|
| 220 |
+
except OSError:
|
| 221 |
+
log(f"WARNING: cannot scan while sizing scene, skipping: {current}")
|
| 222 |
+
return total
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def run_checked(cmd: list[str], cwd: Path) -> None:
|
| 226 |
+
log("+ " + " ".join(cmd))
|
| 227 |
+
subprocess.run(cmd, cwd=cwd, check=True)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def archive_marker_payload(max_image_width: int, max_image_height: int) -> dict[str, object]:
|
| 231 |
+
return {
|
| 232 |
+
"created_at": datetime.now().isoformat(timespec="seconds"),
|
| 233 |
+
"image_downsample": {
|
| 234 |
+
"enabled": True,
|
| 235 |
+
"version": "modality-aware-v2",
|
| 236 |
+
"max_width": max_image_width,
|
| 237 |
+
"max_height": max_image_height,
|
| 238 |
+
},
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def archive_marker_matches(marker: Path, max_image_width: int, max_image_height: int) -> bool:
|
| 243 |
+
if not marker.exists():
|
| 244 |
+
return False
|
| 245 |
+
try:
|
| 246 |
+
payload = json.loads(marker.read_text())
|
| 247 |
+
except (json.JSONDecodeError, OSError):
|
| 248 |
+
return False
|
| 249 |
+
image_downsample = payload.get("image_downsample")
|
| 250 |
+
if not isinstance(image_downsample, dict):
|
| 251 |
+
return False
|
| 252 |
+
return (
|
| 253 |
+
image_downsample.get("enabled") is True
|
| 254 |
+
and image_downsample.get("version") == "modality-aware-v2"
|
| 255 |
+
and image_downsample.get("max_width") == max_image_width
|
| 256 |
+
and image_downsample.get("max_height") == max_image_height
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def image_dimensions(path: Path) -> tuple[int, int] | None:
|
| 261 |
+
result = subprocess.run(
|
| 262 |
+
["identify", "-ping", "-format", "%w %h", str(path)],
|
| 263 |
+
text=True,
|
| 264 |
+
stdout=subprocess.PIPE,
|
| 265 |
+
stderr=subprocess.PIPE,
|
| 266 |
+
check=False,
|
| 267 |
+
)
|
| 268 |
+
if result.returncode != 0:
|
| 269 |
+
log(f"WARNING: cannot identify image, keeping original: {path} ({result.stderr.strip()})")
|
| 270 |
+
return None
|
| 271 |
+
try:
|
| 272 |
+
width_text, height_text = result.stdout.strip().split()
|
| 273 |
+
return int(width_text), int(height_text)
|
| 274 |
+
except ValueError:
|
| 275 |
+
log(f"WARNING: unexpected identify output for {path}: {result.stdout.strip()!r}")
|
| 276 |
+
return None
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def npy_shape(path: Path) -> tuple[int, ...] | None:
|
| 280 |
+
try:
|
| 281 |
+
with path.open("rb") as handle:
|
| 282 |
+
if handle.read(6) != b"\x93NUMPY":
|
| 283 |
+
return None
|
| 284 |
+
major, _minor = handle.read(2)
|
| 285 |
+
if major == 1:
|
| 286 |
+
header_len = struct.unpack("<H", handle.read(2))[0]
|
| 287 |
+
elif major in (2, 3):
|
| 288 |
+
header_len = struct.unpack("<I", handle.read(4))[0]
|
| 289 |
+
else:
|
| 290 |
+
return None
|
| 291 |
+
header = handle.read(header_len).decode("latin1")
|
| 292 |
+
payload = ast.literal_eval(header)
|
| 293 |
+
shape = payload.get("shape")
|
| 294 |
+
if isinstance(shape, tuple) and all(isinstance(value, int) for value in shape):
|
| 295 |
+
return shape
|
| 296 |
+
except (OSError, SyntaxError, ValueError, struct.error):
|
| 297 |
+
return None
|
| 298 |
+
return None
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def numpy_python() -> str:
|
| 302 |
+
configured = os.environ.get("NPY_RESIZE_PYTHON")
|
| 303 |
+
if configured:
|
| 304 |
+
return configured
|
| 305 |
+
if DEFAULT_NUMPY_PYTHON.exists():
|
| 306 |
+
return str(DEFAULT_NUMPY_PYTHON)
|
| 307 |
+
return sys.executable
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def check_numpy_python() -> bool:
|
| 311 |
+
result = subprocess.run(
|
| 312 |
+
[numpy_python(), "-c", "import numpy"],
|
| 313 |
+
stdout=subprocess.DEVNULL,
|
| 314 |
+
stderr=subprocess.PIPE,
|
| 315 |
+
text=True,
|
| 316 |
+
check=False,
|
| 317 |
+
)
|
| 318 |
+
if result.returncode == 0:
|
| 319 |
+
return True
|
| 320 |
+
log(
|
| 321 |
+
"ERROR: instance .npy resizing needs numpy. "
|
| 322 |
+
f"Tried {numpy_python()}: {result.stderr.strip()}"
|
| 323 |
+
)
|
| 324 |
+
return False
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def hardlink_or_copy(source: Path, dest: Path) -> None:
|
| 328 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 329 |
+
try:
|
| 330 |
+
os.link(source, dest)
|
| 331 |
+
except OSError:
|
| 332 |
+
shutil.copy2(source, dest)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def resize_image(source: Path, dest: Path, resize_geometry: str, filter_name: str) -> None:
|
| 336 |
+
subprocess.run(
|
| 337 |
+
[
|
| 338 |
+
"convert",
|
| 339 |
+
str(source),
|
| 340 |
+
"-filter",
|
| 341 |
+
filter_name,
|
| 342 |
+
"-resize",
|
| 343 |
+
resize_geometry,
|
| 344 |
+
str(dest),
|
| 345 |
+
],
|
| 346 |
+
check=True,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def path_modality(path: Path) -> str:
|
| 351 |
+
parts = path.parts
|
| 352 |
+
if len(parts) >= 2:
|
| 353 |
+
return parts[-2]
|
| 354 |
+
return ""
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def image_filter_for(source: Path) -> str:
|
| 358 |
+
return PNG_MODALITY_FILTERS.get(path_modality(source), "Lanczos")
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def npy_resize_helper_script() -> str:
|
| 362 |
+
return r"""
|
| 363 |
+
import sys
|
| 364 |
+
from pathlib import Path
|
| 365 |
+
|
| 366 |
+
import numpy as np
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def nearest_indices(old_size: int, new_size: int) -> np.ndarray:
|
| 370 |
+
if old_size == new_size:
|
| 371 |
+
return np.arange(old_size)
|
| 372 |
+
scale = old_size / new_size
|
| 373 |
+
return np.minimum((np.arange(new_size) * scale).astype(np.int64), old_size - 1)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
source = Path(sys.argv[1])
|
| 377 |
+
dest = Path(sys.argv[2])
|
| 378 |
+
new_width = int(sys.argv[3])
|
| 379 |
+
new_height = int(sys.argv[4])
|
| 380 |
+
array = np.load(source)
|
| 381 |
+
if array.ndim < 2:
|
| 382 |
+
raise ValueError(f"Expected at least 2D array, got shape {array.shape} for {source}")
|
| 383 |
+
old_height, old_width = array.shape[:2]
|
| 384 |
+
y_idx = nearest_indices(old_height, new_height)
|
| 385 |
+
x_idx = nearest_indices(old_width, new_width)
|
| 386 |
+
resized = array[y_idx][:, x_idx]
|
| 387 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 388 |
+
np.save(dest, resized)
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def resize_npy_nearest(source: Path, dest: Path, new_width: int, new_height: int) -> None:
|
| 393 |
+
subprocess.run(
|
| 394 |
+
[
|
| 395 |
+
numpy_python(),
|
| 396 |
+
"-c",
|
| 397 |
+
npy_resize_helper_script(),
|
| 398 |
+
str(source),
|
| 399 |
+
str(dest),
|
| 400 |
+
str(new_width),
|
| 401 |
+
str(new_height),
|
| 402 |
+
],
|
| 403 |
+
check=True,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def scaled_size(width: int, height: int, max_width: int, max_height: int) -> tuple[int, int]:
|
| 408 |
+
scale = min(max_width / width, max_height / height, 1.0)
|
| 409 |
+
new_width = max(1, int(round(width * scale)))
|
| 410 |
+
new_height = max(1, int(round(height * scale)))
|
| 411 |
+
return new_width, new_height
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def progress_bar(done: int, total: int, width: int = 24) -> str:
|
| 415 |
+
if total <= 0:
|
| 416 |
+
return "[" + "-" * width + "]"
|
| 417 |
+
filled = min(width, int(width * done / total))
|
| 418 |
+
return "[" + "#" * filled + "-" * (width - filled) + "]"
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def log_staging_progress(
|
| 422 |
+
scene_name: str,
|
| 423 |
+
processed_entries: int,
|
| 424 |
+
total_entries: int,
|
| 425 |
+
processed_images: int,
|
| 426 |
+
total_images: int,
|
| 427 |
+
resized_count: int,
|
| 428 |
+
) -> None:
|
| 429 |
+
percent = 100.0 if total_entries <= 0 else processed_entries * 100.0 / total_entries
|
| 430 |
+
log(
|
| 431 |
+
f"Staging {scene_name}: {progress_bar(processed_entries, total_entries)} "
|
| 432 |
+
f"{percent:5.1f}% ({processed_entries}/{total_entries} entries), "
|
| 433 |
+
f"images {processed_images}/{total_images}, resized {resized_count}"
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def stage_scene_for_archive(
|
| 438 |
+
scene: Path,
|
| 439 |
+
staging_root: Path,
|
| 440 |
+
max_image_width: int,
|
| 441 |
+
max_image_height: int,
|
| 442 |
+
progress_interval: int,
|
| 443 |
+
) -> tuple[Path, int, int]:
|
| 444 |
+
staged_scene = staging_root / scene.name
|
| 445 |
+
if staged_scene.exists():
|
| 446 |
+
shutil.rmtree(staged_scene)
|
| 447 |
+
staged_scene.mkdir(parents=True, exist_ok=True)
|
| 448 |
+
|
| 449 |
+
entries = list(scene.rglob("*"))
|
| 450 |
+
total_entries = len(entries)
|
| 451 |
+
total_images = sum(
|
| 452 |
+
1
|
| 453 |
+
for path in entries
|
| 454 |
+
if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS
|
| 455 |
+
)
|
| 456 |
+
image_count = 0
|
| 457 |
+
resized_count = 0
|
| 458 |
+
npy_count = 0
|
| 459 |
+
resized_npy_count = 0
|
| 460 |
+
resize_records: dict[str, dict[str, object]] = {}
|
| 461 |
+
resize_geometry = f"{max_image_width}x{max_image_height}>"
|
| 462 |
+
next_progress_at = time.monotonic()
|
| 463 |
+
log_staging_progress(scene.name, 0, total_entries, 0, total_images, 0)
|
| 464 |
+
|
| 465 |
+
for processed_entries, source in enumerate(entries, start=1):
|
| 466 |
+
relative = source.relative_to(scene)
|
| 467 |
+
dest = staged_scene / relative
|
| 468 |
+
|
| 469 |
+
if source.is_dir():
|
| 470 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 471 |
+
elif source.is_symlink():
|
| 472 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 473 |
+
os.symlink(os.readlink(source), dest)
|
| 474 |
+
elif not source.is_file():
|
| 475 |
+
pass
|
| 476 |
+
elif source.suffix.lower() == ".npy" and path_modality(source) == "instance":
|
| 477 |
+
npy_count += 1
|
| 478 |
+
array_shape = npy_shape(source)
|
| 479 |
+
if not array_shape or len(array_shape) < 2:
|
| 480 |
+
hardlink_or_copy(source, dest)
|
| 481 |
+
else:
|
| 482 |
+
height, width = array_shape[:2]
|
| 483 |
+
new_width, new_height = scaled_size(width, height, max_image_width, max_image_height)
|
| 484 |
+
if width <= max_image_width and height <= max_image_height:
|
| 485 |
+
hardlink_or_copy(source, dest)
|
| 486 |
+
else:
|
| 487 |
+
resize_npy_nearest(source, dest, new_width, new_height)
|
| 488 |
+
resized_npy_count += 1
|
| 489 |
+
resize_records[str(relative)] = {
|
| 490 |
+
"modality": "instance",
|
| 491 |
+
"original_size": [width, height],
|
| 492 |
+
"resized_size": [new_width, new_height],
|
| 493 |
+
"interpolation": "nearest",
|
| 494 |
+
}
|
| 495 |
+
elif source.suffix.lower() not in IMAGE_EXTENSIONS:
|
| 496 |
+
hardlink_or_copy(source, dest)
|
| 497 |
+
else:
|
| 498 |
+
image_count += 1
|
| 499 |
+
dimensions = image_dimensions(source)
|
| 500 |
+
if dimensions is None:
|
| 501 |
+
hardlink_or_copy(source, dest)
|
| 502 |
+
else:
|
| 503 |
+
width, height = dimensions
|
| 504 |
+
new_width, new_height = scaled_size(width, height, max_image_width, max_image_height)
|
| 505 |
+
if width <= max_image_width and height <= max_image_height:
|
| 506 |
+
hardlink_or_copy(source, dest)
|
| 507 |
+
else:
|
| 508 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 509 |
+
filter_name = image_filter_for(source)
|
| 510 |
+
resize_image(source, dest, resize_geometry, filter_name)
|
| 511 |
+
resized_count += 1
|
| 512 |
+
resize_records[str(relative)] = {
|
| 513 |
+
"modality": path_modality(source) or "image",
|
| 514 |
+
"original_size": [width, height],
|
| 515 |
+
"resized_size": [new_width, new_height],
|
| 516 |
+
"interpolation": filter_name,
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
now = time.monotonic()
|
| 520 |
+
if processed_entries == total_entries or now >= next_progress_at:
|
| 521 |
+
log_staging_progress(
|
| 522 |
+
scene.name,
|
| 523 |
+
processed_entries,
|
| 524 |
+
total_entries,
|
| 525 |
+
image_count,
|
| 526 |
+
total_images,
|
| 527 |
+
resized_count,
|
| 528 |
+
)
|
| 529 |
+
next_progress_at = now + max(1, progress_interval)
|
| 530 |
+
|
| 531 |
+
metadata = {
|
| 532 |
+
"created_at": datetime.now().isoformat(timespec="seconds"),
|
| 533 |
+
"max_size": [max_image_width, max_image_height],
|
| 534 |
+
"notes": [
|
| 535 |
+
"RGB/image PNG files use Lanczos interpolation.",
|
| 536 |
+
"Depth and optical-flow PNG encodings use linear Triangle interpolation.",
|
| 537 |
+
"Instance .npy label maps use nearest-neighbor resizing to preserve IDs.",
|
| 538 |
+
"Flow PNG values in this dataset are normalized encodings; pixel scaling is applied at decode time using the resized width and height.",
|
| 539 |
+
"Camera JSON files in this dataset contain pose only. If downstream code uses intrinsics, scale fx/cx by resized_width/original_width and fy/cy by resized_height/original_height.",
|
| 540 |
+
],
|
| 541 |
+
"counts": {
|
| 542 |
+
"images": image_count,
|
| 543 |
+
"resized_images": resized_count,
|
| 544 |
+
"instance_arrays": npy_count,
|
| 545 |
+
"resized_instance_arrays": resized_npy_count,
|
| 546 |
+
},
|
| 547 |
+
"files": resize_records,
|
| 548 |
+
}
|
| 549 |
+
(staged_scene / "_resize_metadata.json").write_text(json.dumps(metadata, indent=2) + "\n")
|
| 550 |
+
return staged_scene, image_count, resized_count
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def configure_huggingface_cache(root: Path) -> None:
|
| 554 |
+
cache_root = root / ".cache" / "huggingface"
|
| 555 |
+
tmp_root = root / ".cache" / "tmp"
|
| 556 |
+
xet_cache = cache_root / "xet"
|
| 557 |
+
for path in (cache_root, tmp_root, xet_cache):
|
| 558 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 559 |
+
|
| 560 |
+
os.environ.setdefault("HF_HOME", str(cache_root))
|
| 561 |
+
os.environ.setdefault("HF_XET_CACHE", str(xet_cache))
|
| 562 |
+
os.environ.setdefault("TMPDIR", str(tmp_root))
|
| 563 |
+
os.environ.setdefault("TEMP", str(tmp_root))
|
| 564 |
+
os.environ.setdefault("TMP", str(tmp_root))
|
| 565 |
+
os.environ.setdefault("HF_XET_HIGH_PERFORMANCE", "1")
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def log_disk_space(path: Path) -> None:
|
| 569 |
+
usage = shutil.disk_usage(path)
|
| 570 |
+
log(
|
| 571 |
+
f"Disk space for {path}: {human_bytes(usage.free)} free "
|
| 572 |
+
f"of {human_bytes(usage.total)} total"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def build_archive(
|
| 577 |
+
root: Path,
|
| 578 |
+
scene: Path,
|
| 579 |
+
archive_dir: Path,
|
| 580 |
+
zstd_level: int,
|
| 581 |
+
max_image_width: int,
|
| 582 |
+
max_image_height: int,
|
| 583 |
+
staging_progress_every: int,
|
| 584 |
+
) -> Path:
|
| 585 |
+
archive_dir.mkdir(parents=True, exist_ok=True)
|
| 586 |
+
archive = archive_dir / f"{scene.name}.tar.zst"
|
| 587 |
+
complete_marker = archive_dir / f"{scene.name}.tar.zst.done"
|
| 588 |
+
tmp_archive = archive_dir / f"{scene.name}.tar.zst.tmp"
|
| 589 |
+
|
| 590 |
+
if archive.exists() and archive_marker_matches(complete_marker, max_image_width, max_image_height):
|
| 591 |
+
log(f"Archive already exists, skipping pack: {archive}")
|
| 592 |
+
return archive
|
| 593 |
+
|
| 594 |
+
tmp_archive.unlink(missing_ok=True)
|
| 595 |
+
complete_marker.unlink(missing_ok=True)
|
| 596 |
+
|
| 597 |
+
staging_root = archive_dir / ".staging" / scene.name
|
| 598 |
+
try:
|
| 599 |
+
log(
|
| 600 |
+
f"Staging scene with image resize limit {max_image_width}x{max_image_height}: "
|
| 601 |
+
f"{scene.name}"
|
| 602 |
+
)
|
| 603 |
+
staged_scene, image_count, resized_count = stage_scene_for_archive(
|
| 604 |
+
scene,
|
| 605 |
+
staging_root,
|
| 606 |
+
max_image_width,
|
| 607 |
+
max_image_height,
|
| 608 |
+
staging_progress_every,
|
| 609 |
+
)
|
| 610 |
+
log(
|
| 611 |
+
f"Image staging complete for {scene.name}: "
|
| 612 |
+
f"{resized_count}/{image_count} images resized"
|
| 613 |
+
)
|
| 614 |
+
log(f"Packing scene: {scene.name}")
|
| 615 |
+
run_checked(
|
| 616 |
+
[
|
| 617 |
+
"tar",
|
| 618 |
+
"-I",
|
| 619 |
+
f"zstd -T0 -{zstd_level}",
|
| 620 |
+
"-cf",
|
| 621 |
+
str(tmp_archive),
|
| 622 |
+
scene.name,
|
| 623 |
+
],
|
| 624 |
+
cwd=staged_scene.parent,
|
| 625 |
+
)
|
| 626 |
+
tmp_archive.rename(archive)
|
| 627 |
+
finally:
|
| 628 |
+
shutil.rmtree(staging_root, ignore_errors=True)
|
| 629 |
+
|
| 630 |
+
complete_marker.write_text(
|
| 631 |
+
json.dumps(archive_marker_payload(max_image_width, max_image_height), indent=2) + "\n"
|
| 632 |
+
)
|
| 633 |
+
log(f"Packed archive: {archive}")
|
| 634 |
+
return archive
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def upload_with_retry(
|
| 638 |
+
api,
|
| 639 |
+
description: str,
|
| 640 |
+
rate_limit_sleep: int,
|
| 641 |
+
func,
|
| 642 |
+
*args,
|
| 643 |
+
**kwargs,
|
| 644 |
+
) -> object:
|
| 645 |
+
attempt = 1
|
| 646 |
+
while True:
|
| 647 |
+
try:
|
| 648 |
+
log(f"{description} (attempt {attempt})")
|
| 649 |
+
return func(*args, **kwargs)
|
| 650 |
+
except (Exception, ssl.SSLError) as exc:
|
| 651 |
+
delay = retry_delay_seconds(str(exc), rate_limit_sleep)
|
| 652 |
+
if delay is None:
|
| 653 |
+
log(f"ERROR: {description} failed: {exc}")
|
| 654 |
+
raise
|
| 655 |
+
log(f"Retryable error during: {description}: {exc}. Sleeping {delay} seconds.")
|
| 656 |
+
time.sleep(delay)
|
| 657 |
+
attempt += 1
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def upload_archive_with_retry(
|
| 661 |
+
token: str,
|
| 662 |
+
archive: Path,
|
| 663 |
+
repo_id: str,
|
| 664 |
+
rate_limit_sleep: int,
|
| 665 |
+
overall_prefix: str,
|
| 666 |
+
) -> None:
|
| 667 |
+
from huggingface_hub import HfApi
|
| 668 |
+
|
| 669 |
+
path_in_repo = f"archives/{archive.name}"
|
| 670 |
+
description = f"Uploading {archive.name} to {repo_id}/{path_in_repo}"
|
| 671 |
+
total_bytes = archive.stat().st_size
|
| 672 |
+
attempt = 1
|
| 673 |
+
while True:
|
| 674 |
+
try:
|
| 675 |
+
api = HfApi(token=token)
|
| 676 |
+
log(f"{description} (attempt {attempt})")
|
| 677 |
+
log(
|
| 678 |
+
f"Starting Hugging Face upload progress for {overall_prefix}{archive.name} "
|
| 679 |
+
f"({human_bytes(total_bytes)})"
|
| 680 |
+
)
|
| 681 |
+
api.upload_file(
|
| 682 |
+
path_or_fileobj=archive,
|
| 683 |
+
path_in_repo=path_in_repo,
|
| 684 |
+
repo_id=repo_id,
|
| 685 |
+
repo_type="dataset",
|
| 686 |
+
commit_message=f"Add {archive.name}",
|
| 687 |
+
)
|
| 688 |
+
break
|
| 689 |
+
except (Exception, ssl.SSLError) as exc:
|
| 690 |
+
delay = retry_delay_seconds(str(exc), rate_limit_sleep)
|
| 691 |
+
if delay is None:
|
| 692 |
+
log(f"ERROR: {description} failed: {exc}")
|
| 693 |
+
raise
|
| 694 |
+
log(f"Retryable error during: {description}: {exc}. Sleeping {delay} seconds.")
|
| 695 |
+
time.sleep(delay)
|
| 696 |
+
attempt += 1
|
| 697 |
+
log(f"Uploaded: {archive.name}")
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def remote_file_exists_with_retry(
|
| 701 |
+
api,
|
| 702 |
+
repo_id: str,
|
| 703 |
+
path_in_repo: str,
|
| 704 |
+
rate_limit_sleep: int,
|
| 705 |
+
) -> bool:
|
| 706 |
+
return bool(
|
| 707 |
+
upload_with_retry(
|
| 708 |
+
api,
|
| 709 |
+
f"Checking remote file: {path_in_repo}",
|
| 710 |
+
rate_limit_sleep,
|
| 711 |
+
api.file_exists,
|
| 712 |
+
repo_id=repo_id,
|
| 713 |
+
filename=path_in_repo,
|
| 714 |
+
repo_type="dataset",
|
| 715 |
+
)
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def already_uploaded(
|
| 720 |
+
api,
|
| 721 |
+
repo_id: str,
|
| 722 |
+
path_in_repo: str,
|
| 723 |
+
marker: Path,
|
| 724 |
+
rate_limit_sleep: int,
|
| 725 |
+
) -> bool:
|
| 726 |
+
exists = remote_file_exists_with_retry(api, repo_id, path_in_repo, rate_limit_sleep)
|
| 727 |
+
if exists:
|
| 728 |
+
if not marker.exists():
|
| 729 |
+
marker.write_text(datetime.now().isoformat(timespec="seconds") + "\n")
|
| 730 |
+
return True
|
| 731 |
+
if marker.exists():
|
| 732 |
+
log(f"Local uploaded marker is stale, removing: {marker}")
|
| 733 |
+
marker.unlink()
|
| 734 |
+
return False
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def write_manifest(root: Path, scenes: list[Path], archive_dir: Path) -> Path:
|
| 738 |
+
manifest = {
|
| 739 |
+
"created_at": datetime.now().isoformat(timespec="seconds"),
|
| 740 |
+
"format": "One tar.zst archive per scene under archives/",
|
| 741 |
+
"scenes": [scene.name for scene in scenes],
|
| 742 |
+
}
|
| 743 |
+
path = archive_dir / "archive_manifest.json"
|
| 744 |
+
archive_dir.mkdir(parents=True, exist_ok=True)
|
| 745 |
+
path.write_text(json.dumps(manifest, indent=2) + "\n")
|
| 746 |
+
return path
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def process_scene(
|
| 750 |
+
token: str,
|
| 751 |
+
root: Path,
|
| 752 |
+
scene: Path,
|
| 753 |
+
scene_index: int,
|
| 754 |
+
total_scenes: int,
|
| 755 |
+
archive_dir: Path,
|
| 756 |
+
repo_id: str,
|
| 757 |
+
rate_limit_sleep: int,
|
| 758 |
+
zstd_level: int,
|
| 759 |
+
max_image_width: int,
|
| 760 |
+
max_image_height: int,
|
| 761 |
+
staging_progress_every: int,
|
| 762 |
+
delete_after_upload: bool,
|
| 763 |
+
uploaded_dir: Path,
|
| 764 |
+
) -> str:
|
| 765 |
+
from huggingface_hub import HfApi
|
| 766 |
+
|
| 767 |
+
api = HfApi(token=token)
|
| 768 |
+
overall_prefix = f"scene {scene_index}/{total_scenes} "
|
| 769 |
+
uploaded_marker = uploaded_dir / f"{scene.name}.uploaded"
|
| 770 |
+
path_in_repo = f"archives/{scene.name}.tar.zst"
|
| 771 |
+
if already_uploaded(
|
| 772 |
+
api,
|
| 773 |
+
repo_id,
|
| 774 |
+
path_in_repo,
|
| 775 |
+
uploaded_marker,
|
| 776 |
+
rate_limit_sleep,
|
| 777 |
+
):
|
| 778 |
+
log(f"Scene {scene_index}/{total_scenes} already exists on remote, skipping: {scene.name}")
|
| 779 |
+
return scene.name
|
| 780 |
+
|
| 781 |
+
archive = build_archive(
|
| 782 |
+
root,
|
| 783 |
+
scene,
|
| 784 |
+
archive_dir,
|
| 785 |
+
zstd_level,
|
| 786 |
+
max_image_width,
|
| 787 |
+
max_image_height,
|
| 788 |
+
staging_progress_every,
|
| 789 |
+
)
|
| 790 |
+
upload_archive_with_retry(
|
| 791 |
+
token,
|
| 792 |
+
archive,
|
| 793 |
+
repo_id,
|
| 794 |
+
rate_limit_sleep,
|
| 795 |
+
overall_prefix,
|
| 796 |
+
)
|
| 797 |
+
uploaded_marker.write_text(
|
| 798 |
+
json.dumps(archive_marker_payload(max_image_width, max_image_height), indent=2) + "\n"
|
| 799 |
+
)
|
| 800 |
+
if delete_after_upload:
|
| 801 |
+
log(f"Deleting uploaded archive to save disk: {archive}")
|
| 802 |
+
archive.unlink(missing_ok=True)
|
| 803 |
+
archive.with_suffix(archive.suffix + ".done").unlink(missing_ok=True)
|
| 804 |
+
return scene.name
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def main() -> int:
|
| 808 |
+
args = parse_args()
|
| 809 |
+
token = os.environ.get("HF_TOKEN")
|
| 810 |
+
if not token:
|
| 811 |
+
log("ERROR: HF_TOKEN is not set.")
|
| 812 |
+
log("Run: export HF_TOKEN=hf_xxx")
|
| 813 |
+
return 1
|
| 814 |
+
|
| 815 |
+
if not shutil.which("tar") or not shutil.which("zstd"):
|
| 816 |
+
log("ERROR: both tar and zstd must be installed.")
|
| 817 |
+
return 1
|
| 818 |
+
if not shutil.which("identify") or not shutil.which("convert"):
|
| 819 |
+
log("ERROR: ImageMagick identify and convert must be installed for image downsampling.")
|
| 820 |
+
return 1
|
| 821 |
+
if args.workers < 1:
|
| 822 |
+
log("ERROR: --workers must be at least 1.")
|
| 823 |
+
return 1
|
| 824 |
+
if args.max_image_width < 1 or args.max_image_height < 1:
|
| 825 |
+
log("ERROR: --max-image-width and --max-image-height must be at least 1.")
|
| 826 |
+
return 1
|
| 827 |
+
if args.staging_progress_every < 1:
|
| 828 |
+
log("ERROR: --staging-progress-every must be at least 1.")
|
| 829 |
+
return 1
|
| 830 |
+
if not check_numpy_python():
|
| 831 |
+
return 1
|
| 832 |
+
|
| 833 |
+
root = Path(__file__).resolve().parent
|
| 834 |
+
configure_huggingface_cache(root)
|
| 835 |
+
|
| 836 |
+
from huggingface_hub import HfApi
|
| 837 |
+
|
| 838 |
+
archive_dir = root / args.archive_dir
|
| 839 |
+
scenes = scene_dirs(root, args.only)
|
| 840 |
+
if not scenes:
|
| 841 |
+
log("ERROR: no scene directories found.")
|
| 842 |
+
return 1
|
| 843 |
+
|
| 844 |
+
log(f"Dataset root: {root}")
|
| 845 |
+
log(f"Target repo: {args.repo_id}")
|
| 846 |
+
log(f"Scenes to process: {len(scenes)}")
|
| 847 |
+
log(f"Archive directory: {archive_dir}")
|
| 848 |
+
log(f"Delete archive after upload: {args.delete_after_upload}")
|
| 849 |
+
log(f"Scene workers: {args.workers}")
|
| 850 |
+
log(f"Upload image resize limit: {args.max_image_width}x{args.max_image_height}")
|
| 851 |
+
log(f"Staging progress interval: {args.staging_progress_every} seconds")
|
| 852 |
+
log(f"NumPy resize Python: {numpy_python()}")
|
| 853 |
+
log(f"HF_HOME: {os.environ['HF_HOME']}")
|
| 854 |
+
log(f"HF_XET_CACHE: {os.environ['HF_XET_CACHE']}")
|
| 855 |
+
log(f"TMPDIR: {os.environ['TMPDIR']}")
|
| 856 |
+
log_disk_space(Path(os.environ["HF_XET_CACHE"]))
|
| 857 |
+
log_disk_space(archive_dir)
|
| 858 |
+
describe_proxy_environment()
|
| 859 |
+
|
| 860 |
+
uploaded_dir = archive_dir / ".uploaded"
|
| 861 |
+
uploaded_dir.mkdir(parents=True, exist_ok=True)
|
| 862 |
+
|
| 863 |
+
api = HfApi(token=token)
|
| 864 |
+
upload_with_retry(
|
| 865 |
+
api,
|
| 866 |
+
f"Ensuring repo exists: {args.repo_id}",
|
| 867 |
+
args.rate_limit_sleep,
|
| 868 |
+
api.create_repo,
|
| 869 |
+
repo_id=args.repo_id,
|
| 870 |
+
repo_type="dataset",
|
| 871 |
+
private=args.private,
|
| 872 |
+
exist_ok=True,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
manifest = write_manifest(root, scenes, archive_dir)
|
| 876 |
+
manifest_marker = uploaded_dir / "archive_manifest.uploaded"
|
| 877 |
+
if already_uploaded(api, args.repo_id, "archive_manifest.json", manifest_marker, args.rate_limit_sleep):
|
| 878 |
+
log("Archive manifest already exists on remote, skipping.")
|
| 879 |
+
else:
|
| 880 |
+
upload_with_retry(
|
| 881 |
+
api,
|
| 882 |
+
"Uploading archive manifest",
|
| 883 |
+
args.rate_limit_sleep,
|
| 884 |
+
api.upload_file,
|
| 885 |
+
path_or_fileobj=manifest,
|
| 886 |
+
path_in_repo="archive_manifest.json",
|
| 887 |
+
repo_id=args.repo_id,
|
| 888 |
+
repo_type="dataset",
|
| 889 |
+
commit_message="Add archive manifest",
|
| 890 |
+
)
|
| 891 |
+
manifest_marker.write_text(datetime.now().isoformat(timespec="seconds") + "\n")
|
| 892 |
+
|
| 893 |
+
readme = root / "README.md"
|
| 894 |
+
readme_marker = uploaded_dir / "README.uploaded"
|
| 895 |
+
if readme.exists() and already_uploaded(api, args.repo_id, "README.md", readme_marker, args.rate_limit_sleep):
|
| 896 |
+
log("README already exists on remote, skipping.")
|
| 897 |
+
elif readme.exists():
|
| 898 |
+
upload_with_retry(
|
| 899 |
+
api,
|
| 900 |
+
"Uploading README",
|
| 901 |
+
args.rate_limit_sleep,
|
| 902 |
+
api.upload_file,
|
| 903 |
+
path_or_fileobj=readme,
|
| 904 |
+
path_in_repo="README.md",
|
| 905 |
+
repo_id=args.repo_id,
|
| 906 |
+
repo_type="dataset",
|
| 907 |
+
commit_message="Add dataset card",
|
| 908 |
+
)
|
| 909 |
+
readme_marker.write_text(datetime.now().isoformat(timespec="seconds") + "\n")
|
| 910 |
+
|
| 911 |
+
if args.workers == 1:
|
| 912 |
+
for scene_index, scene in enumerate(scenes, start=1):
|
| 913 |
+
process_scene(
|
| 914 |
+
token,
|
| 915 |
+
root,
|
| 916 |
+
scene,
|
| 917 |
+
scene_index,
|
| 918 |
+
len(scenes),
|
| 919 |
+
archive_dir,
|
| 920 |
+
args.repo_id,
|
| 921 |
+
args.rate_limit_sleep,
|
| 922 |
+
args.zstd_level,
|
| 923 |
+
args.max_image_width,
|
| 924 |
+
args.max_image_height,
|
| 925 |
+
args.staging_progress_every,
|
| 926 |
+
args.delete_after_upload,
|
| 927 |
+
uploaded_dir,
|
| 928 |
+
)
|
| 929 |
+
else:
|
| 930 |
+
log(
|
| 931 |
+
"Parallel mode enabled. Disk usage can grow by roughly "
|
| 932 |
+
f"{args.workers} archives while uploads are in flight."
|
| 933 |
+
)
|
| 934 |
+
with ThreadPoolExecutor(max_workers=args.workers) as executor:
|
| 935 |
+
futures = [
|
| 936 |
+
executor.submit(
|
| 937 |
+
process_scene,
|
| 938 |
+
token,
|
| 939 |
+
root,
|
| 940 |
+
scene,
|
| 941 |
+
scene_index,
|
| 942 |
+
len(scenes),
|
| 943 |
+
archive_dir,
|
| 944 |
+
args.repo_id,
|
| 945 |
+
args.rate_limit_sleep,
|
| 946 |
+
args.zstd_level,
|
| 947 |
+
args.max_image_width,
|
| 948 |
+
args.max_image_height,
|
| 949 |
+
args.staging_progress_every,
|
| 950 |
+
args.delete_after_upload,
|
| 951 |
+
uploaded_dir,
|
| 952 |
+
)
|
| 953 |
+
for scene_index, scene in enumerate(scenes, start=1)
|
| 954 |
+
]
|
| 955 |
+
for future in as_completed(futures):
|
| 956 |
+
scene_name = future.result()
|
| 957 |
+
log(f"Scene finished: {scene_name}")
|
| 958 |
+
|
| 959 |
+
log("All selected scenes were packed and uploaded.")
|
| 960 |
+
return 0
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
if __name__ == "__main__":
|
| 964 |
+
sys.exit(main())
|