diff --git a/src/mapillary/utils/filter.py b/src/mapillary/utils/filter.py index b2e8ccd1..3e6363bd 100644 --- a/src/mapillary/utils/filter.py +++ b/src/mapillary/utils/filter.py @@ -244,6 +244,53 @@ def features_in_bounding_box(data: list, bbox: dict) -> list: return output +def _compile_glob(pattern: str) -> tuple[str, list[str], str]: + """ + Split a ``*`` wildcard pattern into its first, middle and last literal pieces + + :param pattern: The pattern, where ``*`` matches any run of characters + :type pattern: str + + :return: The literal start, the literal middle pieces and the literal end + :rtype: tuple + """ + + first, *rest = pattern.split("*") + *mid, last = rest + return first, mid, last + + +def _glob_match(glob: tuple[str, list[str], str], s: str) -> bool: + """ + Match a string against a compiled ``*`` wildcard pattern in linear time + + Each middle piece is matched at its leftmost position, which is always + correct, so there is no backtracking + + :param glob: The compiled pattern from ``_compile_glob`` + :type glob: tuple + + :param s: The string to match + :type s: str + + :return: True if the whole string matches the pattern + :rtype: bool + """ + + first, mid, last = glob + if len(s) < len(first) + len(last): + return False + if not (s.startswith(first) and s.endswith(last)): + return False + pos, end = len(first), len(s) - len(last) + for piece in mid: + i = s.find(piece, pos, end) + if i < 0: + return False + pos = i + len(piece) + return True + + def filter_values(data: list, values: list, property: str = "value") -> list: """ Filter the features based on the existence of a specified value @@ -255,7 +302,9 @@ def filter_values(data: list, values: list, property: str = "value") -> list: :param data: The data to be filtered :type data: dict - :param values: A list of values to filter by + :param values: A list of values to filter by. A ``*`` in a string value + matches any run of characters, e.g. ``object--support--*``. + Values without ``*`` must match exactly. :type values: list :param property: The specific parameter to look into @@ -265,9 +314,17 @@ def filter_values(data: list, values: list, property: str = "value") -> list: :rtype: dict """ - return [ - feature for feature in data if feature["properties"].get(property) in values - ] + exact = [v for v in values if not (isinstance(v, str) and "*" in v)] + globs = [_compile_glob(v) for v in values if isinstance(v, str) and "*" in v] + + def matches(candidate) -> bool: + if candidate in exact: + return True + return isinstance(candidate, str) and any( + _glob_match(g, candidate) for g in globs + ) + + return [feature for feature in data if matches(feature["properties"].get(property))] def existed_at(data: list, existed_at: str) -> list: diff --git a/tests/utils/test_filter.py b/tests/utils/test_filter.py index b39cd83c..0f5952c4 100644 --- a/tests/utils/test_filter.py +++ b/tests/utils/test_filter.py @@ -12,11 +12,14 @@ """ # Package imports +import time + import pytest import logging # Logger # Local imports from mapillary.utils.filter import pipeline # Pipeline +from mapillary.utils.filter import filter_values from tests.conftest import data # Data as fixture logger = logging.getLogger(__name__) @@ -97,3 +100,74 @@ def test_pipeline_haversine_dist(data: dict, operation, expected): len(actual) != len(fetched_data["features"]) or len(fetched_data["features"]) == 0 ), f"{test_that} failed, got {actual}" + + +def _features(*vals): + return [{"properties": {"value": v}} for v in vals] + + +@pytest.mark.parametrize( + "values, expected", + [ + (["object--street-light"], ["object--street-light"]), + ( + ["object--support--*"], + ["object--support--pole", "object--support--utility-pole"], + ), + (["*--pole"], ["object--support--pole"]), + (["*street*"], ["object--street-light"]), + ( + ["object--support--pole", "object--street-*"], + ["object--support--pole", "object--street-light"], + ), + (["object--support--"], []), + (["object.support.*"], []), + ([], []), + ( + ["*"], + [ + "object--support--pole", + "object--support--utility-pole", + "object--street-light", + "regulatory--stop--g1", + ], + ), + (["object--**--pole"], ["object--support--pole"]), + (["object--support--pole*pole"], []), + (["object--support--utility-pole*pole"], []), + ], +) +def test_filter_values_wildcard(values, expected): + data = _features( + "object--support--pole", + "object--support--utility-pole", + "object--street-light", + "regulatory--stop--g1", + ) + result = [f["properties"]["value"] for f in filter_values(data, values)] + assert result == expected + + +def test_filter_values_non_string_property(): + data = [ + {"properties": {"value": None}}, + {"properties": {}}, + {"properties": {"value": 5}}, + ] + assert filter_values(data, ["*"]) == [] + assert filter_values(data, [5]) == [data[2]] + + +def test_filter_values_wildcard_prefix_and_suffix_do_not_overlap(): + data = _features("aba", "abba", "ab") + result = [f["properties"]["value"] for f in filter_values(data, ["ab*ba"])] + assert result == ["abba"] + + +def test_filter_values_wildcard_near_miss_is_linear(): + # Many wildcards against a long near-miss: a backtracking matcher blows up here + data = _features("a" * 5000) + start = time.perf_counter() + result = filter_values(data, ["a*" * 30 + "b"]) + assert result == [] + assert time.perf_counter() - start < 1