SynthesizeAIWS25 / scripts /unpack_dataset.py
tancilon's picture
update unpack_dataset.py
6a50045
#!/usr/bin/env python3
"""
Extract all tar archives under train/ and val/ directories.
"""
from __future__ import annotations
import argparse
import tarfile
from pathlib import Path
def iter_archives(root: Path) -> list[Path]:
patterns = ("*.tar", "*.tar.gz", "*.tgz")
archives: list[Path] = []
for pattern in patterns:
archives.extend(root.rglob(pattern))
return sorted(set(archives))
def extract_archive(archive: Path, dest: Path, *, dry_run: bool) -> None:
if dry_run:
print(f"[dry-run] {archive} -> {dest}")
return
with tarfile.open(archive, "r:*") as tar:
tar.extractall(path=dest)
print(f"extracted {archive} -> {dest}")
def delete_archives(archives: list[Path]) -> None:
"""Delete archives after successful extraction to save space."""
for archive in archives:
try:
archive.unlink()
print(f"deleted {archive}")
except FileNotFoundError:
continue
def remove_dot_underscore_files(root: Path) -> None:
"""Remove macOS resource fork files like ._foo."""
for path in root.rglob("._*"):
try:
path.unlink()
print(f"removed {path}")
except FileNotFoundError:
continue
def main() -> int:
parser = argparse.ArgumentParser(
description="Extract tar archives under train/ and val/ directories."
)
parser.add_argument(
"--root",
type=Path,
default=Path("."),
help="Project root containing train/ and val/ (default: current directory).",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="List archives without extracting.",
)
args = parser.parse_args()
root = args.root.resolve()
targets = [root / "train", root / "val"]
archives: list[Path] = []
for target in targets:
if target.is_dir():
archives.extend(iter_archives(target))
else:
print(f"skip missing directory: {target}")
if not archives:
print("no archives found")
return 0
for archive in archives:
extract_archive(archive, archive.parent, dry_run=args.dry_run)
if not args.dry_run:
delete_archives(archives)
for target in targets:
if target.is_dir():
remove_dot_underscore_files(target)
return 0
if __name__ == "__main__":
raise SystemExit(main())