Пример #1
0
def run_med_to_csv(file:str=None,out_file:str=None, params:dict=None):
    '''
    Only supports outputing bundles, not individual meds
    :param file: the target input file to be output to CSV, or ALL
    :param out_file: basename to be used for file outputs, can be None: default name will be used
    :param params: Customization parameters for the CSV output
    :param incr: Number of medications to be saved per file (not rows)
    :return:
    '''
    smoresLog.debug('Preparing to generate CSV')
    incr = int(util.read_config_value('OUTPUT_CONF')['file_size_max'])
    csv_files = {}
    csv_outputs = params.keys() if params is not None else ''
    if 'detail' in csv_outputs:
        for _d in params['detail'].values():
            base_filename, ext = process_filename(_d['type'])
            csv_files[_d] = {'file': base_filename, 'ext': ext, 'detail': _d}

    if file is not None:
        kits = MedKit.get_medkit(file)
        if type(kits) is dict:
            i=1
            for file, kit in kits.items():
                _file, ext = process_filename(out_file=out_file, info_type=kit.file_name.split('.')[0])
                save_csv_bundle(kit.m_dict, _file, incr=incr, ext=ext)
                i += 1
        else:
            _file, ext = process_filename(out_file=out_file, info_type=kits.file_name.split('.')[0])
            save_csv_bundle(kits.m_dict, _file, incr=incr, ext=ext)

    else:
        smores_error('#Kx001.2')
    return
Пример #2
0
    def process_file(curr_medkit):
        try:
            c_records = 0
            c_dup = 0
            errors = []
            _last = None
            with open(curr_medkit.path, 'r') as file_handle:
                reader = csv.DictReader(file_handle, delimiter=",", skipinitialspace=True)

                for line in tqdm(enumerate(reader), total=curr_medkit.file_lines, desc="Progress", unit=' rows'):
                    _med, _dup, _err, _type = line_read(curr_medkit, line, _last, False)
                    if _med is None:
                        smores_error(_err)
                    elif not _med:
                        pass
                    else:
                        if not _dup:
                            curr_medkit.add_med(_med, _type)
                            c_records += 1
                            _last = _med
                        if _dup:
                            c_dup += 1
                        if len(_err) > 0:
                            errors.append(_err)

        except FileNotFoundError:
            return False, "#Cx001.1"
        except PermissionError:
            return False, "#Cx001.2"
        except BaseException as e:
            print(e)
            return False, None
        else:
            time.sleep(.01) # Clean exit of tqdm
            return {'records': c_records, 'dups': c_dup, 'errors': errors}
Пример #3
0
def load_session(session:str, SMOREs_version:str):
    import pickle
    print('Loading Session...')
    _load_path = Path('../input/')
    input_file = _load_path.joinpath(session)
    filehandler = open(input_file, 'rb')
    try:
        session = pickle.load(filehandler)
        if session['version'] != SMOREs_version:
            print('\nWarning: Version of data loaded from previous session is not the same. Some functionality may not be supported.')
            print('Current: {0}\nLoaded: {1} \n'.format(SMOREs_version, session['version']))
        md_e = md.MedicationDictionary.load_session(session['MedicationDictionary'])
        mk_e = MedKit.load_session(session['MedKit'])
        if len(md_e) == 0 and len(mk_e) == 0:
            print('Success!')
        else:
            # TODO Smores Error Encode
            print('Errors encountered while loading session')
            if len(md_e) > 0:
                print('Medication Dictionaries with Errors: {0}'.format(md_e))
            if len(mk_e) > 0:
                print('Files with Errors: {0}'.format(mk_e))
        if 'date' in session.keys():
            print('\nSession Date: {0}'.format(session['date'].strftime("%Y-%m-%d %H:%M")))
        return list(MedKit.get_medkit().keys())
    except FileNotFoundError:
        smores_error('#Cx001.1')
        return None
    except PermissionError:
        smores_error('#Cx001.2')
        return None
Пример #4
0
    def get_ndc_rxnorm(self, ndc):
        if len(ndc) < 11:
            _zeroes = 11 - len(ndc)
            for i in range(_zeroes):
                ndc = '0' + ndc

        success, response, api_url = self.call_api('NDC_STATUS', ndc)
        e_class = ''
        _r, status, name = (None for i in range(3))
        if success and response is not None:
            APIlog.debug('Good Response from API.')
            try:
                json_detail = response['ndcStatus']
                APIlog.debug(json_detail)
                status = json_detail['status']
                name = str(json_detail['conceptName']) if 'conceptName' in json_detail.keys() else 'UNK'
                _r = [json_detail['rxcui']] if 'rxcui' in json_detail.keys() and response['ndcStatus'] != 'UNKNOWN' else []
                if 'ndcHistory' in json_detail.keys() and len(json_detail['ndcHistory']) > 0:
                    for _mapping in json_detail['ndcHistory']:
                        _actCui = _mapping['activeRxcui']
                        _origCui = _mapping['originalRxcui']
                        if len(_actCui) > 0 and _actCui not in _r:
                            _r.append(_actCui)
                        if len(_origCui) > 0 and _origCui not in _r:
                            _r.append(_origCui)
            except KeyError or IndexError:
                smores_error(self.get_e('1'), api_url, logger=APIlog)
                return False
            else:
                return _r
        else:
            smores_error(self.get_e('1'), api_url, logger=APIlog)
            return None
Пример #5
0
def get_rxn_lookup(medObj: Union[m.Medication, m.LocalMed, m.NDC]):
    """
    DEPRECATED
    Lookup RxCUI for codes from a different source
    :param medObj:
    :return:
    """
    if isinstance(medObj, m.RxCUI):
        smores_error('TBD')
        return 0, []

    success_count, errors = 0, []
    non_rxc_dict = medObj.get_cui_all(omit=['PARENT', 'RXNORM'], inc_obj=True)
    _e = {}
    if len(non_rxc_dict) > 0:
        for src in non_rxc_dict:
            _src_e = []
            _src_s = 0
            for medC, medO in non_rxc_dict[src].items():
                rxc_l = medO.get_linked_cui('RXNORM')
                for _o in rxc_l:
                    if _o is None:
                        _src_e.append(medC)
                    else:
                        _src_s += 1
                        medObj.add_cui(_o)
            success_count += 1 if _src_s > 0 else 0
            if len(_src_e) > 0:
                _e[src] = _src_e
    if len(_e) > 0:
        errors = _e
    return success_count, errors
Пример #6
0
 def get_ndc_base(self, ndc):
     """
     Returns base information on a provided NDC code from the openFDA API
     :param ndc: str of valid NDC format
     :return: NONE or dict{ndc, name, status}
     """
     success, response, api_url = self.call_api('PACK_STATUS', ndc)
     _r, package_ndc, generic, brand, dose, form = (None for i in range(6))
     if success and 'error' not in response.keys():
         results = response['results'][0]
         if len(results['packaging']) > 1:
             for _ndc in results['packaging']:
                 if _ndc['package_ndc'] == ndc:
                     package_ndc = _ndc['package_ndc']
             if package_ndc is None:
                 package_ndc = results['product_ndc']
         else:
             package_ndc = results['packaging'][0]['package_ndc']
         _ndc = self.process_ndc(results)
         _r = {
             'ndc': package_ndc,
             'name': _ndc['name'],
             'status': _ndc['status']
         }
     else:
         smores_error(self.get_e('1'), api_url, logger=APIlog)
     return _r
Пример #7
0
def get_rxn_status(medObj: Union[m.Medication, m.LocalMed, m.RxCUI],
                   api: str = 'RXNAV'):
    '''
    :param med_id: A string representing a medication or a Medication object
    :param med_id_type: Value representing the type/source of the med_id
    :param api: API to call for the rxn_status - Default RXNAV (UMLS may be a secondary option in future)
    :return:
    '''
    # smoresLog.debug('MED_ID: {0} - Source: {1}'.format(med_id, med_id_type))
    if api == 'RXNAV':
        if isinstance(medObj, m.RxCUI):
            if medObj.valid:
                return True, {medObj.cui: medObj.status}
            else:
                return False, {medObj.cui: None}
        else:
            rx_md = medObj.get_dict('RXNORM')
            if rx_md is not None:
                rxc_l = rx_md.get_med_list(inc_obj=True)
                rxc_status = {}
                for cui, RxCUI in rxc_l.items():
                    rxc_status[cui] = RxCUI.get_status()
                return True, rxc_status
            else:
                return False, None
    else:
        smores_error('#Cx004.2', 'Unknown Target')
        return False, None
Пример #8
0
 def get_ndc_product(self, ndc):
     success, response, api_url = self.call_api('PRODUCT', ndc)
     _r, product_ndc, generic, brand, dose, form = (None for i in range(6))
     if success and 'error' not in response.keys():
         results = response['results'][0]
         _r_keys = results.keys()
         try:
             generic = results['generic_name'] if 'generic_name' in _r_keys else False
             brand = results['brand_name'] if 'brand_name' in _r_keys else False
             _dose = [ing['strength'] for ing in
                      results['active_ingredients']] if 'active_ingredients' in _r_keys else False
             form = results['dosage_form']
             dose = '(' + '|'.join(_d for _d in _dose) + ')' if _dose else ''
             if generic and brand:
                 _base = generic + ' [' + brand + ']'
             elif generic:
                 _base = generic
             elif brand:
                 _base = brand
             else:
                 _base = ''
             full_name = ' '.join([_base, dose, form]).upper()
             _list_expire = datetime.strptime(results[
                                                  'listing_expiration_date' if 'listing_expiration_date' in _r_keys else 'marketing_end_date'],
                                              '%Y%m%d')
             _d = datetime.today()
             status = 'valid' if _list_expire > _d else 'expired'
             _r = {'ndc': product_ndc, 'name': full_name, 'status': status}
         except KeyError:
             _r = None
             smores_error(self.get_e('2'), api_url, logger=APIlog)
     else:
         smores_error(self.get_e('1'), api_url, logger=APIlog)
     return _r
Пример #9
0
    def get_cui_status(self, rxcui) -> [bool, str]:
        success, response, api_url = self.call_api('STATUS', rxcui)
        e_index = {'remapped': '5', 'quantified': '7', 'active': '6', 'obsolete': '5', 'retired': '5', 'alien': '4', 'non-rxnorm': '4', 'never%20active': '4', 'unknown': '4'}
        if success and response is not None:
            APIlog.debug('Good Response from API.')
            _r, cui_status = False, None
            try:
                cui_status = str(response['rxcuiStatus']['status']).upper()

                if cui_status.upper() in ['REMAPPED', 'QUANTIFIED', 'ACTIVE', 'OBSOLETE', 'RETIRED'] \
                        and 'minConceptGroup' not in response['rxcuiStatus']:
                    smores_error(self.get_e(e_index[cui_status.lower()]), rxcui, logger=APIlog)
                    _r = True

                elif cui_status.upper() in ['ALIEN', 'NON-RXNORM', ' NEVER%20ACTIVE']:
                    smores_error(self.get_e(e_index[cui_status.lower()]), rxcui, logger=APIlog)
                    _r = False

                elif len(cui_status) == 0 or cui_status.upper() == 'UNKNOWN':
                    smores_error(self.get_e(e_index[cui_status.lower()]), rxcui, logger=APIlog)
                    _r = False
                else:
                    _r = True

            except KeyError or IndexError:
                smores_error(self.get_e(e_index[cui_status.lower()]), api_url,  logger=APIlog)
                return False, None
            else:
                return _r, cui_status
        else:
            smores_error(self.get_e('1'), api_url, logger=APIlog)
            return False, None
Пример #10
0
 def get_cui_base(self, rxcui):
     success, response, api_url = self.call_api('STATUS', rxcui.cui)
     error_index = {
         'Remapped': '5',
         'Quantified': '8',
         'Active': '1',
         'Obsolete': '6',
         'Retired': '5',
         'Alien': '5'
     }
     if success and response is not None:
         APIlog.debug('Good Response from API.')
         try:
             rxcui.set_status(str(response['rxcuiStatus']['status']))
             json_detail = response['rxcuiStatus']['minConceptGroup'][
                 'minConcept'][0]
             APIlog.debug(json_detail)
             rxcui.set_tty(
                 str(json_detail['tty']) if 'tty' in
                 json_detail.keys() else 'UNK')
             rxcui.set_name(
                 str(json_detail['name']) if 'name' in
                 json_detail.keys() else 'UNK')
         except KeyError or IndexError:
             smores_error(self.get_e('2'), api_url, logger=APIlog)
             return False
         else:
             return True
     else:
         smores_error(self.get_e('1'), api_url, logger=APIlog)
         return None
Пример #11
0
    def get_cui_base(self, ndc):
        if len(ndc) < 11:
            _zeroes = 11 - len(ndc)
            for i in range(_zeroes):
                ndc = '0' + ndc

        success, response, api_url = self.call_api('NDC_STATUS', ndc)
        e_class = ''
        _r, status, name = (None for i in range(3))
        if success and response is not None:
            APIlog.debug('Good Response from API.')
            try:
                json_detail = response['ndcStatus']
                APIlog.debug(json_detail)
                status = json_detail['status']
                name = str(json_detail['conceptName']
                           ) if 'conceptName' in json_detail.keys() else 'UNK'
                _r = {'status': status, 'name': name}
            except KeyError or IndexError:
                smores_error(self.get_e('1'), api_url, logger=APIlog)
                return False
            else:
                return _r
        else:
            smores_error(self.get_e('1'), api_url, logger=APIlog)
            return None
Пример #12
0
 def _do_file_load(file: str):
     tic = timeit.default_timer()
     success, result = smores.load_file(file)
     if success:
         self.inputs['loaded'] = True
         self.inputs['files'][file] = {_c: False for _c in self.cmds}
         self.inputs['count'] += result['records']
         toc = timeit.default_timer()
         elapsed = str(round(toc - tic, 2))
         print('\nElapsed Time: ' + str(elapsed) + ' seconds')
         print(
             "\nSuccess! {0} New Medication(s) Successfully Loaded from File"
             .format(result['records']))
         if result['dups'] > 0:
             print(
                 "{0} Duplicate Local ID's were found. New Information "
                 "was added to previous record.".format(
                     str(result['dups'])))
         return result['errors']
     else:
         if result is not None:
             smores_error(result, console_p=True)
         else:
             print('Something went wrong...')
         return
Пример #13
0
    def __init__(self,
                 authuri: str,
                 authendpoint: Union[str, dict],
                 authkey=None,
                 authuser=None,
                 authpwd=None):
        self.auth_param = {}
        self.auth_uri = authuri
        self.auth_ticket = None
        self.auth_ticket_expire = None

        if authkey is not None:
            self.auth_method = 'apikey'
            self.auth_param['apikey'] = authkey
        elif authuser is not None:
            if authpwd is None or len(authpwd) == 0:
                smores_error('{0}{1}.{2}'.format(Authenticate.e_class,
                                                 Authenticate.e_subclass, '2'),
                             logger=APIlog)
            else:
                self.auth_method = 'user'
                self.auth_param['user'] = authuser
                self.auth_param['pwd'] = authpwd
        else:
            self.auth_method = False
            smores_error('{0}{1}.{2}'.format(Authenticate.e_class,
                                             Authenticate.e_subclass, '3'),
                         logger=APIlog)
        self.auth_endpoint = authendpoint if type(
            authendpoint) is str else authendpoint[self.auth_method]
Пример #14
0
    def get_cui_base(self, cui, src: str = 'CUI'):
        """

        :param cui:
        :param src:
        :return: {status , name, }
        """
        if src.upper() in self.valid_codesets or src == 'CUI':
            if src != 'CUI':
                src = 'source/' + src
            _opts = {'ticket': self.get_st(), 'SRC': src}
            success, response, api_url = self.call_api('STATUS', cui, _opts)
            if success and response is not None:
                try:
                    cui_base = {}
                    cui_base['cui'] = response['result']['ui']
                    cui_base['source'] = response['result']['rootSource']
                    cui_base['status'] = 'ACTIVE' if not response['result'][
                        'obsolete'] else 'OBSOLETE'
                    cui_base['name'] = response['result']['name']
                except KeyError or IndexError:
                    smores_error(self.get_e('1'), api_url, logger=APIlog)
                    return False, None
                else:
                    return True, cui_base
            return success, response
        else:
            smores_error(self.get_e('4'), self.api_url, logger=APIlog)
            return False, None
Пример #15
0
def run_med_to_json(med_id=None, med_id_type:str=None, file:str=None,
                    out_file:str=None):
    '''

    :param med_id:
    :param med_id_type:
    :param file:
    :param out_file:
    :param incr:
    :return:
    '''
    smoresLog.debug('Preparing to generate FHIR JSON Files')

    def get_bundle_json(in_dict:md.MedicationDictionary, json_file:str):
        incr = int(util.read_config_value('OUTPUT_CONF')['file_size_max'])
        _total = in_dict.get_med_count()
        _iters = int(math.ceil(_total/incr)) if incr is not None else 1
        _med_list = list(in_dict.med_list.values())
        fhir_construct = {'resourceType': 'Bundle', 'date': datetime.today().strftime('%Y-%m-%d %H:%M:%S%z'), 'total':0, 'entry':[]}
        if _iters > 1:
            _count = 0
            print('Medications will be saved across {0} files.'.format(_iters))
            for i in trange(_iters, desc='File Number', position=0):
                bundle = fhir_construct.copy()
                list_end = _count + incr if (_count + incr) < _total else _total
                _b = [med.get_fhir() for med in _med_list[_count:list_end]]
                bundle['entry'] = _b
                bundle['total'] = list_end - _count
                write_file(output_file=json_file, iter=i+1, data=bundle, ext='json')
                _count += incr
        else:
            bundle = fhir_construct
            for med in _med_list:
                 bundle['entry'].append(med.get_fhir())
                 bundle['total'] += 1
            write_file(output_file=json_file, data=fhir_construct, ext='json')
        return

    def get_single_json(object:m.Medication):
        return object.get_fhir()

    if file is not None:
        kits = MedKit.get_medkit(file)
        if type(kits) is dict:
            i=1
            for file, kit in kits.items():
                _file, _ = process_filename(out_file=out_file, info_type=kit.file_name.split('.')[0])
                get_bundle_json(kit.m_dict, _file)
                i += 1
        else:
            _file, _ = process_filename(out_file=out_file, info_type=kits.file_name.split('.')[0])
            get_bundle_json(kits.m_dict, _file)

    elif med_id is not None and med_id_type is not None:
        med_o = m.get_med_by_id(med_id, file)
        med_o.add_json(get_single_json(med_o))
    else:
        smores_error('#Kx001.2')
    return
Пример #16
0
 def get_endpoint(self, api_call):
     try:
         return self.endpoints[api_call]
     except KeyError:
         smores_error(self.get_e('2', c_ovrd=SMORESapi.e_subclass),
                      [api_call, self.api_name],
                      logger=APIlog)
         return False
Пример #17
0
 def get_ndc_product(self, ndc):
     success, response, api_url = self.call_api('PRODUCT', ndc)
     if success and 'error' not in response.keys():
         results = response['results'][0]
         _r = self.process_ndc(results)
     else:
         smores_error(self.get_e('1'), api_url, logger=APIlog)
     return _r
Пример #18
0
def line_read(medkit, input, last_id=None, skip1=True):
    _n, line = input
    if _n == 0 and skip1:
        return False, False, None, None
    else:
        try:
            config_i_keys = util.read_config_value('INFILE_KEYS')
            i_local_key = config_i_keys['local_id_col_id']
            i_code_key = config_i_keys['code_col_id']
            i_code_type_key = config_i_keys['code_type_col_id']
            i_name_key = config_i_keys['local_name_col_id']
            i_code_name = config_i_keys['code_name_col_id']
        except KeyError as e:
            print(e)
            return None, "#Cx001.6", None, None

        is_dup = False
        has_err = {}
        cui_type = None
        local_id = line[i_local_key]
        if local_id == last_id or m.med_exists(local_id, medkit.file_name):
            temp_med = m.get_med_by_id(local_id, medkit.file_name)
            is_dup = True
        else:
            temp_med = m.LocalMed(input_key=local_id, source=medkit.file_name)

        if len(line[i_code_key]) != 0:
            cui_type = line[i_code_type_key].upper()
            cui_type = 'RXNORM' if cui_type == 'RXCUI' else cui_type  # Prevent automatic fail incase RXCUI instead of RXNORM
            if util.validate_id(line[i_code_key], cui_type):
                # Support for inclusion of local name for local code id's
                if cui_type == 'LOCAL' and not temp_med.isNameSet():
                    temp_med.set_name(line[i_code_name])

                elif cui_type in util.OPTIONS_CUI_TYPES:
                    if i_code_name in line.keys() and len(
                            line[i_code_name]) > 0:
                        _e = temp_med.add_cui(line[i_code_key], cui_type,
                                              line[i_code_name])
                    else:
                        _e = temp_med.add_cui(line[i_code_key], cui_type)
                    if _e > 0:
                        smores_error('#Ax000.1', line[i_local_key])
                        has_err[line[i_code_key]] = "#Ax000.1"

        else:
            smores_error('#Ax000.3', line[i_local_key])
            has_err[line[i_code_key]] = "#Ax000.3"

        if i_name_key in line.keys() and len(line[i_name_key]) > 0:
            clean_rx = r'\\["n]'
            temp_med.set_name(re.sub(clean_rx, '', line[i_name_key]))

        return local_id, is_dup, has_err, cui_type
Пример #19
0
    def call_api(self, call_type, val, c_opt=None):
        if self.last_call is None or ((datetime.today() - self.last_call).total_seconds() * 1000) > self.def_wait:
            pass
        else:
            time.sleep(self.def_wait)
            self.last_call = datetime.today()

        payload = {}
        endpoint = self.get_endpoint(call_type)
        api_call = self.api_url + endpoint['base']

        if endpoint:
            api_call = re.sub(r'\*CODE\*', str(val), api_call)

            for _pl, _p in endpoint['payload'].items():
                if type(_p) is list:
                    if _p[1] == 'PRIMARY':
                        _pl_val = val
                    elif c_opt is not None and _p[1] in c_opt:
                        _pl_val = c_opt[_p[1]]
                    else:
                        smores_error(self.get_e('4', c_ovrd=SMORESapi.e_subclass), [self.api_short, _pl], logger=APIlog)
                        return False
                    payload[_pl] = _p[0] + str(_pl_val)
                else:
                    if _p == 'PRIMARY':
                        _pl_val = val
                    elif c_opt is not None:
                        _pl_val = c_opt
                    elif _p is not None:
                        _pl_val = _p
                    else:
                        smores_error(self.get_e('4', c_ovrd=SMORESapi.e_subclass), [self.api_short, _pl], logger=APIlog)
                        return False
                    payload[_pl] = str(_pl_val)
        else:
            smores_error(self.get_e('2'), [api_call, self.api_name], logger=APIlog)
            return False

        try:
            payload_str = "&".join("%s=%s" % (k, v) for k, v in payload.items())
            response = requests.get(api_call, params=payload_str)
            response.raise_for_status()
            if response.from_cache:
                APIlog.info('API Results from cache: %s', response.url)
            return True, response.json(), response.url
        except (requests.ConnectionError, requests.Timeout) as e:
            smores_error(self.get_e('1', c_ovrd=SMORESapi.e_subclass), [api_call, self.api_name, e], logger=APIlog)
            return False, api_call, None
        except requests.exceptions.HTTPError as e:
            smores_error(self.get_e('3', c_ovrd=SMORESapi.e_subclass), [api_call, self.api_name, e], logger=APIlog)
            return False, api_call, None
Пример #20
0
 def get_remap_cuis(self, rxcui):
     success, response, api_url = self.call_api('STATUS', rxcui)
     remapped = []
     if success and response is not None:
         APIlog.debug('Good Response from API.')
         try:
             json_detail = response['rxcuiStatus']['minConceptGroup']['minConcept']
             remapped = [index['rxcui'] for index in json_detail]
         except KeyError:
             pass
     else:
         smores_error(self.get_e('1'), api_url, logger=APIlog)
     return remapped
Пример #21
0
def run_client_cmd(client_cmd:str, med_id:str=None, med_id_type:str=None, file:str=None):
    client_cmds = {'rxn_status': {'func': get_rxn_status, 'display': 'RxNorm Status', 'restrict': None},
                   'rxn_ing': {'func': get_rxn_ingredients, 'display': 'RxNorm Ingredients', 'restrict': None},
                   'rxn_lookup': {'func': get_rxn_lookup, 'display': 'RxNorm Lookup', 'restrict': None, 'requires': True},
                   'rxn_remap': {'func': get_rxn_remap, 'display': 'Remapped RxNorm', 'restrict': None},
                   'rxn_history': {'func': get_rxn_history,
                                   'display': 'Retired RxNorm History',
                                   'restrict': m.RxCUI.get_historical_list}
                   # 'rxn_search': get_rxn_search
                   }
    try:
        this_cmd = client_cmds[client_cmd]['func']
        this_display = client_cmds[client_cmd]['display']
        this_restriction = client_cmds[client_cmd]['restrict']
        this_cmd_requires = client_cmds[client_cmd]['requires'] if 'requires' in  client_cmds[client_cmd].keys() else None
    except KeyError:
        smores_error('TBD', client_cmd)
        return

    if file is not None:
        if this_cmd_requires:
            if not get_cmd_requirements(client_cmd, file):
                print('Command {0} does not meet the requirements needed to execute the command'.format(client_cmd))
                return 0, [], file
        success_count, errors = 0, []
        if file == 'ALL':
            medkits = MedKit.get_medkit()
            num_kits = len(medkits)
            if num_kits > 1:
                kits_prog = tqdm(total=num_kits, unit='Files')
            for id, kit in medkits.items():
                _c, _e = process_event(kit, this_cmd, this_display, this_restriction)
                success_count += _c
                if len(_e) > 0:
                    errors = errors + _e if type(_e) is list else errors.append(_e)
                if num_kits > 1:
                    kits_prog.update(1)

        else:
            medkit = MedKit.get_medkit(file) if not isinstance(file, MedKit) else file
            success_count, errors = process_event(medkit, this_cmd, this_display, this_restriction)
        return success_count, errors, file

    elif med_id is not None and med_id_type is not None:
        med = m.get_med_by_id(med_id, med_id_type)
        success, error = this_cmd(med_id=med)
        return success, error, med_id

    else:
        smores_error('TBD', client_cmd)
        return 0, [], med_id
Пример #22
0
    def get_ndc_rxnorm(self, ndc):
        success, response, api_url = self.call_api('PACK_STATUS', ndc)
        _r = None
        if success and 'error' not in response.keys():
            results = response['results'][0]
            try:
                _r = results['openfda']['rxcui']
            except KeyError:
                _r = None
                smores_error(self.get_e('2'), api_url, logger=APIlog)
        else:
            smores_error(self.get_e('1'), api_url, logger=APIlog)

        return _r
Пример #23
0
def resolve_target_path(target):
    if ':\\' in target:
        target_path = Path(target).resolve()
    elif 'tests/' in target:
        target_path = Path("..", 'tests', target).resolve()
    else:
        target_path = Path("..", 'input', target).resolve()

    try:
        if target_path.exists():
            return target_path
        else:
            raise FileNotFoundError

    except FileNotFoundError:
        smores_error("#Cx001.1")
        return False
    except PermissionError:
        smores_error('#Cx001.2')
        return False
    except OSError as e:
        smores_error('#Cx001.6', supplement=e, console_p=True)
        return False
    except BaseException as e:
        smores_error('#Cx001.6', supplement=e, console_p=True)
        return False, None
Пример #24
0
 def set_name(self, in_name):
     if len(in_name) > 0 and self.name is None:
         self.name = in_name
     elif in_name != self.name:
         if isinstance(self.name, list):
             self.name.append(in_name)
         else:
             _t = [self.name, in_name]
             self.name = _t
     elif in_name == self.name:
         pass
     else:
         self.name = "#Mx002.2"
         smores_error('#Mx002.2')
Пример #25
0
 def get_ndc_base(self, ndc):
     """
     Returns base information on a provided NDC code from the openFDA API
     :param ndc: str of valid NDC format
     :return: NONE or dict{ndc, name, status}
     """
     success, response, api_url = self.call_api('PACK_STATUS', ndc)
     _r, package_ndc, generic, brand, dose, form = (None for i in range(6))
     if success and 'error' not in response.keys():
         results = response['results'][0]
         _r_keys = results.keys()
         if len(results['packaging']) > 1:
             for _ndc in results['packaging']:
                 if _ndc['package_ndc'] == ndc:
                     package_ndc = _ndc['package_ndc']
             if package_ndc is None:
                 package_ndc = results['product_ndc']
         else:
             package_ndc = results['packaging'][0]['package_ndc']
         generic = results[
             'generic_name'] if 'generic_name' in _r_keys else False
         brand = results['brand_name'] if 'brand_name' in _r_keys else False
         _dose = [ing['strength'] for ing in results['active_ingredients']
                  ] if 'active_ingredients' in _r_keys else False
         form = results['dosage_form']
         dose = '(' + '|'.join(_d for _d in _dose) + ')' if _dose else ''
         if generic and brand:
             _base = generic + ' [' + brand + ']'
         elif generic:
             _base = generic
         elif brand:
             _base = brand
         else:
             _base = ''
         full_name = ' '.join([_base, dose, form]).upper()
         if 'listing_expiration_date' in _r_keys or 'marketing_end_date' in _r_keys:
             _list_expire = datetime.strptime(
                 results['listing_expiration_date'
                         if 'listing_expiration_date' in
                         _r_keys else 'marketing_end_date'], '%Y%m%d')
         else:
             _list_expire = datetime.strptime('99991231', '%Y%m%d')
         _d = datetime.today()
         status = 'valid' if _list_expire > _d else 'expired'
         _r = {'ndc': package_ndc, 'name': full_name, 'status': status}
     else:
         smores_error(self.get_e('1'), api_url, logger=APIlog)
     return _r
Пример #26
0
    def process_ndc(self, ndc_data):
        try:
            _r_keys = ndc_data.keys()
            if len(_r_keys) == 0:
                return None
            _r, product_ndc, package_ndc, generic, brand, dose, form, unii = (
                None for i in range(8))

            product_ndc = ndc_data[
                'product_ndc'] if 'product_ndc' in _r_keys else False
            generic = ndc_data[
                'generic_name'] if 'generic_name' in _r_keys else False
            brand = ndc_data['brand_name'] if 'brand_name' in _r_keys else False
            _dose = [
                ing['strength'] for ing in ndc_data['active_ingredients']
            ] if 'active_ingredients' in _r_keys else False
            form = ndc_data['dosage_form']
            dose = '(' + '|'.join(_d for _d in _dose) + ')' if _dose else ''
            unii = ndc_data['openfda']['unii']
            package_ndc = ndc_data[
                'packaging'] if 'packaging' in _r_keys else False
            if generic and brand:
                _base = generic + ' [' + brand + ']'
            elif generic:
                _base = generic
            elif brand:
                _base = brand
            else:
                _base = ''
            full_name = ' '.join([_base, dose, form]).upper()
            _list_expire = datetime.strptime(
                ndc_data['listing_expiration_date' if 'listing_expiration_date'
                         in _r_keys else 'marketing_end_date'], '%Y%m%d')
            _d = datetime.today()
            status = 'valid' if _list_expire > _d else 'expired'
            _r = {
                'ndc': product_ndc,
                'name': full_name,
                'status': status,
                'unii': unii
            }
            if package_ndc:
                _r['packaging'] = package_ndc
        except KeyError:
            _r = None
            smores_error(self.get_e('2'), '', logger=APIlog)
        else:
            return _r
Пример #27
0
 def get_status(self):
     if self.status is None:
         valid, status = self.api.get_cui_status(self.cui)
         if valid:
             self.set_status(status)
             return self.status
         else:
             _error = smores_error('#Bx001.3')
             smoresLog.warning(_error + '\n')
     else:
         if not self.valid:
             _error = smores_error('#Bx001.3')
             smoresLog.warning(_error + '\n')
             return None
         else:
             return self.status
Пример #28
0
 def set_status(self, in_status):
     if in_status is not None:
         self.status = in_status.upper()
     else:
         # TODO This error call needs to be refactored
         _error = smores_error('#Bx001.3')
         smoresLog.error(str(_error) + '\n')
Пример #29
0
 def get_file_lines(self) -> int:
     try:
         smoresLog.debug('Getting Number of Lines in File...')
         fp = open(self.path, "r+")
         buf = mmap.mmap(fp.fileno(), 0)
         lines = 0
         while buf.readline():
             lines += 1
         smoresLog.info('File Size of {0} Lines Found...'.format(lines))
         return lines - 1
     except FileNotFoundError:
         smores_error('#Cx001.1')
         return 0
     except PermissionError:
         smores_error('#Cx001.2')
         return 0
Пример #30
0
    def run_cmd(self, arg, cmd_call):
        cmd_func = smores.run_client_cmd
        if len(arg) > 0:
            validated_cui, cui_type = self.validate_args(arg, cmd_call)  #
            if validated_cui is not None:
                id_result = self.run_id_call(cmd_func, cui_type, validated_cui,
                                             cmd_call)
            else:
                id_result = None

            if id_result is not None:
                print('Command Completed: {0}\nResults for {1} {2}'.format(
                    cmd_call, cui_type, validated_cui))
                if type(id_result) is dict:
                    if 'print' in id_result.keys():
                        for rx_c, rx_res in id_result['print'].items():
                            if rx_c == validated_cui:
                                print(' {0}'.format(rx_res))
                            else:
                                print(' {0} : {1}'.format(rx_c, rx_res))
                    else:
                        for rx_k, rx_val in id_result.items():
                            if rx_k == validated_cui:
                                print(rx_val)
                            else:
                                print('{0} : {1}'.format(rx_k, rx_val))
                else:
                    print('Result: {0}'.format(id_result))
            else:
                smores_error('#Cx004.3')

        elif self.inputs['loaded']:
            count_ran, errors, file = self.run_file_call(cmd_func, cmd_call)

            if count_ran is None:
                return
            else:
                self.set_touched(file, cmd_call)
                print('Command {0} Completed for {1} medications'.format(
                    cmd_call, count_ran))

            if len(errors) > 0 and len(errors[0]) > 0:
                self.update_errors(cmd_call, errors)
        else:
            print(
                "No Files Loaded!\nYou Must load a file containing local medications first "
                "or specifiy a specific ID to check")