__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. """
  147. xchar = '>' if '>' in value else ':'
  148. x = value.split(xchar)
  149. x = {"code":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"code":x[0],"indicator":None,"frequency":None}
  150. return x
  151. class Parser (Process):
  152. def __init__(self,path):
  153. """
  154. :path path of the configuration file (it can be absolute)
  155. """
  156. Process.__init__(self)
  157. self.utils = Formatters()
  158. self.get = void()
  159. self.get.value = self.get_map
  160. self.get.default_value = self.get_default_value
  161. _config = json.loads(open(path).read())
  162. self._custom_config = self.get_custom(path)
  163. self.config = _config['parser']
  164. self.store = _config['store']
  165. self.files = []
  166. self.set = void()
  167. self.set.files = self.set_files
  168. self.emit = void()
  169. self.emit.pre = None
  170. self.emit.post = None
  171. def get_custom(self,path) :
  172. """
  173. :path path of the configuration file (it can be absolute)
  174. """
  175. #
  176. #
  177. _path = path.replace('config.json','')
  178. if _path.endswith(os.sep) :
  179. _path = _path[:-1]
  180. _config = {}
  181. _path = os.sep.join([_path,'custom'])
  182. if os.path.exists(_path) :
  183. files = os.listdir(_path)
  184. if files :
  185. fullname = os.sep.join([_path,files[0]])
  186. _config = json.loads ( (open(fullname)).read() )
  187. return _config
  188. def set_files(self,files):
  189. self.files = files
  190. def get_map(self,row,config,version=None):
  191. # label = config['label'] if 'label' in config else None
  192. handler = Formatters()
  193. if 'map' not in config and hasattr(handler,config['apply']):
  194. pointer = getattr(handler,config['apply'])
  195. object_value = pointer(row)
  196. return object_value
  197. omap = config['map'] if not version or version not in config else config[version]
  198. anchors = config['anchors'] if 'anchors' in config else []
  199. if type(row[0]) == str:
  200. object_value = {}
  201. for key in omap :
  202. index = omap[key]
  203. if anchors and set(anchors) & set(row):
  204. _key = list(set(anchors) & set(row))[0]
  205. aindex = row.index(_key)
  206. index = aindex + index
  207. if index < len(row) :
  208. value = row[index]
  209. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  210. if config['cast'][key] in ['float','int'] :
  211. value = eval(config['cast'][key])(value)
  212. elif hasattr(handler,config['cast'][key]):
  213. pointer = getattr(handler,config['cast'][key])
  214. value = pointer(value)
  215. else:
  216. print ("Missing Pointer ",config['cast'][key])
  217. # print (key,value)
  218. if type(value) == dict :
  219. for objkey in value :
  220. if type(value[objkey]) == dict :
  221. continue
  222. if 'syn' in config and value[objkey] in config['syn'] :
  223. value[objkey] = config['syn'][ value[objkey]]
  224. value = {key:value} if key not in value else value
  225. else:
  226. if 'syn' in config and value in config['syn'] :
  227. value = config['syn'][value]
  228. if type(value) == dict :
  229. object_value = dict(object_value, **value)
  230. else:
  231. object_value[key] = value
  232. else:
  233. #
  234. # we are dealing with a complex object
  235. object_value = []
  236. for row_item in row :
  237. value = self.get.value(row_item,config,version)
  238. object_value.append(value)
  239. #
  240. # We need to add the index of the object it matters in determining the claim types
  241. #
  242. # object_value.append( list(get_map(row_item,config,version)))
  243. # object_value = {label:object_value}
  244. return object_value
  245. def apply(self,content,_code) :
  246. """
  247. :content content of a file i.e a segment with the envelope
  248. :_code 837 or 835 (helps get the appropriate configuration)
  249. """
  250. util = Formatters()
  251. # header = default_value.copy()
  252. value = {}
  253. for row in content[:] :
  254. row = util.split(row.replace('\n','').replace('~',''))
  255. _info = util.get.config(self.config[_code][0],row)
  256. if self._custom_config and _code in self._custom_config:
  257. _cinfo = util.get.config(self._custom_config[_code],row)
  258. else:
  259. _cinfo = {}
  260. # _info = self.consolidate(row=row,type=_code,config=_info,util=util)
  261. # print ([row[0],_info])
  262. # print ()
  263. # continue
  264. # _cinfo = util.get.config(self._custom_config[_code],row)
  265. if _info :
  266. try:
  267. _info = jsonmerge.merge(_info,_cinfo)
  268. tmp = self.get.value(row,_info)
  269. if not tmp :
  270. continue
  271. if 'label' in _info :
  272. label = _info['label']
  273. if type(tmp) == list :
  274. value[label] = tmp if label not in value else value[label] + tmp
  275. else:
  276. if label not in value:
  277. value[label] = [tmp]
  278. # elif len(list(tmp.keys())) == 1 :
  279. # # print "\t",len(claim[label]),tmp
  280. # index = len(value[label]) -1
  281. # value[label][index] = dict(value[label][index],**tmp)
  282. else:
  283. value[label].append(tmp)
  284. tmp['_index'] = len(value[label]) -1
  285. # if len(value[label]) > 0 :
  286. # labels = []
  287. # for item in value[label] :
  288. # item['_index'] = len(labels)
  289. # if item not in labels :
  290. # labels.append(item)
  291. # value[label] = labels
  292. elif 'field' in _info :
  293. name = _info['field']
  294. # value[name] = tmp
  295. value = jsonmerge.merge(value,{name:tmp})
  296. else:
  297. value = dict(value,**tmp)
  298. pass
  299. except Exception as e :
  300. print ('__',e.args)
  301. pass
  302. return value if value else {}
  303. def get_default_value(self,content,_code):
  304. util = Formatters()
  305. TOP_ROW = content[1].split('*')
  306. CATEGORY= content[2].split('*')[1].strip()
  307. VERSION = content[1].split('*')[-1].replace('~','').replace('\n','')
  308. SUBMITTED_DATE = util.parse.date(TOP_ROW[4])
  309. SENDER_ID = TOP_ROW[2]
  310. row = util.split(content[3])
  311. _info = util.get_config(self.config[_code][0],row)
  312. value = self.get.value(row,_info,VERSION) if _info else {}
  313. value['category'] = {"setid": CATEGORY,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  314. value["submitted"] = SUBMITTED_DATE
  315. # value['version'] = VERSION
  316. if _code== '835' :
  317. value['payer_id'] = SENDER_ID
  318. else:
  319. value['provider_id'] = SENDER_ID
  320. #
  321. # Let's parse this for default values
  322. return value
  323. def read(self,filename) :
  324. """
  325. :formerly get_content
  326. This function returns the of the EDI file parsed given the configuration specified. it is capable of identifying a file given the content
  327. :section loop prefix (HL, CLP)
  328. :config configuration with formatting rules, labels ...
  329. :filename location of the file
  330. """
  331. # section = section if section else config['SECTION']
  332. logs = []
  333. claims = []
  334. try:
  335. file = open(filename.strip(),errors='ignore')
  336. INITIAL_ROWS = list(islice(file,4)) #.readlines(4)
  337. _code = "unknown"
  338. if len(INITIAL_ROWS) == 1 :
  339. file = INITIAL_ROWS[0].split('~')
  340. INITIAL_ROWS = file[:4]
  341. if len(INITIAL_ROWS) < 3 :
  342. return None,[{"name":filename,"completed":False}],None
  343. # section = 'HL' if INITIAL_ROWS[1].split('*')[1] == 'HC' else 'CLP'
  344. # _code = '837' if section == 'HL' else '835'
  345. # print ([_code,section])
  346. _code = INITIAL_ROWS[2].split('*')[1].strip()
  347. # section = 'CLP' if _code == '835' else 'HL'
  348. section = self.config[_code][0]['SECTION'].strip()
  349. #
  350. # adjusting the
  351. DEFAULT_VALUE = self.get.default_value(INITIAL_ROWS,_code)
  352. DEFAULT_VALUE['name'] = filename.strip()
  353. #
  354. # In the initial rows, there's redundant information (so much for x12 standard)
  355. # index 1 identifies file type i.e CLM for claim and CLP for remittance
  356. segment = []
  357. index = 0;
  358. _toprows = []
  359. for row in file :
  360. row = row.replace('\r','')
  361. if not segment and not row.startswith(section):
  362. _toprows += [row]
  363. if row.startswith(section) and not segment:
  364. segment = [row]
  365. continue
  366. elif segment and not row.startswith(section):
  367. segment.append(row)
  368. if len(segment) > 1 and row.startswith(section):
  369. #
  370. # process the segment somewhere (create a thread maybe?)
  371. #
  372. # default_claim = dict({"index":index},**DEFAULT_VALUE)
  373. # print (_toprows)
  374. _claim = self.apply(segment,_code)
  375. # if _claim['claim_id'] == 'P1080351470' :
  376. # print (_claim)
  377. # _claim = dict(DEFAULT_VALUE,**_claim)
  378. if _claim :
  379. _claim['index'] = index #len(claims)
  380. claims.append(dict(DEFAULT_VALUE,**_claim))
  381. segment = [row]
  382. index += 1
  383. pass
  384. #
  385. # Handling the last claim found
  386. if segment[0].startswith(section) :
  387. default_claim = dict({"name":index},**DEFAULT_VALUE)
  388. claim = self.apply(segment,_code)
  389. if claim :
  390. claim['index'] = len(claims)
  391. claim = jsonmerge.merge(claim,self.apply(_toprows,_code))
  392. claims.append(dict(DEFAULT_VALUE,**claim))
  393. if type(file) != list :
  394. file.close()
  395. # x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  396. except Exception as e:
  397. logs.append ({"parse":_code,"completed":False,"name":filename,"msg":e.args[0]})
  398. return [],logs,None
  399. rate = 0 if len(claims) == 0 else (1 + index)/len(claims)
  400. logs.append ({"parse":"claims" if _code == '837' else 'remits',"completed":True,"name":filename,"rate":rate})
  401. # self.finish(claims,logs,_code)
  402. return claims,logs,_code
  403. def run(self):
  404. if self.emit.pre :
  405. self.emit.pre()
  406. for filename in self.files :
  407. content,logs,_code = self.read(filename)
  408. self.finish(content,logs,_code)
  409. def finish(self,content,logs,_code) :
  410. args = self.store
  411. _args = json.loads(json.dumps(self.store))
  412. if args['type'] == 'mongo.MongoWriter' :
  413. args['args']['doc'] = 'claims' if _code == '837' else 'remits'
  414. _args['args']['doc'] = 'logs'
  415. else:
  416. args['args']['table'] = 'claims' if _code == '837' else 'remits'
  417. _args['args']['table'] = 'logs'
  418. if content :
  419. writer = transport.factory.instance(**args)
  420. writer.write(content)
  421. writer.close()
  422. if logs :
  423. logger = transport.factory.instance(**_args)
  424. logger.write(logs)
  425. logger.close()
  426. if self.emit.post :
  427. self.emit.post(content,logs)
  428. # p = Parser('/home/steve/.healthcareio/config.json')
  429. # p.set.files(['../../data/small/claims/ssiUB1122042711220427127438.clm_191122T043504'])
  430. # path = '../../data/small/claims/ssiUB1122042711220427127438.clm_191122T043504'
  431. # path = '../../data/small/claims/problems-with-procs'
  432. # path = '../../data/small/remits/1SG03927258.dat_181018T074559'
  433. # _path = "../../data/small/remits/1TR21426701.dat_180703T074559"
  434. # p.start()
  435. # p.join()
  436. # claims,logs = p.read(path)
  437. # print (json.dumps(claims[3]))
  438. # print (logs)