parser.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 json
  18. def split(row,sep='*',prefix='HI'):
  19. """
  20. This function is designed to split an x12 row and
  21. """
  22. if row.startswith(prefix) is False:
  23. value = []
  24. for row_value in row.replace('~','').split(sep) :
  25. if '>' in row_value :
  26. if row_value.startswith('HC') or row_value.startswith('AD'):
  27. value += row_value.split('>')[:2]
  28. else:
  29. value += row_value.split('>') if row.startswith('CLM') is False else [row_value]
  30. else :
  31. value.append(row_value)
  32. return [xchar.replace('\r','') for xchar in value] #row.replace('~','').split(sep)
  33. else:
  34. return [ [prefix]+ split(item,'>') for item in row.replace('~','').split(sep)[1:] ]
  35. def get_config(config,row):
  36. """
  37. This function will return the meaningfull parts of the configuration for a given item
  38. """
  39. _row = list(row) if type(row[0]) == str else list(row[0])
  40. _info = config[_row[0]] if _row[0] in config else {}
  41. key = None
  42. if '@ref' in _info:
  43. key = list(set(_row) & set(_info['@ref'].keys()))
  44. if key :
  45. key = key[0]
  46. return _info['@ref'][key]
  47. else:
  48. return {}
  49. if not _info and 'SIMILAR' in config:
  50. #
  51. # Let's look for the nearest key using the edit distance
  52. if _row[0] in config['SIMILAR'] :
  53. key = config['SIMILAR'][_row[0]]
  54. _info = config[key]
  55. return _info
  56. def format_date(value) :
  57. if len(value) == 8 :
  58. year = value[:4]
  59. month = value[4:6]
  60. day = value[6:]
  61. return "-".join([year,month,day])[:10] #{"year":year,"month":month,"day":day}
  62. elif len(value) == 6 :
  63. year = '20' + value[:2]
  64. month = value[2:4]
  65. day = value[4:]
  66. return "-".join([year,month,day])
  67. def format_time(value):
  68. return ":".join([value[:2],value[2:] ])[:5]
  69. def format_proc(value):
  70. for xchar in [':','<'] :
  71. if xchar in value and len(value.split(xchar)) == 2 :
  72. _value = {"type":value.split(':')[0].strip(),"code":value.split(':')[1].strip()}
  73. break
  74. else:
  75. _value = str(value)
  76. return _value
  77. def format_diag(value):
  78. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  79. def format_pos(value):
  80. xchar = '>' if '>' in value else ':'
  81. x = value.split(xchar)
  82. x = {"code":x[0],"indicator":x[1],"frequency":x[2]} if len(x) == 3 else {"code":x[0],"indicator":None,"frequency":None}
  83. return x
  84. def get_map(row,config,version):
  85. label = config['label'] if 'label' in config else None
  86. omap = config['map'] if version not in config else config[version]
  87. anchors = config['anchors'] if 'anchors' in config else []
  88. if type(row[0]) == str:
  89. object_value = {}
  90. for key in omap :
  91. index = omap[key]
  92. if anchors and set(anchors) & set(row):
  93. _key = list(set(anchors) & set(row))[0]
  94. aindex = row.index(_key)
  95. index = aindex + index
  96. if index < len(row) :
  97. value = row[index]
  98. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  99. value = eval(config['cast'][key])(value)
  100. if type(value) == dict :
  101. for objkey in value :
  102. if 'syn' in config and value[objkey] in config['syn'] :
  103. value[objkey] = config['syn'][ value[objkey]]
  104. value = {key:value}
  105. else:
  106. if 'syn' in config and value in config['syn'] :
  107. value = config['syn'][value]
  108. if type(value) == dict :
  109. object_value = dict(object_value, **value)
  110. else:
  111. object_value[key] = value
  112. else:
  113. #
  114. # we are dealing with a complex object
  115. object_value = []
  116. for row_item in row :
  117. value = get_map(row_item,config,version)
  118. object_value.append(value)
  119. # object_value.append( list(get_map(row_item,config,version)))
  120. # object_value = {label:object_value}
  121. return object_value
  122. def get_locations(x12_file,section='HL') :
  123. locations = []
  124. for line in x12_file :
  125. if line.strip().startswith(section) :
  126. i = x12_file.index(line)
  127. locations.append(i)
  128. return locations
  129. #def get_claims(filename,config,section) :
  130. def get_content(filename,config,section=None) :
  131. """
  132. This function returns the of the EDI file parsed given the configuration specified
  133. :section loop prefix (HL, CLP)
  134. :config configuration with formatting rules, labels ...
  135. :filename location of the file
  136. """
  137. section = section if section else config['SECTION']
  138. x12_file = open(filename).read().split('\n')
  139. if len(x12_file) == 1 :
  140. x12_file = x12_file[0].split('~')
  141. partitions = '\n'.join(x12_file).split(section+'*')
  142. locations = get_locations(x12_file,section)
  143. claims = []
  144. logs = []
  145. # VERSION = x12_file[2].split('*')[3].replace('~','')
  146. TOP_ROW = x12_file[1].split('*')
  147. CATEGORY= x12_file[2].split('*')[1].strip()
  148. VERSION = x12_file[1].split('*')[-1].replace('~','')
  149. SUBMITTED_DATE = format_date(TOP_ROW[4])
  150. SENDER_ID = TOP_ROW[2]
  151. row = split(x12_file[3])
  152. _info = get_config(config,row)
  153. _default_value = get_map(row,_info,VERSION) if _info else {}
  154. N = len(locations)
  155. # for index in range(0,N-1):
  156. # beg = locations[index]
  157. # end = locations[index+1]
  158. # claim = {}
  159. for segment in partitions :
  160. claim = {}
  161. # for row in x12_file[beg:end] :
  162. segment = segment.replace('\n','').split('~')
  163. for row in segment :
  164. row = split(row)
  165. _info = get_config(config,row)
  166. if _info :
  167. try:
  168. # tmp = get_map(row,_info,VERSION)
  169. # if 'parser' in _info :
  170. # pointer = eval(_info['parser'])
  171. # print (pointer(row))
  172. tmp = get_map(row,_info,VERSION)
  173. except Exception as e:
  174. if sys.version_info[0] > 2 :
  175. # logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  176. logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":row})
  177. else:
  178. # logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  179. logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":row})
  180. claim = {}
  181. break
  182. if 'label' not in _info :
  183. tmp['version'] = VERSION
  184. tmp['submitted'] = SUBMITTED_DATE
  185. if TOP_ROW[1] == 'HP' :
  186. tmp['payer_id'] = SENDER_ID
  187. elif TOP_ROW[1] == 'HC':
  188. tmp['provider_id'] = SENDER_ID
  189. tmp['category'] = {"setid": CATEGORY,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  190. claim = dict(claim, **tmp)
  191. else:
  192. label = _info['label']
  193. if type(tmp) == list :
  194. claim[label] = tmp if label not in claim else claim[label] + tmp
  195. else:
  196. if label not in claim:
  197. claim[label] = [tmp]
  198. elif len(list(tmp.keys())) == 1 :
  199. # print "\t",len(claim[label]),tmp
  200. index = len(claim[label]) -1
  201. claim[label][index] = dict(claim[label][index],**tmp)
  202. else:
  203. claim[label].append(tmp)
  204. if len(claim[label]) > 0 :
  205. labels = []
  206. for item in claim[label] :
  207. if item not in labels :
  208. labels.append(item)
  209. claim[label] = labels
  210. # claim[label] = list( set(claim[label])) #-- removing redundancies
  211. if claim and 'claim_id' in claim:
  212. claim = dict(claim,**_default_value)
  213. claim['name'] = filename.split(os.sep)[-1] #.replace(ROOT,'')
  214. claim['index'] = len(claims) if len(claims) > 0 else 0
  215. claims.append(claim)
  216. return claims,logs