File size: 5,733 Bytes
b11d41e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import os
from collections import defaultdict
import numpy as np
import random


def fix_seed(seed):
    random.seed(seed)
    np.random.seed(seed)

def collect_video_paths(base_path):
    """
    Traverses the base_path directory, collecting video file paths
    organized by class folder names.
    
    Args:
        base_path (str): The root directory containing class subfolders.

    Returns:
        dict: A dictionary mapping each class name to a list of video file paths.
    """
    video_dict = defaultdict(list)
    
    if not os.path.exists(base_path):
        raise FileNotFoundError(f"Directory not found: {base_path}")
    
    for class_name in os.listdir(base_path):
        class_dir = os.path.join(base_path, class_name)
        if os.path.isdir(class_dir):
            for video_file in os.listdir(class_dir):
                video_path = os.path.join(class_dir, video_file)
                video_dict[class_name].append(video_path)
    
    return video_dict


def separate_by_class(video_dict):
    """
    Reorganizes video_dict into a nested dictionary:
    {
        class_name: {
            video_key: [list of video paths]
        }
    }
    where video_key is derived from the filename (e.g., 'abc_001.mp4' → 'abc')
    """
    all_class_dict = defaultdict(lambda: defaultdict(list))

    for video_class, videos in video_dict.items():
        for v in videos:
            video_name = os.path.basename(v)

            split_video_name = video_name.split("_")
            len_split = len(split_video_name)
            video_key = "_".join(split_video_name[:min(len_split, 4) - 1])

            all_class_dict[video_class][video_key].append(v)

    sorted_class_dict = {}
    for cls in sorted(all_class_dict.keys(), key=str):
        inner_dict = all_class_dict[cls]
        sorted_inner_dict = dict(sorted(inner_dict.items(), key=lambda x: str(x[0])))
        sorted_class_dict[cls] = sorted_inner_dict


    return sorted_class_dict


def get_train_val_test(video_list_class, split_configuration=[0.9, 0.05, 0.05]):

    train_val_test_dict = defaultdict(dict)

    for video_class, video_keys in video_list_class.items():
        # Shuffle video keys
        tmp_video_key = list(video_keys)
        random.shuffle(tmp_video_key)

        n_total = len(tmp_video_key)
        n_train = round(split_configuration[0] * n_total)
        n_val = round(split_configuration[1] * n_total)

        # Make sure all samples are used, including remainder
        n_test = n_total - n_train - n_val

        # Split the shuffled list
        train = tmp_video_key[:n_train]
        val = tmp_video_key[n_train:n_train + n_val]
        test = tmp_video_key[n_train + n_val:n_train + n_val + n_test]

        train_val_test_dict[video_class] = {
            "train": train,
            "val": val,
            "test": test
        }

    return train_val_test_dict

def collect_videos(out_data, full_video_dict, train_list, val_list, test_list):
        for video_class, splits in out_data.items():
            for split_name, video_keys in splits.items():
                for video_key in video_keys:
                    video_paths = full_video_dict[video_class][video_key]
                    if split_name == "train":
                        train_list.extend(video_paths)
                    elif split_name == "val":
                        val_list.extend(video_paths)
                    elif split_name == "test":
                        test_list.extend(video_paths)
        
def write_txt(file_path, video_list):
    with open(file_path, "w") as f:
        for path in video_list:
            video_name = ".".join(os.path.basename(path).split(".")[:-1])
            f.write(f"{video_name}\n")


def _print_inspect(video_list_class):
    for video_class, values in video_list_class.items():
        print(f"### {video_class} ### with total {len(values)}")
        for video_key in values:
            print(video_key, len(values[video_key]))

if __name__ == "__main__":
    fix_seed(11293)
    nas_path = "/mnt/nas192"
    train_path = os.path.join(
        nas_path,
        "Research_materials/PIA_clip_dataset/CLIP4Clip_format/PIA_clip_outdoor_v2/original_train_set_processed"
    )
    val_test_path = os.path.join(
        nas_path,
        "Research_materials/PIA_clip_dataset/CLIP4Clip_format/PIA_clip_outdoor_v2/original_val_test_set_processed"
    )

    video_list_train = collect_video_paths(train_path)
    video_list_class_train = separate_by_class(video_list_train)
    video_list_val_test = collect_video_paths(val_test_path)
    video_list_class_val_test = separate_by_class(video_list_val_test)


    
    split_configuration = {
        "video_list_class_train": [0.94, 0.03, 0.03],
        "video_list_class_val_test": [0.9, 0.05, 0.05]
    }

    out_train = get_train_val_test(video_list_class_train, split_configuration["video_list_class_train"])
    out_val_test = get_train_val_test(video_list_class_val_test, split_configuration["video_list_class_val_test"])

    train_list = []
    val_list = []
    test_list = []

    collect_videos(out_train, video_list_class_train, train_list, val_list, test_list)
    print(f"Length Train {len(train_list)} {len(val_list)} {len(test_list)}")
    collect_videos(out_val_test, video_list_class_val_test, train_list, val_list, test_list)
    print(f"Length Train Val Test {len(train_list)} {len(val_list)} {len(test_list)}")
    
    # txt_out_dir = "./"
    # write_txt(os.path.join(txt_out_dir, "train_list.txt"), train_list)
    # write_txt(os.path.join(txt_out_dir, "val_list.txt"), val_list)
    # write_txt(os.path.join(txt_out_dir, "test_list.txt"), test_list)

    # print("Saved train.txt, val.txt, and test.txt in ./splits")