position_helper.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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_path = os.path.join(folder_path, file_name)
  14. yaml_content = load_yaml_file(file_path=position_file_path, default_value=[])
  15. positions = [item.strip() for item in yaml_content if item and isinstance(item, str) and item.strip()]
  16. return {name: index for index, name in enumerate(positions)}
  17. def sort_by_position_map(
  18. position_map: dict[str, int],
  19. data: list[Any],
  20. name_func: Callable[[Any], str],
  21. ) -> list[Any]:
  22. """
  23. Sort the objects by the position map.
  24. If the name of the object is not in the position map, it will be put at the end.
  25. :param position_map: the map holding positions in the form of {name: index}
  26. :param name_func: the function to get the name of the object
  27. :param data: the data to be sorted
  28. :return: the sorted objects
  29. """
  30. if not position_map or not data:
  31. return data
  32. return sorted(data, key=lambda x: position_map.get(name_func(x), float('inf')))
  33. def sort_to_dict_by_position_map(
  34. position_map: dict[str, int],
  35. data: list[Any],
  36. name_func: Callable[[Any], str],
  37. ) -> OrderedDict[str, Any]:
  38. """
  39. Sort the objects into a ordered dict by the position map.
  40. If the name of the object is not in the position map, it will be put at the end.
  41. :param position_map: the map holding positions in the form of {name: index}
  42. :param name_func: the function to get the name of the object
  43. :param data: the data to be sorted
  44. :return: an OrderedDict with the sorted pairs of name and object
  45. """
  46. sorted_items = sort_by_position_map(position_map, data, name_func)
  47. return OrderedDict([(name_func(item), item) for item in sorted_items])