__init__.py 18 KB

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