Nikok98v commited on
Commit
d0e87e4
·
verified ·
1 Parent(s): 62d1f65

Upload extract-embeddings.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. extract-embeddings.py +939 -0
extract-embeddings.py ADDED
@@ -0,0 +1,939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import snapshot_download
2
+ import sys
3
+ import os
4
+ import torch
5
+ import numpy as np
6
+ import pandas as pd
7
+ import json
8
+ import re
9
+ import pydicom
10
+ from datetime import datetime
11
+ from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
12
+ from pathlib import Path
13
+ import threading
14
+ import multiprocessing as mp
15
+
16
+ # Download and setup model
17
+ model_path = snapshot_download(repo_id="Lab-Rasool/sybil")
18
+ sys.path.append(model_path)
19
+
20
+ from modeling_sybil_hf import SybilHFWrapper
21
+ from configuration_sybil import SybilConfig
22
+
23
+ def load_model(device_id=0):
24
+ """
25
+ Load and initialize the Sybil model once.
26
+
27
+ Args:
28
+ device_id: GPU device ID to load model on
29
+
30
+ Returns:
31
+ Initialized SybilHFWrapper model
32
+ """
33
+ print(f"Loading Sybil model on GPU {device_id}...")
34
+ config = SybilConfig()
35
+ model = SybilHFWrapper(config)
36
+
37
+ # Move model to specific GPU
38
+ device = torch.device(f'cuda:{device_id}')
39
+
40
+ # CRITICAL: Set the model's internal device attribute
41
+ # This ensures preprocessing moves data to the correct GPU
42
+ model.device = device
43
+
44
+ # Move all ensemble models to the correct GPU
45
+ for m in model.models:
46
+ m.to(device)
47
+ m.eval()
48
+
49
+ print(f"Model loaded successfully on GPU {device_id}!")
50
+ print(f" Model internal device: {model.device}")
51
+ return model, device
52
+
53
+ def is_localizer_scan(dicom_folder):
54
+ """
55
+ Check if a DICOM folder contains a localizer/scout scan.
56
+ Based on preprocessing.py logic.
57
+
58
+ Returns:
59
+ Tuple of (is_localizer, reason)
60
+ """
61
+ folder_path = Path(dicom_folder)
62
+ folder_name = folder_path.name.lower()
63
+ localizer_keywords = ['localizer', 'scout', 'topogram', 'surview', 'scanogram']
64
+
65
+ # Check folder name
66
+ if any(keyword in folder_name for keyword in localizer_keywords):
67
+ return True, f"Folder name contains localizer keyword: {folder_name}"
68
+
69
+ try:
70
+ dcm_files = list(folder_path.glob("*.dcm"))
71
+ if not dcm_files:
72
+ return False, "No DICOM files found"
73
+
74
+ # Check first few DICOM files for localizer metadata
75
+ sample_files = dcm_files[:min(3, len(dcm_files))]
76
+ for dcm_file in sample_files:
77
+ try:
78
+ dcm = pydicom.dcmread(str(dcm_file), stop_before_pixels=True)
79
+
80
+ # Check ImageType field
81
+ if hasattr(dcm, 'ImageType'):
82
+ image_type_str = ' '.join(str(val).lower() for val in dcm.ImageType)
83
+ if any(keyword in image_type_str for keyword in localizer_keywords):
84
+ return True, f"ImageType indicates localizer: {dcm.ImageType}"
85
+
86
+ # Check SeriesDescription field
87
+ if hasattr(dcm, 'SeriesDescription'):
88
+ if any(keyword in dcm.SeriesDescription.lower() for keyword in localizer_keywords):
89
+ return True, f"SeriesDescription indicates localizer: {dcm.SeriesDescription}"
90
+ except Exception as e:
91
+ continue
92
+ except Exception as e:
93
+ pass
94
+
95
+ return False, "Not a localizer scan"
96
+
97
+ def extract_timepoint_from_path(scan_dir):
98
+ """
99
+ Extract timepoint from scan directory path based on year.
100
+ 1999 -> T0, 2000 -> T1, 2001 -> T2, etc.
101
+
102
+ Looks for year patterns in folder names in date format MM-DD-YYYY.
103
+
104
+ Args:
105
+ scan_dir: Directory path string
106
+
107
+ Returns:
108
+ Timepoint string (e.g., 'T0', 'T1', 'T2') or None if not found
109
+ """
110
+ # Split path into components
111
+ path_parts = scan_dir.split('/')
112
+
113
+ # Look for date patterns like "01-02-2000-NLST-LSS"
114
+ # Pattern: Date format MM-DD-YYYY at the start of a folder name
115
+ date_pattern = r'^\d{2}-\d{2}-(19\d{2}|20\d{2})'
116
+
117
+ base_year = 1999
118
+
119
+ for part in path_parts:
120
+ # Check for date pattern (e.g., "01-02-2000-NLST-LSS-50335")
121
+ match = re.match(date_pattern, part)
122
+ if match:
123
+ year = int(match.group(1))
124
+ if 1999 <= year <= 2010: # Reasonable range for NLST
125
+ timepoint_num = year - base_year
126
+ print(f" DEBUG: Found year {year} in '{part}' -> T{timepoint_num}")
127
+ return f'T{timepoint_num}'
128
+
129
+ return None
130
+
131
+ def extract_embedding_single_model(model_idx, ensemble_model, pixel_values, device):
132
+ """
133
+ Extract embedding from a single ensemble model.
134
+
135
+ Args:
136
+ model_idx: Index of the model in the ensemble
137
+ ensemble_model: Single model from the ensemble
138
+ pixel_values: Preprocessed pixel values tensor (already on correct device)
139
+ device: Device to run on (e.g., cuda:0, cuda:1)
140
+
141
+ Returns:
142
+ numpy array of embeddings from this model
143
+ """
144
+ embeddings_buffer = []
145
+
146
+ def create_hook(buffer):
147
+ def hook(module, input, output):
148
+ # Capture the output of ReLU layer (before dropout)
149
+ buffer.append(output.detach().cpu())
150
+ return hook
151
+
152
+ # Register hook on the ReLU layer (this is AFTER pooling, BEFORE dropout/classification)
153
+ hook_handle = ensemble_model.relu.register_forward_hook(create_hook(embeddings_buffer))
154
+
155
+ # Run forward pass on THIS model only with keyword argument
156
+ with torch.no_grad():
157
+ _ = ensemble_model(pixel_values=pixel_values)
158
+
159
+ # Remove hook
160
+ hook_handle.remove()
161
+
162
+ # Get the embeddings (should be shape [1, 512])
163
+ if embeddings_buffer:
164
+ embedding = embeddings_buffer[0].numpy().squeeze()
165
+ print(f"Model {model_idx + 1}: Embedding shape = {embedding.shape}")
166
+ return embedding
167
+ return None
168
+
169
+ def extract_embeddings(model, dicom_paths, device, use_parallel=True):
170
+ """
171
+ Extract embeddings from the layer after ReLU, before Dropout.
172
+ Processes ensemble models in parallel for speed.
173
+
174
+ Args:
175
+ model: Pre-loaded SybilHFWrapper model
176
+ dicom_paths: List of DICOM file paths
177
+ device: Device to run on (e.g., cuda:0, cuda:1)
178
+ use_parallel: If True, process ensemble models in parallel
179
+
180
+ Returns:
181
+ numpy array of shape (512,) - averaged embeddings across ensemble
182
+ """
183
+ # Preprocess ONCE (not 5 times!)
184
+ # The model's preprocessing handles moving data to the correct device
185
+ with torch.no_grad():
186
+ # Get the preprocessed input by calling the wrapper's preprocess_dicom method
187
+ # This returns the tensor that would be fed to each ensemble model
188
+ pixel_values = model.preprocess_dicom(dicom_paths)
189
+
190
+ if use_parallel:
191
+ # Process all ensemble models in parallel using ThreadPoolExecutor
192
+ all_embeddings = []
193
+
194
+ with ThreadPoolExecutor(max_workers=len(model.models)) as executor:
195
+ # Submit all models for parallel processing with the SAME preprocessed input
196
+ futures = [
197
+ executor.submit(extract_embedding_single_model, model_idx, ensemble_model, pixel_values, device)
198
+ for model_idx, ensemble_model in enumerate(model.models)
199
+ ]
200
+
201
+ # Collect results as they complete
202
+ for future in futures:
203
+ embedding = future.result()
204
+ if embedding is not None:
205
+ all_embeddings.append(embedding)
206
+ else:
207
+ # Sequential processing (original implementation)
208
+ all_embeddings = []
209
+ for model_idx, ensemble_model in enumerate(model.models):
210
+ embedding = extract_embedding_single_model(model_idx, ensemble_model, pixel_values, device)
211
+ if embedding is not None:
212
+ all_embeddings.append(embedding)
213
+
214
+ # Average embeddings across ensemble
215
+ averaged_embedding = np.mean(all_embeddings, axis=0)
216
+ return averaged_embedding
217
+
218
+ def check_directory_for_dicoms(dirpath):
219
+ """
220
+ Check a single directory for valid DICOM files.
221
+ Returns (dirpath, num_files, subject_id, filter_reason) or None if invalid.
222
+ """
223
+ try:
224
+ # Quick check: does this directory have .dcm files?
225
+ dcm_files = [f for f in os.listdir(dirpath)
226
+ if f.endswith('.dcm') and os.path.isfile(os.path.join(dirpath, f))]
227
+
228
+ if not dcm_files:
229
+ return None
230
+
231
+ num_files = len(dcm_files)
232
+
233
+ # Filter out scans with 1-2 DICOM files (likely localizers)
234
+ if num_files <= 2:
235
+ return (dirpath, num_files, None, 'too_few_slices')
236
+
237
+ # Check if it's a localizer scan
238
+ is_loc, _ = is_localizer_scan(dirpath)
239
+ if is_loc:
240
+ return (dirpath, num_files, None, 'localizer')
241
+
242
+ # Extract subject ID (PID) from path
243
+ # Path structure: /NLST/<PID>/<date-info>/<scan-info>
244
+ # Example: /NLST/106639/01-02-1999-NLST-LSS-45699/1.000000-0OPLGEHSQXAnullna...
245
+ path_parts = dirpath.rstrip('/').split('/')
246
+
247
+ # Find the PID: it's the part after 'NLST' directory
248
+ try:
249
+ nlst_idx = path_parts.index('NLST')
250
+ subject_id = path_parts[nlst_idx + 1] # PID is right after 'NLST'
251
+ except (ValueError, IndexError):
252
+ # Fallback to old logic if path structure is different
253
+ subject_id = path_parts[-3] if len(path_parts) >= 3 else path_parts[-1]
254
+
255
+ return (dirpath, num_files, subject_id, 'valid')
256
+
257
+ except Exception as e:
258
+ return None
259
+
260
+ def save_directory_cache(dicom_dirs, cache_file):
261
+ """
262
+ Save the list of DICOM directories to a cache file.
263
+
264
+ Args:
265
+ dicom_dirs: List of directory paths
266
+ cache_file: Path to cache file
267
+ """
268
+ print(f"\n💾 Saving directory cache to {cache_file}...")
269
+ cache_data = {
270
+ "timestamp": datetime.now().isoformat(),
271
+ "num_directories": len(dicom_dirs),
272
+ "directories": dicom_dirs
273
+ }
274
+ with open(cache_file, 'w') as f:
275
+ json.dump(cache_data, f, indent=2)
276
+ print(f"✓ Cache saved with {len(dicom_dirs)} directories\n")
277
+
278
+ def load_directory_cache(cache_file):
279
+ """
280
+ Load the list of DICOM directories from a cache file.
281
+
282
+ Args:
283
+ cache_file: Path to cache file
284
+
285
+ Returns:
286
+ List of directory paths, or None if cache doesn't exist or is invalid
287
+ """
288
+ if not os.path.exists(cache_file):
289
+ return None
290
+
291
+ try:
292
+ with open(cache_file, 'r') as f:
293
+ cache_data = json.load(f)
294
+
295
+ dicom_dirs = cache_data.get("directories", [])
296
+ timestamp = cache_data.get("timestamp", "unknown")
297
+
298
+ print(f"\n✓ Loaded directory cache from {cache_file}")
299
+ print(f" Cache created: {timestamp}")
300
+ print(f" Directories: {len(dicom_dirs)}\n")
301
+
302
+ return dicom_dirs
303
+ except Exception as e:
304
+ print(f"⚠️ Failed to load cache: {e}")
305
+ return None
306
+
307
+ def find_dicom_directories(root_dir, max_subjects=None, num_workers=12, cache_file=None, filter_pids=None):
308
+ """
309
+ Walk through directory tree and find all directories containing DICOM files.
310
+ Uses parallel processing for much faster scanning of large directory trees.
311
+ Only returns leaf directories (directories with .dcm files, not their parents).
312
+ Filters out localizer scans with 1-2 DICOM files.
313
+
314
+ Args:
315
+ root_dir: Root directory to search
316
+ max_subjects: Optional maximum number of unique subjects to process (None = all)
317
+ num_workers: Number of parallel workers for directory scanning (default: 12)
318
+ cache_file: Optional path to cache file for saving/loading directory list
319
+ filter_pids: Optional set of PIDs to filter (only include these subjects)
320
+
321
+ Returns:
322
+ List of directory paths containing .dcm files
323
+ """
324
+ # Try to load from cache first
325
+ if cache_file:
326
+ cached_dirs = load_directory_cache(cache_file)
327
+ if cached_dirs is not None:
328
+ print("✓ Using cached directory list (skipping scan)")
329
+
330
+ # Apply PID filter if specified
331
+ if filter_pids:
332
+ print(f" Filtering to {len(filter_pids)} PIDs from CSV...")
333
+ filtered_dirs = []
334
+ for d in cached_dirs:
335
+ # Extract PID from path: /NLST/<PID>/<date>/<scan>
336
+ path_parts = d.rstrip('/').split('/')
337
+ try:
338
+ nlst_idx = path_parts.index('NLST')
339
+ subject_id = path_parts[nlst_idx + 1]
340
+ except (ValueError, IndexError):
341
+ subject_id = path_parts[-3] if len(path_parts) >= 3 else path_parts[-1]
342
+
343
+ if subject_id in filter_pids:
344
+ filtered_dirs.append(d)
345
+ print(f" ✓ Found {len(filtered_dirs)} scans matching PIDs")
346
+ return filtered_dirs
347
+
348
+ # Still apply max_subjects limit if specified
349
+ if max_subjects:
350
+ subjects_seen = set()
351
+ filtered_dirs = []
352
+ for d in cached_dirs:
353
+ # Extract PID from path: /NLST/<PID>/<date>/<scan>
354
+ path_parts = d.rstrip('/').split('/')
355
+ try:
356
+ nlst_idx = path_parts.index('NLST')
357
+ subject_id = path_parts[nlst_idx + 1]
358
+ except (ValueError, IndexError):
359
+ subject_id = path_parts[-3] if len(path_parts) >= 3 else path_parts[-1]
360
+
361
+ # Check if we should include this scan
362
+ # Add scan if: (1) already collecting this subject, OR (2) under subject limit
363
+ if subject_id in subjects_seen:
364
+ # Already collecting this subject - add this scan
365
+ filtered_dirs.append(d)
366
+ elif len(subjects_seen) < max_subjects:
367
+ # New subject and under limit - start collecting this subject
368
+ subjects_seen.add(subject_id)
369
+ filtered_dirs.append(d)
370
+
371
+ # Stop once we have enough subjects
372
+ if len(subjects_seen) >= max_subjects:
373
+ # Count remaining scans from these subjects
374
+ remaining_count = 0
375
+ for remaining_d in cached_dirs[cached_dirs.index(d)+1:]:
376
+ remaining_parts = remaining_d.rstrip('/').split('/')
377
+ try:
378
+ remaining_nlst_idx = remaining_parts.index('NLST')
379
+ remaining_subject_id = remaining_parts[remaining_nlst_idx + 1]
380
+ except (ValueError, IndexError):
381
+ remaining_subject_id = remaining_parts[-3] if len(remaining_parts) >= 3 else remaining_parts[-1]
382
+ if remaining_subject_id in subjects_seen:
383
+ filtered_dirs.append(remaining_d)
384
+ break
385
+
386
+ print(f" ✓ Limited to {len(subjects_seen)} subjects ({len(filtered_dirs)} total scans)")
387
+ return filtered_dirs
388
+ return cached_dirs
389
+
390
+ print(f"Starting parallel directory scan with {num_workers} workers...")
391
+ print("This is much faster than the old sequential scan!")
392
+
393
+ # Phase 1: Fast parallel scan to find all directories with DICOM files
394
+ print("\nPhase 1: Scanning filesystem for DICOM directories...")
395
+ start_time = datetime.now()
396
+
397
+ # Collect all directories first (fast)
398
+ all_dirs = []
399
+ for dirpath, dirnames, filenames in os.walk(root_dir):
400
+ # Quick check: if directory has .dcm files, add to list
401
+ if any(f.endswith('.dcm') for f in filenames):
402
+ all_dirs.append(dirpath)
403
+
404
+ print(f"Found {len(all_dirs)} potential DICOM directories in {(datetime.now() - start_time).total_seconds():.1f}s")
405
+
406
+ # Phase 2: Parallel validation and filtering
407
+ print(f"\nPhase 2: Validating directories in parallel ({num_workers} workers)...")
408
+
409
+ from concurrent.futures import ProcessPoolExecutor, as_completed
410
+
411
+ dicom_dirs = []
412
+ subjects_found = set()
413
+ filtered_stats = {'localizers': 0, 'too_few_slices': 0}
414
+
415
+ with ProcessPoolExecutor(max_workers=num_workers) as executor:
416
+ # Submit all directories for checking
417
+ future_to_dir = {executor.submit(check_directory_for_dicoms, d): d for d in all_dirs}
418
+
419
+ # Process results as they complete
420
+ for i, future in enumerate(as_completed(future_to_dir), 1):
421
+ # Print progress every 1000 dirs (more frequent for visibility)
422
+ if i % 1000 == 0:
423
+ elapsed = (datetime.now() - start_time).total_seconds()
424
+ rate = i / elapsed if elapsed > 0 else 0
425
+ remaining = (len(all_dirs) - i) / rate if rate > 0 else 0
426
+ print(f" [{i}/{len(all_dirs)}] Found: {len(dicom_dirs)} scans from {len(subjects_found)} PIDs | "
427
+ f"Filtered: {filtered_stats['localizers'] + filtered_stats['too_few_slices']} | "
428
+ f"ETA: {remaining/60:.1f} min")
429
+
430
+ try:
431
+ result = future.result()
432
+ if result is None:
433
+ continue
434
+
435
+ dirpath, num_files, subject_id, status = result
436
+
437
+ if status == 'too_few_slices':
438
+ filtered_stats['too_few_slices'] += 1
439
+ elif status == 'localizer':
440
+ filtered_stats['localizers'] += 1
441
+ elif status == 'valid':
442
+ # Check PID filter
443
+ if filter_pids is not None and subject_id not in filter_pids:
444
+ continue
445
+
446
+ # Check subject limit
447
+ if max_subjects is not None and subject_id not in subjects_found and len(subjects_found) >= max_subjects:
448
+ continue
449
+
450
+ subjects_found.add(subject_id)
451
+ dicom_dirs.append(dirpath)
452
+
453
+ # Print when we find a new PID match (helpful for filtered runs)
454
+ if filter_pids and len(dicom_dirs) % 100 == 1:
455
+ print(f" ✓ Found {len(dicom_dirs)} scans so far ({len(subjects_found)} unique PIDs)")
456
+
457
+ # Stop if we've hit subject limit
458
+ if max_subjects is not None and len(subjects_found) >= max_subjects:
459
+ print(f"\n✓ Reached limit of {max_subjects} subjects. Stopping search.")
460
+ # Cancel remaining futures
461
+ for f in future_to_dir:
462
+ f.cancel()
463
+ break
464
+
465
+ except Exception as e:
466
+ continue
467
+
468
+ scan_time = (datetime.now() - start_time).total_seconds()
469
+
470
+ print(f"\n{'='*80}")
471
+ print(f"Directory Scan Complete in {scan_time:.1f}s ({scan_time/60:.1f} minutes)")
472
+ print(f"{'='*80}")
473
+ print(f"Filtering Summary:")
474
+ print(f" ✅ Valid scans found: {len(dicom_dirs)}")
475
+ print(f" 🚫 Localizers filtered: {filtered_stats['localizers']}")
476
+ print(f" ⏭️ Too few slices (≤2) filtered: {filtered_stats['too_few_slices']}")
477
+ print(f" 📊 Unique subjects: {len(subjects_found)}")
478
+ print(f" ⚡ Speed: {len(all_dirs)/scan_time:.0f} dirs/second")
479
+ print(f"{'='*80}\n")
480
+
481
+ # Save to cache if specified
482
+ if cache_file:
483
+ save_directory_cache(dicom_dirs, cache_file)
484
+
485
+ return dicom_dirs
486
+
487
+ def prepare_scan_metadata(scan_dir):
488
+ """
489
+ Prepare metadata for a scan without processing.
490
+
491
+ Args:
492
+ scan_dir: Directory containing DICOM files for one scan
493
+
494
+ Returns:
495
+ tuple: (dicom_file_paths, num_files, subject_id, scan_id)
496
+ """
497
+ # Count DICOM files (ensure they are actual files, not directories)
498
+ dicom_files = [f for f in os.listdir(scan_dir)
499
+ if f.endswith('.dcm') and os.path.isfile(os.path.join(scan_dir, f))]
500
+ num_dicom_files = len(dicom_files)
501
+
502
+ if num_dicom_files == 0:
503
+ raise ValueError("No valid DICOM files found")
504
+
505
+ # Create list of full paths to DICOM files
506
+ dicom_file_paths = [os.path.join(scan_dir, f) for f in dicom_files]
507
+
508
+ # Parse directory path to extract identifiers
509
+ # Path structure: /NLST/<PID>/<date-info>/<scan-info>
510
+ path_parts = scan_dir.rstrip('/').split('/')
511
+ scan_id = path_parts[-1] if path_parts[-1] else path_parts[-2]
512
+
513
+ # Extract PID from path
514
+ try:
515
+ nlst_idx = path_parts.index('NLST')
516
+ subject_id = path_parts[nlst_idx + 1] # PID is right after 'NLST'
517
+ except (ValueError, IndexError):
518
+ # Fallback to old logic
519
+ subject_id = path_parts[-3] if len(path_parts) >= 3 else path_parts[-1]
520
+
521
+ return dicom_file_paths, num_dicom_files, subject_id, scan_id
522
+
523
+ def save_checkpoint(all_embeddings, all_metadata, failed, output_dir, checkpoint_num):
524
+ """
525
+ Save a checkpoint of embeddings and metadata.
526
+
527
+ Args:
528
+ all_embeddings: List of embedding arrays
529
+ all_metadata: List of metadata dictionaries
530
+ failed: List of failed scans
531
+ output_dir: Output directory
532
+ checkpoint_num: Checkpoint number
533
+ """
534
+ print(f"\n💾 Saving checkpoint {checkpoint_num}...")
535
+
536
+ # Convert embeddings to array
537
+ embeddings_array = np.array(all_embeddings)
538
+ embedding_dim = int(embeddings_array.shape[1]) if len(embeddings_array.shape) > 1 else int(embeddings_array.shape[0])
539
+
540
+ # Create DataFrame
541
+ df_data = {
542
+ 'case_number': [m['case_number'] for m in all_metadata],
543
+ 'subject_id': [m['subject_id'] for m in all_metadata],
544
+ 'scan_id': [m['scan_id'] for m in all_metadata],
545
+ 'timepoint': [m.get('timepoint') for m in all_metadata],
546
+ 'dicom_directory': [m['dicom_directory'] for m in all_metadata],
547
+ 'num_dicom_files': [m['num_dicom_files'] for m in all_metadata],
548
+ 'embedding_index': [m['embedding_index'] for m in all_metadata],
549
+ 'embedding': list(embeddings_array)
550
+ }
551
+ df = pd.DataFrame(df_data)
552
+
553
+ # Save checkpoint parquet
554
+ checkpoint_path = os.path.join(output_dir, f"checkpoint_{checkpoint_num}_embeddings.parquet")
555
+ df.to_parquet(checkpoint_path, index=False, compression='snappy')
556
+ print(f" ✓ Saved embeddings checkpoint: {checkpoint_path}")
557
+
558
+ # Save checkpoint metadata
559
+ checkpoint_metadata = {
560
+ "checkpoint_num": checkpoint_num,
561
+ "timestamp": datetime.now().isoformat(),
562
+ "total_scans": len(all_embeddings),
563
+ "failed_scans": len(failed),
564
+ "embedding_shape": list(embeddings_array.shape),
565
+ "scans": all_metadata,
566
+ "failed_scans": failed
567
+ }
568
+ metadata_path = os.path.join(output_dir, f"checkpoint_{checkpoint_num}_metadata.json")
569
+ with open(metadata_path, 'w') as f:
570
+ json.dump(checkpoint_metadata, f, indent=2)
571
+ print(f" ✓ Saved metadata checkpoint: {metadata_path}")
572
+ print(f"💾 Checkpoint {checkpoint_num} complete!\n")
573
+
574
+ def process_scan(model, device, scan_dir):
575
+ """
576
+ Process a single scan directory and extract embeddings.
577
+
578
+ Args:
579
+ model: Pre-loaded SybilHFWrapper model
580
+ device: Device to run on (e.g., cuda:0, cuda:1)
581
+ scan_dir: Directory containing DICOM files for one scan
582
+
583
+ Returns:
584
+ tuple: (embeddings, scan_metadata)
585
+ """
586
+ dicom_file_paths, num_dicom_files, subject_id, scan_id = prepare_scan_metadata(scan_dir)
587
+
588
+ print(f"\nProcessing: {scan_dir}")
589
+ print(f"DICOM files: {num_dicom_files}")
590
+
591
+ # Extract embeddings
592
+ embeddings = extract_embeddings(model, dicom_file_paths, device)
593
+
594
+ print(f"Embedding shape: {embeddings.shape}")
595
+
596
+ # Extract timepoint from path (e.g., 1999 -> T0, 2000 -> T1)
597
+ timepoint = extract_timepoint_from_path(scan_dir)
598
+ if timepoint:
599
+ print(f"Timepoint: {timepoint}")
600
+ else:
601
+ print(f"Timepoint: Not detected")
602
+
603
+ # Create metadata for this scan
604
+ scan_metadata = {
605
+ "case_number": subject_id, # Case number (e.g., 205749)
606
+ "subject_id": subject_id,
607
+ "scan_id": scan_id,
608
+ "timepoint": timepoint, # T0, T1, T2, etc. or None
609
+ "dicom_directory": scan_dir,
610
+ "num_dicom_files": num_dicom_files,
611
+ "embedding_index": None, # Will be set later
612
+ "statistics": {
613
+ "mean": float(np.mean(embeddings)),
614
+ "std": float(np.std(embeddings)),
615
+ "min": float(np.min(embeddings)),
616
+ "max": float(np.max(embeddings))
617
+ }
618
+ }
619
+
620
+ return embeddings, scan_metadata
621
+
622
+ # Main execution
623
+ if __name__ == "__main__":
624
+ import argparse
625
+
626
+ # Parse command line arguments
627
+ parser = argparse.ArgumentParser(description='Extract Sybil embeddings from DICOM scans')
628
+ parser.add_argument('--pid-csv', type=str, default=None,
629
+ help='CSV file with "pid" column to filter subjects (e.g., subsets/hybridModels-train.csv)')
630
+ parser.add_argument('--output-dir', type=str, default='embeddings_output_full',
631
+ help='Output directory for embeddings')
632
+ parser.add_argument('--max-subjects', type=int, default=None,
633
+ help='Maximum number of subjects to process (for testing)')
634
+ parser.add_argument('--num-parallel', type=int, default=1,
635
+ help='Number of parallel scans (default: 1 for sequential processing)')
636
+ parser.add_argument('--num-gpus', type=int, default=1,
637
+ help='Number of GPUs to use (default: 1)')
638
+ args = parser.parse_args()
639
+
640
+ # ==========================================
641
+ # CONFIGURATION - Edit these variables as needed
642
+ # ==========================================
643
+ root_dir = "/roshare/nlst_global/data_23Dec2024/manifest-NLST_allCT/NLST"
644
+ output_dir = args.output_dir
645
+ max_subjects = args.max_subjects
646
+ num_gpus = args.num_gpus # Use specified number of GPUs
647
+ num_parallel_scans = args.num_parallel
648
+ num_scan_workers = 12 # Number of workers for parallel directory scanning (fast filesystem scan)
649
+ checkpoint_interval = 20000 # Save checkpoint every N scans
650
+
651
+ # Always use the main cache file from the full run
652
+ main_cache = "embeddings_output_full/directory_cache.json"
653
+ if os.path.exists(main_cache):
654
+ cache_file = main_cache
655
+ print(f"✓ Found main directory cache: {main_cache}")
656
+ else:
657
+ cache_file = os.path.join(output_dir, "directory_cache.json")
658
+
659
+ # Load PIDs from CSV if provided
660
+ filter_pids = None
661
+ if args.pid_csv:
662
+ print(f"Loading subject PIDs from: {args.pid_csv}")
663
+ import pandas as pd
664
+ csv_data = pd.read_csv(args.pid_csv)
665
+ filter_pids = set(str(pid) for pid in csv_data['pid'].unique())
666
+ print(f" Found {len(filter_pids)} unique PIDs to extract")
667
+ print(f" Examples: {list(filter_pids)[:5]}")
668
+
669
+ # Create output directory
670
+ os.makedirs(output_dir, exist_ok=True)
671
+
672
+ # Verify root directory exists
673
+ if not os.path.exists(root_dir):
674
+ raise ValueError(f"Root directory does not exist: {root_dir}")
675
+
676
+ print(f"\nSearching for DICOM directories in: {root_dir}")
677
+ if filter_pids:
678
+ print(f"Filtering to {len(filter_pids)} PIDs from CSV")
679
+ if max_subjects:
680
+ print(f"Limiting to {max_subjects} subjects")
681
+ print("⚡ Using parallel directory scanning for speed!\n")
682
+
683
+ # Find all directories containing DICOM files (FAST with parallel processing!)
684
+ # Will use cached directory list if available, otherwise scan and save cache
685
+ dicom_dirs = find_dicom_directories(root_dir, max_subjects=max_subjects,
686
+ num_workers=num_scan_workers, cache_file=cache_file,
687
+ filter_pids=filter_pids)
688
+
689
+ if len(dicom_dirs) == 0:
690
+ raise ValueError(f"No directories with DICOM files found in {root_dir}")
691
+
692
+ print(f"\n{'='*80}")
693
+ print(f"Found {len(dicom_dirs)} directories containing DICOM files")
694
+ print(f"{'='*80}\n")
695
+
696
+ # Detect and load models on multiple GPUs
697
+ print(f"🎮 Detected {num_gpus} GPU(s)")
698
+ print(f"🚀 Will process {num_parallel_scans} scans in parallel ({num_parallel_scans // num_gpus} per GPU)")
699
+ print(f"💾 Checkpoints will be saved every {checkpoint_interval} scans\n")
700
+
701
+ # Load models on each GPU
702
+ models_and_devices = []
703
+ for gpu_id in range(num_gpus):
704
+ model, device = load_model(gpu_id)
705
+ models_and_devices.append((model, device, gpu_id))
706
+
707
+ # Process each scan directory and collect all embeddings
708
+ all_embeddings = []
709
+ all_metadata = []
710
+ failed = []
711
+ checkpoint_counter = 0
712
+
713
+ if num_parallel_scans > 1:
714
+ # Parallel processing of multiple scans across multiple GPUs
715
+ print(f"Processing {num_parallel_scans} scans in parallel across {num_gpus} GPU(s)...")
716
+ print(f"Note: This requires ~{(num_parallel_scans // num_gpus) * 10}GB VRAM per GPU.\n")
717
+
718
+ from functools import partial
719
+ from concurrent.futures import as_completed
720
+
721
+ # Process scans in batches for checkpoint saving
722
+ batch_size = checkpoint_interval
723
+ num_batches = (len(dicom_dirs) + batch_size - 1) // batch_size
724
+
725
+ for batch_idx in range(num_batches):
726
+ start_idx = batch_idx * batch_size
727
+ end_idx = min(start_idx + batch_size, len(dicom_dirs))
728
+ batch_dirs = dicom_dirs[start_idx:end_idx]
729
+
730
+ print(f"\n{'='*80}")
731
+ print(f"Processing batch {batch_idx + 1}/{num_batches} (scans {start_idx + 1} to {end_idx})")
732
+ print(f"{'='*80}\n")
733
+
734
+ # Use ThreadPoolExecutor for parallel scan processing
735
+ # IMPORTANT: max_workers limits concurrent execution to prevent OOM
736
+ with ThreadPoolExecutor(max_workers=num_parallel_scans) as executor:
737
+ # Submit scans in controlled batches to avoid memory issues
738
+ # We submit only max_workers scans at once, then submit more as they complete
739
+ future_to_info = {}
740
+ scan_queue = list(enumerate(batch_dirs))
741
+ scans_submitted = 0
742
+
743
+ # Submit initial batch (up to max_workers scans)
744
+ while scan_queue and scans_submitted < num_parallel_scans:
745
+ i, scan_dir = scan_queue.pop(0)
746
+ # Select GPU in round-robin fashion
747
+ gpu_idx = i % num_gpus
748
+ model, device, gpu_id = models_and_devices[gpu_idx]
749
+
750
+ # Create partial function with model and device
751
+ process_func = partial(process_scan, model, device)
752
+ future = executor.submit(process_func, scan_dir)
753
+ future_to_info[future] = (start_idx + i + 1, scan_dir, gpu_id)
754
+ scans_submitted += 1
755
+
756
+ # Process results as they complete and submit new scans
757
+ while future_to_info:
758
+ # Wait for next completion
759
+ done_futures = []
760
+ for future in list(future_to_info.keys()):
761
+ if future.done():
762
+ done_futures.append(future)
763
+
764
+ if not done_futures:
765
+ import time
766
+ time.sleep(0.1)
767
+ continue
768
+
769
+ # Process completed futures
770
+ for future in done_futures:
771
+ scan_num, scan_dir, gpu_id = future_to_info.pop(future)
772
+ try:
773
+ print(f"[{scan_num}/{len(dicom_dirs)}] Processing on GPU {gpu_id}...")
774
+ embeddings, scan_metadata = future.result()
775
+
776
+ # Set the index for this scan
777
+ scan_metadata["embedding_index"] = len(all_embeddings)
778
+
779
+ # Collect embeddings and metadata
780
+ all_embeddings.append(embeddings)
781
+ all_metadata.append(scan_metadata)
782
+
783
+ except Exception as e:
784
+ print(f"ERROR processing {scan_dir}: {e}")
785
+ failed.append({"scan_dir": scan_dir, "error": str(e)})
786
+
787
+ # Submit next scan from queue
788
+ if scan_queue:
789
+ i, next_scan_dir = scan_queue.pop(0)
790
+ gpu_idx = i % num_gpus
791
+ model, device, gpu_id = models_and_devices[gpu_idx]
792
+
793
+ process_func = partial(process_scan, model, device)
794
+ new_future = executor.submit(process_func, next_scan_dir)
795
+ future_to_info[new_future] = (start_idx + i + 1, next_scan_dir, gpu_id)
796
+
797
+ # Save checkpoint after each batch
798
+ checkpoint_counter += 1
799
+ save_checkpoint(all_embeddings, all_metadata, failed, output_dir, checkpoint_counter)
800
+
801
+ print(f"Progress: {len(all_embeddings)}/{len(dicom_dirs)} scans completed "
802
+ f"({len(all_embeddings)/len(dicom_dirs)*100:.1f}%)\n")
803
+ else:
804
+ # Sequential processing (original behavior)
805
+ model, device, gpu_id = models_and_devices[0] # Use first GPU
806
+
807
+ for i, scan_dir in enumerate(dicom_dirs, 1):
808
+ try:
809
+ print(f"\n[{i}/{len(dicom_dirs)}] Processing scan...")
810
+
811
+ # Process scan and get results
812
+ embeddings, scan_metadata = process_scan(model, device, scan_dir)
813
+
814
+ # Set the index for this scan
815
+ scan_metadata["embedding_index"] = len(all_embeddings)
816
+
817
+ # Collect embeddings and metadata
818
+ all_embeddings.append(embeddings)
819
+ all_metadata.append(scan_metadata)
820
+
821
+ # Save checkpoint every checkpoint_interval scans
822
+ if i % checkpoint_interval == 0:
823
+ checkpoint_counter += 1
824
+ save_checkpoint(all_embeddings, all_metadata, failed, output_dir, checkpoint_counter)
825
+
826
+ except Exception as e:
827
+ print(f"ERROR processing {scan_dir}: {e}")
828
+ failed.append({"scan_dir": scan_dir, "error": str(e)})
829
+
830
+ # Convert embeddings list to numpy array
831
+ # Shape will be (num_scans, embedding_dim)
832
+ embeddings_array = np.array(all_embeddings)
833
+ embedding_dim = int(embeddings_array.shape[1]) if len(embeddings_array.shape) > 1 else int(embeddings_array.shape[0])
834
+
835
+ # Create DataFrame with embeddings and metadata for Parquet
836
+ # Store embeddings as a single array column
837
+ df_data = {
838
+ 'case_number': [m['case_number'] for m in all_metadata],
839
+ 'subject_id': [m['subject_id'] for m in all_metadata],
840
+ 'scan_id': [m['scan_id'] for m in all_metadata],
841
+ 'timepoint': [m.get('timepoint') for m in all_metadata], # T0, T1, T2, etc.
842
+ 'dicom_directory': [m['dicom_directory'] for m in all_metadata],
843
+ 'num_dicom_files': [m['num_dicom_files'] for m in all_metadata],
844
+ 'embedding_index': [m['embedding_index'] for m in all_metadata],
845
+ 'embedding': list(embeddings_array) # Store as list of arrays
846
+ }
847
+
848
+ # Create DataFrame
849
+ df = pd.DataFrame(df_data)
850
+
851
+ # Save final complete file as Parquet
852
+ embeddings_filename = "all_embeddings.parquet"
853
+ embeddings_path = os.path.join(output_dir, embeddings_filename)
854
+ df.to_parquet(embeddings_path, index=False, compression='snappy')
855
+ print(f"\n✅ Saved FINAL embeddings to Parquet: {embeddings_path}")
856
+
857
+ # Create comprehensive metadata JSON
858
+ dataset_metadata = {
859
+ "dataset_info": {
860
+ "root_directory": root_dir,
861
+ "total_scans": len(all_embeddings),
862
+ "failed_scans": len(failed),
863
+ "embedding_shape": list(embeddings_array.shape),
864
+ "embedding_dim": embedding_dim,
865
+ "extraction_timestamp": datetime.now().isoformat(),
866
+ "file_format": "parquet"
867
+ },
868
+ "model_info": {
869
+ "model": "Lab-Rasool/sybil",
870
+ "layer": "after_relu_before_dropout",
871
+ "ensemble_averaged": True,
872
+ "num_ensemble_models": 5
873
+ },
874
+ "embeddings_file": embeddings_filename,
875
+ "parquet_schema": {
876
+ "metadata_columns": ["case_number", "subject_id", "scan_id", "timepoint", "dicom_directory", "num_dicom_files", "embedding_index"],
877
+ "embedding_column": "embedding",
878
+ "embedding_shape": f"({embedding_dim},)",
879
+ "total_columns": 8,
880
+ "timepoint_info": "T0=1999, T1=2000, T2=2001, etc. Extracted from year in path. Can be None if not detected."
881
+ },
882
+ "filtering_info": {
883
+ "localizer_detection": "Scans identified as localizers (by folder name or DICOM metadata) are filtered out",
884
+ "min_slices": "Scans with ≤2 DICOM files are filtered out (likely localizers)",
885
+ "accepted_scans": len(all_embeddings)
886
+ },
887
+ "scans": all_metadata,
888
+ "failed_scans": failed
889
+ }
890
+
891
+ metadata_filename = "dataset_metadata.json"
892
+ metadata_path = os.path.join(output_dir, metadata_filename)
893
+ with open(metadata_path, 'w') as f:
894
+ json.dump(dataset_metadata, f, indent=2)
895
+ print(f"✅ Saved FINAL metadata: {metadata_path}")
896
+
897
+ # Summary
898
+ print(f"\n{'='*80}")
899
+ print(f"PROCESSING COMPLETE")
900
+ print(f"{'='*80}")
901
+ print(f"Successfully processed: {len(all_embeddings)}/{len(dicom_dirs)} scans")
902
+ print(f"Failed: {len(failed)}/{len(dicom_dirs)} scans")
903
+ print(f"\nEmbeddings array shape: {embeddings_array.shape}")
904
+ print(f"Saved embeddings to: {embeddings_path}")
905
+ print(f"Saved metadata to: {metadata_path}")
906
+
907
+ # Timepoint summary
908
+ timepoint_counts = {}
909
+ for m in all_metadata:
910
+ tp = m.get('timepoint', 'Unknown')
911
+ timepoint_counts[tp] = timepoint_counts.get(tp, 0) + 1
912
+
913
+ if timepoint_counts:
914
+ print(f"\n📅 Timepoint Distribution:")
915
+ for tp in sorted(timepoint_counts.keys(), key=lambda x: (x is None, x)):
916
+ count = timepoint_counts[tp]
917
+ if tp is None:
918
+ print(f" Unknown/Not detected: {count} scans")
919
+ else:
920
+ print(f" {tp}: {count} scans")
921
+
922
+ if failed:
923
+ print(f"\nFailed scans: {len(failed)}")
924
+ for fail_info in failed[:5]: # Show first 5 failures
925
+ print(f" - {fail_info['scan_dir']}")
926
+ print(f" Error: {fail_info['error']}")
927
+ if len(failed) > 5:
928
+ print(f" ... and {len(failed) - 5} more failures")
929
+
930
+ print(f"\n{'='*80}")
931
+ print(f"For downstream training, load embeddings with:")
932
+ print(f" import pandas as pd")
933
+ print(f" import numpy as np")
934
+ print(f" df = pd.read_parquet('{embeddings_path}')")
935
+ print(f" # Total rows: {len(df)}, Total columns: {len(df.columns)}")
936
+ print(f" # Extract embeddings array: embeddings = np.stack(df['embedding'].values)")
937
+ print(f" # Shape: {embeddings_array.shape}")
938
+ print(f" # Access individual: df.loc[0, 'embedding'] -> array of shape ({embedding_dim},)")
939
+ print(f"{'='*80}")