animal-wildlife / extract.py
lucabaggi's picture
feat: add extraction script
59e608f verified
raw
history blame
4.44 kB
import os
import random
from pathlib import Path
import shutil
import zipfile
import argparse
import tempfile
def reorganize_dataset(
zip_file: str,
*,
destination_dir: str = "./data",
split_ratio: float = 0.8,
random_seed: int = 42,
remove_zip: bool = False,
) -> None:
"""Reorganize dataset into train and test directories.
Args:
zip_file (str): Path to the zip file.
dest_dir (str, optional): Path to the destination directory. Defaults to './data'.
train_ratio (float, optional): Ratio of data to be used for training. Defaults to 0.7.
random_seed (int, optional): Random seed for reproducibility. Defaults to 42.
remove_zip (bool, optional): Whether to remove the zip file after extraction. Defaults to False.
Raises:
ValueError: If the source directory or destination directory does not exist.
ValueError: If the destination directory is not empty.
"""
# Convert the destination directory to a Path object
dest_dir = Path(destination_dir)
# Check if the source directory exists
if not Path(zip_file).is_file():
raise ValueError(f"Source directory '{zip_file}' does not exist.")
# Check if the destination directory is empty
if dest_dir.exists() and any(dest_dir.iterdir()):
raise ValueError(f"Destination directory '{dest_dir}' is not empty.")
# Set the random seed for reproducibility
random.seed(random_seed)
# Create train and test directories in the destination directory
train_dir = dest_dir / "train"
test_dir = dest_dir / "test"
train_dir.mkdir(parents=True, exist_ok=True)
test_dir.mkdir(parents=True, exist_ok=True)
# Extract the zip file to a temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
with zipfile.ZipFile(zip_file, "r") as zip_ref:
zip_ref.extractall(temp_dir)
# Navigate to the animals directory inside the extracted files
root_dir = Path(temp_dir) / "animals" / "animals"
# Iterate through each animal directory
for animal_path in root_dir.iterdir():
if animal_path.is_dir() and animal_path.name not in ["train", "test"]:
# Create corresponding directories in train and test
(train_dir / animal_path.name).mkdir(parents=True, exist_ok=True)
(test_dir / animal_path.name).mkdir(parents=True, exist_ok=True)
# Get all files in the animal directory
files = [file for file in animal_path.iterdir() if file.is_file()]
random.shuffle(files)
# Split files into train and test sets
split_index = int(len(files) * split_ratio)
train_files = files[:split_index]
test_files = files[split_index:]
# Move files to train directory
for file in train_files:
dst = train_dir / animal_path.name / file.name
shutil.move(str(file), str(dst))
# Move files to test directory
for file in test_files:
dst = test_dir / animal_path.name / file.name
shutil.move(str(file), str(dst))
# Remove the zip file if the flag is set to True
if remove_zip:
os.remove(zip_file)
print(f"Dataset reorganization complete! (Seed: {random_seed})")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Reorganize dataset.")
parser.add_argument("zip_file", type=str, help="Path to the zip file.")
parser.add_argument(
"--destination-dir",
type=str,
default="./data",
help="Path to the destination directory.",
)
parser.add_argument(
"--split-ratio",
type=float,
default=0.8,
help="Ratio of data to be used for training.",
)
parser.add_argument(
"--random-seed", type=int, default=42, help="Random seed for reproducibility."
)
parser.add_argument(
"--remove-zip",
action="store_true",
help="Whether to remove the source zip archive file after extraction.",
)
args = parser.parse_args()
reorganize_dataset(
args.zip_file,
destination_dir=args.destination_dir,
split_ratio=args.split_ratio,
random_seed=args.random_seed,
remove_zip=args.remove_zip,
)