PromptDepth / tools /pack_and_upload_scenes.py
Yukki1011's picture
Add small-scene-first upload script
37a972a verified
Raw
History Blame Contribute Delete
31.3 kB
#!/usr/bin/env python3
import argparse
import ast
import json
import os
import re
import shutil
import ssl
import struct
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
EXCLUDED_DIRS = {
".agents",
".cache",
".codex",
".git",
".vscode",
"__pycache__",
"_hf_scene_archives",
"alignment_test_outputs",
"outputs",
}
IMAGE_EXTENSIONS = {
".bmp",
".gif",
".jpeg",
".jpg",
".png",
".tif",
".tiff",
".webp",
}
PNG_MODALITY_FILTERS = {
"image": "Lanczos",
"depth": "Triangle",
"flow": "Triangle",
"flow_scaled": "Triangle",
}
DEFAULT_NUMPY_PYTHON = Path("/home/wangxy/miniconda3/envs/promptdepth/bin/python")
def log(message: str) -> None:
now = datetime.now().isoformat(timespec="seconds")
print(f"[{now}] {message}", flush=True)
def human_bytes(size: float) -> str:
units = ("B", "KiB", "MiB", "GiB", "TiB")
value = float(size)
for unit in units:
if abs(value) < 1024.0 or unit == units[-1]:
if unit == "B":
return f"{value:.0f} {unit}"
return f"{value:.1f} {unit}"
value /= 1024.0
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Pack each scene as a tar.zst archive and upload archives to Hugging Face."
)
parser.add_argument("repo_id", help="Dataset repo id, for example Yukki1011/PromptDepth")
parser.add_argument("--private", action="store_true", help="Create repo as private if needed")
parser.add_argument(
"--archive-dir",
default="_hf_scene_archives",
help="Temporary directory for scene archives",
)
parser.add_argument(
"--delete-after-upload",
action="store_true",
help="Delete each scene archive after it is uploaded successfully",
)
parser.add_argument(
"--zstd-level",
type=int,
default=1,
help="zstd compression level. 1 is fastest and usually best for PNG-heavy data",
)
parser.add_argument(
"--rate-limit-sleep",
type=int,
default=5,
help="Seconds to sleep before retrying after a rate limit",
)
parser.add_argument(
"--only",
nargs="*",
default=None,
help="Optional scene names to process. Default: all scenes",
)
parser.add_argument(
"--workers",
type=int,
default=1,
help="Number of scenes to pack/upload in parallel. Use 1 for sequential processing",
)
parser.add_argument(
"--max-image-width",
type=int,
default=1280,
help="Resize uploaded image files to fit within this width. Default keeps 720p width",
)
parser.add_argument(
"--max-image-height",
type=int,
default=720,
help="Resize uploaded image files to fit within this height. Default keeps 720p height",
)
parser.add_argument(
"--staging-progress-every",
type=int,
default=10,
help="Seconds between staging progress log updates",
)
parser.add_argument(
"--progress-every",
type=int,
default=30,
help="Deprecated. Hugging Face/Xet progress output is used when available.",
)
return parser.parse_args()
def retry_delay_seconds(message: str, default_hourly_sleep: int) -> int | None:
lower = message.lower()
if "repository commits" in lower and "rate limit" in lower:
return default_hourly_sleep
if "too many requests" in lower or "429" in lower:
return default_hourly_sleep
retry_after = re.search(r"retry after\s+(\d+)\s+seconds", lower)
if retry_after:
return default_hourly_sleep
transient_network_markers = (
"broken pipe",
"connection error",
"unexpected_eof_while_reading",
"unexpected eof",
"connection reset",
"connection aborted",
"connecterror",
"connectionerror",
"connection timed out",
"connection timeout",
"connect timeout",
"http error",
"httperror",
"incomplete read",
"incompleteread",
"max retries exceeded",
"network is unreachable",
"no route to host",
"operation timed out",
"protocolerror",
"readtimeout",
"read timed out",
"request timeout",
"request timed out",
"temporarily unavailable",
"remote disconnected",
"remote end closed connection",
"protocol violation",
"tlsv1 alert",
"client has been closed",
"connection refused",
"name resolution",
"temporary failure in name resolution",
)
if any(marker in lower for marker in transient_network_markers):
return max(10, default_hourly_sleep)
return None
def describe_proxy_environment() -> None:
proxy_vars = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy")
configured = [f"{name}={os.environ[name]}" for name in proxy_vars if os.environ.get(name)]
if configured:
log("Proxy environment detected: " + ", ".join(configured))
if any("127.0.0.1:" in value or "localhost:" in value for value in configured):
log("Localhost proxy detected; make sure the proxy is running on this server, not only on your laptop.")
def scene_dirs(root: Path, only: list[str] | None) -> list[Path]:
selected = set(only or [])
scenes = []
for child in sorted(root.iterdir()):
if not child.is_dir() or child.name in EXCLUDED_DIRS:
continue
if selected and child.name not in selected:
continue
scenes.append(child)
scenes.sort(key=lambda scene: (directory_size_bytes(scene), scene.name))
return scenes
def directory_size_bytes(path: Path) -> int:
total = 0
stack = [path]
while stack:
current = stack.pop()
try:
with os.scandir(current) as entries:
for entry in entries:
try:
if entry.is_dir(follow_symlinks=False):
stack.append(Path(entry.path))
elif entry.is_file(follow_symlinks=False):
total += entry.stat(follow_symlinks=False).st_size
except OSError:
log(f"WARNING: cannot stat while sizing scene, skipping: {entry.path}")
except OSError:
log(f"WARNING: cannot scan while sizing scene, skipping: {current}")
return total
def run_checked(cmd: list[str], cwd: Path) -> None:
log("+ " + " ".join(cmd))
subprocess.run(cmd, cwd=cwd, check=True)
def archive_marker_payload(max_image_width: int, max_image_height: int) -> dict[str, object]:
return {
"created_at": datetime.now().isoformat(timespec="seconds"),
"image_downsample": {
"enabled": True,
"version": "modality-aware-v2",
"max_width": max_image_width,
"max_height": max_image_height,
},
}
def archive_marker_matches(marker: Path, max_image_width: int, max_image_height: int) -> bool:
if not marker.exists():
return False
try:
payload = json.loads(marker.read_text())
except (json.JSONDecodeError, OSError):
return False
image_downsample = payload.get("image_downsample")
if not isinstance(image_downsample, dict):
return False
return (
image_downsample.get("enabled") is True
and image_downsample.get("version") == "modality-aware-v2"
and image_downsample.get("max_width") == max_image_width
and image_downsample.get("max_height") == max_image_height
)
def image_dimensions(path: Path) -> tuple[int, int] | None:
result = subprocess.run(
["identify", "-ping", "-format", "%w %h", str(path)],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if result.returncode != 0:
log(f"WARNING: cannot identify image, keeping original: {path} ({result.stderr.strip()})")
return None
try:
width_text, height_text = result.stdout.strip().split()
return int(width_text), int(height_text)
except ValueError:
log(f"WARNING: unexpected identify output for {path}: {result.stdout.strip()!r}")
return None
def npy_shape(path: Path) -> tuple[int, ...] | None:
try:
with path.open("rb") as handle:
if handle.read(6) != b"\x93NUMPY":
return None
major, _minor = handle.read(2)
if major == 1:
header_len = struct.unpack("<H", handle.read(2))[0]
elif major in (2, 3):
header_len = struct.unpack("<I", handle.read(4))[0]
else:
return None
header = handle.read(header_len).decode("latin1")
payload = ast.literal_eval(header)
shape = payload.get("shape")
if isinstance(shape, tuple) and all(isinstance(value, int) for value in shape):
return shape
except (OSError, SyntaxError, ValueError, struct.error):
return None
return None
def numpy_python() -> str:
configured = os.environ.get("NPY_RESIZE_PYTHON")
if configured:
return configured
if DEFAULT_NUMPY_PYTHON.exists():
return str(DEFAULT_NUMPY_PYTHON)
return sys.executable
def check_numpy_python() -> bool:
result = subprocess.run(
[numpy_python(), "-c", "import numpy"],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
check=False,
)
if result.returncode == 0:
return True
log(
"ERROR: instance .npy resizing needs numpy. "
f"Tried {numpy_python()}: {result.stderr.strip()}"
)
return False
def hardlink_or_copy(source: Path, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
try:
os.link(source, dest)
except OSError:
shutil.copy2(source, dest)
def resize_image(source: Path, dest: Path, resize_geometry: str, filter_name: str) -> None:
subprocess.run(
[
"convert",
str(source),
"-filter",
filter_name,
"-resize",
resize_geometry,
str(dest),
],
check=True,
)
def path_modality(path: Path) -> str:
parts = path.parts
if len(parts) >= 2:
return parts[-2]
return ""
def image_filter_for(source: Path) -> str:
return PNG_MODALITY_FILTERS.get(path_modality(source), "Lanczos")
def npy_resize_helper_script() -> str:
return r"""
import sys
from pathlib import Path
import numpy as np
def nearest_indices(old_size: int, new_size: int) -> np.ndarray:
if old_size == new_size:
return np.arange(old_size)
scale = old_size / new_size
return np.minimum((np.arange(new_size) * scale).astype(np.int64), old_size - 1)
source = Path(sys.argv[1])
dest = Path(sys.argv[2])
new_width = int(sys.argv[3])
new_height = int(sys.argv[4])
array = np.load(source)
if array.ndim < 2:
raise ValueError(f"Expected at least 2D array, got shape {array.shape} for {source}")
old_height, old_width = array.shape[:2]
y_idx = nearest_indices(old_height, new_height)
x_idx = nearest_indices(old_width, new_width)
resized = array[y_idx][:, x_idx]
dest.parent.mkdir(parents=True, exist_ok=True)
np.save(dest, resized)
"""
def resize_npy_nearest(source: Path, dest: Path, new_width: int, new_height: int) -> None:
subprocess.run(
[
numpy_python(),
"-c",
npy_resize_helper_script(),
str(source),
str(dest),
str(new_width),
str(new_height),
],
check=True,
)
def scaled_size(width: int, height: int, max_width: int, max_height: int) -> tuple[int, int]:
scale = min(max_width / width, max_height / height, 1.0)
new_width = max(1, int(round(width * scale)))
new_height = max(1, int(round(height * scale)))
return new_width, new_height
def progress_bar(done: int, total: int, width: int = 24) -> str:
if total <= 0:
return "[" + "-" * width + "]"
filled = min(width, int(width * done / total))
return "[" + "#" * filled + "-" * (width - filled) + "]"
def log_staging_progress(
scene_name: str,
processed_entries: int,
total_entries: int,
processed_images: int,
total_images: int,
resized_count: int,
) -> None:
percent = 100.0 if total_entries <= 0 else processed_entries * 100.0 / total_entries
log(
f"Staging {scene_name}: {progress_bar(processed_entries, total_entries)} "
f"{percent:5.1f}% ({processed_entries}/{total_entries} entries), "
f"images {processed_images}/{total_images}, resized {resized_count}"
)
def stage_scene_for_archive(
scene: Path,
staging_root: Path,
max_image_width: int,
max_image_height: int,
progress_interval: int,
) -> tuple[Path, int, int]:
staged_scene = staging_root / scene.name
if staged_scene.exists():
shutil.rmtree(staged_scene)
staged_scene.mkdir(parents=True, exist_ok=True)
entries = list(scene.rglob("*"))
total_entries = len(entries)
total_images = sum(
1
for path in entries
if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS
)
image_count = 0
resized_count = 0
npy_count = 0
resized_npy_count = 0
resize_records: dict[str, dict[str, object]] = {}
resize_geometry = f"{max_image_width}x{max_image_height}>"
next_progress_at = time.monotonic()
log_staging_progress(scene.name, 0, total_entries, 0, total_images, 0)
for processed_entries, source in enumerate(entries, start=1):
relative = source.relative_to(scene)
dest = staged_scene / relative
if source.is_dir():
dest.mkdir(parents=True, exist_ok=True)
elif source.is_symlink():
dest.parent.mkdir(parents=True, exist_ok=True)
os.symlink(os.readlink(source), dest)
elif not source.is_file():
pass
elif source.suffix.lower() == ".npy" and path_modality(source) == "instance":
npy_count += 1
array_shape = npy_shape(source)
if not array_shape or len(array_shape) < 2:
hardlink_or_copy(source, dest)
else:
height, width = array_shape[:2]
new_width, new_height = scaled_size(width, height, max_image_width, max_image_height)
if width <= max_image_width and height <= max_image_height:
hardlink_or_copy(source, dest)
else:
resize_npy_nearest(source, dest, new_width, new_height)
resized_npy_count += 1
resize_records[str(relative)] = {
"modality": "instance",
"original_size": [width, height],
"resized_size": [new_width, new_height],
"interpolation": "nearest",
}
elif source.suffix.lower() not in IMAGE_EXTENSIONS:
hardlink_or_copy(source, dest)
else:
image_count += 1
dimensions = image_dimensions(source)
if dimensions is None:
hardlink_or_copy(source, dest)
else:
width, height = dimensions
new_width, new_height = scaled_size(width, height, max_image_width, max_image_height)
if width <= max_image_width and height <= max_image_height:
hardlink_or_copy(source, dest)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
filter_name = image_filter_for(source)
resize_image(source, dest, resize_geometry, filter_name)
resized_count += 1
resize_records[str(relative)] = {
"modality": path_modality(source) or "image",
"original_size": [width, height],
"resized_size": [new_width, new_height],
"interpolation": filter_name,
}
now = time.monotonic()
if processed_entries == total_entries or now >= next_progress_at:
log_staging_progress(
scene.name,
processed_entries,
total_entries,
image_count,
total_images,
resized_count,
)
next_progress_at = now + max(1, progress_interval)
metadata = {
"created_at": datetime.now().isoformat(timespec="seconds"),
"max_size": [max_image_width, max_image_height],
"notes": [
"RGB/image PNG files use Lanczos interpolation.",
"Depth and optical-flow PNG encodings use linear Triangle interpolation.",
"Instance .npy label maps use nearest-neighbor resizing to preserve IDs.",
"Flow PNG values in this dataset are normalized encodings; pixel scaling is applied at decode time using the resized width and height.",
"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.",
],
"counts": {
"images": image_count,
"resized_images": resized_count,
"instance_arrays": npy_count,
"resized_instance_arrays": resized_npy_count,
},
"files": resize_records,
}
(staged_scene / "_resize_metadata.json").write_text(json.dumps(metadata, indent=2) + "\n")
return staged_scene, image_count, resized_count
def configure_huggingface_cache(root: Path) -> None:
cache_root = root / ".cache" / "huggingface"
tmp_root = root / ".cache" / "tmp"
xet_cache = cache_root / "xet"
for path in (cache_root, tmp_root, xet_cache):
path.mkdir(parents=True, exist_ok=True)
os.environ.setdefault("HF_HOME", str(cache_root))
os.environ.setdefault("HF_XET_CACHE", str(xet_cache))
os.environ.setdefault("TMPDIR", str(tmp_root))
os.environ.setdefault("TEMP", str(tmp_root))
os.environ.setdefault("TMP", str(tmp_root))
os.environ.setdefault("HF_XET_HIGH_PERFORMANCE", "1")
def log_disk_space(path: Path) -> None:
usage = shutil.disk_usage(path)
log(
f"Disk space for {path}: {human_bytes(usage.free)} free "
f"of {human_bytes(usage.total)} total"
)
def build_archive(
root: Path,
scene: Path,
archive_dir: Path,
zstd_level: int,
max_image_width: int,
max_image_height: int,
staging_progress_every: int,
) -> Path:
archive_dir.mkdir(parents=True, exist_ok=True)
archive = archive_dir / f"{scene.name}.tar.zst"
complete_marker = archive_dir / f"{scene.name}.tar.zst.done"
tmp_archive = archive_dir / f"{scene.name}.tar.zst.tmp"
if archive.exists() and archive_marker_matches(complete_marker, max_image_width, max_image_height):
log(f"Archive already exists, skipping pack: {archive}")
return archive
tmp_archive.unlink(missing_ok=True)
complete_marker.unlink(missing_ok=True)
staging_root = archive_dir / ".staging" / scene.name
try:
log(
f"Staging scene with image resize limit {max_image_width}x{max_image_height}: "
f"{scene.name}"
)
staged_scene, image_count, resized_count = stage_scene_for_archive(
scene,
staging_root,
max_image_width,
max_image_height,
staging_progress_every,
)
log(
f"Image staging complete for {scene.name}: "
f"{resized_count}/{image_count} images resized"
)
log(f"Packing scene: {scene.name}")
run_checked(
[
"tar",
"-I",
f"zstd -T0 -{zstd_level}",
"-cf",
str(tmp_archive),
scene.name,
],
cwd=staged_scene.parent,
)
tmp_archive.rename(archive)
finally:
shutil.rmtree(staging_root, ignore_errors=True)
complete_marker.write_text(
json.dumps(archive_marker_payload(max_image_width, max_image_height), indent=2) + "\n"
)
log(f"Packed archive: {archive}")
return archive
def upload_with_retry(
api,
description: str,
rate_limit_sleep: int,
func,
*args,
**kwargs,
) -> object:
attempt = 1
while True:
try:
log(f"{description} (attempt {attempt})")
return func(*args, **kwargs)
except (Exception, ssl.SSLError) as exc:
delay = retry_delay_seconds(str(exc), rate_limit_sleep)
if delay is None:
log(f"ERROR: {description} failed: {exc}")
raise
log(f"Retryable error during: {description}: {exc}. Sleeping {delay} seconds.")
time.sleep(delay)
attempt += 1
def upload_archive_with_retry(
token: str,
archive: Path,
repo_id: str,
rate_limit_sleep: int,
overall_prefix: str,
) -> None:
from huggingface_hub import HfApi
path_in_repo = f"archives/{archive.name}"
description = f"Uploading {archive.name} to {repo_id}/{path_in_repo}"
total_bytes = archive.stat().st_size
attempt = 1
while True:
try:
api = HfApi(token=token)
log(f"{description} (attempt {attempt})")
log(
f"Starting Hugging Face upload progress for {overall_prefix}{archive.name} "
f"({human_bytes(total_bytes)})"
)
api.upload_file(
path_or_fileobj=archive,
path_in_repo=path_in_repo,
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Add {archive.name}",
)
break
except (Exception, ssl.SSLError) as exc:
delay = retry_delay_seconds(str(exc), rate_limit_sleep)
if delay is None:
log(f"ERROR: {description} failed: {exc}")
raise
log(f"Retryable error during: {description}: {exc}. Sleeping {delay} seconds.")
time.sleep(delay)
attempt += 1
log(f"Uploaded: {archive.name}")
def remote_file_exists_with_retry(
api,
repo_id: str,
path_in_repo: str,
rate_limit_sleep: int,
) -> bool:
return bool(
upload_with_retry(
api,
f"Checking remote file: {path_in_repo}",
rate_limit_sleep,
api.file_exists,
repo_id=repo_id,
filename=path_in_repo,
repo_type="dataset",
)
)
def already_uploaded(
api,
repo_id: str,
path_in_repo: str,
marker: Path,
rate_limit_sleep: int,
) -> bool:
exists = remote_file_exists_with_retry(api, repo_id, path_in_repo, rate_limit_sleep)
if exists:
if not marker.exists():
marker.write_text(datetime.now().isoformat(timespec="seconds") + "\n")
return True
if marker.exists():
log(f"Local uploaded marker is stale, removing: {marker}")
marker.unlink()
return False
def write_manifest(root: Path, scenes: list[Path], archive_dir: Path) -> Path:
manifest = {
"created_at": datetime.now().isoformat(timespec="seconds"),
"format": "One tar.zst archive per scene under archives/",
"scenes": [scene.name for scene in scenes],
}
path = archive_dir / "archive_manifest.json"
archive_dir.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(manifest, indent=2) + "\n")
return path
def process_scene(
token: str,
root: Path,
scene: Path,
scene_index: int,
total_scenes: int,
archive_dir: Path,
repo_id: str,
rate_limit_sleep: int,
zstd_level: int,
max_image_width: int,
max_image_height: int,
staging_progress_every: int,
delete_after_upload: bool,
uploaded_dir: Path,
) -> str:
from huggingface_hub import HfApi
api = HfApi(token=token)
overall_prefix = f"scene {scene_index}/{total_scenes} "
uploaded_marker = uploaded_dir / f"{scene.name}.uploaded"
path_in_repo = f"archives/{scene.name}.tar.zst"
if already_uploaded(
api,
repo_id,
path_in_repo,
uploaded_marker,
rate_limit_sleep,
):
log(f"Scene {scene_index}/{total_scenes} already exists on remote, skipping: {scene.name}")
return scene.name
archive = build_archive(
root,
scene,
archive_dir,
zstd_level,
max_image_width,
max_image_height,
staging_progress_every,
)
upload_archive_with_retry(
token,
archive,
repo_id,
rate_limit_sleep,
overall_prefix,
)
uploaded_marker.write_text(
json.dumps(archive_marker_payload(max_image_width, max_image_height), indent=2) + "\n"
)
if delete_after_upload:
log(f"Deleting uploaded archive to save disk: {archive}")
archive.unlink(missing_ok=True)
archive.with_suffix(archive.suffix + ".done").unlink(missing_ok=True)
return scene.name
def main() -> int:
args = parse_args()
token = os.environ.get("HF_TOKEN")
if not token:
log("ERROR: HF_TOKEN is not set.")
log("Run: export HF_TOKEN=hf_xxx")
return 1
if not shutil.which("tar") or not shutil.which("zstd"):
log("ERROR: both tar and zstd must be installed.")
return 1
if not shutil.which("identify") or not shutil.which("convert"):
log("ERROR: ImageMagick identify and convert must be installed for image downsampling.")
return 1
if args.workers < 1:
log("ERROR: --workers must be at least 1.")
return 1
if args.max_image_width < 1 or args.max_image_height < 1:
log("ERROR: --max-image-width and --max-image-height must be at least 1.")
return 1
if args.staging_progress_every < 1:
log("ERROR: --staging-progress-every must be at least 1.")
return 1
if not check_numpy_python():
return 1
root = Path(__file__).resolve().parent
configure_huggingface_cache(root)
from huggingface_hub import HfApi
archive_dir = root / args.archive_dir
scenes = scene_dirs(root, args.only)
if not scenes:
log("ERROR: no scene directories found.")
return 1
log(f"Dataset root: {root}")
log(f"Target repo: {args.repo_id}")
log(f"Scenes to process: {len(scenes)}")
log(f"Archive directory: {archive_dir}")
log(f"Delete archive after upload: {args.delete_after_upload}")
log(f"Scene workers: {args.workers}")
log(f"Upload image resize limit: {args.max_image_width}x{args.max_image_height}")
log(f"Staging progress interval: {args.staging_progress_every} seconds")
log(f"NumPy resize Python: {numpy_python()}")
log(f"HF_HOME: {os.environ['HF_HOME']}")
log(f"HF_XET_CACHE: {os.environ['HF_XET_CACHE']}")
log(f"TMPDIR: {os.environ['TMPDIR']}")
log_disk_space(Path(os.environ["HF_XET_CACHE"]))
log_disk_space(archive_dir)
describe_proxy_environment()
uploaded_dir = archive_dir / ".uploaded"
uploaded_dir.mkdir(parents=True, exist_ok=True)
api = HfApi(token=token)
upload_with_retry(
api,
f"Ensuring repo exists: {args.repo_id}",
args.rate_limit_sleep,
api.create_repo,
repo_id=args.repo_id,
repo_type="dataset",
private=args.private,
exist_ok=True,
)
manifest = write_manifest(root, scenes, archive_dir)
manifest_marker = uploaded_dir / "archive_manifest.uploaded"
if already_uploaded(api, args.repo_id, "archive_manifest.json", manifest_marker, args.rate_limit_sleep):
log("Archive manifest already exists on remote, skipping.")
else:
upload_with_retry(
api,
"Uploading archive manifest",
args.rate_limit_sleep,
api.upload_file,
path_or_fileobj=manifest,
path_in_repo="archive_manifest.json",
repo_id=args.repo_id,
repo_type="dataset",
commit_message="Add archive manifest",
)
manifest_marker.write_text(datetime.now().isoformat(timespec="seconds") + "\n")
readme = root / "README.md"
readme_marker = uploaded_dir / "README.uploaded"
if readme.exists() and already_uploaded(api, args.repo_id, "README.md", readme_marker, args.rate_limit_sleep):
log("README already exists on remote, skipping.")
elif readme.exists():
upload_with_retry(
api,
"Uploading README",
args.rate_limit_sleep,
api.upload_file,
path_or_fileobj=readme,
path_in_repo="README.md",
repo_id=args.repo_id,
repo_type="dataset",
commit_message="Add dataset card",
)
readme_marker.write_text(datetime.now().isoformat(timespec="seconds") + "\n")
if args.workers == 1:
for scene_index, scene in enumerate(scenes, start=1):
process_scene(
token,
root,
scene,
scene_index,
len(scenes),
archive_dir,
args.repo_id,
args.rate_limit_sleep,
args.zstd_level,
args.max_image_width,
args.max_image_height,
args.staging_progress_every,
args.delete_after_upload,
uploaded_dir,
)
else:
log(
"Parallel mode enabled. Disk usage can grow by roughly "
f"{args.workers} archives while uploads are in flight."
)
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = [
executor.submit(
process_scene,
token,
root,
scene,
scene_index,
len(scenes),
archive_dir,
args.repo_id,
args.rate_limit_sleep,
args.zstd_level,
args.max_image_width,
args.max_image_height,
args.staging_progress_every,
args.delete_after_upload,
uploaded_dir,
)
for scene_index, scene in enumerate(scenes, start=1)
]
for future in as_completed(futures):
scene_name = future.result()
log(f"Scene finished: {scene_name}")
log("All selected scenes were packed and uploaded.")
return 0
if __name__ == "__main__":
sys.exit(main())