parser.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. year = value[:4]
  57. month = value[4:6]
  58. day = value[6:]
  59. return "-".join([year,month,day])[:10] #{"year":year,"month":month,"day":day}
  60. def format_time(value):
  61. return ":".join([value[:2],value[2:] ])[:5]
  62. def format_proc(value):
  63. if ':' in value :
  64. return {"procedure_type":value.split(':')[0].strip(),"procedure_code":value.split(':')[1].strip()}
  65. else:
  66. return value
  67. def format_diag(value):
  68. return [ {"code":item[2], "type":item[1]} for item in value if len(item) > 1]
  69. def get_map(row,config,version):
  70. label = config['label'] if 'label' in config else None
  71. omap = config['map'] if version not in config else config[version]
  72. anchors = config['anchors'] if 'anchors' in config else []
  73. if type(row[0]) == str:
  74. object_value = {}
  75. for key in omap :
  76. index = omap[key]
  77. if anchors and set(anchors) & set(row):
  78. _key = list(set(anchors) & set(row))[0]
  79. aindex = row.index(_key)
  80. index = aindex + index
  81. if index < len(row) :
  82. value = row[index]
  83. if 'cast' in config and key in config['cast'] and value.strip() != '' :
  84. value = eval(config['cast'][key])(value)
  85. pass
  86. if 'syn' in config and value in config['syn'] :
  87. value = config['syn'][value]
  88. if type(value) == dict :
  89. object_value = dict(object_value, **value)
  90. else:
  91. object_value[key] = value
  92. else:
  93. #
  94. # we are dealing with a complex object
  95. object_value = []
  96. for row_item in row :
  97. value = get_map(row_item,config,version)
  98. object_value.append(value)
  99. # object_value.append( list(get_map(row_item,config,version)))
  100. # object_value = {label:object_value}
  101. return object_value
  102. def get_locations(x12_file,section='HL') :
  103. locations = []
  104. for line in x12_file :
  105. if line.strip().startswith(section) :
  106. i = x12_file.index(line)
  107. locations.append(i)
  108. return locations
  109. #def get_claims(filename,config,section) :
  110. def get_content(filename,config,section=None) :
  111. """
  112. This function returns the of the EDI file parsed given the configuration specified
  113. :section loop prefix (HL, CLP)
  114. :config configuration with formatting rules, labels ...
  115. :filename location of the file
  116. """
  117. section = section if section else config['SECTION']
  118. x12_file = open(filename).read().split('\n')
  119. if len(x12_file) == 1 :
  120. x12_file = x12_file[0].split('~')
  121. locations = get_locations(x12_file,section)
  122. claims = []
  123. logs = []
  124. # VERSION = x12_file[2].split('*')[3].replace('~','')
  125. TOP_ROW = x12_file[1].split('*')
  126. VERSION = x12_file[1].split('*')[-1].replace('~','')
  127. SUBMITTED_DATE = format_date(TOP_ROW[4])
  128. SENDER_ID = TOP_ROW[2]
  129. row = split(x12_file[3])
  130. _info = get_config(config,row)
  131. _default_value = get_map(row,_info,VERSION) if _info else {}
  132. N = len(locations)
  133. for index in range(0,N-1):
  134. beg = locations[index]
  135. end = locations[index+1]
  136. claim = {}
  137. for row in x12_file[beg:end] :
  138. row = split(row)
  139. _info = get_config(config,row)
  140. if _info :
  141. try:
  142. # tmp = get_map(row,_info,VERSION)
  143. # if 'parser' in _info :
  144. # pointer = eval(_info['parser'])
  145. # print (pointer(row))
  146. tmp = get_map(row,_info,VERSION)
  147. except Exception as e:
  148. if sys.verion_info[0] > 2 :
  149. logs.append ({"version":VERSION,"filename":filename,"msg":e.args[0],"X12":x12_file[beg:end]})
  150. else:
  151. logs.append ({"version":VERSION,"filename":filename,"msg":e.message,"X12":x12_file[beg:end]})
  152. claim = {}
  153. break
  154. if 'label' not in _info :
  155. tmp['version'] = VERSION
  156. tmp['submitted'] = SUBMITTED_DATE
  157. if TOP_ROW[1] == 'HP' :
  158. tmp['payer_id'] = SENDER_ID
  159. else:
  160. tmp['provider_id'] = SENDER_ID
  161. claim = dict(claim, **tmp)
  162. else:
  163. label = _info['label']
  164. if type(tmp) == list :
  165. claim[label] = tmp if label not in claim else claim[label] + tmp
  166. else:
  167. if label not in claim:
  168. claim[label] = [tmp]
  169. elif len(list(tmp.keys())) == 1 :
  170. # print "\t",len(claim[label]),tmp
  171. index = len(claim[label]) -1
  172. claim[label][index] = dict(claim[label][index],**tmp)
  173. else:
  174. claim[label].append(tmp)
  175. if claim and 'claim_id' in claim:
  176. claim = dict(claim,**_default_value)
  177. claim['name'] = filename[:-5].split(os.sep)[-1] #.replace(ROOT,'')
  178. claim['index'] = index
  179. claims.append(claim)
  180. return claims,logs