def run(self, scan_info, scan_obj):
        """ main function to run on scan """
        if not len(scan_obj.resource(self.resourcename).files().get()) > 0:
            LOGGER.warn('Preview NIFTI -- '+scan_info['scan_id']+' -- No file(s) for '+self.resourcename)
        else:
            LOGGER.debug("downloading "+self.resourcename+"...")

            fpath = XnatUtils.download_biggest_file_from_obj(self.directory, scan_obj.resource(self.resourcename))

            if not os.path.exists(fpath):
                LOGGER.warn('Preview NIFTI -- '+scan_info['scan_id']+' -- '+self.resourcename+' file size is zero.')
            else:
                sm_gif = str(os.path.join(self.directory, os.path.splitext(os.path.basename(fpath))[0] + "_sm.gif"))
                lg_gif = str(os.path.join(self.directory, os.path.splitext(os.path.basename(fpath))[0] + "_lg.gif"))

                # Generate preview from the nifti file
                self.generate_preview(fpath, sm_gif, lg_gif)

                if os.path.isfile(sm_gif):
                    LOGGER.debug('GIF Made / upload ...')
                    scan_obj.resource('SNAPSHOTS').file('snap_t.gif').put(sm_gif, 'GIF', 'THUMBNAIL')
                    scan_obj.resource('SNAPSHOTS').file('snap.gif').put(lg_gif, 'GIF', 'ORIGINAL')
                else:
                    LOGGER.error('Preview NIFTI -- '+scan_info['scan_id']+' -- GIF FAILED')
                    self.log_warning_error('GIF failed for NIFTI', scan_info, error=True)

                self.clean_directory()
示例#2
0
def make_preview_nifti(xnat, options):
    """generate previewe for a project on XNAT."""
    # make directory
    if not os.path.exists(options.directory):
        os.makedirs(options.directory)

    # list of scans for the project
    list_scans = XnatUtils.list_project_scans(xnat, options.project)
    # filter the list to keep scans with DICOM and no NIFTI
    if not options.force:
        print "Filtering scans to keep scans with NIFTI but no SNAPSHOTS."
        list_scans = filter(lambda x: 'NIFTI' in x['resources'] and
                                      'SNAPSHOTS' not in x['resources'],
                            list_scans)
    # if sessions, filter:
    if options.sessions:
        list_scans = filter(
            lambda x: x['session_label'] in options.sessions.split(','),
            list_scans)
    number_scans = len(list_scans)
    for index, scan in enumerate(sorted(list_scans,
                                        key=lambda k: k['session_label'])):
        message = ' * {index}/{total} -- Session: {session} -- Scan: {scan}'
        print message.format(index=index+1,
                             total=number_scans,
                             session=scan['session_label'],
                             scan=scan['ID'])
        scan_obj = XnatUtils.get_full_object(xnat, scan)

        res_obj = scan_obj.resource(options.resource)
        if res_obj.exists() and len(res_obj.files().get()) > 0:
            if options.force and scan_obj.resource("SNAPSHOTS").exists():
                scan_obj.resource("SNAPSHOTS").delete()
            print "   --> downloading "+options.resource+" ..."
            filename = XnatUtils.download_biggest_file_from_obj(
                                            options.directory, res_obj)
            if not filename:
                print '    - warning: '+options.resource+' -- no files.'
            else:
                if filename.endswith('.nii.gz'):
                    os.system('gzip -d '+filename)
                    filename = filename[:-3]
                fname = os.path.basename(filename).split('.')[0] + "_sm.gif"
                smgif = os.path.join(options.directory, fname)
                fname = os.path.basename(filename).split('.')[0] + "_lg.gif"
                lggif = os.path.join(options.directory, fname)

                status = generate_preview(filename, smgif, lggif)

                if not status:
                    print '   --> GIF FAILED'
                else:
                    if os.path.isfile(smgif):
                        print '   --> GIF Made / upload to XNAT...'
                        scan_obj.resource('SNAPSHOTS').file('snap_t.gif')\
                                .put(smgif, 'GIF', 'THUMBNAIL')
                        scan_obj.resource('SNAPSHOTS').file('snap.gif')\
                                .put(lggif, 'GIF', 'ORIGINAL')
                    else:
                        print '   --> GIF FAILED'

                    if os.path.isfile(smgif):
                        os.remove(smgif)
                        os.remove(lggif)

                if os.path.isfile(filename):
                    os.remove(filename)
        else:
            print("    - ERROR : issue with resource %s: no file or resource. "
                  % (options.resource))
    for SCAN in SCANS:
        NEED_PAR = False
        NEED_REC = True
        sys.stdout.write('Checking scan %s in session %s\n' % (SCAN['ID'], SCAN['session_label']))
        if 'DICOM' not in SCAN['resources'] and 'secondary' in SCAN['resources'] and SCAN['ID'] not in KNOWN_IGNORE_LIST \
                and 'superpacs' not in SCAN['type'].lower():
            sys.stdout.write(' -DICOM not found. Checking to see if PAR and REC do\n')
            if 'PAR' not in SCAN['resources']:
                sys.stdout.write('  -PAR not found. Marked for upload\n')
                NEED_PAR = True
            if 'REC' not in SCAN['resources']:
                sys.stdout.write('  -REC not found. Marked for upload\n')
                NEED_REC = True
            SCAN_OBJECT = XnatUtils.get_full_object(XNAT, SCAN)
            if SCAN_OBJECT.exists():
                DL_FILE = XnatUtils.download_biggest_file_from_obj('/tmp', SCAN_OBJECT.resource('secondary'))
                ZIP_FILE_NAME = DL_FILE.replace('.dcm', '.ZIP')
                os.rename(DL_FILE, ZIP_FILE_NAME)
                sys.stdout.write('   -Got file %s\n' % ZIP_FILE_NAME)
                TEMP_DIR_LOCATION = os.path.join('/tmp', '-x-'.join([SCAN['session_label'], SCAN['ID']]))

                if not os.path.isdir(TEMP_DIR_LOCATION):
                    os.makedirs(TEMP_DIR_LOCATION)
                else:
                    shutil.rmtree(TEMP_DIR_LOCATION)
                    os.makedirs(TEMP_DIR_LOCATION)

                TMP_DIR_LIST.append(TEMP_DIR_LOCATION)
                sys.stdout.write('  -Extracting all resources to %s\n' % TEMP_DIR_LOCATION)
                try:
                    ZIP_FILE = zipfile.ZipFile(ZIP_FILE_NAME)