__init__.py 18 KB

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