Example #1
0
def ecg_to_dcm(src, dest, extra_ds=dicom.dataset.Dataset(), format_ch='d', callback=None):
    """Convert 12-Lead Electrocardiogram data into DICOM-ECG standard compliant format."""
    # Data values are encoded interleaved. That is:
    # Lead I, II, III, aVR, aVL, aVF, V1, V2, V3, V4, V5, V6, I, II, III, ...
    # The unit of signals collected by the cardiac conduction is: 0.4V/(2^15).
    if not dest:
        dest = fileutil.replace_ext(src, '.dcm')
        
    data_set = ECGDataset(src, '<{}'.format(format_ch * 12), 500,
                          ('I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6'),
                          adjust_callback=callback)
    data_set.update(extra_ds)
    data_set.save_as(dest)
Example #2
0
def main():
    args = _parse_args()

    _load_config(args)
    logger = _get_logger(args)

    if not args.source or not os.path.isfile(args.source):
        logger.error('Invalid source file: {}'.format(args.source))
        _report_error(_ErrorCode.source_file_not_found)

    if not args.target:
        args.target = fileutil.replace_ext(args.source, '.dcm')

    import tempfile
    if args.host:
        fd, dest_dcm = tempfile.mkstemp()
        os.close(fd)
    else:
        dest_dcm = args.target

    import dat2dcm_v2
    from PatientInfoProvider import fetch_patient_info
    try:
        extra_ds = {}
        if args.info:
            extra_ds = fetch_patient_info(args.info,
                                          criteria_arg=args.criteria)
        dat2dcm_v2.ecg_to_dcm(args.source, dest_dcm, extra_ds, args.format)
        logger.info('{} -> {}'.format(args.source, dest_dcm))
    except Exception as exc:
        logger.info('Failed to complete this operation: {} -> {}. {!r}'.format(
            args.source, dest_dcm, exc))
        raise

    if args.host:
        import ftplib

        try:
            with ftplib.FTP() as ftp:
                ftp.connect(args.host, int(args.port, 0) if args.port else 0)
                ftp.login(args.user, args.passwd)
                args.target = os.path.basename(args.target)
                with open(dest_dcm, 'rb') as fp:
                    ftp.storbinary('STOR {}'.format(args.target), fp)
                logger.info('The target file is saved as: {}'.format(
                    args.target))
        except (ftplib.Error, OSError) as e:
            logger.error('{!r}'.format(e))
            _report_error(_ErrorCode.ftp_error)
        finally:
            os.unlink(dest_dcm)
Example #3
0
def fecg_to_dcm(src, dest=None):
    '''Convert Foetus Electrocardiogram data into DICOM-ECG standard compliant format.'''
    # Data values are encoded interleaved. That is:
    # lead 1, 2, 3, 4, 5, 1, 2, ...
    if not dest:
        dest = fileutil.replace_ext(src, '.dcm')

    data_set = DCMECGDataset(src,
                             '<{}'.format('d' * 5),
                             1000,
                             5, ('', '', '', '', ''),
                             adjust_callback=lambda v: int(v * 100),
                             is_12_lead_ecg=False)
    data_set.save_as(dest)
Example #4
0
def ecg_to_dcm(src, dest=None):
    '''Convert 12-Lead Electrocardiogram data into DICOM-ECG standard compliant format.'''
    # Data values are encoded interleaved. That is:
    # Lead I, II, III, aVR, aVL, aVF, V1, V2, V3, V4, V5, V6, I, II, III, ...
    # The unit of signals collected by the cardiac conduction is: 0.4V/(2^15).
    if not dest:
        dest = fileutil.replace_ext(src, '.dcm')

    data_set = DCMECGDataset(src,
                             '<{}'.format('d' * 12),
                             500,
                             12, ('I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1',
                                  'V2', 'V3', 'V4', 'V5', 'V6'),
                             adjust_callback=lambda v: int(v * 1000 / 6))
    data_set.save_as(dest)
Example #5
0
def main():
    args = _parse_args()

    _load_config(args)
    logger = _get_logger(args)

    if not args.source or not os.path.isfile(args.source):
        logger.error('Invalid source file: {}'.format(args.source))
        _report_error(_ErrorCode.source_file_not_found)

    if not args.target:
        args.target = fileutil.replace_ext(args.source, '.dcm')

    import tempfile
    if args.host:
        fd, dest_dcm = tempfile.mkstemp(); os.close(fd)
    else:
        dest_dcm = args.target

    import dat2dcm_v2
    from PatientInfoProvider import fetch_patient_info
    try:
        extra_ds = {}
        if args.info:
            extra_ds = fetch_patient_info(args.info, criteria_arg=args.criteria)
        dat2dcm_v2.ecg_to_dcm(args.source, dest_dcm, extra_ds, args.format)
        logger.info('{} -> {}'.format(args.source, dest_dcm))
    except Exception as exc:
        logger.info('Failed to complete this operation: {} -> {}. {!r}'.format(args.source, dest_dcm, exc))
        raise

    if args.host:
        import ftplib

        try:
            with ftplib.FTP() as ftp:
                ftp.connect(args.host, int(args.port, 0) if args.port else 0)
                ftp.login(args.user, args.passwd)
                args.target = os.path.basename(args.target)
                with open(dest_dcm, 'rb') as fp:
                    ftp.storbinary('STOR {}'.format(args.target), fp)
                logger.info('The target file is saved as: {}'.format(args.target))
        except (ftplib.Error, OSError) as e:
            logger.error('{!r}'.format(e))
            _report_error(_ErrorCode.ftp_error)
        finally:
            os.unlink(dest_dcm)
Example #6
0
def ecg_to_dcm(src, dest=None):
    """Convert 12-Lead Electrocardiogram data into DICOM-ECG standard compliant format."""
    # Data values are encoded interleaved. That is:
    # Lead I, II, III, aVR, aVL, aVF, V1, V2, V3, V4, V5, V6, I, II, III, ...
    # The unit of signals collected by the cardiac conduction is: 0.4V/(2^15).
    if not dest:
        dest = fileutil.replace_ext(src, ".dcm")

    data_set = DCMECGDataset(
        src,
        "<{}".format("d" * 12),
        500,
        12,
        ("I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6"),
        adjust_callback=lambda v: int(v * 1000 / 6),
    )
    data_set.save_as(dest)
Example #7
0
def fecg_to_dcm(src, dest=None):
    """Convert Foetus Electrocardiogram data into DICOM-ECG standard compliant format."""
    # Data values are encoded interleaved. That is:
    # lead 1, 2, 3, 4, 5, 1, 2, ...
    if not dest:
        dest = fileutil.replace_ext(src, ".dcm")

    data_set = DCMECGDataset(
        src,
        "<{}".format("d" * 5),
        1000,
        5,
        ("", "", "", "", ""),
        adjust_callback=lambda v: int(v * 100),
        is_12_lead_ecg=False,
    )
    data_set.save_as(dest)
Example #8
0
import dicom  # [pydicom](http://www.pydicom.org/)

import fileutil
import unpacker

_frozen = hasattr(sys, "frozen") or hasattr(sys, "importers")

if _frozen:
    __file__ = sys.executable  # Fix issue #6
else:
    import warnings  # Fix issue #7

# Fix issue #5
# Don't use os.environ['HOME'], use os.path.expanduser('~') instead.
logger_filename = os.path.join(os.path.expanduser("~"), fileutil.replace_ext(os.path.basename(__file__), ".log"))
logging.basicConfig(level=logging.NOTSET, filename=logger_filename, format="%(asctime)s [%(levelname)s]: %(message)s")
# logging.captureWarnings(True)
logger = logging.getLogger(__name__)


# PS3.16 CID 3001 ECG Leads
CID_3001_for_12_Lead_ECG = {
    "I": ("2:1", "Lead I"),
    "II": ("2:2", "Lead II"),
    "III": ("2:61", "Lead III"),
    "aVR": ("2:62", "aVR, augmented voltage, right"),
    "aVL": ("2:63", "aVL, augmented voltage, left"),
    "aVF": ("2:64", "aVF, augmented voltage, foot"),
    "V1": ("2:3", "Lead V1"),
    "V2": ("2:4", "Lead V2"),
Example #9
0
import fileutil
import unpacker

_frozen = hasattr(sys, 'frozen') or hasattr(sys, 'importers')

if _frozen:
    __file__ = sys.executable  # Fix issue #6
else:
    import warnings  # Fix issue #7

# Fix issue #5
# Don't use os.environ['HOME'], use os.path.expanduser('~') instead.
logger_filename = os.path.join(
    os.path.expanduser('~'),
    fileutil.replace_ext(os.path.basename(__file__), '.log'))
logging.basicConfig(level=logging.NOTSET,
                    filename=logger_filename,
                    format='%(asctime)s [%(levelname)s]: %(message)s')
#logging.captureWarnings(True)
logger = logging.getLogger(__name__)

# PS3.16 CID 3001 ECG Leads
CID_3001_for_12_Lead_ECG = {
    'I': ('2:1', 'Lead I'),
    'II': ('2:2', 'Lead II'),
    'III': ('2:61', 'Lead III'),
    'aVR': ('2:62', 'aVR, augmented voltage, right'),
    'aVL': ('2:63', 'aVL, augmented voltage, left'),
    'aVF': ('2:64', 'aVF, augmented voltage, foot'),
    'V1': ('2:3', 'Lead V1'),
Example #10
0
from flask import Flask, abort, flash, g, redirect, \
     render_template, request, session, url_for

import fileutil

module_path = os.path.dirname(__file__)
path_of = lambda resource: os.path.join(module_path, resource)

# configuration
DATABASE = path_of('data/db/seveny.db')
DEBUG = True
SECRET_KEY = 'haha'

config_envvar = 'FLASK_SETTINGS'
if config_envvar not in os.environ:
    os.environ[config_envvar] = fileutil.replace_ext(__file__, '.cfg')

app = Flask(__name__)
#app.config.from_envvar(config_envvar, slient=True)
app.config.from_object(__name__)


def init_db():
    import contextlib

    with contextlib.closing(connect_db()) as db:
        with app.open_resource(path_of('schema.sql'), mode='r') as fp:
            db.cursor().executescript(fp.read())
        db.commit()

Example #11
0
     render_template, request, session, url_for

import fileutil


module_path = os.path.dirname(__file__)
path_of = lambda resource: os.path.join(module_path, resource)

# configuration
DATABASE = path_of('data/db/seveny.db')
DEBUG = True
SECRET_KEY = 'haha'

config_envvar = 'FLASK_SETTINGS'
if config_envvar not in os.environ:
    os.environ[config_envvar] = fileutil.replace_ext(__file__, '.cfg')

app = Flask(__name__)
#app.config.from_envvar(config_envvar, slient=True)
app.config.from_object(__name__)


def init_db():
    import contextlib

    with contextlib.closing(connect_db()) as db:
        with app.open_resource(path_of('schema.sql'), mode='r') as fp:
            db.cursor().executescript(fp.read())
        db.commit()