Datasets:
File size: 2,446 Bytes
8bfc2cd 6a50045 0160c62 8bfc2cd 0160c62 6a50045 0160c62 8bfc2cd | 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 | #!/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())
|