SreekarB commited on
Commit
e4a92db
·
verified ·
1 Parent(s): eb5080c

Upload 4 files

Browse files
Files changed (2) hide show
  1. app.py +63 -47
  2. data_preprocessing.py +59 -1
app.py CHANGED
@@ -2215,7 +2215,7 @@ def create_interface():
2215
  try:
2216
  # Start by setting up data for the VAE
2217
  from vae_model import DemoVAE
2218
- from data_preprocessing import load_and_preprocess_data
2219
  from main import run_analysis
2220
  import numpy as np
2221
  import os
@@ -2231,36 +2231,52 @@ def create_interface():
2231
  logger.info("Looking for data in directory and preprocessing...")
2232
 
2233
  # This part is similar to app.train_models but only focuses on VAE
2234
- if data_dir == "SreekarB/OSFData1":
2235
- # Use dataset, similar to existing code in app.train_models
2236
- # For brevity, we'll call the full train_models function but only
2237
- # extract the VAE-related results
2238
- results = app.train_models(
2239
- data_dir=data_dir,
2240
- latent_dim=latent_dim,
2241
- nepochs=nepochs,
2242
- bsize=bsize,
2243
- num_samples=num_samples
2244
- )
2245
-
2246
- # Store results in app_state for the next tabs
2247
- app_state['vae'] = results.get('vae', None)
2248
- app_state['latents'] = results.get('latents', None)
2249
- app_state['demographics'] = results.get('demographics', None)
2250
- app_state['vae_trained'] = True
2251
-
2252
- # Process VAE results with data preference
2253
- fc_figure, learning_fig = process_vae_results(
2254
- results,
2255
- prefer_real_data=prefer_real_data,
2256
- use_synthetic_nifti=use_synthetic_nifti,
2257
- use_synthetic_fc=use_synthetic_fc
2258
- )
2259
-
2260
- # Return the visualizations
2261
- return [fc_figure, learning_fig]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2262
  else:
2263
- # Local directory case
2264
  results = app.train_models(
2265
  data_dir=data_dir,
2266
  latent_dim=latent_dim,
@@ -2268,23 +2284,23 @@ def create_interface():
2268
  bsize=bsize,
2269
  num_samples=num_samples
2270
  )
2271
-
2272
- # Store results in app_state
2273
- app_state['vae'] = results.get('vae', None)
2274
- app_state['latents'] = results.get('latents', None)
2275
- app_state['demographics'] = results.get('demographics', None)
2276
- app_state['vae_trained'] = True
2277
-
2278
- # Process VAE results with data preference
2279
- fc_figure, learning_fig = process_vae_results(
2280
- results,
2281
- prefer_real_data=prefer_real_data,
2282
- use_synthetic_nifti=use_synthetic_nifti,
2283
- use_synthetic_fc=use_synthetic_fc
2284
- )
2285
-
2286
- # Return the visualizations
2287
- return [fc_figure, learning_fig]
2288
  except Exception as e:
2289
  logger.error(f"Error in VAE training: {str(e)}", exc_info=True)
2290
  error_fig = plt.figure(figsize=(10, 6))
 
2215
  try:
2216
  # Start by setting up data for the VAE
2217
  from vae_model import DemoVAE
2218
+ from data_preprocessing import load_and_preprocess_data, download_and_cache_dataset
2219
  from main import run_analysis
2220
  import numpy as np
2221
  import os
 
2231
  logger.info("Looking for data in directory and preprocessing...")
2232
 
2233
  # This part is similar to app.train_models but only focuses on VAE
2234
+ if data_dir == "SreekarB/OSFData1" and use_hf_dataset:
2235
+ # Use our improved download and cache function for HuggingFace datasets
2236
+ logger.info(f"Using improved HuggingFace dataset caching for {data_dir}")
2237
+ try:
2238
+ # Get the dataset and cached NIfTI files
2239
+ _, _, nii_files = download_and_cache_dataset(data_dir)
2240
+
2241
+ if nii_files and len(nii_files) > 0:
2242
+ logger.info(f"Successfully found {len(nii_files)} NIfTI files in dataset cache")
2243
+
2244
+ # Limit to the specified number of samples if needed
2245
+ if num_samples is not None and len(nii_files) > num_samples:
2246
+ logger.info(f"Limiting to {num_samples} NIfTI files as specified")
2247
+ nii_files = nii_files[:num_samples]
2248
+
2249
+ # Use the cached files in the train_models function
2250
+ results = app.train_models(
2251
+ data_dir=data_dir,
2252
+ latent_dim=latent_dim,
2253
+ nepochs=nepochs,
2254
+ bsize=bsize,
2255
+ num_samples=num_samples,
2256
+ hf_nii_files=nii_files # Use our cached files
2257
+ )
2258
+ else:
2259
+ # Fallback to standard train_models
2260
+ logger.warning("No NIfTI files found in cache, using standard train_models")
2261
+ results = app.train_models(
2262
+ data_dir=data_dir,
2263
+ latent_dim=latent_dim,
2264
+ nepochs=nepochs,
2265
+ bsize=bsize,
2266
+ num_samples=num_samples
2267
+ )
2268
+ except Exception as cache_err:
2269
+ logger.error(f"Error using cached dataset: {cache_err}")
2270
+ # Fallback to standard train_models
2271
+ results = app.train_models(
2272
+ data_dir=data_dir,
2273
+ latent_dim=latent_dim,
2274
+ nepochs=nepochs,
2275
+ bsize=bsize,
2276
+ num_samples=num_samples
2277
+ )
2278
  else:
2279
+ # Local directory case or non-HuggingFace dataset
2280
  results = app.train_models(
2281
  data_dir=data_dir,
2282
  latent_dim=latent_dim,
 
2284
  bsize=bsize,
2285
  num_samples=num_samples
2286
  )
2287
+
2288
+ # Store results in app_state
2289
+ app_state['vae'] = results.get('vae', None)
2290
+ app_state['latents'] = results.get('latents', None)
2291
+ app_state['demographics'] = results.get('demographics', None)
2292
+ app_state['vae_trained'] = True
2293
+
2294
+ # Process VAE results with data preference
2295
+ fc_figure, learning_fig = process_vae_results(
2296
+ results,
2297
+ prefer_real_data=prefer_real_data,
2298
+ use_synthetic_nifti=use_synthetic_nifti,
2299
+ use_synthetic_fc=use_synthetic_fc
2300
+ )
2301
+
2302
+ # Return the visualizations
2303
+ return [fc_figure, learning_fig]
2304
  except Exception as e:
2305
  logger.error(f"Error in VAE training: {str(e)}", exc_info=True)
2306
  error_fig = plt.figure(figsize=(10, 6))
data_preprocessing.py CHANGED
@@ -137,6 +137,9 @@ def process_single_fmri(fmri_file, allow_synthetic=False, use_cache=True, try_pr
137
  """
138
  print(f"Processing fMRI file: {fmri_file}")
139
 
 
 
 
140
  # Check if cached FC matrix exists
141
  if use_cache:
142
  file_hash = get_file_hash(fmri_file)
@@ -334,6 +337,7 @@ def process_single_fmri(fmri_file, allow_synthetic=False, use_cache=True, try_pr
334
 
335
  # Import nilearn preprocessing
336
  from nilearn import image
 
337
 
338
  # Load the image
339
  orig_img = load_img(fmri_file)
@@ -346,7 +350,6 @@ def process_single_fmri(fmri_file, allow_synthetic=False, use_cache=True, try_pr
346
 
347
  # Create a temporary preprocessed file
348
  import tempfile
349
- import os
350
 
351
  # Create a preprocessing directory
352
  preproc_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'preproc')
@@ -742,6 +745,47 @@ def clear_cache(cache_type=None):
742
 
743
  print("Cache clearing complete")
744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745
  def load_and_preprocess_data(data_dir, demographic_file, use_hf_dataset=False,
746
  hf_nii_files=None, hf_demo_data=None, hf_demo_types=None,
747
  max_samples=None):
@@ -796,6 +840,20 @@ def load_and_preprocess_data(data_dir, demographic_file, use_hf_dataset=False,
796
  else:
797
  # No demographic data provided
798
  raise ValueError("No demographic data provided")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
799
 
800
  # Use provided NIfTI files from HuggingFace
801
  if hf_nii_files and len(hf_nii_files) > 0:
 
137
  """
138
  print(f"Processing fMRI file: {fmri_file}")
139
 
140
+ # Make sure os is imported to avoid reference error
141
+ import os
142
+
143
  # Check if cached FC matrix exists
144
  if use_cache:
145
  file_hash = get_file_hash(fmri_file)
 
337
 
338
  # Import nilearn preprocessing
339
  from nilearn import image
340
+ import os # Ensure os is imported again here
341
 
342
  # Load the image
343
  orig_img = load_img(fmri_file)
 
350
 
351
  # Create a temporary preprocessed file
352
  import tempfile
 
353
 
354
  # Create a preprocessing directory
355
  preproc_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'preproc')
 
745
 
746
  print("Cache clearing complete")
747
 
748
+ def download_and_cache_dataset(dataset_name, cache_dir=None):
749
+ """
750
+ Download a dataset from HuggingFace and save it to a local cache.
751
+
752
+ Args:
753
+ dataset_name (str): Name of the dataset on HuggingFace (e.g., 'SreekarB/OSFData1')
754
+ cache_dir (str, optional): Directory to store the cached files. If None, uses the default HuggingFace cache.
755
+
756
+ Returns:
757
+ dataset: The loaded dataset object
758
+ cache_path (str): Path to the cached dataset
759
+ nii_files (list): List of NIfTI file paths found in the dataset
760
+ """
761
+ from datasets import load_dataset
762
+ import os
763
+ from huggingface_hub import HfFolder
764
+
765
+ print(f"Loading dataset: {dataset_name}")
766
+
767
+ # Load the dataset (this will download it if not already cached)
768
+ dataset = load_dataset(dataset_name, cache_dir=cache_dir)
769
+
770
+ # Get the cache directory
771
+ if cache_dir is None:
772
+ cache_dir = os.path.join(HfFolder.get_cache_dir(), "datasets")
773
+
774
+ # The dataset is now cached locally
775
+ dataset_cache_path = os.path.join(cache_dir, dataset_name.replace("/", "--"))
776
+ print(f"Dataset cached at: {dataset_cache_path}")
777
+
778
+ # Locate NIfTI files in the cached dataset
779
+ nii_files = []
780
+ for root, dirs, filenames in os.walk(dataset_cache_path):
781
+ for filename in filenames:
782
+ if filename.endswith('.nii') or filename.endswith('.nii.gz'):
783
+ nii_files.append(os.path.join(root, filename))
784
+
785
+ print(f"Found {len(nii_files)} NIfTI files in dataset cache")
786
+
787
+ return dataset, dataset_cache_path, nii_files
788
+
789
  def load_and_preprocess_data(data_dir, demographic_file, use_hf_dataset=False,
790
  hf_nii_files=None, hf_demo_data=None, hf_demo_types=None,
791
  max_samples=None):
 
840
  else:
841
  # No demographic data provided
842
  raise ValueError("No demographic data provided")
843
+
844
+ # Try to properly access the HuggingFace dataset files
845
+ if not (hf_nii_files and len(hf_nii_files) > 0):
846
+ try:
847
+ print(f"Attempting to download and cache dataset: {data_dir}")
848
+ # Try to load and cache the dataset files
849
+ _, _, nii_files_from_hf = download_and_cache_dataset(data_dir)
850
+
851
+ if nii_files_from_hf and len(nii_files_from_hf) > 0:
852
+ print(f"Successfully found {len(nii_files_from_hf)} NIfTI files in HuggingFace dataset cache")
853
+ hf_nii_files = nii_files_from_hf
854
+ except Exception as e:
855
+ print(f"Error accessing HuggingFace dataset files: {e}")
856
+ hf_nii_files = []
857
 
858
  # Use provided NIfTI files from HuggingFace
859
  if hf_nii_files and len(hf_nii_files) > 0: