2026-03-29 18:58:31 -06:00
|
|
|
import json
|
|
|
|
|
import tempfile
|
2022-03-08 13:26:03 -07:00
|
|
|
from pathlib import Path
|
2026-03-29 18:58:31 -06:00
|
|
|
from typing import List, Dict
|
2022-03-08 13:26:03 -07:00
|
|
|
|
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
from modules.map import pmtiles
|
iNaturalist species map (#1033)
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:24:01 -07:00
|
|
|
from modules.map.catalog import MAP_REGIONS, MAP_REGIONS_BY_NAME, MANIFEST_URL, SPECIES_MANIFEST_URL, \
|
|
|
|
|
SPECIES_SIZE_ESTIMATES
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
from modules.map.config import get_maps_config
|
iNaturalist species map (#1033)
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:24:01 -07:00
|
|
|
from modules.map.species import PLANET, SPECIES_DB_SUFFIX, parse_pack_name
|
2026-03-29 18:58:31 -06:00
|
|
|
from wrolpi.common import get_media_directory, walk, logger, get_wrolpi_config, aiohttp_get, verify_gpg_signature
|
|
|
|
|
from wrolpi.downloader import DownloadFrequency, Download, save_downloads_config, download_manager
|
2022-03-08 13:26:03 -07:00
|
|
|
|
|
|
|
|
logger = logger.getChild(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_map_directory() -> Path:
|
2024-08-06 18:13:21 -06:00
|
|
|
map_directory = get_media_directory() / get_wrolpi_config().map_destination
|
2022-03-31 07:31:15 -06:00
|
|
|
if not map_directory.is_dir():
|
2024-03-09 16:27:34 -07:00
|
|
|
map_directory.mkdir(parents=True)
|
2022-03-31 07:31:15 -06:00
|
|
|
return map_directory
|
2022-03-08 13:26:03 -07:00
|
|
|
|
|
|
|
|
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
def iter_map_files(suffix: str) -> List[Path]:
|
|
|
|
|
"""The files in the map directory (at any depth) whose name ends with `suffix`, sorted.
|
|
|
|
|
|
|
|
|
|
Hidden directories are skipped; an unfinished download waits in one under its final name."""
|
|
|
|
|
map_directory = get_map_directory()
|
|
|
|
|
paths = []
|
|
|
|
|
for path in walk(map_directory):
|
|
|
|
|
if not path.name.endswith(suffix) or not path.is_file():
|
|
|
|
|
continue
|
|
|
|
|
if any(i.startswith('.') for i in path.relative_to(map_directory).parts):
|
|
|
|
|
continue
|
|
|
|
|
paths.append(path)
|
|
|
|
|
return sorted(paths)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_map_path(path: Path) -> str:
|
|
|
|
|
"""The name of a map file in the API and the maps config: its path relative to the map directory."""
|
|
|
|
|
return path.relative_to(get_map_directory()).as_posix()
|
|
|
|
|
|
|
|
|
|
|
2026-11-13 15:41:43 -07:00
|
|
|
def find_sidecar_style(path: Path) -> Path | None:
|
|
|
|
|
"""The MapLibre style a person put beside a PMTiles file to say how it is drawn: `<stem>.style.json`, else the
|
|
|
|
|
`style.json` shared by the files of its directory."""
|
|
|
|
|
for candidate in (path.with_suffix('.style.json'), path.parent / 'style.json'):
|
|
|
|
|
if candidate.is_file():
|
|
|
|
|
return candidate
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
def get_pmtiles_files() -> List[dict]:
|
|
|
|
|
"""Find all .pmtiles files in the map directory and return their metadata."""
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
maps_config = get_maps_config()
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
files = []
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
for path in iter_map_files('.pmtiles'):
|
|
|
|
|
stat = path.stat()
|
|
|
|
|
map_path = get_map_path(path)
|
2026-11-13 15:41:43 -07:00
|
|
|
style = find_sidecar_style(path)
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
files.append(dict(
|
|
|
|
|
name=path.name,
|
|
|
|
|
path=str(path.relative_to(get_media_directory())),
|
|
|
|
|
map_path=map_path,
|
|
|
|
|
size=stat.st_size,
|
|
|
|
|
mtime=stat.st_mtime,
|
|
|
|
|
has_search_index=path.with_suffix('.search.db').is_file(),
|
|
|
|
|
visible=not maps_config.is_ignored(map_path),
|
2026-11-13 15:41:43 -07:00
|
|
|
style_path=str(style.relative_to(get_media_directory())) if style else None,
|
The standalone map viewer draws overlays, as the map does (#966)
The standalone viewer (port 8084) drew basemaps only: a map file which is
not a basemap was skipped. It now offers each overlay in its layer panel,
hidden until turned on, with a checkbox per layer, draws it with the style
beside it when there is one, and shows a feature's attributes on a click.
The overlay logic is the map viewer's own. It moved to dependency-free
modules (app/src/map-shared) which a browser can load as they are; the
standalone viewer, which has no build step, loads copies of them from
modules/map/static/js. A test fails while a copy differs from its module
(`npm run sync:map-shared` makes the copies). What differs between the
viewers is passed in: where a map file and its style are fetched from, and
whether a layer can be checked before MapLibre is given it.
The standalone viewer cannot check a layer first, so it adds an overlay's
layers to the map one at a time once the style has loaded: MapLibre refuses a
whole style over one layer it cannot draw, but only that layer when it is
added by itself.
The API also names a style by its path within the map directory, which is
what the standalone viewer is served.
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 17:27:38 -07:00
|
|
|
# The standalone viewer is served the map directory, not the media directory.
|
|
|
|
|
style_map_path=get_map_path(style) if style else None,
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
**pmtiles.describe(path),
|
|
|
|
|
))
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
return files
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2022-03-31 07:31:15 -06:00
|
|
|
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
def _resolve_pmtiles_file(filename: str) -> Path | None:
|
|
|
|
|
"""The PMTiles file in the map directory that `filename` (relative to the map directory) names, if it exists.
|
2026-04-11 20:09:30 -06:00
|
|
|
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
Raises ValueError if the name leads outside of the map directory."""
|
|
|
|
|
map_directory = get_map_directory().resolve()
|
2026-03-29 18:58:31 -06:00
|
|
|
# Prevent path traversal.
|
|
|
|
|
path = (map_directory / filename).resolve()
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
if not path.is_relative_to(map_directory):
|
2026-03-29 18:58:31 -06:00
|
|
|
raise ValueError(f'Invalid filename: {filename}')
|
2022-03-31 07:31:15 -06:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
if path.is_file() and path.suffix == '.pmtiles':
|
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown. The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable). Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.
Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed. A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.
PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
|
|
|
return path
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def delete_pmtiles_file(filename: str) -> bool:
|
|
|
|
|
"""Delete a PMTiles file from the map directory. Returns True if the file was deleted.
|
|
|
|
|
|
|
|
|
|
Also deletes the companion .search.db file if it exists."""
|
|
|
|
|
path = _resolve_pmtiles_file(filename)
|
|
|
|
|
if not path:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
map_path = path.relative_to(get_map_directory().resolve()).as_posix()
|
|
|
|
|
path.unlink()
|
|
|
|
|
logger.warning(f'Deleted PMTiles file: {path}')
|
|
|
|
|
# Also delete companion search index.
|
|
|
|
|
search_db = path.with_suffix('.search.db')
|
|
|
|
|
if search_db.is_file():
|
|
|
|
|
search_db.unlink()
|
|
|
|
|
logger.warning(f'Deleted search index: {search_db}')
|
|
|
|
|
# A file that is gone is not ignored; a later file of the same name starts visible.
|
|
|
|
|
get_maps_config().set_ignored(map_path, False)
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def set_pmtiles_file_visible(filename: str, visible: bool) -> bool:
|
|
|
|
|
"""Show a PMTiles file on the map, or ignore it. Returns False if there is no such file."""
|
|
|
|
|
path = _resolve_pmtiles_file(filename)
|
|
|
|
|
if not path:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
map_path = path.relative_to(get_map_directory().resolve()).as_posix()
|
|
|
|
|
get_maps_config().set_ignored(map_path, not visible)
|
|
|
|
|
return True
|
2022-03-31 07:31:15 -06:00
|
|
|
|
|
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
def get_map_catalog() -> List[dict]:
|
|
|
|
|
"""Return the list of available map regions."""
|
|
|
|
|
return MAP_REGIONS.copy()
|
2022-03-08 13:26:03 -07:00
|
|
|
|
|
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
def _get_map_download(session: Session) -> Download | None:
|
|
|
|
|
"""Find the single recurring map download, if it exists."""
|
|
|
|
|
return session.query(Download).filter_by(url=MANIFEST_URL, downloader='map_catalog').one_or_none()
|
2022-03-08 13:26:03 -07:00
|
|
|
|
|
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
def _get_or_create_map_download(session: Session) -> Download:
|
|
|
|
|
"""Get or create the single recurring map download."""
|
|
|
|
|
download = _get_map_download(session)
|
|
|
|
|
if download:
|
|
|
|
|
return download
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
download = download_manager.get_or_create_download(session, MANIFEST_URL, reset_attempts=True,
|
|
|
|
|
override_skip=True)
|
|
|
|
|
download.downloader = 'map_catalog'
|
|
|
|
|
download.frequency = DownloadFrequency.days180
|
|
|
|
|
download.settings = {'regions': []}
|
|
|
|
|
download.location = '/map/manage'
|
|
|
|
|
download.attempts = 0
|
|
|
|
|
session.flush([download])
|
|
|
|
|
return download
|
2022-10-22 14:40:08 -06:00
|
|
|
|
2022-10-27 20:22:11 -06:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
def get_map_subscriptions(session: Session) -> List[dict]:
|
|
|
|
|
"""Return the list of subscribed regions."""
|
|
|
|
|
regions = []
|
|
|
|
|
download = _get_map_download(session)
|
|
|
|
|
if download and download.settings:
|
|
|
|
|
regions.extend(download.settings.get('regions', []))
|
|
|
|
|
return regions
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2022-03-31 07:31:15 -06:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
async def subscribe(session: Session, name: str, region: str):
|
|
|
|
|
"""Subscribe to a map region."""
|
|
|
|
|
if name not in MAP_REGIONS_BY_NAME:
|
|
|
|
|
raise ValueError(f'{name!r} is not a valid map region name')
|
|
|
|
|
|
|
|
|
|
region_info = MAP_REGIONS_BY_NAME[name]
|
|
|
|
|
if region != region_info['region']:
|
|
|
|
|
raise ValueError(f'Region {region!r} does not match name {name!r}')
|
|
|
|
|
|
|
|
|
|
download = _get_or_create_map_download(session)
|
|
|
|
|
regions = list(download.settings.get('regions', []))
|
|
|
|
|
|
|
|
|
|
# Don't add duplicates.
|
|
|
|
|
if any(r['region'] == region for r in regions):
|
|
|
|
|
return
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
entry = {'region': region}
|
|
|
|
|
if region_info.get('terrain'):
|
|
|
|
|
entry['terrain'] = True
|
2022-03-08 13:26:03 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
regions.append(entry)
|
|
|
|
|
download.settings = {**download.settings, 'regions': regions}
|
|
|
|
|
download.renew(reset_attempts=True)
|
|
|
|
|
session.commit()
|
|
|
|
|
save_downloads_config.activate_switch()
|
2023-08-17 08:27:49 -06:00
|
|
|
|
|
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
async def unsubscribe(session: Session, region: str):
|
|
|
|
|
"""Remove a region from the subscriptions."""
|
|
|
|
|
download = _get_map_download(session)
|
|
|
|
|
if not download:
|
|
|
|
|
raise ValueError(f'No map subscriptions exist')
|
2024-03-06 17:41:04 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
regions = [r for r in download.settings.get('regions', []) if r['region'] != region]
|
|
|
|
|
if regions:
|
|
|
|
|
download.settings = {**download.settings, 'regions': regions}
|
|
|
|
|
else:
|
|
|
|
|
# No more subscriptions — delete the download.
|
|
|
|
|
session.delete(download)
|
|
|
|
|
session.commit()
|
|
|
|
|
save_downloads_config.activate_switch()
|
2024-03-06 17:41:04 -07:00
|
|
|
|
|
|
|
|
|
iNaturalist species map (#1033)
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:24:01 -07:00
|
|
|
# Species packs are kept in this directory of the map directory.
|
|
|
|
|
SPECIES_DIRECTORY = 'inat'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_species_directory() -> Path:
|
|
|
|
|
species_directory = get_map_directory() / SPECIES_DIRECTORY
|
|
|
|
|
species_directory.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
return species_directory
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_species_catalog() -> List[dict]:
|
|
|
|
|
"""The map regions that have a species pack, and the planet (every region in one pack)."""
|
|
|
|
|
planet = dict(name='Planet (every region)', region=PLANET, bbox='-180.0,-90.0,180.0,90.0',
|
|
|
|
|
size_estimate=SPECIES_SIZE_ESTIMATES[PLANET])
|
|
|
|
|
return [planet] + [dict(name=i['name'], region=i['region'], bbox=i['bbox'],
|
|
|
|
|
size_estimate=SPECIES_SIZE_ESTIMATES[i['region']])
|
|
|
|
|
for i in MAP_REGIONS if i['region'] in SPECIES_SIZE_ESTIMATES]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_species_files() -> List[dict]:
|
|
|
|
|
"""The species packs in the species directory: the newest version of each region.
|
|
|
|
|
|
|
|
|
|
An older version left beside a newer one (a download cut short before it deleted the old) is ignored, so its
|
|
|
|
|
observations are never counted twice."""
|
|
|
|
|
newest = dict()
|
|
|
|
|
for path in sorted(get_species_directory().glob(f'*{SPECIES_DB_SUFFIX}')):
|
|
|
|
|
if path.is_file() and (parsed := parse_pack_name(path.name)):
|
|
|
|
|
region, version = parsed
|
|
|
|
|
if region not in newest or version > newest[region]['version']:
|
|
|
|
|
newest[region] = dict(name=path.name, region=region, version=version, size=path.stat().st_size)
|
|
|
|
|
return sorted(newest.values(), key=lambda i: i['region'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def delete_species_files(region: str) -> bool:
|
|
|
|
|
"""Delete every version of a region's species pack. Returns True if any were deleted."""
|
|
|
|
|
deleted = False
|
|
|
|
|
for path in get_species_directory().glob(f'*{SPECIES_DB_SUFFIX}'):
|
|
|
|
|
if (parsed := parse_pack_name(path.name)) and parsed[0] == region:
|
|
|
|
|
logger.warning(f'Deleting species pack: {path}')
|
|
|
|
|
path.unlink()
|
|
|
|
|
deleted = True
|
|
|
|
|
return deleted
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_species_download(session: Session) -> Download | None:
|
|
|
|
|
"""The single recurring species download, if it exists."""
|
|
|
|
|
return session.query(Download).filter_by(url=SPECIES_MANIFEST_URL, downloader='species_catalog').one_or_none()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_species_subscriptions(session: Session) -> List[dict]:
|
|
|
|
|
"""The subscribed species regions."""
|
|
|
|
|
download = _get_species_download(session)
|
|
|
|
|
return list((download.settings or {}).get('regions', [])) if download else []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def species_subscribe(session: Session, region: str):
|
|
|
|
|
"""Subscribe to a region's species pack."""
|
|
|
|
|
if region not in SPECIES_SIZE_ESTIMATES:
|
|
|
|
|
raise ValueError(f'{region!r} has no species pack')
|
|
|
|
|
|
|
|
|
|
download = _get_species_download(session)
|
|
|
|
|
if not download:
|
|
|
|
|
download = download_manager.get_or_create_download(session, SPECIES_MANIFEST_URL, reset_attempts=True,
|
|
|
|
|
override_skip=True)
|
|
|
|
|
download.downloader = 'species_catalog'
|
|
|
|
|
# Packs are built monthly from iNaturalist's export.
|
|
|
|
|
download.frequency = DownloadFrequency.days30
|
|
|
|
|
download.settings = {'regions': []}
|
|
|
|
|
download.location = '/map/manage'
|
|
|
|
|
download.attempts = 0
|
|
|
|
|
session.flush([download])
|
|
|
|
|
|
|
|
|
|
regions = list(download.settings.get('regions', []))
|
|
|
|
|
if any(i['region'] == region for i in regions):
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
download.settings = {**download.settings, 'regions': [*regions, {'region': region}]}
|
|
|
|
|
download.renew(reset_attempts=True)
|
|
|
|
|
session.commit()
|
|
|
|
|
save_downloads_config.activate_switch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def species_unsubscribe(session: Session, region: str):
|
|
|
|
|
"""Stop updating a region's species pack. A downloaded pack is kept."""
|
|
|
|
|
download = _get_species_download(session)
|
|
|
|
|
if not download:
|
|
|
|
|
raise ValueError('No species subscriptions exist')
|
|
|
|
|
|
|
|
|
|
regions = [i for i in download.settings.get('regions', []) if i['region'] != region]
|
|
|
|
|
if regions:
|
|
|
|
|
download.settings = {**download.settings, 'regions': regions}
|
|
|
|
|
else:
|
|
|
|
|
session.delete(download)
|
|
|
|
|
session.commit()
|
|
|
|
|
save_downloads_config.activate_switch()
|
|
|
|
|
|
|
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
async def fetch_manifest(url: str = None) -> dict:
|
iNaturalist species map (#1033)
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:24:01 -07:00
|
|
|
"""Fetch a manifest JSON (the map manifest by default) from the CDN and verify its GPG signature."""
|
2026-03-29 18:58:31 -06:00
|
|
|
url = url or MANIFEST_URL
|
|
|
|
|
sig_url = f'{url}.sig'
|
2024-03-06 17:41:04 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
# Fetch manifest.
|
|
|
|
|
async with aiohttp_get(url, timeout=30) as response:
|
|
|
|
|
if response.status != 200:
|
|
|
|
|
raise RuntimeError(f'Failed to fetch manifest: HTTP {response.status}')
|
|
|
|
|
manifest_bytes = await response.content.read()
|
2024-03-06 17:41:04 -07:00
|
|
|
|
2026-03-29 18:58:31 -06:00
|
|
|
# Fetch detached signature.
|
|
|
|
|
try:
|
|
|
|
|
async with aiohttp_get(sig_url, timeout=30) as response:
|
|
|
|
|
if response.status != 200:
|
|
|
|
|
raise RuntimeError(f'Failed to fetch manifest signature: HTTP {response.status}')
|
|
|
|
|
signature_bytes = await response.content.read()
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.warning(f'Could not fetch manifest signature from {sig_url}: {e}')
|
|
|
|
|
raise RuntimeError(f'Manifest signature not available: {e}')
|
|
|
|
|
|
|
|
|
|
# Write to temp files and verify signature against on-disk files.
|
|
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
|
|
|
manifest_path = Path(tmpdir) / 'manifest.json'
|
|
|
|
|
sig_path = Path(tmpdir) / 'manifest.json.sig'
|
|
|
|
|
manifest_path.write_bytes(manifest_bytes)
|
|
|
|
|
sig_path.write_bytes(signature_bytes)
|
|
|
|
|
|
|
|
|
|
if not await verify_gpg_signature(manifest_path, sig_path):
|
|
|
|
|
raise RuntimeError('Manifest GPG signature verification failed — file may be tampered with')
|
|
|
|
|
|
|
|
|
|
logger.info('Manifest GPG signature verified successfully')
|
|
|
|
|
return json.loads(manifest_bytes)
|