Example #1
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument('-d',
                            '--dir',
                            metavar='DIR',
                            default='.',
                            help='set working directory [%(default)s]')
    arg_parser.add_argument('-l',
                            '--delay',
                            metavar='X',
                            type=float,
                            default=60.0,
                            help='set checking interval in min [%(default)s]')
    arg_parser.add_argument(
        '-r',
        '--delay_var',
        metavar='DX',
        type=float,
        default=5,
        help='set random variance in the delay as percentage [%(default)s]')
    arg_parser.add_argument(
        '-m',
        '--max_count',
        metavar='NUM',
        type=int,
        default=0,
        help='maximum number of actions to be performed [%(default)s]')
    arg_parser.add_argument(
        '-c',
        '--cmd',
        metavar='EXECUTABLE',
        default=os.path.dirname(__file__) + '/dcm_analyze_dir.py {}',
        help='execute when finding a new dir with DICOMs [%(default)s]')
    return arg_parser
Example #2
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Define DEFAULT values
    # verbosity
    d_verbose = D_VERB_LVL
    # default input directory
    d_input_dir = '.'
    # default output directory
    d_output_dir = '.'
    # default method
    d_method = 'pydicom'
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=d_verbose,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument('-i',
                            '--in_dirpath',
                            metavar='DIR',
                            default=d_input_dir,
                            help='set input directory [%(default)s]')
    arg_parser.add_argument('-o',
                            '--out_dirpath',
                            metavar='DIR',
                            default=d_output_dir,
                            help='set output directory [%(default)s]')
    arg_parser.add_argument('-m',
                            '--method',
                            metavar='METHOD',
                            default=d_method,
                            help='set extraction method [%(default)s]')
    arg_parser.add_argument('-t',
                            '--type_ext',
                            action='store_true',
                            help='add type extension [%(default)s]')
    return arg_parser
Example #3
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument('-i',
                            '--in_dirpath',
                            metavar='DIR',
                            default='.',
                            help='set input directory [%(default)s]')
    arg_parser.add_argument('-o',
                            '--out_dirpath',
                            metavar='DIR',
                            default='.',
                            help='set output directory [%(default)s]')
    arg_parser.add_argument('-b',
                            '--basename',
                            metavar='NAME',
                            default='{name}_{date}_{time}_{sys}',
                            help='set output directory [%(default)s]')
    arg_parser.add_argument('-m',
                            '--method',
                            metavar='METHOD',
                            default='pydicom',
                            help='set extraction method [%(default)s]')
    arg_parser.add_argument('-a',
                            '--file_format',
                            metavar='METHOD',
                            default='pdf',
                            help='set output format [%(default)s]')
    return arg_parser
Example #4
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver', '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v', '--verbose',
        action='count', default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    arg_parser.add_argument(
        '-q', '--quiet',
        action='store_true',
        help='override verbosity settings to suppress output [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument(
        '-f', '--force',
        action='store_true',
        help='force new processing [%(default)s]')
    arg_parser.add_argument(
        '-i', '--in_dirpath', metavar='DIR',
        default='.',
        help='set input directory [%(default)s]')
    arg_parser.add_argument(
        '-o', '--out_dirpath', metavar='DIR',
        default='.',
        help='set output directory [%(default)s]')
    arg_parser.add_argument(
        '-n', '--name', metavar='STR',
        default='{name}_{date}_{time}_{sys}',
        help='set output directory [%(default)s]')
    arg_parser.add_argument(
        '-m', '--method', metavar='tlz|tgz|tbz2|7z|zip|txz',
        default='tlz',
        help='set compression method [%(default)s]')
    arg_parser.add_argument(
        '-k', '--keep',
        action='store_true',
        help='Keep DICOM sources after do_backup (and test). [%(default)s]')
    return arg_parser
Example #5
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver', '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v', '--verbose',
        action='count', default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    arg_parser.add_argument(
        '-q', '--quiet',
        action='store_true',
        help='override verbosity settings to suppress output [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument(
        '-f', '--force',
        action='store_true',
        help='force new processing [%(default)s]')
    arg_parser.add_argument(
        '-i', '--in_dirpath', metavar='DIR',
        default='.',
        help='set input directory [%(default)s]')
    arg_parser.add_argument(
        '-o', '--out_dirpath', metavar='DIR',
        default='.',
        help='set output directory [%(default)s]')
    arg_parser.add_argument(
        '-m', '--method', metavar='copy|move|symlink|link',
        default='symlink',
        help='Move DICOM sources instead of copying [%(default)s]')
    arg_parser.add_argument(
        '-s', '--subpath',
        default='{study}/{name}_{date}_{time}_{sys}',
        help='Append DICOM-generated subpath to output [%(default)s]')
    arg_parser.add_argument(
        '-e', '--extra_subpath',
        default='dcm',
        help='Append static subpath to output [%(default)s]')
    return arg_parser
Example #6
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument('-d',
                            '--dirpath',
                            metavar='DIR',
                            default='.',
                            help='set working directory [%(default)s]')
    arg_parser.add_argument(
        '-m',
        '--match',
        metavar='STR',
        default='{"_concat":"and","OperatorsName":"*****@*****.**"}',
        help='set a match in the DICOM information [%(default)s]')
    arg_parser.add_argument('-a',
                            '--action',
                            metavar='STR',
                            default='email+preprocess',
                            help='set action to perform [%(default)s]')
    return arg_parser
Example #7
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-d',
                            '--dirpath',
                            metavar='DIR',
                            default='.',
                            help='set working directory [%(default)s]')
    arg_parser.add_argument('-c',
                            '--dcm_info',
                            metavar='DIR',
                            default='{'
                            '"PatientID": null, '
                            '"PatientBirthDate": null, '
                            '"PatientName": null}',
                            help='set DICOM fields to update [%(default)s]')
    arg_parser.add_argument(
        '-b',
        '--backup_prefix',
        default=None,
        help='set prefix to be prepended to backup files [%(default)s]')
    return arg_parser
Example #8
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('ui_mode',
                            nargs='?',
                            default='tui',
                            help='set UI mode [%(default)s]')
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument(
        '-c',
        '--config',
        metavar='FILE',
        default=CFG_FILENAME,
        help='set configuration file name/path [%(default)s]')
    return arg_parser
Example #9
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument(
        '-s',
        '--summary',
        default=utl.D_SUMMARY + '.' + utl.EXT['json'],
        help='set expt. summary filepath (empty to skip) [%(default)s]')
    arg_parser.add_argument('-d',
                            '--dirpath',
                            metavar='DIR',
                            default='.',
                            help='set i/o directory path [%(default)s]')
    return arg_parser
Example #10
0
def handle_arg():
    """
    Handle command-line application arguments.
    """
    # :: Create Argument Parser
    arg_parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=fmtm('v.{version} - {author}\n{license}', INFO),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    # :: Add POSIX standard arguments
    arg_parser.add_argument(
        '--ver',
        '--version',
        version=fmt(
            '%(prog)s - ver. {version}\n{}\n{copyright} {author}\n{notice}',
            next(line for line in __doc__.splitlines() if line), **INFO),
        action='version')
    arg_parser.add_argument(
        '-v',
        '--verbose',
        action='count',
        default=D_VERB_LVL,
        help='increase the level of verbosity [%(default)s]')
    # :: Add additional arguments
    arg_parser.add_argument('-f',
                            '--force',
                            action='store_true',
                            help='force new processing [%(default)s]')
    arg_parser.add_argument('-i',
                            '--in_dirpath',
                            metavar='DIR',
                            default='.',
                            help='set input directory [%(default)s]')
    arg_parser.add_argument('-o',
                            '--out_dirpath',
                            metavar='DIR',
                            default='.',
                            help='set output directory [%(default)s]')
    arg_parser.add_argument(
        '-s',
        '--subpath',
        default=utl.TPL['acquire'],
        help='Append DICOM-generated subpath to output [%(default)s]')
    arg_parser.add_argument(
        '-n',
        '--niz_subpath',
        default=utl.ID['niz'],
        help='Sub-path for NIfTI extraction. Empty to skip [%(default)s]')
    arg_parser.add_argument(
        '-m',
        '--meta_subpath',
        default=utl.ID['meta'],
        help='Sub-path for META extraction. Empty to skip [%(default)s]')
    arg_parser.add_argument(
        '-p',
        '--prot_subpath',
        default=utl.ID['prot'],
        help='Sub-path for PROT extraction. Empty to skip [%(default)s]')
    arg_parser.add_argument(
        '-t',
        '--info_subpath',
        default=utl.ID['info'],
        help='Sub-path for INFO extraction. Empty to skip [%(default)s]')
    arg_parser.add_argument(
        '-r',
        '--report_subpath',
        default=utl.TPL['report'],
        help='Template for the report filename. Empty to skip [%(default)s]')
    arg_parser.add_argument(
        '-b',
        '--backup_subpath',
        default=utl.TPL['backup'],
        help='Template for the backup filename. Empty to skip [%(default)s]')
    return arg_parser
Example #11
0
File: util.py Project: norok2/dcmpi
def fill_from_dicom(format_str,
                    filepath,
                    compression=None,
                    extra_fields=False,
                    tmp_path='/tmp'):
    """
    Fill a format string with information from a DICOM file.

    Parameters
    ==========
    format_str : str
        | String used to set a format.
        | Field syntax: [FIELD::FORMAT] (::FORMAT part is optional)
        | Accepted fields (including accepted formats):
        * study : Study Description : 2-int comma-sep. range for slicing.
        * date : Study Date. Format : anything accepted by 'strftime'.
        * time : Study Time. Format : anything accepted by 'strftime'.
        * name : Patient Name. Format : 'mpicbs' to guess ID (only subjects).
        * sys : StationName. Format : 'mpicbs' to guess local names.
    filepath : str
        DICOM file where to get information from.
    compression : str or None (optional)
        Determine the (de)compression method used to access the data.
    extra_fields : bool (optional)
        | If True, accept fields directly from pydcm. No format is supported.
        | Note that this feature MUST be used with care.

    Returns
    =======
    The formatted string.

    """
    fields = {
        'study': (
            'StudyDescription',
            lambda t, f:  # slice according to 2-int tuple set in 'f'
            t[int(f.split(',')[0]):int(f.split(',')[1])] if f else t,
            ''),
        'date':
        ('StudyDate', lambda t, f: time.strftime(f, get_date(t)), '%Y-%m-%d'),
        'time':
        ('StudyTime', lambda t, f: time.strftime(f, get_time(t)), '%H-%M'),
        'name':
        ('PatientName', lambda t, f: t[:4]
         if f == 'mpicbs' and (t[3] == 'T' or t[3] == 'X') else t, 'mpicbs'),
        'sys': ('StationName', lambda t, f: STATION[t]
                if f == 'mpicbs' and t in STATION else t, 'mpicbs'),
    }

    filename = os.path.basename(filepath)
    temp_filepath = os.path.join(tmp_path, filename)
    shutil.copy(filepath, temp_filepath)
    if compression and compression in COMPRESSIONS:
        dcm_filepath = os.path.splitext(temp_filepath)[0]
        cmd = COMPRESSIONS[compression]['bwd'] + ' {}'.format(temp_filepath)
        execute(cmd)
    else:
        dcm_filepath = temp_filepath
    try:
        dcm = pydcm.read_file(dcm_filepath)
    except Exception as e:
        print(e)
        print('E: Could not open DICOM file: {}.'.format(dcm_filepath))
        out_str = ''
    else:
        if extra_fields:
            for item in dir(dcm):
                if item[0].isupper():
                    fields[item] = (item, None, None)
        format_kws = {}
        for field_id, field_formatter in sorted(fields.items()):
            dcm_id, fmt_func, field_fmt = field_formatter
            try:
                format_kws[field_id] = \
                    fmt_func(getattr(dcm, dcm_id), field_fmt) \
                        if fmt_func else getattr(dcm, dcm_id)
            except TypeError:
                format_kws[field_id] = getattr(dcm, dcm_id)
        out_str = fmtm(format_str, format_kws)
    finally:
        if os.path.isfile(temp_filepath):
            os.remove(temp_filepath)
        elif os.path.isfile(dcm_filepath):
            os.remove(dcm_filepath)
    return out_str
Example #12
0
def dcmpi_run(
        in_dirpath,
        out_dirpath,
        subpath=utl.TPL['acquire'],
        dcm_subpath=utl.ID['dicom'],
        niz_subpath=utl.ID['niz'],
        meta_subpath=utl.ID['meta'],
        prot_subpath=utl.ID['prot'],
        info_subpath=utl.ID['info'],
        report_template=utl.TPL['report'],
        backup_template=utl.TPL['backup'],
        actions=ACTIONS,
        force=False,
        verbose=D_VERB_LVL):
    """
    Standard preprocessing of DICOM files.

    Args:
        in_dirpath (str): Path to input directory.
        out_dirpath (str): Path to output directory.
        subpath (str):
        dcm_subpath (str):
        niz_subpath (str):
        meta_subpath (str):
        prot_subpath (str):
        info_subpath (str):
        report_template (str):
        backup_template (str):
        actions (dict):
        force (bool): Force new processing.
        verbose (int): Set level of verbosity.

    Returns:
        None.
    """
    from dcmpi.do_acquire_sources import do_acquire_sources
    from dcmpi.do_sorting import sorting

    # import
    dcm_dirpaths = do_acquire_sources(
        in_dirpath, out_dirpath, 'copy', subpath, dcm_subpath, force, verbose)
    for dcm_dirpath in dcm_dirpaths:
        base_dirpath = os.path.dirname(dcm_dirpath)
        # sort
        sorting(
            dcm_dirpath, utl.D_SUMMARY + '.' + utl.EXT['json'],
            force, verbose)
        # run other actions
        dirpath = {
            'niz': niz_subpath,
            'meta': meta_subpath,
            'prot': prot_subpath,
            'info': info_subpath, }
        dirpath = {
            k: os.path.join(base_dirpath, v) for k, v in dirpath.items() if v}
        for action, (func, kws) in actions.items():
            kws = kws.copy()
            for key, val in kws.items():
                if isinstance(val, str):
                    kws[key] = fmtm(val)
            kws.update(dict(force=force, verbose=verbose))
            try:
                func(**kws)
            except Exception as e:
                warnings.warn(str(e))

        msg('Done: {}'.format(dcm_dirpath))