File size: 4,437 Bytes
f145f6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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,
    )