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