parser.py 11 KB

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