__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. class void :
  24. pass
  25. class Formatters :
  26. def __init__(self):
  27. # self.config = config
  28. self.get = void()
  29. self.get.config = self.get_config
  30. self.parse = void()
  31. self.parse.sv3 = self.sv3
  32. self.parse.sv2 = self.sv2
  33. self.sv2_parse = self.sv2
  34. self.sv3_parse = self.sv3
  35. self.format_proc = self.procedure
  36. self.format_diag = self.diagnosis
  37. self.parse.procedure = self.procedure
  38. self.parse.diagnosis = self.diagnosis
  39. self.parse.date = self.date
  40. self.format_date = self.date
  41. self.format_pos = self.pos
  42. self.format_time = self.time
  43. def split(self,row,sep='*',prefix='HI') :
  44. """
  45. This function is designed to split an x12 row and
  46. """
  47. value = []
  48. if row.startswith(prefix) is False:
  49. for row_value in row.replace('~','').split(sep) :
  50. if '>' in row_value :
  51. if row_value.startswith('HC') or row_value.startswith('AD'):
  52. value += row_value.split('>')[:2]
  53. else:
  54. value += row_value.split('>') if row.startswith('CLM') is False else [row_value]
  55. else :
  56. value.append(row_value.replace('\n',''))
  57. value = [xchar.replace('\r','') for xchar in value] #row.replace('~','').split(sep)
  58. else:
  59. value = [ [prefix]+ self.split(item,'>') for item in row.replace('~','').split(sep)[1:] ]
  60. return value if type(value) == list and type(value[0]) != list else value[0]
  61. def get_config(self,config,row):
  62. """
  63. This function will return the meaningfull parts of the configuration for a given item
  64. """
  65. _row = list(row) if type(row[0]) == str else list(row[0])
  66. _info = config[_row[0]] if _row[0] in config else {}
  67. key = None
  68. if '@ref' in _info:
  69. key = list(set(_row) & set(_info['@ref'].keys()))
  70. if key :
  71. key = key[0]
  72. return _info['@ref'][key]
  73. else:
  74. return {}
  75. if not _info and 'SIMILAR' in config:
  76. #
  77. # Let's look for the nearest key using the edit distance
  78. if _row[0] in config['SIMILAR'] :
  79. key = config['SIMILAR'][_row[0]]
  80. _info = config[key]
  81. return _info
  82. def hash(self,value):
  83. salt = os.environ['HEALTHCAREIO_SALT'] if 'HEALTHCAREIO_SALT' in os.environ else ''
  84. _value = str(value)+ salt
  85. if sys.version_info[0] > 2 :
  86. return hashlib.md5(_value.encode('utf-8')).hexdigest()
  87. else:
  88. return hashlib.md5(_value).hexdigest()
  89. def suppress (self,value):
  90. return 'N/A'
  91. def date(self,value):
  92. if len(value) > 8 or '-' in value:
  93. value = value.split('-')[0]
  94. if len(value) == 8 :
  95. year = value[:4]
  96. month = value[4:6]
  97. day = value[6:]
  98. return "-".join([year,month,day])[:10] #{"year":year,"month":month,"day":day}
  99. elif len(value) == 6 :
  100. year = '20' + value[:2]
  101. month = value[2:4]
  102. day = value[4:]
  103. #
  104. # We have a date formatting issue
  105. return "-".join([year,month,day])
  106. def time(self,value):
  107. pass
  108. def sv3(self,value):
  109. if '>' in value [1]:
  110. terms = value[1].split('>')
  111. return {'type':terms[0],'code':terms[1],"amount":float(value[2])}
  112. else:
  113. return {"code":value[2],"type":value[1],"amount":float(value[3])}
  114. def sv2(self,value):
  115. #
  116. # @TODO: Sometimes there's a suffix (need to inventory all the variations)
  117. #
  118. if '>' in value or ':' in value:
  119. xchar = '>' if '>' in value else ':'
  120. _values = value.split(xchar)
  121. modifier = {}
  122. if len(_values) > 2 :
  123. modifier= {"code":_values[2]}
  124. if len(_values) > 3 :
  125. modifier['type'] = _values[3]
  126. _value = {"code":_values[1],"type":_values[0]}
  127. if modifier :
  128. _value['modifier'] = modifier
  129. return _value
  130. else:
  131. return value
  132. def procedure(self,value):
  133. for xchar in [':','<'] :
  134. if xchar in value and len(value.split(xchar)) > 1 :
  135. #_value = {"type":value.split(':')[0].strip(),"code":value.split(':')[1].strip()}
  136. _value = {"type":value.split(xchar)[0].strip(),"code":value.split(xchar)[1].strip()}
  137. break
  138. else:
  139. _value = str(value)
  140. return _value
  141. def diagnosis(self,alue):
  142. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  143. def pos(self,value):
  144. """
  145. formatting place of service information within a segment (REF)
  146. @TODO: In order to accomodate the other elements they need to be specified in the configuration
  147. Otherwise it causes problems on export
  148. """
  149. xchar = '>' if '>' in value else ':'
  150. x = value.split(xchar)
  151. x = {"code":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"code":x[0],"indicator":None,"frequency":None}
  152. return x['code']
  153. class Parser (Process):
  154. def __init__(self,path):
  155. """
  156. :path path of the configuration file (it can be absolute)
  157. """
  158. Process.__init__(self)
  159. self.utils = Formatters()
  160. self.get = void()
  161. self.get.value = self.get_map
  162. self.get.default_value = self.get_default_value
  163. _config = json.loads(open(path).read())
  164. self._custom_config = self.get_custom(path)
  165. self.config = _config['parser']
  166. self.store = _config['store']
  167. self.files = []
  168. self.set = void()
  169. self.set.files = self.set_files
  170. self.emit = void()
  171. self.emit.pre = None
  172. self.emit.post = None
  173. def get_custom(self,path) :
  174. """
  175. :path path of the configuration file (it can be absolute)
  176. """
  177. #
  178. #
  179. _path = path.replace('config.json','')
  180. if _path.endswith(os.sep) :
  181. _path = _path[:-1]
  182. _config = {}
  183. _path = os.sep.join([_path,'custom'])
  184. if os.path.exists(_path) :
  185. files = os.listdir(_path)
  186. if files :
  187. fullname = os.sep.join([_path,files[0]])
  188. _config = json.loads ( (open(fullname)).read() )
  189. return _config
  190. def set_files(self,files):
  191. self.files = files
  192. def get_map(self,row,config,version=None):
  193. # label = config['label'] if 'label' in config else None
  194. handler = Formatters()
  195. if 'map' not in config and hasattr(handler,config['apply']):
  196. pointer = getattr(handler,config['apply'])
  197. object_value = pointer(row)
  198. return object_value
  199. omap = config['map'] if not version or version not in config else config[version]
  200. anchors = config['anchors'] if 'anchors' in config else []
  201. if type(row[0]) == str:
  202. object_value = {}
  203. for key in omap :
  204. index = omap[key]
  205. if anchors and set(anchors) & set(row):
  206. _key = list(set(anchors) & set(row))[0]
  207. aindex = row.index(_key)
  208. index = aindex + index
  209. if index < len(row) :
  210. value = row[index]
  211. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  212. if config['cast'][key] in ['float','int'] :
  213. value = eval(config['cast'][key])(value)
  214. elif hasattr(handler,config['cast'][key]):
  215. pointer = getattr(handler,config['cast'][key])
  216. value = pointer(value)
  217. else:
  218. print ("Missing Pointer ",config['cast'][key])
  219. # print (key,value)
  220. if type(value) == dict :
  221. for objkey in value :
  222. if type(value[objkey]) == dict :
  223. continue
  224. if 'syn' in config and value[objkey] in config['syn'] :
  225. value[objkey] = config['syn'][ value[objkey]]
  226. value = {key:value} if key not in value else value
  227. else:
  228. if 'syn' in config and value in config['syn'] :
  229. value = config['syn'][value]
  230. if type(value) == dict :
  231. object_value = dict(object_value, **value)
  232. else:
  233. object_value[key] = value
  234. else:
  235. #
  236. # we are dealing with a complex object
  237. object_value = []
  238. for row_item in row :
  239. value = self.get.value(row_item,config,version)
  240. object_value.append(value)
  241. #
  242. # We need to add the index of the object it matters in determining the claim types
  243. #
  244. # object_value.append( list(get_map(row_item,config,version)))
  245. # object_value = {label:object_value}
  246. return object_value
  247. def apply(self,content,_code) :
  248. """
  249. :content content of a file i.e a segment with the envelope
  250. :_code 837 or 835 (helps get the appropriate configuration)
  251. """
  252. util = Formatters()
  253. # header = default_value.copy()
  254. value = {}
  255. for row in content[:] :
  256. row = util.split(row.replace('\n','').replace('~',''))
  257. _info = util.get.config(self.config[_code][0],row)
  258. if self._custom_config and _code in self._custom_config:
  259. _cinfo = util.get.config(self._custom_config[_code],row)
  260. else:
  261. _cinfo = {}
  262. # _info = self.consolidate(row=row,type=_code,config=_info,util=util)
  263. # print ([row[0],_info])
  264. # print ()
  265. # continue
  266. # _cinfo = util.get.config(self._custom_config[_code],row)
  267. if _info :
  268. try:
  269. _info = jsonmerge.merge(_info,_cinfo)
  270. tmp = self.get.value(row,_info)
  271. if not tmp :
  272. continue
  273. if 'label' in _info :
  274. label = _info['label']
  275. if type(tmp) == list :
  276. value[label] = tmp if label not in value else value[label] + tmp
  277. else:
  278. if label not in value:
  279. value[label] = [tmp]
  280. # elif len(list(tmp.keys())) == 1 :
  281. # # print "\t",len(claim[label]),tmp
  282. # index = len(value[label]) -1
  283. # value[label][index] = dict(value[label][index],**tmp)
  284. else:
  285. value[label].append(tmp)
  286. tmp['_index'] = len(value[label]) -1
  287. # if len(value[label]) > 0 :
  288. # labels = []
  289. # for item in value[label] :
  290. # item['_index'] = len(labels)
  291. # if item not in labels :
  292. # labels.append(item)
  293. # value[label] = labels
  294. elif 'field' in _info :
  295. name = _info['field']
  296. # value[name] = tmp
  297. value = jsonmerge.merge(value,{name:tmp})
  298. else:
  299. value = dict(value,**tmp)
  300. pass
  301. except Exception as e :
  302. print ('__',e.args)
  303. pass
  304. return value if value else {}
  305. def get_default_value(self,content,_code):
  306. util = Formatters()
  307. TOP_ROW = content[1].split('*')
  308. CATEGORY= content[2].split('*')[1].strip()
  309. VERSION = content[1].split('*')[-1].replace('~','').replace('\n','')
  310. SUBMITTED_DATE = util.parse.date(TOP_ROW[4])
  311. SENDER_ID = TOP_ROW[2]
  312. row = util.split(content[3])
  313. _info = util.get_config(self.config[_code][0],row)
  314. value = self.get.value(row,_info,VERSION) if _info else {}
  315. value['category'] = {"setid": CATEGORY,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  316. value["submitted"] = SUBMITTED_DATE
  317. # value['version'] = VERSION
  318. if _code== '835' :
  319. value['payer_id'] = SENDER_ID
  320. else:
  321. value['provider_id'] = SENDER_ID
  322. #
  323. # Let's parse this for default values
  324. return value
  325. def read(self,filename) :
  326. """
  327. :formerly get_content
  328. This function returns the of the EDI file parsed given the configuration specified. it is capable of identifying a file given the content
  329. :section loop prefix (HL, CLP)
  330. :config configuration with formatting rules, labels ...
  331. :filename location of the file
  332. """
  333. # section = section if section else config['SECTION']
  334. logs = []
  335. claims = []
  336. try:
  337. file = open(filename.strip(),errors='ignore')
  338. INITIAL_ROWS = list(islice(file,4)) #.readlines(4)
  339. _code = "unknown"
  340. if len(INITIAL_ROWS) == 1 :
  341. file = INITIAL_ROWS[0].split('~')
  342. INITIAL_ROWS = file[:4]
  343. if len(INITIAL_ROWS) < 3 :
  344. return None,[{"name":filename,"completed":False}],None
  345. # section = 'HL' if INITIAL_ROWS[1].split('*')[1] == 'HC' else 'CLP'
  346. # _code = '837' if section == 'HL' else '835'
  347. # print ([_code,section])
  348. _code = INITIAL_ROWS[2].split('*')[1].strip()
  349. # section = 'CLP' if _code == '835' else 'HL'
  350. section = self.config[_code][0]['SECTION'].strip()
  351. #
  352. # adjusting the
  353. DEFAULT_VALUE = self.get.default_value(INITIAL_ROWS,_code)
  354. DEFAULT_VALUE['name'] = filename.strip()
  355. #
  356. # In the initial rows, there's redundant information (so much for x12 standard)
  357. # index 1 identifies file type i.e CLM for claim and CLP for remittance
  358. segment = []
  359. index = 0;
  360. _toprows = []
  361. for row in file :
  362. row = row.replace('\r','')
  363. if not segment and not row.startswith(section):
  364. _toprows += [row]
  365. if row.startswith(section) and not segment:
  366. segment = [row]
  367. continue
  368. elif segment and not row.startswith(section):
  369. segment.append(row)
  370. if len(segment) > 1 and row.startswith(section):
  371. #
  372. # process the segment somewhere (create a thread maybe?)
  373. #
  374. # default_claim = dict({"index":index},**DEFAULT_VALUE)
  375. # print (_toprows)
  376. _claim = self.apply(segment,_code)
  377. # if _claim['claim_id'] == 'P1080351470' :
  378. # print (_claim)
  379. # _claim = dict(DEFAULT_VALUE,**_claim)
  380. if _claim :
  381. _claim['index'] = index #len(claims)
  382. claims.append(dict(DEFAULT_VALUE,**_claim))
  383. segment = [row]
  384. index += 1
  385. pass
  386. #
  387. # Handling the last claim found
  388. if segment[0].startswith(section) :
  389. default_claim = dict({"name":index},**DEFAULT_VALUE)
  390. claim = self.apply(segment,_code)
  391. if claim :
  392. claim['index'] = len(claims)
  393. claim = jsonmerge.merge(claim,self.apply(_toprows,_code))
  394. claims.append(dict(DEFAULT_VALUE,**claim))
  395. if type(file) != list :
  396. file.close()
  397. # x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  398. except Exception as e:
  399. logs.append ({"parse":_code,"completed":False,"name":filename,"msg":e.args[0]})
  400. return [],logs,None
  401. rate = 0 if len(claims) == 0 else (1 + index)/len(claims)
  402. logs.append ({"parse":"claims" if _code == '837' else 'remits',"completed":True,"name":filename,"rate":rate})
  403. # self.finish(claims,logs,_code)
  404. return claims,logs,_code
  405. def run(self):
  406. if self.emit.pre :
  407. self.emit.pre()
  408. for filename in self.files :
  409. content,logs,_code = self.read(filename)
  410. self.finish(content,logs,_code)
  411. def finish(self,content,logs,_code) :
  412. args = self.store
  413. _args = json.loads(json.dumps(self.store))
  414. if args['type'] == 'mongo.MongoWriter' :
  415. args['args']['doc'] = 'claims' if _code == '837' else 'remits'
  416. _args['args']['doc'] = 'logs'
  417. else:
  418. args['args']['table'] = 'claims' if _code == '837' else 'remits'
  419. _args['args']['table'] = 'logs'
  420. if content :
  421. writer = transport.factory.instance(**args)
  422. writer.write(content)
  423. writer.close()
  424. if logs :
  425. logger = transport.factory.instance(**_args)
  426. logger.write(logs)
  427. logger.close()
  428. if self.emit.post :
  429. self.emit.post(content,logs)
  430. # p = Parser('/home/steve/.healthcareio/config.json')
  431. # p.set.files(['../../data/small/claims/ssiUB1122042711220427127438.clm_191122T043504'])
  432. # path = '../../data/small/claims/ssiUB1122042711220427127438.clm_191122T043504'
  433. # path = '../../data/small/claims/problems-with-procs'
  434. # path = '../../data/small/remits/1SG03927258.dat_181018T074559'
  435. # _path = "../../data/small/remits/1TR21426701.dat_180703T074559"
  436. # p.start()
  437. # p.join()
  438. # claims,logs = p.read(path)
  439. # print (json.dumps(claims[3]))
  440. # print (logs)