filter.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import re
  2. from module.logger import logger
  3. class Filter:
  4. def __init__(self, regex, attr, preset=()):
  5. """
  6. Args:
  7. regex: Regular expression.
  8. attr: Attribute name.
  9. preset: Build-in string preset.
  10. """
  11. if isinstance(regex, str):
  12. regex = re.compile(regex)
  13. self.regex = regex
  14. self.attr = attr
  15. self.preset = tuple(list(p.lower() for p in preset))
  16. self.filter_raw = []
  17. self.filter = []
  18. def load(self, string):
  19. string = str(string)
  20. self.filter_raw = [f.strip(' \t\r\n') for f in string.split('>')]
  21. self.filter = [self.parse_filter(f) for f in self.filter_raw]
  22. def is_preset(self, filter):
  23. return len(filter) and filter.lower() in self.preset
  24. def apply(self, objs, func=None):
  25. """
  26. Args:
  27. objs (list): List of objects and strings
  28. func (callable): A function to filter object.
  29. Function should receive an object as arguments, and return a bool.
  30. True means add it to output.
  31. Returns:
  32. list: A list of objects and preset strings, such as [object, object, object, 'reset']
  33. """
  34. out = []
  35. for raw, filter in zip(self.filter_raw, self.filter):
  36. if self.is_preset(raw):
  37. raw = raw.lower()
  38. if raw not in out:
  39. out.append(raw)
  40. else:
  41. for index, obj in enumerate(objs):
  42. if self.apply_filter_to_obj(obj=obj, filter=filter) and obj not in out:
  43. out.append(obj)
  44. if func is not None:
  45. objs, out = out, []
  46. for obj in objs:
  47. if isinstance(obj, str):
  48. out.append(obj)
  49. elif func(obj):
  50. out.append(obj)
  51. else:
  52. # Drop this object
  53. pass
  54. return out
  55. def apply_filter_to_obj(self, obj, filter):
  56. """
  57. Args:
  58. obj (object):
  59. filter (list[str]):
  60. Returns:
  61. bool: If an object satisfy a filter.
  62. """
  63. for attr, value in zip(self.attr, filter):
  64. if not value:
  65. continue
  66. if str(obj.__getattribute__(attr)).lower() != str(value):
  67. return False
  68. return True
  69. def parse_filter(self, string):
  70. """
  71. Args:
  72. string (str):
  73. Returns:
  74. list[strNone]:
  75. """
  76. string = string.replace(' ', '').lower()
  77. result = re.search(self.regex, string)
  78. if self.is_preset(string):
  79. return [string]
  80. if result and len(string) and result.span()[1]:
  81. return [result.group(index + 1) for index, attr in enumerate(self.attr)]
  82. else:
  83. logger.warning(f'Invalid filter: "{string}". This selector does not match the regex, nor a preset.')
  84. # Invalid filter will be ignored.
  85. # Return strange things and make it impossible to match
  86. return ['1nVa1d'] + [None] * (len(self.attr) - 1)