parser.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 sv3_parse(value):
  80. if '>' in value :
  81. terms = value.split('>')
  82. return {'type':terms[0],'code':terms[1]}
  83. pass
  84. def sv2_parse(value):
  85. #
  86. # @TODO: Sometimes there's a suffix (need to inventory all the variations)
  87. #
  88. if '>' in value or ':' in value:
  89. xchar = '>' if '>' in value else ':'
  90. _values = value.split(xchar)
  91. modifier = {}
  92. if len(_values) > 2 :
  93. modifier= {"code":_values[2]}
  94. if len(_values) > 3 :
  95. modifier['type'] = _values[3]
  96. _value = {"code":_values[1],"type":_values[0]}
  97. if modifier :
  98. _value['modifier'] = modifier
  99. return _value
  100. else:
  101. return value
  102. def format_proc(value):
  103. for xchar in [':','<'] :
  104. if xchar in value and len(value.split(xchar)) > 1 :
  105. #_value = {"type":value.split(':')[0].strip(),"code":value.split(':')[1].strip()}
  106. _value = {"type":value.split(xchar)[0].strip(),"code":value.split(xchar)[1].strip()}
  107. break
  108. else:
  109. _value = str(value)
  110. return _value
  111. def format_diag(value):
  112. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  113. def format_pos(value):
  114. xchar = '>' if '>' in value else ':'
  115. x = value.split(xchar)
  116. x = {"code":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"code":x[0],"indicator":None,"frequency":None}
  117. return x
  118. def get_map(row,config,version=None):
  119. label = config['label'] if 'label' in config else None
  120. omap = config['map'] if not version or version not in config else config[version]
  121. anchors = config['anchors'] if 'anchors' in config else []
  122. if type(row[0]) == str:
  123. object_value = {}
  124. for key in omap :
  125. index = omap[key]
  126. if anchors and set(anchors) & set(row):
  127. _key = list(set(anchors) & set(row))[0]
  128. aindex = row.index(_key)
  129. index = aindex + index
  130. if index < len(row) :
  131. value = row[index]
  132. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  133. value = eval(config['cast'][key])(value)
  134. if type(value) == dict :
  135. for objkey in value :
  136. if type(value[objkey]) == dict :
  137. continue
  138. if 'syn' in config and value[objkey] in config['syn'] :
  139. value[objkey] = config['syn'][ value[objkey]]
  140. value = {key:value} if key not in value else value
  141. else:
  142. if 'syn' in config and value in config['syn'] :
  143. value = config['syn'][value]
  144. if type(value) == dict :
  145. object_value = dict(object_value, **value)
  146. else:
  147. object_value[key] = value
  148. else:
  149. #
  150. # we are dealing with a complex object
  151. object_value = []
  152. for row_item in row :
  153. value = get_map(row_item,config,version)
  154. object_value.append(value)
  155. #
  156. # We need to add the index of the object it matters in determining the claim types
  157. #
  158. # object_value.append( list(get_map(row_item,config,version)))
  159. # object_value = {label:object_value}
  160. return object_value
  161. def get_locations(x12_file,section='HL') :
  162. locations = []
  163. for line in x12_file :
  164. if line.strip().startswith(section) :
  165. i = x12_file.index(line)
  166. locations.append(i)
  167. return locations
  168. #def get_claims(filename,config,section) :
  169. def get_content(filename,config,section=None) :
  170. """
  171. This function returns the of the EDI file parsed given the configuration specified
  172. :section loop prefix (HL, CLP)
  173. :config configuration with formatting rules, labels ...
  174. :filename location of the file
  175. """
  176. section = section if section else config['SECTION']
  177. logs = []
  178. try:
  179. x12_file = open(filename.strip(),errors='ignore').read().split('\n')
  180. except Exception as e:
  181. #
  182. # We have an error here that should be logged
  183. if sys.version_info[0] > 2 :
  184. # logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  185. logs.append ({"version":"unknown","filename":filename,"msg":e.args[0]})
  186. else:
  187. # logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  188. logs.append ({"version":"unknown","filename":filename,"msg":e.message})
  189. return [],logs
  190. pass
  191. if len(x12_file) == 1 :
  192. x12_file = x12_file[0].split('~')
  193. #partitions = '\n'.join(x12_file).split(section+'*')
  194. locations = get_locations(x12_file,section)
  195. claims = []
  196. #
  197. # given locations it is possible to build up the partitions (made of segments)
  198. beg = locations [0]
  199. partitions = []
  200. for end in locations[1:] :
  201. partitions.append ("\n".join(x12_file[beg:end]))
  202. beg = end
  203. # VERSION = x12_file[2].split('*')[3].replace('~','')
  204. TOP_ROW = x12_file[1].split('*')
  205. CATEGORY= x12_file[2].split('*')[1].strip()
  206. VERSION = x12_file[1].split('*')[-1].replace('~','')
  207. SUBMITTED_DATE = format_date(TOP_ROW[4])
  208. SENDER_ID = TOP_ROW[2]
  209. row = split(x12_file[3])
  210. _info = get_config(config,row)
  211. _default_value = get_map(row,_info,VERSION) if _info else {}
  212. N = len(locations)
  213. # for index in range(0,N-1):
  214. # beg = locations[index]
  215. # end = locations[index+1]
  216. # claim = {}
  217. for segment in partitions :
  218. claim = {}
  219. # for row in x12_file[beg:end] :
  220. segment = segment.replace('\n','').split('~')
  221. for row in segment :
  222. row = split(row)
  223. _info = get_config(config,row)
  224. if _info :
  225. try:
  226. # tmp = get_map(row,_info,VERSION)
  227. # if 'parser' in _info :
  228. # pointer = eval(_info['parser'])
  229. # print (pointer(row))
  230. tmp = get_map(row,_info,VERSION)
  231. except Exception as e:
  232. if sys.version_info[0] > 2 :
  233. # logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  234. logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":row,"completed":False,"rows":len(row)})
  235. else:
  236. # logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  237. logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":row,"rows":len(row),"completed":False})
  238. claim = {}
  239. break
  240. if 'label' not in _info :
  241. tmp['version'] = VERSION
  242. tmp['submitted'] = SUBMITTED_DATE
  243. if TOP_ROW[1] == 'HP' :
  244. tmp['payer_id'] = SENDER_ID
  245. elif TOP_ROW[1] == 'HC':
  246. tmp['provider_id'] = SENDER_ID
  247. tmp['category'] = {"setid": CATEGORY,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  248. claim = dict(claim, **tmp)
  249. else:
  250. label = _info['label']
  251. if type(tmp) == list :
  252. claim[label] = tmp if label not in claim else claim[label] + tmp
  253. else:
  254. if label not in claim:
  255. claim[label] = [tmp]
  256. elif len(list(tmp.keys())) == 1 :
  257. # print "\t",len(claim[label]),tmp
  258. index = len(claim[label]) -1
  259. claim[label][index] = dict(claim[label][index],**tmp)
  260. else:
  261. claim[label].append(tmp)
  262. if len(claim[label]) > 0 :
  263. labels = []
  264. for item in claim[label] :
  265. item['_index'] = len(labels)
  266. if item not in labels :
  267. labels.append(item)
  268. claim[label] = labels
  269. # claim[label] = list( set(claim[label])) #-- removing redundancies
  270. if claim and 'claim_id' in claim:
  271. claim = dict(claim,**_default_value)
  272. claim['name'] = filename.split(os.sep)[-1] #.replace(ROOT,'')
  273. claim['index'] = len(claims) if len(claims) > 0 else 0
  274. claims.append(claim)
  275. else:
  276. #
  277. # Could not find claim identifier associated with data
  278. #
  279. pass
  280. return claims,logs