File size: 4,230 Bytes
2211607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import shutil
import re
from collections import defaultdict

def get_all_source_folders(scrape_dir):
    """
    Recursively scrapes a directory to get all folders.
    Returns a dictionary mapping: folder_name -> list of full_source_paths
    """
    source_folders = defaultdict(list)
    
    if not os.path.exists(scrape_dir):
        print(f"Error: Scrape directory '{scrape_dir}' does not exist.")
        return source_folders

    # Walk through the entire directory tree
    for root, dirs, files in os.walk(scrape_dir):
        for d in dirs:
            source_folders[d].append(os.path.join(root, d))
                    
    return source_folders

def get_subfolder_names(folder_path):
    """Returns a list of subfolder names immediately inside a given directory."""
    return [d for d in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, d))]

def process_folders(scrape_dir, dest_root_path):
    # 1. Scrape all folders from the source directory
    source_folders = get_all_source_folders(scrape_dir)
    if not source_folders:
        print("No source folders found.")
        return

    # 2. Find matching folders in the destination root path (Second-to-last level)
    dest_matches = defaultdict(list)
    for root, dirs, files in os.walk(dest_root_path):
        for d in dirs:
            if d in source_folders:
                dest_matches[d].append(os.path.join(root, d))

    # Pattern to extract the date and hour: YYYY-MM-DD_HH
    file_pattern = re.compile(r'^(\d{4}-\d{2}-\d{2}_\d{2})-\d{2}-\d{2}')

    # 3. Process each matched robot folder
    for folder_name, dest_paths in dest_matches.items():
        # Check for multiple destination matches to avoid conflicts
        if len(dest_paths) > 1:
            print(f"NOTICE: Found {len(dest_paths)} destination matches for '{folder_name}'. Skipping.")
            continue
            
        src_paths = source_folders[folder_name]
        # Check for multiple source matches
        if len(src_paths) > 1:
            print(f"NOTICE: Found {len(src_paths)} source matches for '{folder_name}'. Skipping.")
            continue
        
        dest_path = dest_paths[0]
        src_path = src_paths[0]

        # 4. Get the last level subfolders (e.g., 'camera') from the source
        # We NO LONGER check if these exist in the destination first.
        src_subfolders = get_subfolder_names(src_path)

        # 5. Process files INSIDE the source subfolders
        for subfolder in src_subfolders:
            src_sub_path = os.path.join(src_path, subfolder)
            dest_sub_path = os.path.join(dest_path, subfolder)

            # Ensure the camera folder exists in the destination before copying
            os.makedirs(dest_sub_path, exist_ok=True)

            # Get all files in this specific source subfolder and sort chronologically
            files = [f for f in os.listdir(src_sub_path) if os.path.isfile(os.path.join(src_sub_path, f))]
            files.sort() 
            
            selected_files = {}
            for file_name in files:
                match = file_pattern.search(file_name)
                if match:
                    hour_key = match.group(1)
                    if hour_key not in selected_files:
                        selected_files[hour_key] = file_name

            # 6. Copy the filtered files while checking for duplicates
            copied_count = 0
            for file_name in selected_files.values():
                src_file = os.path.join(src_sub_path, file_name)
                dest_file = os.path.join(dest_sub_path, file_name)
                
                # Skip if file was already copied
                if os.path.exists(dest_file):
                    continue
                    
                shutil.copy2(src_file, dest_file)
                copied_count += 1
                
            if copied_count > 0:
                print(f"Copied {copied_count} new files into '{folder_name}/{subfolder}'.")
            
    print("\nProcess completed.")

if __name__ == "__main__":
    # Define your paths here
    SCRAPE_DIRECTORY = "../Datasets/" 
    DESTINATION_ROOT = "Roots"
    
    process_folders(SCRAPE_DIRECTORY, DESTINATION_ROOT)