__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. """
  2. (c) 2019 Healthcare/IO 1.0
  3. Vanderbilt University Medical Center, Health Information Privacy Laboratory
  4. https://hiplab.mc.vanderbilt.edu/healthcareio
  5. Authors:
  6. Khanhly Nguyen,
  7. Steve L. Nyemba<steve.l.nyemba@vanderbilt.edu>
  8. License:
  9. MIT, terms are available at https://opensource.org/licenses/MIT
  10. This parser was originally written by Khanhly Nguyen for her internship and is intended to parse x12 835,837 and others provided the appropriate configuration
  11. USAGE :
  12. - COMMAND LINE
  13. - EMBEDDED
  14. """
  15. import hashlib
  16. import json
  17. import os
  18. import sys
  19. from itertools import islice
  20. from multiprocessing import Process
  21. import transport
  22. import jsonmerge
  23. import copy
  24. class void :
  25. pass
  26. class Formatters :
  27. def __init__(self):
  28. # self.config = config
  29. self.get = void()
  30. self.get.config = self.get_config
  31. self.parse = void()
  32. self.parse.sv3 = self.sv3
  33. self.parse.sv2 = self.sv2
  34. self.sv2_parser = self.sv2
  35. self.sv3_parser = self.sv3
  36. self.sv3_parse = self.sv3
  37. self.format_proc = self.procedure
  38. self.format_diag = self.diagnosis
  39. self.parse.procedure = self.procedure
  40. self.parse.diagnosis = self.diagnosis
  41. self.parse.date = self.date
  42. self.format_date = self.date
  43. self.format_pos = self.pos
  44. self.format_time = self.time
  45. def split(self,row,sep='*',prefix='HI') :
  46. """
  47. This function is designed to split an x12 row and
  48. """
  49. value = []
  50. if row.startswith(prefix) is False:
  51. for row_value in row.replace('~','').split(sep) :
  52. if '>' in row_value and not row_value.startswith('HC'):
  53. # if row_value.startswith('HC') or row_value.startswith('AD'):
  54. if row_value.startswith('AD'):
  55. value += row_value.split('>')[:2]
  56. pass
  57. else:
  58. value += [row_value]
  59. # value += row_value.split('>') if row.startswith('CLM') is False else [row_value]
  60. else :
  61. value.append(row_value.replace('\n',''))
  62. value = [xchar.replace('\r','') for xchar in value] #row.replace('~','').split(sep)
  63. else:
  64. value = [ [prefix]+ self.split(item,'>') for item in row.replace('~','').split(sep)[1:] ]
  65. return value if type(value) == list and type(value[0]) != list else value[0]
  66. def get_config(self,config,row):
  67. """
  68. This function will return the meaningfull parts of the configuration for a given item
  69. """
  70. _row = list(row) if type(row[0]) == str else list(row[0])
  71. _info = config[_row[0]] if _row[0] in config else {}
  72. _rinfo = {}
  73. key = None
  74. if '@ref' in _info:
  75. keys = list(set(_row) & set(_info['@ref'].keys()))
  76. if keys :
  77. _rinfo = {}
  78. for key in keys :
  79. _rinfo = jsonmerge.merge(_rinfo,_info['@ref'][key])
  80. return _rinfo
  81. # key = key[0]
  82. # return _info['@ref'][key]
  83. else:
  84. return {}
  85. if not _info and 'SIMILAR' in config:
  86. #
  87. # Let's look for the nearest key using the edit distance
  88. if _row[0] in config['SIMILAR'] :
  89. key = config['SIMILAR'][_row[0]]
  90. _info = config[key]
  91. return _info
  92. def hash(self,value):
  93. salt = os.environ['HEALTHCAREIO_SALT'] if 'HEALTHCAREIO_SALT' in os.environ else ''
  94. _value = str(value)+ salt
  95. if sys.version_info[0] > 2 :
  96. return hashlib.md5(_value.encode('utf-8')).hexdigest()
  97. else:
  98. return hashlib.md5(_value).hexdigest()
  99. def suppress (self,value):
  100. return 'N/A'
  101. def date(self,value):
  102. if len(value) > 8 or '-' in value:
  103. value = value.split('-')[0]
  104. if len(value) == 8 :
  105. year = value[:4]
  106. month = value[4:6]
  107. day = value[6:]
  108. return "-".join([year,month,day])[:10] #{"year":year,"month":month,"day":day}
  109. elif len(value) == 6 :
  110. year = '20' + value[:2]
  111. month = value[2:4]
  112. day = value[4:]
  113. #
  114. # We have a date formatting issue
  115. return "-".join([year,month,day])
  116. def time(self,value):
  117. pass
  118. def sv3(self,value):
  119. if '>' in value [1]:
  120. terms = value[1].split('>')
  121. return {'type':terms[0],'code':terms[1],"amount":float(value[2])}
  122. else:
  123. return {"code":value[2],"type":value[1],"amount":float(value[3])}
  124. def sv2(self,value):
  125. #
  126. # @TODO: Sometimes there's a suffix (need to inventory all the variations)
  127. #
  128. if '>' in value or ':' in value:
  129. xchar = '>' if '>' in value else ':'
  130. _values = value.split(xchar)
  131. modifier = {}
  132. if len(_values) > 2 :
  133. modifier= {"code":_values[2]}
  134. if len(_values) > 3 :
  135. modifier['type'] = _values[3]
  136. _value = {"code":_values[1],"type":_values[0]}
  137. if modifier :
  138. _value['modifier'] = modifier
  139. return _value
  140. else:
  141. return value
  142. def procedure(self,value):
  143. for xchar in [':','<','|','>'] :
  144. if xchar in value and len(value.split(xchar)) > 1 :
  145. #_value = {"type":value.split(':')[0].strip(),"code":value.split(':')[1].strip()}
  146. _value = {"type":value.split(xchar)[0].strip(),"code":value.split(xchar)[1].strip()}
  147. if len(value.split(xchar)) >2 :
  148. index = 1;
  149. for modifier in value.split(xchar)[2:] :
  150. _value['modifier_'+str(index)] = modifier
  151. index += 1
  152. break
  153. else:
  154. _value = str(value)
  155. return _value
  156. def diagnosis(self,value):
  157. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  158. def pos(self,value):
  159. """
  160. formatting place of service information within a segment (REF)
  161. @TODO: In order to accomodate the other elements they need to be specified in the configuration
  162. Otherwise it causes problems on export
  163. """
  164. xchar = '>' if '>' in value else ':'
  165. x = value.split(xchar)
  166. x = {"code":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"code":x[0],"indicator":None,"frequency":None}
  167. return x['code']
  168. class Parser (Process):
  169. def __init__(self,path):
  170. """
  171. :path path of the configuration file (it can be absolute)
  172. """
  173. Process.__init__(self)
  174. self.utils = Formatters()
  175. self.get = void()
  176. self.get.value = self.get_map
  177. self.get.default_value = self.get_default_value
  178. _config = json.loads(open(path).read())
  179. self._custom_config = self.get_custom(path)
  180. self.config = _config['parser']
  181. self.store = _config['store']
  182. self.cache = {}
  183. self.files = []
  184. self.set = void()
  185. self.set.files = self.set_files
  186. self.emit = void()
  187. self.emit.pre = None
  188. self.emit.post = None
  189. def get_custom(self,path) :
  190. """
  191. :path path of the configuration file (it can be absolute)
  192. """
  193. #
  194. #
  195. _path = path.replace('config.json','')
  196. if _path.endswith(os.sep) :
  197. _path = _path[:-1]
  198. _config = {}
  199. _path = os.sep.join([_path,'custom'])
  200. if os.path.exists(_path) :
  201. files = os.listdir(_path)
  202. if files :
  203. fullname = os.sep.join([_path,files[0]])
  204. _config = json.loads ( (open(fullname)).read() )
  205. return _config
  206. def set_files(self,files):
  207. self.files = files
  208. def get_map(self,row,config,version=None):
  209. # label = config['label'] if 'label' in config else None
  210. handler = Formatters()
  211. if 'map' not in config and hasattr(handler,config['apply']):
  212. pointer = getattr(handler,config['apply'])
  213. object_value = pointer(row)
  214. return object_value
  215. #
  216. # Pull the goto configuration that skips rows
  217. #
  218. omap = config['map'] if not version or version not in config else config[version]
  219. anchors = config['anchors'] if 'anchors' in config else []
  220. rewrite = config['rewrite'] if 'rewrite' in config else {}
  221. if type(row[0]) == str:
  222. object_value = {}
  223. for key in omap :
  224. index = omap[key]
  225. if anchors and set(anchors) & set(row):
  226. _key = list(set(anchors) & set(row))[0]
  227. aindex = row.index(_key)
  228. index = aindex + index
  229. if index < len(row) :
  230. value = row[index]
  231. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  232. if config['cast'][key] in ['float','int'] :
  233. value = eval(config['cast'][key])(value)
  234. elif hasattr(handler,config['cast'][key]):
  235. pointer = getattr(handler,config['cast'][key])
  236. value = pointer(value)
  237. else:
  238. print ("Missing Pointer ",key,config['cast'])
  239. if type(value) == dict :
  240. for objkey in value :
  241. if type(value[objkey]) == dict :
  242. continue
  243. if 'syn' in config and value[objkey] in config['syn'] :
  244. # value[objkey] = config['syn'][ value[objkey]]
  245. pass
  246. if key in rewrite :
  247. _key = rewrite[key]
  248. if _key in value :
  249. value = value[_key]
  250. else:
  251. value = ""
  252. value = {key:value} if key not in value else value
  253. else:
  254. if 'syn' in config and value in config['syn'] :
  255. # value = config['syn'][value]
  256. pass
  257. if type(value) == dict :
  258. # object_value = dict(object_value, **value)
  259. object_value = jsonmerge.merge(object_value, value)
  260. else:
  261. object_value[key] = value
  262. else:
  263. #
  264. # we are dealing with a complex object
  265. object_value = []
  266. for row_item in row :
  267. value = self.get.value(row_item,config,version)
  268. object_value.append(value)
  269. #
  270. # We need to add the index of the object it matters in determining the claim types
  271. #
  272. # object_value.append( list(get_map(row_item,config,version)))
  273. # object_value = {label:object_value}
  274. return object_value
  275. def set_cache(self,tmp,_info) :
  276. """
  277. insert into cache a value that the, these are in reference to a loop
  278. """
  279. if 'cache' in _info :
  280. key = _info['cache']['key']
  281. value=_info['cache']['value']
  282. field = _info['cache']['field']
  283. if value in tmp :
  284. self.cache [key] = {field:tmp[value]}
  285. pass
  286. def get_cache(self,row) :
  287. """
  288. retrieve cache element for a current
  289. """
  290. key = row[0]
  291. return self.cache[key] if key in self.cache else {}
  292. def apply(self,content,_code) :
  293. """
  294. :content content of a file i.e a segment with the envelope
  295. :_code 837 or 835 (helps get the appropriate configuration)
  296. """
  297. util = Formatters()
  298. # header = default_value.copy()
  299. value = {}
  300. for row in content[:] :
  301. row = util.split(row.replace('\n','').replace('~',''))
  302. _info = util.get.config(self.config[_code][0],row)
  303. if self._custom_config and _code in self._custom_config:
  304. _cinfo = util.get.config(self._custom_config[_code],row)
  305. else:
  306. _cinfo = {}
  307. if _info or _cinfo:
  308. try:
  309. _info = jsonmerge.merge(_info,_cinfo)
  310. tmp = self.get.value(row,_info)
  311. if not tmp :
  312. continue
  313. #
  314. # At this point we have the configuration and the row parsed into values
  315. # We should check to see if we don't have anything in the cache to be added to it
  316. #
  317. if row[0] in self.cache :
  318. tmp = jsonmerge.merge(tmp,self.get_cache(row))
  319. if 'label' in _info :
  320. label = _info['label']
  321. if type(tmp) == list :
  322. value[label] = tmp if label not in value else value[label] + tmp
  323. else:
  324. # if 'DTM' in row :
  325. # print ([label,tmp,label in value])
  326. if label not in value :
  327. value[label] = []
  328. value[label].append(tmp)
  329. # if label not in value:
  330. # value[label] = [tmp]
  331. # else:
  332. # value[label].append(tmp)
  333. if '_index' not in tmp :
  334. #
  335. # In case we asked it to be overriden, then this will not apply
  336. # X12 occasionally requires references to other elements in a loop (alas)
  337. #
  338. tmp['_index'] = len(value[label]) -1
  339. elif 'field' in _info :
  340. name = _info['field']
  341. # value[name] = tmp
  342. # value = jsonmerge.merge(value,{name:tmp})
  343. value = dict(value,**{name:tmp})
  344. else:
  345. value = dict(value,**tmp)
  346. pass
  347. except Exception as e :
  348. print (e.args[0])
  349. # print ('__',(dir(e.args)))
  350. pass
  351. #
  352. # At this point the object is completely built,
  353. # if there ar any attributes to be cached it will be done here
  354. #
  355. if 'cache' in _info :
  356. self.set_cache(tmp,_info)
  357. return value if value else {}
  358. def get_default_value(self,content,_code):
  359. util = Formatters()
  360. TOP_ROW = content[1].split('*')
  361. SUBMITTED_DATE = util.parse.date(TOP_ROW[4])
  362. CATEGORY= content[2].split('*')[1].strip()
  363. VERSION = content[1].split('*')[-1].replace('~','').replace('\n','')
  364. SENDER_ID = TOP_ROW[2]
  365. row = util.split(content[3])
  366. _info = util.get_config(self.config[_code][0],row)
  367. value = self.get.value(row,_info,VERSION) if _info else {}
  368. value['category'] = {"setid": _code,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  369. value["submitted"] = SUBMITTED_DATE
  370. value['sender_id'] = SENDER_ID
  371. value = dict(value,**self.apply(content,_code))
  372. # Let's parse this for default values
  373. return value #jsonmerge.merge(value,self.apply(content,_code))
  374. def read(self,filename) :
  375. """
  376. :formerly get_content
  377. This function returns the of the EDI file parsed given the configuration specified. it is capable of identifying a file given the content
  378. :section loop prefix (HL, CLP)
  379. :config configuration with formatting rules, labels ...
  380. :filename location of the file
  381. """
  382. # section = section if section else config['SECTION']
  383. logs = []
  384. claims = []
  385. try:
  386. self.cache = {}
  387. file = open(filename.strip())
  388. file = file.read().split('CLP')
  389. _code = '835'
  390. section = 'CLP'
  391. if len(file) == 1 :
  392. file = file[0].split('CLM')
  393. _code = '837'
  394. section = 'HL'
  395. INITIAL_ROWS = file[0].split(section)[0].split('\n')
  396. if len(INITIAL_ROWS) == 1 :
  397. INITIAL_ROWS = INITIAL_ROWS[0].split('~')
  398. # for item in file[1:] :
  399. # item = item.replace('~','\n')
  400. # print (INITIAL_ROWS)
  401. DEFAULT_VALUE = self.get.default_value(INITIAL_ROWS,_code)
  402. DEFAULT_VALUE['name'] = filename.strip()
  403. file = section.join(file).split('\n')
  404. if len(file) == 1:
  405. file = file[0].split('~')
  406. #
  407. # In the initial rows, there's redundant information (so much for x12 standard)
  408. # index 1 identifies file type i.e CLM for claim and CLP for remittance
  409. segment = []
  410. index = 0;
  411. _toprows = []
  412. _default = None
  413. for row in file :
  414. row = row.replace('\r','')
  415. # if not segment and not row.startswith(section):
  416. # _toprows += [row]
  417. if row.startswith(section) and not segment:
  418. segment = [row]
  419. continue
  420. elif segment and not row.startswith(section):
  421. segment.append(row)
  422. if len(segment) > 1 and row.startswith(section):
  423. #
  424. # process the segment somewhere (create a thread maybe?)
  425. #
  426. _claim = self.apply(segment,_code)
  427. if _claim :
  428. _claim['index'] = index #len(claims)
  429. # claims.append(dict(DEFAULT_VALUE,**_claim))
  430. #
  431. # schema = [ {key:{"mergeStrategy":"append" if list( type(_claim[key])) else "overwrite"}} for key in _claim.keys()] # if type(_claim[key]) == list]
  432. # _schema = set(DEFAULT_VALUE.keys()) - schema
  433. # if schema :
  434. # schema = {"properties":dict.fromkeys(schema,{"mergeStrategy":"append"})}
  435. # else:
  436. # schema = {"properties":{}}
  437. # schema = jsonmerge.merge(schema['properties'],dict.fromkeys(_schema,{"mergeStrategy":"overwrite"}))
  438. schema = {"properties":{}}
  439. for attr in _claim.keys() :
  440. schema['properties'][attr] = {"mergeStrategy": "append" if type(_claim[attr]) == list else "overwrite" }
  441. merger = jsonmerge.Merger(schema)
  442. _baseclaim = None
  443. _baseclaim = merger.merge(_baseclaim,copy.deepcopy(DEFAULT_VALUE))
  444. _claim = merger.merge(_baseclaim,_claim)
  445. # _claim = merger.merge(DEFAULT_VALUE.copy(),_claim)
  446. claims.append( _claim)
  447. segment = [row]
  448. index += 1
  449. pass
  450. #
  451. # Handling the last claim found
  452. if segment and segment[0].startswith(section) :
  453. # default_claim = dict({"name":index},**DEFAULT_VALUE)
  454. claim = self.apply(segment,_code)
  455. if claim :
  456. claim['index'] = len(claims)
  457. # schema = [key for key in claim.keys() if type(claim[key]) == list]
  458. # if schema :
  459. # schema = {"properties":dict.fromkeys(schema,{"mergeStrategy":"append"})}
  460. # else:
  461. # print (claim.keys())
  462. # schema = {}
  463. #
  464. # @TODO: Fix merger related to schema (drops certain fields ... NOT cool)
  465. # merger = jsonmerge.Merger(schema)
  466. # top_row_claim = self.apply(_toprows,_code)
  467. # claim = merger.merge(claim,self.apply(_toprows,_code))
  468. # claims.append(dict(DEFAULT_VALUE,**claim))
  469. schema = {"properties":{}}
  470. for attr in claim.keys() :
  471. schema['properties'][attr] = {"mergeStrategy": "append" if type(claim[attr]) == list else "overwrite" }
  472. merger = jsonmerge.Merger(schema)
  473. _baseclaim = None
  474. _baseclaim = merger.merge(_baseclaim,copy.deepcopy(DEFAULT_VALUE))
  475. claim = merger.merge(_baseclaim,claim)
  476. claims.append(claim)
  477. # claims.append(merger.merge(DEFAULT_VALUE.copy(),claim))
  478. if type(file) != list :
  479. file.close()
  480. # x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  481. except Exception as e:
  482. logs.append ({"parse":_code,"completed":False,"name":filename,"msg":e.args[0]})
  483. return [],logs,None
  484. rate = 0 if len(claims) == 0 else (1 + index)/len(claims)
  485. logs.append ({"parse":"claims" if _code == '837' else 'remits',"completed":True,"name":filename,"rate":rate})
  486. # self.finish(claims,logs,_code)
  487. return claims,logs,_code
  488. def run(self):
  489. if self.emit.pre :
  490. self.emit.pre()
  491. for filename in self.files :
  492. content,logs,_code = self.read(filename)
  493. self.finish(content,logs,_code)
  494. def finish(self,content,logs,_code) :
  495. args = self.store
  496. _args = json.loads(json.dumps(self.store))
  497. if args['type'] == 'mongo.MongoWriter' :
  498. args['args']['doc'] = 'claims' if _code == '837' else 'remits'
  499. _args['args']['doc'] = 'logs'
  500. else:
  501. args['args']['table'] = 'claims' if _code == '837' else 'remits'
  502. _args['args']['table'] = 'logs'
  503. if content :
  504. writer = transport.factory.instance(**args)
  505. writer.write(content)
  506. writer.close()
  507. if logs :
  508. logger = transport.factory.instance(**_args)
  509. logger.write(logs)
  510. logger.close()
  511. if self.emit.post :
  512. self.emit.post(content,logs)