import re


def parse_label_map(label_map_path):
  """Parse label map file into a dictionary
  Args:
    label_map_path:

  Returns:
    a dictionary : key: obj_id value: obj-name
  """
  # Open image has different label maps:  {name: ... id: .... display_name: ...}
  # MSCOCO and PASCAL has: {id:... name: ...}
  is_oid = False
  if 'oid' in label_map_path.split('/')[-1]:
    is_oid = True
    parser = re.compile(r'name:\s+\"(?P<name>[/\w_-]+)\"\s+id:\s+(?P<id>[0-9]+)\s+display_name:\s+\"(?P<display_name>[\w_-]+)\"')
  else:
      parser = re.compile(r'id:[^\d]*(?P<id>[0-9]+)\s+name:[^\']*\'(?P<name>[\w_-]+)\'')
  # Read label_map file
  with open(label_map_path, 'r') as f:
    lines = f.read().splitlines()
    lines = ''.join(lines)

    # match group having the same language 
    result = parser.findall(lines)
    if is_oid:
      label_map_dict = {int(item[1]): item[2] for item in result}
    else:
      label_map_dict = {int(item[0]): item[1] for item in result}

    return label_map_dict