Metadata-Version: 2.4
Name: heislime
Version: 1.1.1
Summary: HeiGIT street-level imagery (SLI) mining engine
Author: HeiGIT
License-Expression: AGPL-3.0-only
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Requires-Dist: bokeh>=3.10.0
Requires-Dist: contextily>=1.7.1
Requires-Dist: dask[distributed]>=2026.8.0
Requires-Dist: diskcache>=5.6.3
Requires-Dist: distributed>=2026.8.0
Requires-Dist: geojson>=3.3.0
Requires-Dist: geopandas>=1.1.4
Requires-Dist: h3>=4.5.0
Requires-Dist: httpx>=0.28.1
Requires-Dist: mapillary>=1.0.15
Requires-Dist: mercantile>=1.2.1
Requires-Dist: pandas>=3.0.6
Requires-Dist: pillow>=12.3.0
Requires-Dist: polars>=1.44.1
Requires-Dist: pyarrow>=25.0.1
Requires-Dist: pydantic>=2.13.4
Requires-Dist: pyiqa>=0.1.16
Requires-Dist: semver>=3.0.4
Requires-Dist: shapely>=2.1.2
Requires-Dist: torch>=2.13.0
Requires-Dist: torchvision>=0.28.0
Requires-Dist: transformers>=5.16.1
Requires-Dist: vt2geojson>=0.2.1
Requires-Python: >=3.12
Project-URL: Homepage, https://gitlab.heigit.org/giscience/heimeterstick/heislime
Project-URL: Repository, https://gitlab.heigit.org/giscience/heimeterstick/heislime.git
Project-URL: Issues, https://gitlab.heigit.org/giscience/heimeterstick/heislime/-/issues
Description-Content-Type: text/markdown

![](logo.png)
HeiGIT Street-level imagery (SLI) mining engine

HeiSlime is a Python toolbox that uses geographic context to select the few street-level images that are useful for an analysis, before a computer vision model ever sees them.

## Installation

```bash
pip install git+https://gitlab.heigit.org/giscience/heimeterstick/heislime.git@main
```

## Usage
## Requirements

You will need an access to your SLI provider and provide the respective access token to the library (e.g. `MLY_TOKEN` variable set in the following script).

The ohsome filter additionally require an ohsome token that can be requested form https://account.heigit.org


```python
from shapely.geometry import box

from heislime.filter.osm import ProximityFilter
from heislime.filter.sli import ContainsObject
from heislime.osm.ohsome import OhsomeProvider
from heislime.pipeline import Pipeline
from heislime.sli.base import SLIProviderSpec
from heislime.sli.mly import MapillaryParams, MapillaryProvider

pipeline = Pipeline(
    sli_providers=[
        SLIProviderSpec(
            provider=MapillaryProvider(access_token=MLY_TOKEN),
            params=MapillaryParams(zoom=14, image_type='flat'),
        )
    ],
    osm_provider=OhsomeProvider(access_token=OHSOME_TOKEN),
)

result = pipeline.execute(
    aoi=box(8.670057, 49.412244, 8.681214, 49.417171),
    osm_filters=[ProximityFilter(distance=25, query='highway=primary')],
    sli_filters=[ContainsObject(labels=['a tree', 'a sidewalk'])],
)
```

## Disaggregation and distributed execution

For large areas, give the pipeline a `partitioner`.
The AoI is split along the [H3](https://h3geo.org) grid (each part is one H3 cell clipped to the AoI) and every part runs the full fetch + filter chain as its own
[Dask](https://distributed.dask.org) task.
Without a `client`, a local cluster is started on the first
`execute` and torn down by `close()` / the `with` block; pass your own `distributed.Client` to run on a real cluster.

```python
from distributed import Client

from heislime.partition.h3 import H3Partitioner

with Pipeline(
        sli_providers=[...],
        osm_provider=OhsomeProvider(access_token=OHSOME_TOKEN),
        partitioner=H3Partitioner(resolution=8),  # ~0.7 km² cells; 9 is ~0.1 km²
        client=Client('tcp://scheduler:8786'),  # omit for a local cluster
) as pipeline:
    result = pipeline.execute(aoi=city_boundary, sli_filters=[QualityFilter()])
```

The result carries an extra `partition` column with the H3 cell each image was processed in.
Pick the resolution so parts are large: SLI filters load their model once per part.

Filters run in order: distribution filters first, then OSM filters, then SLI filters. Because the SLI filters download and run a model over every
remaining image, put the cheap spatial filters first to cut the candidate set down. Enrichers run after the filters, and
selectors run last, once over the whole result (across all partitions), so they can use the entries the enrichers added.

When you need more than one SLI filter, wrap them in a `ChainedImageFilter` so every image is downloaded and decoded
once and the later (usually more expensive) filters only see the images that survived the earlier ones:

```python
from heislime.filter.sli import ChainedImageFilter
from heislime.filter.sli import QualityFilter
from heislime.filter.sli import ContainsObject

sli_filters=[
    ChainedImageFilter(
        filters=[QualityFilter(), ContainsObject(labels=['a tree'])],
        batch_size=32,
    )
]
```

By default `execute` returns the filtered `GeoDataFrame`. Pass a `materializer` to turn the result into something else,
for example the image binaries on disk or a georeferenced file:

```python
from pathlib import Path

from heislime.materialize.file import ImageMaterializer
from heislime.materialize.geo import GeoDataMaterializer
from heislime.filter.sli import ContainsObject

image_paths = pipeline.execute(
    aoi=aoi,
    sli_filters=[ContainsObject(labels=['a tree'])],
    materializer=ImageMaterializer(output_dir=Path('out/images'), extension='jpg'),
)

geojson_path = pipeline.execute(
    aoi=aoi,
    materializer=GeoDataMaterializer(output_dir=Path('out'), extension='geojson'),
)
```

## Filters

| Filter               | Type         | Purpose                                                                                                                                                 | Key parameters                                                                                                                   |
|----------------------|--------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| `SpatialThinning`    | Distribution | Thins dense image sequences down to roughly one image per `distance` metres.                                                                            | `distance` (metres), `per_sequence` (default False)                                                                              |
| `ScoreThinning`      | Distribution | Keeps the highest-scoring image among neighbours closer than `distance` metres. Needs a score, so pass it as a selector (see [Score thinning](#score-thinning)). | `distance` (metres), `column` (default `score`), `per_sequence` (default False)                                                  |
| `ProximityFilter`    | OSM          | Keeps images within a given distance of any OSM geometry matching a query.                                                                              | `distance` (metres), `query` (ohsome filter expression), `time` (snapshot, default `latest`)                                     |
| `InsideFilter`       | OSM          | Keeps SLI features that fall inside an OSM geometry.                                                                                                    | `predicate` (within/intersects), `query` (ohsome filter expression), `time` (snapshot, default `latest`)                         |
| `ExcludeFilter`      | OSM          | The negative of the two above: drops images inside, or within `distance` metres of, matching OSM geometries (tunnels, motorways, private land, ...).    | `query`, `distance` (metres, optional), `predicate`, `time`                                                                      |
| `VisibilityFilter`   | OSM          | Keeps images that plausibly see a target: within `distance` metres, inside the camera's field of view (panoramas always pass), and no occluder polygon on the line of sight. | `query`, `distance` (metres), `field_of_view` (degrees, default 90), `occluders` (query, default buildings; `None` to skip), `time` |
| `ContainsObject`     | SLI          | Keeps images in which an open-vocabulary detector finds the prompted objects. Runs OWLv2 over the downloaded image binaries.                            | `labels` (text prompts), `threshold` (default `0.25`), `mode` (`any` / `all`), `batch_size`, `max_workers`, `device`, `model_id` |
| `PrivacyFilter`      | SLI          | Drops images showing a face or licence plate whose box covers at least `min_area` of the frame. Runs OWLv2.                                             | `targets` (prompts), `threshold` (default `0.3`), `min_area` (fraction, default `0.002`), `device`, `model_id`                   |
| `QualityFilter`      | SLI          | Retains only the images whose no-reference quality score passes a threshold.                                                                            | `threshold` (default `0.45`), `metric_name` (default `topiq_nr`)                                                                 |
| `WeatherFilter`      | SLI          | Keeps images whose visible weather is one of `conditions`. Runs zero-shot CLIP classification over the downloaded image binaries.                       | `conditions` (`sunny` / `rainy` / `snowy` / `overcast`), `threshold` (default `0.3`), `device`, `model_id`                       |
| `ExifFilter`         | SLI          | Keeps images whose EXIF metadata satisfies a SQL condition. No model and no pixel decoding, so put it first in a `ChainedImageFilter`.                | `where` (SQL condition over EXIF tags), `batch_size`, `max_workers`                                                              |
| `ChainedImageFilter` | SLI          | Runs several SLI image filters over one shared download/decode pass, cheapest first.                                                                    | `filters`, `batch_size`, `max_workers`                                                                                           |

`TemporalThinning` and `VisibilityFilter` rely on the `captured_at`, `compass_angle` and `is_pano` columns that providers
attach to every image; filters raise a `ValueError` when a column they need is missing.

### EXIF conditions

```python
from heislime.filter.sli import ExifFilter

ExifFilter(where="lower(Make) IN ('gopro', 'insta360') AND FocalLength BETWEEN 2 AND 10")
ExifFilter(where="ISOSpeedRatings <= 400 AND (GPSHPositioningError < 5 OR GPSHPositioningError IS NULL)")
ExifFilter(where="Model ILIKE 'hero%' AND DateTimeOriginal >= '2023-01-01'")
```

- `where` is a SQL `WHERE` clause evaluated by Polars SQL (`pl.sql_expr`):
  `AND` / `OR` / `NOT`, comparisons, `IN`, `BETWEEN`, `LIKE` / `ILIKE`, `IS NULL`, `lower()`, and so on.
- Tag names are Pillow's (`PIL.ExifTags.TAGS` / `GPSTAGS`), case-insensitive, and are checked when the filter is built,
  together with the SQL syntax. The base, Exif and GPS IFDs are all searched.
- String comparisons are case-sensitive,
- A missing tag is `NULL` with the usual SQL semantics: it fails comparisons and matches `IS NULL`.
- Mapillary thumbnails carry no EXIF, so `MapillaryProvider` restores it from the Graph API with the same request that resolves the thumbnail: `Make`, `Model`, `Orientation`, `ExifImageWidth`, `ExifImageHeight`, `FocalLengthIn35mmFilm`, `GPSAltitude` and `GPSImgDirection`.
- The 35mm-equivalent focal length comes from Mapillary's calibrated `camera_parameters` (OpenSfM normalised focal × 36); acquiring the physical `FocalLength` is not possible.

## Enrichers

Enrichers add metadata entries (columns) to the images that stayed after filtering.
They run last in every partition, after the SLI filters and before the materializer, so they only see the reduced candidate set.

> An enricher works on metadata only.

### Score Enricher

`ScoreEnricher` rates how close every image is to a reference one, given weighted criteria, and stores it as `score` (highest is better).
Comparing the scores of two images tells which one is more appropriate.

```python
from heislime.enrich.score import AgeCriterion
from heislime.enrich.score import ProviderCriterion
from heislime.enrich.score import ProximityCriterion
from heislime.enrich.score import ScoreEnricher
from heislime.enrich.score import SeasonCriterion

gdf = pipeline.execute(
  aoi,
  enrichers=[
    ScoreEnricher(
      criteria=[
        ProviderCriterion(scores={'mapillary': 1.0, 'panoramax': 0.7}, weight=0.5),
        SeasonCriterion(seasons=['spring', 'summer'], weight=1),
        AgeCriterion(max_age=5, weight=2),
        ProximityCriterion(query='highway=primary', max_distance=30, weight=3),
      ],
      keep_components=True,
    )
  ],
)

best_first = gdf.sort_values('score', ascending=False)
```

The score is Gower's similarity coefficient between the image and the ideal image:

$$S = \frac{\sum_k w_k \, \delta_k \, s_k}{\sum_k w_k \, \delta_k}$$

where $s_k \in [0, 1]$ is the similarity on criterion $k$, $w_k$ its weight, and $\delta_k = 0$ when the criterion is undefined for the image (e.g. a missing `captured_at`), so missing metadata neither rewards nor penalises an image.
An image with no defined criterion gets `NaN`.

| Criterion            | Similarity to the ideal image                                                                                                    | Key parameters                                                                  |
|----------------------|----------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| `ProviderCriterion`  | The score given to the image's provider; providers not listed get `default`.                                                     | `scores` (provider → [0, 1]), `default` (default `0`)                           |
| `SeasonCriterion`    | `1 - gap / 2`, where `gap` is the circular distance (0, 1 or 2 seasons) between the meteorological season of `captured_at` and the nearest preferred one. Seasons are flipped south of the equator. | `seasons`, `hemisphere` (`auto` / `north` / `south`, default `auto`)            |
| `AgeCriterion`       | `1 - age / max_age`, clipped to [0, 1]; images newer than `reference_time` count as new.                                         | `max_age` (years, default `5`), `reference_time` (default: when the criterion is built) |
| `ProximityCriterion` | `1 - distance / max_distance` to the nearest OSM geometry matching `query`; `0` when none is within `max_distance`.              | `query` (ohsome filter), `max_distance` (metres), `time` (default `latest`)     |

Every criterion takes a `weight` (default `1`) and an optional `name`.

### Score thinning

`ScoreThinning` turns the score into a selection: among images closer than `distance` metres to each other, it keeps the one with the highest score.

```python
from heislime.filter.distribution import ScoreThinning

gdf = pipeline.execute(
    aoi,
    osm_filters=[ProximityFilter(distance=50, query='highway=primary')],
    enrichers=[ScoreEnricher(criteria=[...])],
    selectors=[ScoreThinning(distance=15)],
)
```

## Materializers

A materializer decides what `Pipeline.execute` returns. It receives the filtered `GeoDataFrame` and the SLI providers,
so it can download images if it needs to. The output directory must already exist.

| Materializer            | Returns      | Purpose                                                                                                   | Key parameters                                                            |
|-------------------------|--------------|-----------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| `GeoPandasMaterializer` | `GeoDataFrame` | Identity; returns the filtered frame as is. Used when no materializer is given.                         | –                                                                         |
| `GeoDataMaterializer`   | `Path`       | Writes the filtered frame to `<output_dir>/heislime.<extension>` as a georeferenced file.                 | `output_dir`, `extension` (`geojson` / `gpkg` / `shp`, default `geojson`) |
| `ImageMaterializer`     | `list[Path]` | Downloads every remaining image from its provider and saves it as `<output_dir>/<image_id>.<extension>`. Paths are returned in input row order. | `output_dir`, `extension` (`png` / `jpg`, default `jpg`), `max_workers` (default 8) |

Custom materializers subclass `heislime.materialize.base.Materializer` and implement `materialize(sli_gdf, sli_providers)`.


```
gdf = pipeline.execute(
    aoi,
    osm_filters=[ProximityFilter(distance=50, query='highway=primary')],
    enrichers=[
      ScoreEnricher(
        criteria=[
          ProviderSimilarityCriterion(scores={'mapillary': 1.0, 'panoramax': 0.7}, weight=0.5),
          SeasonSimilarityCriterion(seasons=['spring', 'summer'], weight=1),
          AgeSimilarityCriterion(max_age=5, weight=2),
          ProximitySimilarityCriterion(query='highway=primary', max_distance=30, weight=3),
        ],
        keep_components=True,
      )
    ],
    selectors=[ScoreThinning(distance=15)],
)
```
