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
19 changes: 16 additions & 3 deletions src/mapillary/utils/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"""

import logging
import re

import haversine
from geojson import Feature, Point
Expand Down Expand Up @@ -255,7 +256,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,10 +268,20 @@ 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))]

patterns = [
re.compile(".*".join(re.escape(part) for part in v.split("*")) + r"\Z", re.S)
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(p.match(candidate) for p in patterns)

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


def existed_at(data: list, existed_at: str) -> list:
"""
Expand Down
45 changes: 45 additions & 0 deletions tests/utils/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

# 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 +98,47 @@ 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.*"], []),
([], []),
],
)
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]]