parse-ilf.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import xml.etree.ElementTree as ET
  2. import os
  3. import re
  4. path_to_input_meta='./neuroglancer-scripts-input/metadata'
  5. path_to_metadata='./output/metadata'
  6. os.makedirs(path_to_metadata,exist_ok=True)
  7. def get_rgb_from_hex(hex=None):
  8. if hex is None:
  9. return None
  10. r=hex[1:3]
  11. g=hex[3:5]
  12. b=hex[5:7]
  13. return [int(r, 16), int(g, 16), int(b, 16)]
  14. def process_label(label, parent=None):
  15. name=label.attrib.get('name')
  16. color=label.attrib.get('color')
  17. abbreviation=label.attrib.get('abbreviation')
  18. id=int(label.attrib.get('id'))
  19. node={
  20. 'name': name,
  21. 'rgb': get_rgb_from_hex(color),
  22. 'labelIndex': id,
  23. '_': {
  24. 'abbreviation': abbreviation,
  25. },
  26. 'children': []
  27. }
  28. if parent is not None:
  29. parent['children'].append(node)
  30. for l in label:
  31. process_label(l, node)
  32. def process_ilf_file(filename):
  33. stripped_name=re.sub(r'.ilf$', '', filename)
  34. path_to_ifl=f'{path_to_input_meta}/{filename}'
  35. ilf=ET.parse(path_to_ifl)
  36. root_node={
  37. 'name': 'Root',
  38. 'rgb': None,
  39. 'labelIndex': None,
  40. 'children': []
  41. }
  42. structure=ilf.find('structure')
  43. for label in structure:
  44. process_label(label, root_node)
  45. path_to_region=f"{path_to_metadata}/{stripped_name}.regions.json"
  46. with open(path_to_region, 'w') as fp:
  47. import json
  48. json.dump(root_node, fp, indent=2)
  49. pass
  50. def main():
  51. is_ilf = re.compile(r'.ilf$')
  52. for f in [f for f in os.listdir(path_to_input_meta) if is_ilf.search(f)]:
  53. process_ilf_file(f)
  54. if __name__ == '__main__':
  55. main()