filter.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # https://github.com/LmeSzinc/AzurLaneAutoScript/blob/master/module/base/filter.py
  2. import re
  3. from module.logger import logger
  4. class Filter:
  5. def __init__(self, regex, attr, preset=()):
  6. """
  7. Args:
  8. regex: Regular expression.
  9. attr: Attribute name.
  10. preset: Build-in string preset.
  11. """
  12. if isinstance(regex, str):
  13. regex = re.compile(regex)
  14. self.regex = regex
  15. self.attr = attr
  16. self.preset = tuple(list(p.lower() for p in preset))
  17. self.filter_raw = []
  18. self.filter = []
  19. def load(self, string):
  20. """
  21. Load a filter string, filters are connected with ">"
  22. There are also tons of unicode characters similar to ">"
  23. > \u003E correct
  24. > \uFF1E
  25. ﹥ \uFE65
  26. › \u203a
  27. ˃ \u02c3
  28. ᐳ \u1433
  29. ❯ \u276F
  30. """
  31. string = str(string)
  32. string = re.sub(r'[ \t\r\n]', '', string)
  33. string = re.sub(r'[>﹥›˃ᐳ❯]', '>', string)
  34. self.filter_raw = string.split('>')
  35. self.filter = [self.parse_filter(f) for f in self.filter_raw]
  36. def is_preset(self, filter):
  37. return len(filter) and filter.lower() in self.preset
  38. def apply(self, objs, func=None):
  39. """
  40. Args:
  41. objs (list): List of objects and strings
  42. func (callable): A function that to filter object.
  43. Function should receive an object as arguments, and return a bool.
  44. True means add it to output.
  45. Returns:
  46. list: A list of objects and preset strings, such as [object, object, object, 'reset']
  47. """
  48. out = []
  49. for raw, filter in zip(self.filter_raw, self.filter):
  50. if self.is_preset(raw):
  51. raw = raw.lower()
  52. if raw not in out:
  53. out.append(raw)
  54. else:
  55. for index, obj in enumerate(objs):
  56. if self.apply_filter_to_obj(obj=obj, filter=filter) and obj not in out:
  57. out.append(obj)
  58. if func is not None:
  59. objs, out = out, []
  60. for obj in objs:
  61. if isinstance(obj, str):
  62. out.append(obj)
  63. elif func(obj):
  64. out.append(obj)
  65. else:
  66. # Drop this object
  67. pass
  68. return out
  69. def applys(self, objs, funcs):
  70. """
  71. Args:
  72. objs (list): List of objects and strings
  73. List[func(callable)] : A list of funciton that to filter object.
  74. Function should receive an object as arguments, and return a bool.
  75. True means add it to output.
  76. Returns:
  77. list: A list of objects and preset strings, such as [object, object, object, 'reset']
  78. """
  79. return self.apply(objs, func=lambda x: all(func(x)for func in funcs))
  80. def apply_filter_to_obj(self, obj, filter):
  81. """
  82. Args:
  83. obj (object):
  84. filter (list[str]):
  85. Returns:
  86. bool: If an object satisfy a filter.
  87. """
  88. for attr, value in zip(self.attr, filter):
  89. if not value:
  90. continue
  91. if str(obj.__getattribute__(attr)).lower() != str(value):
  92. return False
  93. return True
  94. def parse_filter(self, string):
  95. """
  96. Args:
  97. string (str):
  98. Returns:
  99. list[strNone]:
  100. """
  101. string = string.replace(' ', '').lower()
  102. result = re.search(self.regex, string)
  103. if self.is_preset(string):
  104. return [string]
  105. if result and len(string) and result.span()[1]:
  106. return [result.group(index + 1) for index, attr in enumerate(self.attr)]
  107. else:
  108. logger.warning(f'Invalid filter: "{string}". This selector does not match the regex, nor a preset.')
  109. # Invalid filter will be ignored.
  110. # Return strange things and make it impossible to match
  111. return ['1nVa1d'] + [None] * (len(self.attr) - 1)