|
| 1 | +""" |
| 2 | +An interface to access OpenNeuro data and metadata. It can download |
| 3 | +and cache OpenNeuro data for playback. |
| 4 | +""" |
| 5 | +import os |
| 6 | +import json |
| 7 | +import boto3 |
| 8 | +from botocore.config import Config |
| 9 | +from botocore import UNSIGNED |
| 10 | +import rtCommon.utils as utils |
| 11 | + |
| 12 | + |
| 13 | +class OpenNeuroCache(): |
| 14 | + def __init__(self, cachePath="/tmp/openneuro/"): |
| 15 | + self.cachePath = cachePath |
| 16 | + self.datasetList = None |
| 17 | + self.s3Client = None |
| 18 | + os.makedirs(cachePath, exist_ok = True) |
| 19 | + |
| 20 | + def getCachePath(self): |
| 21 | + return self.cachePath |
| 22 | + |
| 23 | + def getS3Client(self): |
| 24 | + """Returns an s3 client in order to reuse the same s3 client without |
| 25 | + always creating a new one. Not thread safe currently. |
| 26 | + """ |
| 27 | + if self.s3Client is None: |
| 28 | + self.s3Client = boto3.client("s3", config=Config(signature_version=UNSIGNED)) |
| 29 | + return self.s3Client |
| 30 | + |
| 31 | + def getDatasetList(self, refresh=False): |
| 32 | + """ |
| 33 | + Returns a list of all datasets available in OpenNeuro S3 storage |
| 34 | + "See https://openneuro.org/public/datasets for datasets info" |
| 35 | + Alternate method to access from a command line call: |
| 36 | + aws s3 --no-sign-request ls s3://openneuro.org/ |
| 37 | + """ |
| 38 | + if self.datasetList is None or len(self.datasetList)==0 or refresh is True: |
| 39 | + s3Client = boto3.client("s3", config=Config(signature_version=UNSIGNED)) |
| 40 | + all_datasets = s3Client.list_objects(Bucket='openneuro.org', Delimiter="/") |
| 41 | + self.datasetList = [] |
| 42 | + for dataset in all_datasets.get('CommonPrefixes'): |
| 43 | + dsetName = dataset.get('Prefix') |
| 44 | + # strip trailing slash characters |
| 45 | + dsetName = dsetName.rstrip('/\\') |
| 46 | + self.datasetList.append(dsetName) |
| 47 | + return self.datasetList |
| 48 | + |
| 49 | + def isValidAccessionNumber(self, dsAccessionNum): |
| 50 | + if dsAccessionNum not in self.getDatasetList(): |
| 51 | + print(f"{dsAccessionNum} not in the OpenNeuro S3 datasets.") |
| 52 | + return False |
| 53 | + return True |
| 54 | + |
| 55 | + def getSubjectList(self, dsAccessionNum): |
| 56 | + """ |
| 57 | + Returns a list of all the subjects in a dataset |
| 58 | + Args: |
| 59 | + dsAccessionNum - accession number of dataset to lookup |
| 60 | + Returns: |
| 61 | + list of subjects in that dataset |
| 62 | + """ |
| 63 | + if not self.isValidAccessionNumber(dsAccessionNum): |
| 64 | + return None |
| 65 | + s3 = boto3.client("s3", config=Config(signature_version=UNSIGNED)) |
| 66 | + prefix = dsAccessionNum + '/sub-' |
| 67 | + dsSubjDirs = s3.list_objects(Bucket='openneuro.org', Delimiter="/", Prefix=prefix) |
| 68 | + subjects = [] |
| 69 | + for info in dsSubjDirs.get('CommonPrefixes'): |
| 70 | + subj = info.get('Prefix') |
| 71 | + if subj is not None: |
| 72 | + subj = subj.split('sub-')[1] |
| 73 | + if subj is not None: |
| 74 | + subj = subj.rstrip('/\\') |
| 75 | + subjects.append(subj) |
| 76 | + return subjects |
| 77 | + |
| 78 | + def getDescription(self, dsAccessionNum): |
| 79 | + """ |
| 80 | + Returns the dataset description file as a python dictionary |
| 81 | + """ |
| 82 | + if not self.isValidAccessionNumber(dsAccessionNum): |
| 83 | + return None |
| 84 | + dsDir = self.downloadData(dsAccessionNum, downloadWholeDataset=False) |
| 85 | + filePath = os.path.join(dsDir, 'dataset_description.json') |
| 86 | + descDict = None |
| 87 | + try: |
| 88 | + with open(filePath, 'r') as fp: |
| 89 | + descDict = json.load(fp) |
| 90 | + except Exception as err: |
| 91 | + print(f"Failed to load dataset_description.json: {err}") |
| 92 | + return descDict |
| 93 | + |
| 94 | + def getReadme(self, dsAccessionNum): |
| 95 | + """ |
| 96 | + Return the contents of the dataset README file. |
| 97 | + Downloads toplevel dataset files if needed. |
| 98 | + """ |
| 99 | + if not self.isValidAccessionNumber(dsAccessionNum): |
| 100 | + return None |
| 101 | + dsDir = self.downloadData(dsAccessionNum, downloadWholeDataset=False) |
| 102 | + filePath = os.path.join(dsDir, 'README') |
| 103 | + readme = None |
| 104 | + try: |
| 105 | + readme = utils.readFile(filePath) |
| 106 | + except Exception as err: |
| 107 | + print(f"Failed to load README: {err}") |
| 108 | + return readme |
| 109 | + |
| 110 | + |
| 111 | + def getArchivePath(self, dsAccessionNum): |
| 112 | + """Returns the directory path to the cached dataset files""" |
| 113 | + archivePath = os.path.join(self.cachePath, dsAccessionNum) |
| 114 | + return archivePath |
| 115 | + |
| 116 | + |
| 117 | + def downloadData(self, dsAccessionNum, downloadWholeDataset=False, **entities): |
| 118 | + """ |
| 119 | + This command will sync the specified portion of the dataset to the cache directory. |
| 120 | + Note: if only the accessionNum is supplied then it will just sync the top-level files. |
| 121 | + Sync doesn't re-download files that are already present in the directory. |
| 122 | + Consider using --delete which removes local cache files no longer on the remote. |
| 123 | + Args: |
| 124 | + dsAccessionNum: accession number of the dataset to download data for. |
| 125 | + downloadWholeDataset: boolean, if true all files in the dataset |
| 126 | + will be downloaded. |
| 127 | + entities: BIDS entities (subject, session, task, run, suffix) that |
| 128 | + define the particular subject/run of the data to download. |
| 129 | + Returns: |
| 130 | + Path to the directory containing the downloaded dataset data. |
| 131 | + """ |
| 132 | + if not self.isValidAccessionNumber(dsAccessionNum): |
| 133 | + print(f"{dsAccessionNum} not in the OpenNeuro S3 datasets.") |
| 134 | + return False |
| 135 | + |
| 136 | + includePattern = '' |
| 137 | + if 'subject' in entities: |
| 138 | + subject = entities['subject'] |
| 139 | + if type(subject) is int: |
| 140 | + subject = f'{subject:02d}' |
| 141 | + includePattern += f'sub-{subject}/' |
| 142 | + if 'session' in entities: |
| 143 | + session = entities['session'] |
| 144 | + if includePattern == '': |
| 145 | + includePattern = '*' |
| 146 | + if type(session) is int: |
| 147 | + session = f'{session:02d}' |
| 148 | + includePattern += f'ses-{session}/' |
| 149 | + if 'task' in entities: |
| 150 | + task = entities['task'] |
| 151 | + includePattern += f'*task-{task}' |
| 152 | + if 'run' in entities: |
| 153 | + run = entities['run'] |
| 154 | + if type(run) is int: |
| 155 | + run = f'{run:02d}' |
| 156 | + includePattern += f'*run-{run}' |
| 157 | + if 'suffix' in entities: |
| 158 | + suffix = entities['suffix'] |
| 159 | + includePattern += f'*{suffix}' |
| 160 | + if includePattern != '' or downloadWholeDataset is True: |
| 161 | + includePattern += '*' |
| 162 | + |
| 163 | + datasetDir = os.path.join(self.cachePath, dsAccessionNum) |
| 164 | + awsCmd = f'aws s3 sync --no-sign-request s3://openneuro.org/{dsAccessionNum} ' \ |
| 165 | + f'{datasetDir} --exclude "*/*" --include "{includePattern}"' |
| 166 | + print(f'run {awsCmd}') |
| 167 | + os.system(awsCmd) |
| 168 | + return datasetDir |
| 169 | + |
0 commit comments