parser.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. locations = get_locations(x12_file,section)
  142. claims = []
  143. logs = []
  144. # VERSION = x12_file[2].split('*')[3].replace('~','')
  145. TOP_ROW = x12_file[1].split('*')
  146. CATEGORY= x12_file[2].split('*')[1].strip()
  147. VERSION = x12_file[1].split('*')[-1].replace('~','')
  148. SUBMITTED_DATE = format_date(TOP_ROW[4])
  149. SENDER_ID = TOP_ROW[2]
  150. row = split(x12_file[3])
  151. _info = get_config(config,row)
  152. _default_value = get_map(row,_info,VERSION) if _info else {}
  153. N = len(locations)
  154. for index in range(0,N-1):
  155. beg = locations[index]
  156. end = locations[index+1]
  157. claim = {}
  158. for row in x12_file[beg:end] :
  159. row = split(row)
  160. _info = get_config(config,row)
  161. if _info :
  162. try:
  163. # tmp = get_map(row,_info,VERSION)
  164. # if 'parser' in _info :
  165. # pointer = eval(_info['parser'])
  166. # print (pointer(row))
  167. tmp = get_map(row,_info,VERSION)
  168. except Exception as e:
  169. if sys.version_info[0] > 2 :
  170. logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  171. else:
  172. logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  173. claim = {}
  174. break
  175. if 'label' not in _info :
  176. tmp['version'] = VERSION
  177. tmp['submitted'] = SUBMITTED_DATE
  178. if TOP_ROW[1] == 'HP' :
  179. tmp['payer_id'] = SENDER_ID
  180. elif TOP_ROW[1] == 'HC':
  181. tmp['provider_id'] = SENDER_ID
  182. tmp['category'] = {"setid": CATEGORY,"version":'X'+VERSION.split('X')[1],"id":VERSION.split('X')[0].strip()}
  183. claim = dict(claim, **tmp)
  184. else:
  185. label = _info['label']
  186. if type(tmp) == list :
  187. claim[label] = tmp if label not in claim else claim[label] + tmp
  188. else:
  189. if label not in claim:
  190. claim[label] = [tmp]
  191. elif len(list(tmp.keys())) == 1 :
  192. # print "\t",len(claim[label]),tmp
  193. index = len(claim[label]) -1
  194. claim[label][index] = dict(claim[label][index],**tmp)
  195. else:
  196. claim[label].append(tmp)
  197. if claim and 'claim_id' in claim:
  198. claim = dict(claim,**_default_value)
  199. claim['name'] = filename[:-5].split(os.sep)[-1] #.replace(ROOT,'')
  200. claim['index'] = index
  201. claims.append(claim)
  202. return claims,logs