parser.py 8.2 KB

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