position_helper.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os
  2. from collections import OrderedDict
  3. from collections.abc import Callable
  4. from typing import Any
  5. from core.tools.utils.yaml_utils import load_yaml_file
  6. def get_position_map(folder_path: str, *, file_name: str = "_position.yaml") -> dict[str, int]:
  7. """
  8. Get the mapping from name to index from a YAML file
  9. :param folder_path:
  10. :param file_name: the YAML file name, default to '_position.yaml'
  11. :return: a dict with name as key and index as value
  12. """
  13. position_file_name = os.path.join(folder_path, file_name)
  14. if not position_file_name or not os.path.exists(position_file_name):
  15. return {}
  16. positions = load_yaml_file(position_file_name, ignore_error=True)
  17. position_map = {}
  18. index = 0
  19. for _, name in enumerate(positions):
  20. if name and isinstance(name, str):
  21. position_map[name.strip()] = index
  22. index += 1
  23. return position_map
  24. def sort_by_position_map(
  25. position_map: dict[str, int],
  26. data: list[Any],
  27. name_func: Callable[[Any], str],
  28. ) -> list[Any]:
  29. """
  30. Sort the objects by the position map.
  31. If the name of the object is not in the position map, it will be put at the end.
  32. :param position_map: the map holding positions in the form of {name: index}
  33. :param name_func: the function to get the name of the object
  34. :param data: the data to be sorted
  35. :return: the sorted objects
  36. """
  37. if not position_map or not data:
  38. return data
  39. return sorted(data, key=lambda x: position_map.get(name_func(x), float('inf')))
  40. def sort_to_dict_by_position_map(
  41. position_map: dict[str, int],
  42. data: list[Any],
  43. name_func: Callable[[Any], str],
  44. ) -> OrderedDict[str, Any]:
  45. """
  46. Sort the objects into a ordered dict by the position map.
  47. If the name of the object is not in the position map, it will be put at the end.
  48. :param position_map: the map holding positions in the form of {name: index}
  49. :param name_func: the function to get the name of the object
  50. :param data: the data to be sorted
  51. :return: an OrderedDict with the sorted pairs of name and object
  52. """
  53. sorted_items = sort_by_position_map(position_map, data, name_func)
  54. return OrderedDict([(name_func(item), item) for item in sorted_items])