File size: 5,159 Bytes
9bc98d9 | 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 | import shutil
import zipfile
from pathlib import Path
def prepare_dirs(host: str, name: str) -> tuple[Path, Path, Path]:
"""
Prepare directory structure for a dataset.
Args:
host (str): The dataset host name (e.g., 'esdac').
name (str): The dataset folder name.
Returns:
Tuple of local_processed_dir, drive_download_dir, drive_processed_dir.
"""
script_dir = Path("src") / host / name
local_processed_dir = script_dir / "processed"
if local_processed_dir.exists():
shutil.rmtree(local_processed_dir)
local_processed_dir.mkdir(parents=False, exist_ok=False)
drive_base = Path("datasets") / host / name
drive_download_dir = drive_base / "download"
drive_processed_dir = drive_base / "processed"
drive_processed_dir.mkdir(parents=False, exist_ok=True)
return local_processed_dir, drive_download_dir, drive_processed_dir
def unzip(local_processed_dir: Path, drive_download_dir: Path, zip_files: list[str] = None) -> None:
"""
Unzip specified ZIP files from drive_download_dir into subfolders of local_processed_dir.
Args:
local_processed_dir (Path): Where to extract ZIP contents.
drive_download_dir (Path): Directory containing ZIP files.
zip_files (list[str], optional): List of ZIP filenames to extract. Extracts all if None.
"""
zip_paths = (
[drive_download_dir / zf for zf in zip_files]
if zip_files is not None
else list(drive_download_dir.glob("*.zip"))
)
for zip_path in zip_paths:
target_dir = local_processed_dir / zip_path.stem
target_dir.mkdir(parents=True, exist_ok=True)
try:
with zipfile.ZipFile(zip_path, "r") as zip_ref:
for name in zip_ref.namelist():
try:
zip_ref.extract(name, path=target_dir)
except zipfile.BadZipFile:
print(f"⚠️ Skipped corrupted file in {zip_path.name}: {name}")
print(f"✅ Unzipped {zip_path.name} → {target_dir}")
except Exception as e:
print(f"❌ Failed to unzip {zip_path.name}: {e}")
def unzip_nested(directory: Path):
"""Recursively unzip all ZIP files under directory."""
for zip_path in sorted(directory.rglob("*.zip")):
target = zip_path.with_suffix("")
target.mkdir(parents=True, exist_ok=True)
try:
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(target)
print(f"✅ Unzipped nested: {zip_path.relative_to(directory)} → {target.relative_to(directory)}")
except Exception as e:
print(f"❌ Failed to unzip nested {zip_path}: {e}")
def copy_to_local(local_processed_dir: Path, drive_download_dir: Path, files: list[str]) -> None:
"""
Copy specific files from drive_download_dir to local_processed_dir.
Args:
local_processed_dir (Path): Destination directory.
drive_download_dir (Path): Source directory.
files (list[str]): List of filenames to copy.
"""
for file_name in files:
src_path = drive_download_dir / file_name
dst_path = local_processed_dir / Path(file_name).name
try:
shutil.copy2(src_path, dst_path)
print(f"✅ Copied: {file_name}")
except Exception as e:
print(f"❌ Failed to copy {file_name}: {e}")
def upload(
local_processed_dir: Path,
drive_processed_dir: Path,
move_list: list[Path] = None,
clear_remote_before_upload: bool = True,
remove_local_after_upload: bool = True
) -> None:
"""
Upload processed files from local to drive, optionally clearing remote and cleaning up local.
Args:
local_processed_dir (Path): Directory containing files to move.
drive_processed_dir (Path): Destination directory on Drive.
move_list (list[Path], optional): List of files to move. If None, moves all in local.
clear_remote_before_upload (bool): Whether to clear drive folder before uploading.
remove_local_after_upload (bool): Whether to remove local folder after upload.
"""
if move_list is None:
move_list = [p for p in local_processed_dir.rglob("*") if p.is_file()]
if clear_remote_before_upload and drive_processed_dir.exists():
shutil.rmtree(drive_processed_dir)
print(f"🗑️ Cleared drive processed dir: {drive_processed_dir}")
print(f"📤 Uploading to {drive_processed_dir}")
for src_path in move_list:
if not src_path.is_file():
continue
rel_path = src_path.relative_to(local_processed_dir)
dst_path = drive_processed_dir / rel_path
dst_path.parent.mkdir(parents=True, exist_ok=True)
if dst_path.exists():
dst_path.unlink()
shutil.move(str(src_path), str(dst_path))
print(f" ✅ Moved {rel_path}")
if remove_local_after_upload and local_processed_dir.exists():
shutil.rmtree(local_processed_dir)
print(f"🗑️ Removed local processed dir: {local_processed_dir}")
|