Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 61 additions & 4 deletions src/mapillary/utils/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ChitrarupGuha -- slightly concerned about the performance concern with this regex that could add up slightly more on each call. Each * becomes a .*, so a pattern with k wildcards can backtrack in roughly O(nᵏ) time on near-miss input.

Can we try something like this and test in test_filter.py for an perf degradations? Matching each middle piece at its leftmost position is always correct, so there's no backtracking and str.find keeps the check linear.

Quick AI code of what I was thinking about,

def _compile_glob(pattern: str) -> tuple[str, list[str], str]:
    first, *rest = pattern.split("*")
    *mid, last = rest
    return first, mid, last


def _glob_match(glob: tuple[str, list[str], str], s: str) -> 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

And then,

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:
    return if candidate in exact then True else isinstance(candidate, str) and any(_glob_match(g, candidate) for g in globs)

return [f for f in data if matches(f["properties"].get(property))]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Switched to the str.find approach, added a perf test and edge cases (consecutive *, prefix/suffix overlap). Kept exact as a list so unhashable property values don't raise; happy to switch to a set if you prefer.

@Rubix982 Rubix982 Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @ChitrarupGuha ! Just to verify, the tests succeeded, correct?

I have approved.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the 15 filter_values tests pass locally (including the new perf test), and CI is green on the latest commit. Thanks for the review!

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:
Expand Down
74 changes: 74 additions & 0 deletions tests/utils/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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