__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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.files = []
  183. self.set = void()
  184. self.set.files = self.set_files
  185. self.emit = void()
  186. self.emit.pre = None
  187. self.emit.post = None
  188. def get_custom(self,path) :
  189. """
  190. :path path of the configuration file (it can be absolute)
  191. """
  192. #
  193. #
  194. _path = path.replace('config.json','')
  195. if _path.endswith(os.sep) :
  196. _path = _path[:-1]
  197. _config = {}
  198. _path = os.sep.join([_path,'custom'])
  199. if os.path.exists(_path) :
  200. files = os.listdir(_path)
  201. if files :
  202. fullname = os.sep.join([_path,files[0]])
  203. _config = json.loads ( (open(fullname)).read() )
  204. return _config
  205. def set_files(self,files):
  206. self.files = files
  207. def get_map(self,row,config,version=None):
  208. # label = config['label'] if 'label' in config else None
  209. handler = Formatters()
  210. if 'map' not in config and hasattr(handler,config['apply']):
  211. pointer = getattr(handler,config['apply'])
  212. object_value = pointer(row)
  213. return object_value
  214. #
  215. # Pull the goto configuration that skips rows
  216. #
  217. omap = config['map'] if not version or version not in config else config[version]
  218. anchors = config['anchors'] if 'anchors' in config else []
  219. rewrite = config['rewrite'] if 'rewrite' in config else {}
  220. if type(row[0]) == str:
  221. object_value = {}
  222. for key in omap :
  223. index = omap[key]
  224. if anchors and set(anchors) & set(row):
  225. _key = list(set(anchors) & set(row))[0]
  226. aindex = row.index(_key)
  227. index = aindex + index
  228. if index < len(row) :
  229. value = row[index]
  230. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  231. if config['cast'][key] in ['float','int'] :
  232. value = eval(config['cast'][key])(value)
  233. elif hasattr(handler,config['cast'][key]):
  234. pointer = getattr(handler,config['cast'][key])
  235. value = pointer(value)
  236. else:
  237. print ("Missing Pointer ",key,config['cast'])
  238. if type(value) == dict :
  239. for objkey in value :
  240. if type(value[objkey]) == dict :
  241. continue
  242. if 'syn' in config and value[objkey] in config['syn'] :
  243. # value[objkey] = config['syn'][ value[objkey]]
  244. pass
  245. if key in rewrite :
  246. _key = rewrite[key]
  247. if _key in value :
  248. value = value[_key]
  249. else:
  250. value = ""
  251. value = {key:value} if key not in value else value
  252. else:
  253. if 'syn' in config and value in config['syn'] :
  254. # value = config['syn'][value]
  255. pass
  256. if type(value) == dict :
  257. # object_value = dict(object_value, **value)
  258. object_value = jsonmerge.merge(object_value, value)
  259. else:
  260. object_value[key] = value
  261. else:
  262. #
  263. # we are dealing with a complex object
  264. object_value = []
  265. for row_item in row :
  266. value = self.get.value(row_item,config,version)
  267. object_value.append(value)
  268. #
  269. # We need to add the index of the object it matters in determining the claim types
  270. #
  271. # object_value.append( list(get_map(row_item,config,version)))
  272. # object_value = {label:object_value}
  273. return object_value
  274. def apply(self,content,_code) :
  275. """
  276. :content content of a file i.e a segment with the envelope
  277. :_code 837 or 835 (helps get the appropriate configuration)
  278. """
  279. util = Formatters()
  280. # header = default_value.copy()
  281. value = {}
  282. for row in content[:] :
  283. row = util.split(row.replace('\n','').replace('~',''))
  284. _info = util.get.config(self.config[_code][0],row)
  285. if self._custom_config and _code in self._custom_config:
  286. _cinfo = util.get.config(self._custom_config[_code],row)
  287. else:
  288. _cinfo = {}
  289. if _info or _cinfo:
  290. try:
  291. _info = jsonmerge.merge(_info,_cinfo)
  292. tmp = self.get.value(row,_info)
  293. #
  294. # let's prune the objects not found
  295. if not tmp :
  296. continue
  297. if 'label' in _info :
  298. label = _info['label']
  299. if type(tmp) == list :
  300. value[label] = tmp if label not in value else value[label] + tmp
  301. else:
  302. # if 'DTM' in row :
  303. # print ([label,tmp,label in value])
  304. if label not in value :
  305. value[label] = []
  306. value[label].append(tmp)
  307. # if label not in value:
  308. # value[label] = [tmp]
  309. # else:
  310. # value[label].append(tmp)
  311. tmp['_index'] = len(value[label]) -1
  312. elif 'field' in _info :
  313. name = _info['field']
  314. # value[name] = tmp
  315. # value = jsonmerge.merge(value,{name:tmp})
  316. value = dict(value,**{name:tmp})
  317. else:
  318. value = dict(value,**tmp)
  319. pass
  320. except Exception as e :
  321. print (e.args[0])
  322. # print ('__',(dir(e.args)))
  323. pass
  324. return value if value else {}
  325. def get_default_value(self,content,_code):
  326. util = Formatters()
  327. TOP_ROW = content[1].split('*')
  328. SUBMITTED_DATE = util.parse.date(TOP_ROW[4])
  329. CATEGORY= content[2].split('*')[1].strip()
  330. VERSION = content[1].split('*')[-1].replace('~','').replace('\n','')
  331. SENDER_ID = TOP_ROW[2]
  332. row = util.split(content[3])
  333. _info = util.get_config(self.config[_code][0],row)
  334. value = self.get.value(row,_info,VERSION) if _info else {}
  335. value['category'] = {"setid": _code,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  336. value["submitted"] = SUBMITTED_DATE
  337. value['sender_id'] = SENDER_ID
  338. value = dict(value,**self.apply(content,_code))
  339. # Let's parse this for default values
  340. return value #jsonmerge.merge(value,self.apply(content,_code))
  341. def read(self,filename) :
  342. """
  343. :formerly get_content
  344. This function returns the of the EDI file parsed given the configuration specified. it is capable of identifying a file given the content
  345. :section loop prefix (HL, CLP)
  346. :config configuration with formatting rules, labels ...
  347. :filename location of the file
  348. """
  349. # section = section if section else config['SECTION']
  350. logs = []
  351. claims = []
  352. try:
  353. file = open(filename.strip())
  354. file = file.read().split('CLP')
  355. _code = '835'
  356. section = 'CLP'
  357. if len(file) == 1 :
  358. file = file[0].split('CLM')
  359. _code = '837'
  360. section = 'HL'
  361. INITIAL_ROWS = file[0].split(section)[0].split('\n')
  362. if len(INITIAL_ROWS) == 1 :
  363. INITIAL_ROWS = INITIAL_ROWS[0].split('~')
  364. # for item in file[1:] :
  365. # item = item.replace('~','\n')
  366. # print (INITIAL_ROWS)
  367. DEFAULT_VALUE = self.get.default_value(INITIAL_ROWS,_code)
  368. DEFAULT_VALUE['name'] = filename.strip()
  369. file = section.join(file).split('\n')
  370. if len(file) == 1:
  371. file = file[0].split('~')
  372. #
  373. # In the initial rows, there's redundant information (so much for x12 standard)
  374. # index 1 identifies file type i.e CLM for claim and CLP for remittance
  375. segment = []
  376. index = 0;
  377. _toprows = []
  378. _default = None
  379. for row in file :
  380. row = row.replace('\r','')
  381. # if not segment and not row.startswith(section):
  382. # _toprows += [row]
  383. if row.startswith(section) and not segment:
  384. segment = [row]
  385. continue
  386. elif segment and not row.startswith(section):
  387. segment.append(row)
  388. if len(segment) > 1 and row.startswith(section):
  389. #
  390. # process the segment somewhere (create a thread maybe?)
  391. #
  392. _claim = self.apply(segment,_code)
  393. if _claim :
  394. _claim['index'] = index #len(claims)
  395. # claims.append(dict(DEFAULT_VALUE,**_claim))
  396. #
  397. # schema = [ {key:{"mergeStrategy":"append" if list( type(_claim[key])) else "overwrite"}} for key in _claim.keys()] # if type(_claim[key]) == list]
  398. # _schema = set(DEFAULT_VALUE.keys()) - schema
  399. # if schema :
  400. # schema = {"properties":dict.fromkeys(schema,{"mergeStrategy":"append"})}
  401. # else:
  402. # schema = {"properties":{}}
  403. # schema = jsonmerge.merge(schema['properties'],dict.fromkeys(_schema,{"mergeStrategy":"overwrite"}))
  404. schema = {"properties":{}}
  405. for attr in _claim.keys() :
  406. schema['properties'][attr] = {"mergeStrategy": "append" if type(_claim[attr]) == list else "overwrite" }
  407. merger = jsonmerge.Merger(schema)
  408. _baseclaim = None
  409. _baseclaim = merger.merge(_baseclaim,copy.deepcopy(DEFAULT_VALUE))
  410. _claim = merger.merge(_baseclaim,_claim)
  411. # _claim = merger.merge(DEFAULT_VALUE.copy(),_claim)
  412. claims.append( _claim)
  413. segment = [row]
  414. index += 1
  415. pass
  416. #
  417. # Handling the last claim found
  418. if segment and segment[0].startswith(section) :
  419. # default_claim = dict({"name":index},**DEFAULT_VALUE)
  420. claim = self.apply(segment,_code)
  421. if claim :
  422. claim['index'] = len(claims)
  423. # schema = [key for key in claim.keys() if type(claim[key]) == list]
  424. # if schema :
  425. # schema = {"properties":dict.fromkeys(schema,{"mergeStrategy":"append"})}
  426. # else:
  427. # print (claim.keys())
  428. # schema = {}
  429. #
  430. # @TODO: Fix merger related to schema (drops certain fields ... NOT cool)
  431. # merger = jsonmerge.Merger(schema)
  432. # top_row_claim = self.apply(_toprows,_code)
  433. # claim = merger.merge(claim,self.apply(_toprows,_code))
  434. # claims.append(dict(DEFAULT_VALUE,**claim))
  435. schema = {"properties":{}}
  436. for attr in _claim.keys() :
  437. schema['properties'][attr] = {"mergeStrategy": "append" if type(_claim[attr]) == list else "overwrite" }
  438. _baseclaim = None
  439. _baseclaim = merger.merge(_baseclaim,copy.deepcopy(DEFAULT_VALUE))
  440. claim = merger.merge(_baseclaim,claim)
  441. claims.append(claim)
  442. # claims.append(merger.merge(DEFAULT_VALUE.copy(),claim))
  443. if type(file) != list :
  444. file.close()
  445. # x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  446. except Exception as e:
  447. logs.append ({"parse":_code,"completed":False,"name":filename,"msg":e.args[0]})
  448. return [],logs,None
  449. rate = 0 if len(claims) == 0 else (1 + index)/len(claims)
  450. logs.append ({"parse":"claims" if _code == '837' else 'remits',"completed":True,"name":filename,"rate":rate})
  451. # self.finish(claims,logs,_code)
  452. return claims,logs,_code
  453. def run(self):
  454. if self.emit.pre :
  455. self.emit.pre()
  456. for filename in self.files :
  457. content,logs,_code = self.read(filename)
  458. self.finish(content,logs,_code)
  459. def finish(self,content,logs,_code) :
  460. args = self.store
  461. _args = json.loads(json.dumps(self.store))
  462. if args['type'] == 'mongo.MongoWriter' :
  463. args['args']['doc'] = 'claims' if _code == '837' else 'remits'
  464. _args['args']['doc'] = 'logs'
  465. else:
  466. args['args']['table'] = 'claims' if _code == '837' else 'remits'
  467. _args['args']['table'] = 'logs'
  468. if content :
  469. writer = transport.factory.instance(**args)
  470. writer.write(content)
  471. writer.close()
  472. if logs :
  473. logger = transport.factory.instance(**_args)
  474. logger.write(logs)
  475. logger.close()
  476. if self.emit.post :
  477. self.emit.post(content,logs)