parser.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. """
  2. (c) 2019 EDI-Parser 1.0
  3. Vanderbilt University Medical Center, Health Information Privacy Laboratory
  4. https://hiplab.mc.vanderbilt.edu/tools
  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 os
  16. import sys
  17. import hashlib
  18. import json
  19. def split(row,sep='*',prefix='HI'):
  20. """
  21. This function is designed to split an x12 row and
  22. """
  23. if row.startswith(prefix) is False:
  24. value = []
  25. for row_value in row.replace('~','').split(sep) :
  26. if '>' in row_value :
  27. if row_value.startswith('HC') or row_value.startswith('AD'):
  28. value += row_value.split('>')[:2]
  29. else:
  30. value += row_value.split('>') if row.startswith('CLM') is False else [row_value]
  31. else :
  32. value.append(row_value)
  33. return [xchar.replace('\r','') for xchar in value] #row.replace('~','').split(sep)
  34. else:
  35. return [ [prefix]+ split(item,'>') for item in row.replace('~','').split(sep)[1:] ]
  36. def get_config(config,row):
  37. """
  38. This function will return the meaningfull parts of the configuration for a given item
  39. """
  40. _row = list(row) if type(row[0]) == str else list(row[0])
  41. _info = config[_row[0]] if _row[0] in config else {}
  42. key = None
  43. if '@ref' in _info:
  44. key = list(set(_row) & set(_info['@ref'].keys()))
  45. if key :
  46. key = key[0]
  47. return _info['@ref'][key]
  48. else:
  49. return {}
  50. if not _info and 'SIMILAR' in config:
  51. #
  52. # Let's look for the nearest key using the edit distance
  53. if _row[0] in config['SIMILAR'] :
  54. key = config['SIMILAR'][_row[0]]
  55. _info = config[key]
  56. return _info
  57. def hash(value):
  58. salt = os.environ['HEALTHCAREIO_SALT'] if 'HEALTHCAREIO_SALT' in os.environ else ''
  59. _value = str(value)+ salt
  60. if sys.version_info[0] > 2 :
  61. return hashlib.md5(_value.encode('utf-8')).hexdigest()
  62. else:
  63. return hashlib.md5(_value).hexdigest()
  64. def suppress(value):
  65. return 'N/A'
  66. def format_date(value) :
  67. if len(value) == 8 :
  68. year = value[:4]
  69. month = value[4:6]
  70. day = value[6:]
  71. return "-".join([year,month,day])[:10] #{"year":year,"month":month,"day":day}
  72. elif len(value) == 6 :
  73. year = '20' + value[:2]
  74. month = value[2:4]
  75. day = value[4:]
  76. return "-".join([year,month,day])
  77. def format_time(value):
  78. return ":".join([value[:2],value[2:] ])[:5]
  79. def sv2_parse(value):
  80. #
  81. # @TODO: Sometimes there's a suffix (need to inventory all the variations)
  82. #
  83. if '>' in value or ':' in value:
  84. xchar = '>' if '>' in value else ':'
  85. _values = value.split(xchar)
  86. modifier = {}
  87. if len(_values) > 2 :
  88. modifier= {"code":_values[2]}
  89. if len(_values) > 3 :
  90. modifier['type'] = _values[3]
  91. _value = {"code":_values[1],"type":_values[0]}
  92. if modifier :
  93. _value['modifier'] = modifier
  94. return _value
  95. else:
  96. return value
  97. def format_proc(value):
  98. for xchar in [':','<'] :
  99. if xchar in value and len(value.split(xchar)) > 1 :
  100. #_value = {"type":value.split(':')[0].strip(),"code":value.split(':')[1].strip()}
  101. _value = {"type":value.split(xchar)[0].strip(),"code":value.split(xchar)[1].strip()}
  102. break
  103. else:
  104. _value = str(value)
  105. return _value
  106. def format_diag(value):
  107. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  108. def format_pos(value):
  109. xchar = '>' if '>' in value else ':'
  110. x = value.split(xchar)
  111. x = {"code":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"code":x[0],"indicator":None,"frequency":None}
  112. return x
  113. def get_map(row,config,version=None):
  114. label = config['label'] if 'label' in config else None
  115. omap = config['map'] if not version or version not in config else config[version]
  116. anchors = config['anchors'] if 'anchors' in config else []
  117. if type(row[0]) == str:
  118. object_value = {}
  119. for key in omap :
  120. index = omap[key]
  121. if anchors and set(anchors) & set(row):
  122. _key = list(set(anchors) & set(row))[0]
  123. aindex = row.index(_key)
  124. index = aindex + index
  125. if index < len(row) :
  126. value = row[index]
  127. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  128. value = eval(config['cast'][key])(value)
  129. if type(value) == dict :
  130. for objkey in value :
  131. if type(value[objkey]) == dict :
  132. continue
  133. if 'syn' in config and value[objkey] in config['syn'] :
  134. value[objkey] = config['syn'][ value[objkey]]
  135. value = {key:value} if key not in value else value
  136. else:
  137. if 'syn' in config and value in config['syn'] :
  138. value = config['syn'][value]
  139. if type(value) == dict :
  140. object_value = dict(object_value, **value)
  141. else:
  142. object_value[key] = value
  143. else:
  144. #
  145. # we are dealing with a complex object
  146. object_value = []
  147. for row_item in row :
  148. value = get_map(row_item,config,version)
  149. object_value.append(value)
  150. #
  151. # We need to add the index of the object it matters in determining the claim types
  152. #
  153. # object_value.append( list(get_map(row_item,config,version)))
  154. # object_value = {label:object_value}
  155. return object_value
  156. def get_locations(x12_file,section='HL') :
  157. locations = []
  158. for line in x12_file :
  159. if line.strip().startswith(section) :
  160. i = x12_file.index(line)
  161. locations.append(i)
  162. return locations
  163. #def get_claims(filename,config,section) :
  164. def get_content(filename,config,section=None) :
  165. """
  166. This function returns the of the EDI file parsed given the configuration specified
  167. :section loop prefix (HL, CLP)
  168. :config configuration with formatting rules, labels ...
  169. :filename location of the file
  170. """
  171. section = section if section else config['SECTION']
  172. logs = []
  173. try:
  174. x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  175. except Exception as e:
  176. #
  177. # We have an error here that should be logged
  178. if sys.version_info[0] > 2 :
  179. # logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  180. logs.append ({"version":"unknown","filename":filename,"msg":e.args[0]})
  181. else:
  182. # logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  183. logs.append ({"version":"unknown","filename":filename,"msg":e.message})
  184. return [],logs
  185. pass
  186. if len(x12_file) == 1 :
  187. x12_file = x12_file[0].split('~')
  188. #partitions = '\n'.join(x12_file).split(section+'*')
  189. locations = get_locations(x12_file,section)
  190. claims = []
  191. #
  192. # given locations it is possible to build up the partitions (made of segments)
  193. beg = locations [0]
  194. partitions = []
  195. for end in locations[1:] :
  196. partitions.append ("\n".join(x12_file[beg:end]))
  197. beg = end
  198. # VERSION = x12_file[2].split('*')[3].replace('~','')
  199. TOP_ROW = x12_file[1].split('*')
  200. CATEGORY= x12_file[2].split('*')[1].strip()
  201. VERSION = x12_file[1].split('*')[-1].replace('~','')
  202. SUBMITTED_DATE = format_date(TOP_ROW[4])
  203. SENDER_ID = TOP_ROW[2]
  204. row = split(x12_file[3])
  205. _info = get_config(config,row)
  206. _default_value = get_map(row,_info,VERSION) if _info else {}
  207. N = len(locations)
  208. # for index in range(0,N-1):
  209. # beg = locations[index]
  210. # end = locations[index+1]
  211. # claim = {}
  212. for segment in partitions :
  213. claim = {}
  214. # for row in x12_file[beg:end] :
  215. segment = segment.replace('\n','').split('~')
  216. for row in segment :
  217. row = split(row)
  218. _info = get_config(config,row)
  219. if _info :
  220. try:
  221. # tmp = get_map(row,_info,VERSION)
  222. # if 'parser' in _info :
  223. # pointer = eval(_info['parser'])
  224. # print (pointer(row))
  225. tmp = get_map(row,_info,VERSION)
  226. except Exception as e:
  227. if sys.version_info[0] > 2 :
  228. # logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  229. logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":row,"completed":False,"rows":len(row)})
  230. else:
  231. # logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  232. logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":row,"rows":len(row),"completed":False})
  233. claim = {}
  234. break
  235. if 'label' not in _info :
  236. tmp['version'] = VERSION
  237. tmp['submitted'] = SUBMITTED_DATE
  238. if TOP_ROW[1] == 'HP' :
  239. tmp['payer_id'] = SENDER_ID
  240. elif TOP_ROW[1] == 'HC':
  241. tmp['provider_id'] = SENDER_ID
  242. tmp['category'] = {"setid": CATEGORY,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  243. claim = dict(claim, **tmp)
  244. else:
  245. label = _info['label']
  246. if type(tmp) == list :
  247. claim[label] = tmp if label not in claim else claim[label] + tmp
  248. else:
  249. if label not in claim:
  250. claim[label] = [tmp]
  251. elif len(list(tmp.keys())) == 1 :
  252. # print "\t",len(claim[label]),tmp
  253. index = len(claim[label]) -1
  254. claim[label][index] = dict(claim[label][index],**tmp)
  255. else:
  256. claim[label].append(tmp)
  257. if len(claim[label]) > 0 :
  258. labels = []
  259. for item in claim[label] :
  260. item['_index'] = len(labels)
  261. if item not in labels :
  262. labels.append(item)
  263. claim[label] = labels
  264. # claim[label] = list( set(claim[label])) #-- removing redundancies
  265. if claim and 'claim_id' in claim:
  266. claim = dict(claim,**_default_value)
  267. claim['name'] = filename.split(os.sep)[-1] #.replace(ROOT,'')
  268. claim['index'] = len(claims) if len(claims) > 0 else 0
  269. claims.append(claim)
  270. else:
  271. #
  272. # Could not find claim identifier associated with data
  273. #
  274. pass
  275. return claims,logs