pmchard commited on
Commit
191c3e3
·
verified ·
1 Parent(s): c85999b

Delete re-orgranise_nano.py

Browse files
Files changed (1) hide show
  1. re-orgranise_nano.py +0 -326
re-orgranise_nano.py DELETED
@@ -1,326 +0,0 @@
1
- import os
2
- import shutil
3
- import argparse
4
- import random
5
- from pathlib import Path
6
- from tqdm import tqdm
7
- import logging
8
- from collections import defaultdict
9
-
10
- def reorganize_for_supervised_learning(source_dir, target_dir, test_val_ratio=0.6,
11
- random_seed=42, dry_run=False, log_file=None):
12
- """
13
- Reorganize data from source_dir by category into train/val/test splits.
14
-
15
- Args:
16
- source_dir: Path to the source directory organized by part name
17
- target_dir: Path to the target directory to be organized by category and splits
18
- test_val_ratio: Ratio of defect parts to include in test set (vs validation)
19
- random_seed: Seed for random split reproducibility
20
- dry_run: If True, only log what would be done without actually copying files
21
- log_file: Path to log file to record actions and errors
22
- """
23
- # Set up logging
24
- if log_file:
25
- logging.basicConfig(
26
- level=logging.INFO,
27
- format='%(asctime)s - %(levelname)s - %(message)s',
28
- handlers=[
29
- logging.FileHandler(log_file),
30
- logging.StreamHandler()
31
- ]
32
- )
33
- else:
34
- logging.basicConfig(
35
- level=logging.INFO,
36
- format='%(asctime)s - %(levelname)s - %(message)s'
37
- )
38
-
39
- # Set random seed for reproducibility
40
- random.seed(random_seed)
41
-
42
- source_path = Path(source_dir)
43
- target_path = Path(target_dir)
44
-
45
- logging.info(f"{'DRY RUN: ' if dry_run else ''}Reorganizing from {source_dir} to {target_dir}")
46
- logging.info(f"Split approach: All defect-free parts to Train, defect parts split Test:{test_val_ratio:.0%}, Val:{1-test_val_ratio:.0%}")
47
-
48
- # Create target directory if it doesn't exist and not in dry run mode
49
- if not dry_run:
50
- target_path.mkdir(parents=True, exist_ok=True)
51
-
52
- # Statistics for reporting
53
- stats = {
54
- 'parts_processed': 0,
55
- 'categories_found': set(),
56
- 'defect_free_parts': 0,
57
- 'parts_with_defects': 0,
58
- 'train_set': 0,
59
- 'val_set': 0,
60
- 'test_set': 0,
61
- 'directories_to_create': 0,
62
- 'files_to_copy': 0,
63
- 'errors': 0
64
- }
65
-
66
- # Keep track of directory structure
67
- directory_structure = defaultdict(lambda: defaultdict(list))
68
-
69
- # Get all part directories
70
- part_dirs = [d for d in source_path.iterdir() if d.is_dir()]
71
-
72
- logging.info(f"Found {len(part_dirs)} part directories in {source_dir}")
73
-
74
- # First pass: categorize parts and check for defects
75
- parts_by_category = defaultdict(list)
76
- part_has_defects = {}
77
-
78
- logging.info("Pass 1: Analyzing parts and checking for defects...")
79
-
80
- for part_dir in tqdm(part_dirs, desc="Analyzing parts"):
81
- part_name = part_dir.name
82
-
83
- try:
84
- # Extract category name (first segment before underscore)
85
- category = part_name.split('_')[0]
86
- stats['categories_found'].add(category)
87
-
88
- # Check for MechMind-Nano camera directory
89
- nano_dir = part_dir / "MechMind-Nano"
90
- if not nano_dir.exists() or not nano_dir.is_dir():
91
- logging.warning(f"MechMind-Nano directory not found for part: {part_name}, skipping...")
92
- continue
93
-
94
- # Check for defects
95
- has_defects = False
96
-
97
- # Check defect_masks directory
98
- defect_masks_dir = nano_dir / "defect_masks"
99
- if defect_masks_dir.exists() and defect_masks_dir.is_dir():
100
- # Check if any mask files exist
101
- mask_files = list(defect_masks_dir.glob("*.*"))
102
- if mask_files:
103
- has_defects = True
104
-
105
- # Store part information
106
- parts_by_category[category].append(part_name)
107
- part_has_defects[part_name] = has_defects
108
-
109
- # Update stats
110
- if has_defects:
111
- stats['parts_with_defects'] += 1
112
- else:
113
- stats['defect_free_parts'] += 1
114
-
115
- except Exception as e:
116
- logging.error(f"Error analyzing part {part_name}: {str(e)}")
117
- stats['errors'] += 1
118
-
119
- # Second pass: Determine split assignment and copy files
120
- logging.info("Pass 2: Assigning parts to splits and copying data...")
121
-
122
- for category, parts in parts_by_category.items():
123
- logging.info(f"Processing category: {category} ({len(parts)} parts)")
124
-
125
- # Create category directories
126
- if not dry_run:
127
- (target_path / category / "train").mkdir(parents=True, exist_ok=True)
128
- (target_path / category / "val").mkdir(parents=True, exist_ok=True)
129
- (target_path / category / "test").mkdir(parents=True, exist_ok=True)
130
-
131
- # Separate defect-free and defect parts
132
- defect_free_parts = []
133
- defect_parts = []
134
-
135
- for part in parts:
136
- if part_has_defects[part]:
137
- defect_parts.append(part)
138
- else:
139
- defect_free_parts.append(part)
140
-
141
- logging.info(f" Category {category}: {len(defect_free_parts)} defect-free parts, "
142
- f"{len(defect_parts)} parts with defects")
143
-
144
- # Shuffle defect parts for random assignment
145
- random.shuffle(defect_parts)
146
-
147
- # Determine split counts for defect parts using the test:val ratio
148
- defect_count = len(defect_parts)
149
- test_count = max(1, int(defect_count * test_val_ratio)) if defect_count > 0 else 0
150
- val_count = defect_count - test_count
151
-
152
- # Assign defect parts to test and validation
153
- test_parts = defect_parts[:test_count]
154
- val_parts = defect_parts[test_count:]
155
-
156
- # All defect-free parts go to training
157
- train_parts = defect_free_parts
158
-
159
- logging.info(f" Split assignment - Train: {len(train_parts)} (all defect-free), "
160
- f"Test: {len(test_parts)}, Val: {len(val_parts)}")
161
-
162
- # Update stats
163
- stats['train_set'] += len(train_parts)
164
- stats['val_set'] += len(val_parts)
165
- stats['test_set'] += len(test_parts)
166
-
167
- # Update directory structure tracking
168
- for part in train_parts:
169
- directory_structure[category]['train'].append(part)
170
- for part in val_parts:
171
- directory_structure[category]['val'].append(part)
172
- for part in test_parts:
173
- directory_structure[category]['test'].append(part)
174
-
175
- # Process each part according to its split assignment
176
- for split, parts_list in [('train', train_parts), ('val', val_parts), ('test', test_parts)]:
177
- for part_name in parts_list:
178
- stats['parts_processed'] += 1
179
-
180
- # Source part directory
181
- part_dir = source_path / part_name
182
- nano_dir = part_dir / "MechMind-Nano"
183
-
184
- # Target directory
185
- target_split_dir = target_path / category / split
186
- target_part_dir = target_split_dir / part_name
187
-
188
- logging.info(f" {'Would assign' if dry_run else 'Assigning'} {part_name} to {split} split")
189
-
190
- # In dry run, just count what would be done
191
- if dry_run:
192
- # Count directories and files that would be created/copied
193
- count_directory_contents(nano_dir, stats)
194
- else:
195
- # Create part directory under category/split
196
- target_part_dir.mkdir(exist_ok=True)
197
-
198
- # Copy all contents from MechMind-Nano to the target part directory
199
- copy_directory_contents(nano_dir, target_part_dir, stats)
200
-
201
- # Print summary
202
- logging.info("\n" + "="*50)
203
- logging.info(f"{'DRY RUN SUMMARY:' if dry_run else 'REORGANIZATION COMPLETE:'}")
204
- logging.info("="*50)
205
- logging.info(f"Parts processed: {stats['parts_processed']}")
206
- logging.info(f"Categories found: {len(stats['categories_found'])}")
207
- logging.info(f"Categories: {', '.join(sorted(stats['categories_found']))}")
208
- logging.info(f"Defect-free parts (Training set): {stats['defect_free_parts']}")
209
- logging.info(f"Parts with defects (Test+Val sets): {stats['parts_with_defects']}")
210
-
211
- # Calculate overall ratios
212
- total_parts = stats['train_set'] + stats['val_set'] + stats['test_set']
213
- if total_parts > 0:
214
- train_pct = stats['train_set'] / total_parts * 100
215
- val_pct = stats['val_set'] / total_parts * 100
216
- test_pct = stats['test_set'] / total_parts * 100
217
- logging.info(f"Overall split - Train: {stats['train_set']} ({train_pct:.1f}%), "
218
- f"Val: {stats['val_set']} ({val_pct:.1f}%), "
219
- f"Test: {stats['test_set']} ({test_pct:.1f}%)")
220
-
221
- if dry_run:
222
- logging.info(f"Directories that would be created: {stats['directories_to_create']}")
223
- logging.info(f"Files that would be copied: {stats['files_to_copy']}")
224
- else:
225
- logging.info(f"Directories created: {stats['directories_to_create']}")
226
- logging.info(f"Files copied: {stats['files_to_copy']}")
227
-
228
- logging.info(f"Errors encountered: {stats['errors']}")
229
-
230
- # Log directory structure
231
- logging.info("\n" + "="*50)
232
- logging.info("DIRECTORY STRUCTURE:")
233
- logging.info("="*50)
234
-
235
- for category in sorted(directory_structure.keys()):
236
- logging.info(f"Category: {category}")
237
- for split in ['train', 'val', 'test']:
238
- parts_in_split = directory_structure[category][split]
239
- logging.info(f" {split.upper()} ({len(parts_in_split)} parts):")
240
- for part in sorted(parts_in_split)[:5]: # Show first 5 parts in each split
241
- logging.info(f" - {part}")
242
- if len(parts_in_split) > 5:
243
- logging.info(f" ... and {len(parts_in_split) - 5} more parts")
244
-
245
- if dry_run:
246
- logging.info("\nThis was a dry run. No files were actually copied.")
247
- logging.info(f"To perform the actual reorganization, run without the --dry-run option.")
248
-
249
- return stats, directory_structure
250
-
251
- def count_directory_contents(src_dir, stats):
252
- """
253
- Count directories and files in src_dir for dry run statistics.
254
-
255
- Args:
256
- src_dir: Source directory
257
- stats: Statistics dictionary to update
258
- """
259
- # Walk through all directories and files in the source
260
- for root, dirs, files in os.walk(src_dir):
261
- # Count directories
262
- stats['directories_to_create'] += len(dirs)
263
-
264
- # Count files
265
- stats['files_to_copy'] += len(files)
266
-
267
- def copy_directory_contents(src_dir, dst_dir, stats):
268
- """
269
- Copy all contents from src_dir to dst_dir, preserving the directory structure.
270
-
271
- Args:
272
- src_dir: Source directory
273
- dst_dir: Destination directory
274
- stats: Statistics dictionary to update
275
- """
276
- # Walk through all directories and files in the source
277
- for root, dirs, files in os.walk(src_dir):
278
- # Get the relative path from src_dir
279
- rel_path = os.path.relpath(root, src_dir)
280
-
281
- # Create the corresponding directory in dst_dir
282
- if rel_path != '.':
283
- target_dir = dst_dir / rel_path
284
- target_dir.mkdir(exist_ok=True)
285
- stats['directories_to_create'] += 1
286
- else:
287
- target_dir = dst_dir
288
-
289
- # Copy all files in this directory
290
- for file in files:
291
- src_file = Path(root) / file
292
- dst_file = target_dir / file
293
-
294
- # Copy the file
295
- shutil.copy2(src_file, dst_file)
296
- stats['files_to_copy'] += 1
297
-
298
- def main():
299
- parser = argparse.ArgumentParser(description='Reorganize dataset for supervised learning (MechMind-Nano only)')
300
- parser.add_argument('source_dir', help='Path to the source directory organized by part name')
301
- parser.add_argument('target_dir', help='Path to the target directory to be organized by category and splits')
302
- parser.add_argument('--test-val-ratio', type=float, default=0.6,
303
- help='Ratio of defect parts to include in test set vs validation set (default: 0.6)')
304
- parser.add_argument('--seed', type=int, default=42,
305
- help='Random seed for reproducibility (default: 42)')
306
- parser.add_argument('--dry-run', '-d', action='store_true',
307
- help='Perform a dry run without actually copying files')
308
- parser.add_argument('--log', '-l', default=None, help='Path to log file (optional)')
309
-
310
- args = parser.parse_args()
311
-
312
- # Validate ratio
313
- if args.test_val_ratio <= 0 or args.test_val_ratio >= 1:
314
- parser.error("The test_val_ratio must be between 0 and 1")
315
-
316
- reorganize_for_supervised_learning(
317
- args.source_dir,
318
- args.target_dir,
319
- args.test_val_ratio,
320
- args.seed,
321
- args.dry_run,
322
- args.log
323
- )
324
-
325
- if __name__ == "__main__":
326
- main()