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>
This commit is contained in:
lrnselfreliance 2026-11-29 19:24:01 -07:00 • committed by Roland
parent 8478fc7229
commit a429db441e
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
25 changed files with 4312 additions and 8 deletions

View file

@ -0,0 +1,455 @@
import csv
import gzip
import io
import json
import sqlite3
import zipfile
from unittest import mock
import pytest
from modules.map.species import HIGH_GRID, LOW_GRID, LOOKUP_GRID, cell_id, decode_cells, decode_months, mask_months
from wrolpi.scripts import build_inat_regions as build
# A tiny taxonomy: (taxon_id, ancestry, rank, name).
TAXA = [
(48460, '', 'stateofmatter', 'Life'),
(1, '48460', 'kingdom', 'Animalia'),
(3, '48460/1', 'class', 'Aves'),
(12727, '48460/1/3', 'species', 'Turdus migratorius'),
(999001, '48460/1/3/12727', 'subspecies', 'Turdus migratorius migratorius'),
(47158, '48460/1', 'class', 'Insecta'),
(88, '48460/1/47158', 'species', 'Coccinella septempunctata'),
(6000, '48460/1', 'species', 'Animalia incertae'),
(47126, '48460', 'kingdom', 'Plantae'),
(54000, '48460/47126', 'genus', 'Acer'),
(54001, '48460/47126/54000', 'species', 'Acer macrophyllum'),
]
BEND = (44.06, -121.31)
PRINEVILLE = (44.30, -120.83)
BOUNDARY = (39.74, -104.0) # On the edge of us-west and us-central: in both.
# (lat, lon, taxon_id, uncertainty, withheld, eventDate)
OBSERVATIONS = [
(*BEND, 12727, '10', '', '2026-05-01T08:00:00-07:00'),
(*BEND, 12727, '', '', '2026-05-20'),
(*PRINEVILLE, 999001, '', '', '2025-06-10T09:30:00Z'), # A subspecies: counted as its species.
(*BOUNDARY, 12727, '', '', '2026-07-04'),
(*BEND, 54001, '', 'Coordinate uncertainty increased to 26807m at the request of the observer', '2024-10-01'),
(*PRINEVILLE, 54001, '30000', '', ''), # Imprecise, and no date.
(*BEND, 54000, '', '', '2026-01-01'), # Genus only: skipped.
(*BEND, 424242, '', '', '2026-01-01'), # Unknown taxon: skipped.
('', '', 12727, '', 'Coordinates hidden at the request of the observer', '2026-01-01'), # No coordinates: skipped.
(-50.0, -30.0, 88, '', '', '2026-01-01'), # In no region: skipped.
(*BEND, 88, '', '', '2026-06-15'),
(*BEND, 6000, '', '', 'spring 2026'), # Not a date.
]
COLUMNS = ['id', 'informationWithheld', 'decimalLatitude', 'decimalLongitude', 'coordinateUncertaintyInMeters',
'taxonID', 'scientificName', 'eventDate']
US_REGIONS = [
{'region': 'us-west', 'bbox': '-125.0,24.4,-104.0,49.4'},
{'region': 'us-central', 'bbox': '-104.0,24.4,-87.0,49.4'},
{'region': 'us-east', 'bbox': '-87.0,24.4,-66.9,49.4'},
{'region': 'terrain-z0-8', 'bbox': None},
]
# iNaturalist's English names: (taxon_id, name, locality), in the archive's order. As in the real archive, the name
# iNaturalist shows is listed first and is tied to a place; aliases without a place come after it. The first wins.
VERNACULAR = [
(12727, 'American Robin', 'United States'),
(12727, 'Robin Redbreast', ''),
(12727, 'robin redbreast', ''), # The same name again.
(12727, 'Migratory Thrush', ''),
(54001, 'bigleaf maple', 'Oregon, US'),
(54001, '', ''),
(999001, 'Eastern American Robin', ''),
]
WIKIDATA = {
'12727': {'title': 'American_robin', 'common': 'American robin'},
'54001': {'title': 'Acer_macrophyllum', 'common': 'bigleaf maple'},
'88': {},
}
@pytest.fixture
def taxa_path(test_directory):
path = test_directory / 'taxa.csv.gz'
with gzip.open(path, 'wt', newline='') as fh:
writer = csv.writer(fh, delimiter='\t')
writer.writerow(['taxon_id', 'ancestry', 'rank_level', 'rank', 'name', 'active'])
for taxon_id, ancestry, rank, name in TAXA:
writer.writerow([taxon_id, ancestry, '', rank, name, 'true'])
return path
@pytest.fixture
def taxonomy_path(test_directory):
"""iNaturalist's taxonomy archive, with only the English names."""
path = test_directory / 'inaturalist-taxonomy.dwca.zip'
fh = io.StringIO()
writer = csv.writer(fh)
writer.writerow(['id', 'vernacularName', 'language', 'locality', 'countryCode', 'source', 'lexicon',
'contributor', 'created'])
for taxon_id, name, locality in VERNACULAR:
writer.writerow([taxon_id, name, 'en', locality, '', '', 'English', '', '2026-01-01T00:00:00Z'])
with zipfile.ZipFile(path, 'w') as zf:
zf.writestr('VernacularNames-english.csv', fh.getvalue())
return path
@pytest.fixture
def taxa(taxa_path):
return build.Taxa.load(taxa_path)
@pytest.fixture
def dwca_path(test_directory):
path = test_directory / 'dwca.zip'
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(COLUMNS)
for i, (lat, lon, taxon_id, uncertainty, withheld, event_date) in enumerate(OBSERVATIONS):
writer.writerow([i, withheld, lat, lon, uncertainty, taxon_id, 'name, with a comma', event_date])
with zipfile.ZipFile(path, 'w') as zf:
zf.writestr('eml.xml', '<eml><dataset><pubDate>\n 2026-11-23\n</pubDate></dataset></eml>')
zf.writestr('observations.csv', buffer.getvalue())
return path
def test_dwca_version(dwca_path):
assert build.dwca_version(dwca_path) == '20261123'
def test_read_observations(dwca_path):
observations = list(build.read_observations(dwca_path))
# Only the observation without coordinates is dropped here.
assert len(observations) == len(OBSERVATIONS) - 1
precise = {(lat, lon, taxon_id): p for lat, lon, taxon_id, p, _ in observations}
assert precise[(*BEND, 12727)] is True
assert precise[(*BEND, 54001)] is False, 'withheld'
assert precise[(*PRINEVILLE, 54001)] is False, 'uncertainty over 5 km'
months = {(lat, lon, taxon_id): month for lat, lon, taxon_id, _, month in observations}
assert months[(*PRINEVILLE, 999001)] == 6
assert months[(*PRINEVILLE, 54001)] == 0, 'no date'
assert months[(*BEND, 6000)] == 0, 'not a date'
@pytest.mark.parametrize('event_date,month', [
('2025-09-04T14:22:00+02:00', 9),
('2025-12-31', 12),
('2025-01', 1),
('2025', 0),
('2025-13-01', 0),
('2025-00-01', 0),
('', 0),
('spring 2026', 0),
])
def test_observation_month(event_date, month):
assert build.observation_month(event_date) == month
def test_taxa(taxa):
assert taxa.species_of(12727) == 12727
assert taxa.species_of(999001) == 12727
assert taxa.species_of(54000) is None, 'a genus has no species'
assert taxa.species_of(424242) is None
assert taxa.group_of(12727) == 2 # Birds
assert taxa.group_of(88) == 7 # Insects, not Animalia's "other".
assert taxa.group_of(54001) == 1 # Plants
assert taxa.group_of(6000) == 0
def test_bbox_regions():
regions = build.bbox_regions(US_REGIONS)
assert [name for name, _ in regions] == ['us-west', 'us-central', 'us-east'], 'terrain has no bbox'
assert regions[0][1] == (-125.0, 24.4, -104.0, 49.4)
# Every real map region parses.
assert len(build.bbox_regions()) > 20
def test_split_by_region(test_directory, dwca_path, taxa):
regions = build.bbox_regions(US_REGIONS)
paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory)
assert set(paths) == {'us-west', 'us-central'}, 'us-east received nothing'
assert not (test_directory / 'us-east.tsv').exists()
west = [line.split('\t') for line in paths['us-west'][0].read_text().splitlines()]
central = [line.split('\t') for line in paths['us-central'][0].read_text().splitlines()]
# Bend robin x2, Prineville subspecies, boundary robin, 2 maples, ladybug, other.
assert len(west) == 8
assert central == [['39.74', '-104.0', '12727', '1', '7']], 'the boundary is in both regions'
assert ['44.3', '-120.83', '12727', '1', '6'] in west, 'the subspecies became its species'
assert build.species_in(paths['us-west'][0]) == {12727, 54001, 88, 6000}
@pytest.fixture
def west_pack(test_directory, dwca_path, taxa):
regions = build.bbox_regions(US_REGIONS)
paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory)
db_path = test_directory / build.pack_name('us-west', '20261123')
stats = build.build_pack(paths['us-west'], 'us-west', regions[0][1], taxa, WIKIDATA, '20261123', db_path)
return db_path, stats
def test_load_english_names(taxonomy_path):
assert build.load_english_names(taxonomy_path) == {
12727: ['American Robin', 'Robin Redbreast', 'Migratory Thrush'],
54001: ['bigleaf maple'],
999001: ['Eastern American Robin'],
}
def test_build_pack_common_names(test_directory, dwca_path, taxa, taxonomy_path):
"""iNaturalist's first name is the common name, before Wikidata's; every other name is searchable."""
regions = build.bbox_regions(US_REGIONS)
paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory)
db_path = test_directory / build.pack_name('us-west', '20261123')
wikidata = {**WIKIDATA, '88': {'title': 'Coccinella_septempunctata', 'common': 'seven-spot ladybird'}}
build.build_pack(paths['us-west'], 'us-west', regions[0][1], taxa, wikidata, '20261123', db_path,
build.load_english_names(taxonomy_path))
with sqlite3.connect(db_path) as db:
names = {taxon: (common, other) for taxon, common, other in
db.execute('SELECT taxon_id, common_name, other_names FROM species')}
match = 'SELECT rowid FROM species_fts WHERE species_fts MATCH ?'
assert db.execute(match, ('"redbreast"*',)).fetchall() == [(12727,)], 'an alias finds its species'
assert db.execute(match, ('"american"* "robin"*',)).fetchall() == [(12727,)]
assert names == {
# Wikidata's name ("American robin") is the same name; it is not repeated.
12727: ('American Robin', 'Robin Redbreast; Migratory Thrush'),
54001: ('bigleaf maple', None),
88: ('seven-spot ladybird', None),
6000: (None, None),
}
def test_build_pack(west_pack):
db_path, stats = west_pack
assert db_path.name == 'inat-us-west-20261123.species.db'
assert stats['species'] == 4
assert stats['observations'] == 8
assert stats['precise'] == 6
db = sqlite3.connect(db_path)
meta = dict(db.execute('SELECT key, value FROM meta'))
assert meta['version'] == '20261123'
assert meta['region'] == 'us-west'
assert meta['license'] == 'CC BY-NC 4.0'
assert '10.15468/ab3s5x' in meta['attribution']
assert meta['observations'] == '8'
species = {row[0]: row for row in db.execute(
'SELECT taxon_id, name, common_name, wiki_title, grp, obs_count, min_lat, min_lon, max_lat, max_lon,'
' range_low, range_high FROM species')}
robin = species[12727]
assert robin[1:6] == ('Turdus migratorius', 'American robin', 'American_robin', 2, 4)
assert robin[6:10] == (BOUNDARY[0], BEND[1], PRINEVILLE[0], BOUNDARY[1])
assert decode_cells(robin[10]) == sorted({cell_id(*p, LOW_GRID) for p in (BEND, PRINEVILLE, BOUNDARY)})
assert decode_cells(robin[11]) == sorted({cell_id(*p, HIGH_GRID) for p in (BEND, PRINEVILLE, BOUNDARY)})
maple = species[54001]
assert maple[2:6] == ('bigleaf maple', 'Acer_macrophyllum', 1, 2)
assert maple[6:10] == (None, None, None, None), 'no precise observation, no bbox'
assert decode_cells(maple[10]) == sorted({cell_id(*p, LOW_GRID) for p in (BEND, PRINEVILLE)}), 'blurred still count'
assert maple[11] is None, 'blurred observations make no precise dots'
assert species[88][2:4] == (None, None), 'Wikidata had nothing'
assert species[6000][4] == 0
# The lookup cells add up to every observation, and find the species around Bend.
assert db.execute('SELECT SUM(obs_count) FROM cell_species').fetchone()[0] == 8
bend = cell_id(*BEND, LOOKUP_GRID)
assert dict(db.execute('SELECT taxon_id, obs_count FROM cell_species WHERE cell = ?', (bend,))) == {
12727: 2, 54001: 1, 88: 1, 6000: 1}
# Months: how many each month of the year, and the months seen in each lookup cell.
months = dict(db.execute('SELECT taxon_id, months FROM species'))
assert decode_months(months[12727]) == [0, 0, 0, 0, 2, 1, 1, 0, 0, 0, 0, 0], 'May, May, June (Prineville), July'
assert decode_months(months[54001]) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 'the undated maple is not a month'
assert months[6000] is None, 'never dated'
in_bend = dict(db.execute('SELECT taxon_id, months FROM cell_species WHERE cell = ?', (bend,)))
assert {taxon: mask_months(mask) for taxon, mask in in_bend.items()} == {12727: [5], 54001: [10], 88: [6], 6000: []}
# Names are searchable.
match = 'SELECT rowid FROM species_fts WHERE species_fts MATCH ?'
assert db.execute(match, ('bigleaf',)).fetchall() == [(54001,)]
assert db.execute(match, ('turdus',)).fetchall() == [(12727,)]
def test_parse_wikidata_bindings():
bindings = [
{'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Artemisia_(plant)'}},
{'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Second'},
'common': {'value': 'sagebrush'}},
{'inat': {'value': '2'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Caf%C3%A9'}},
{'inat': {'value': '3'}},
{'article': {'value': 'https://en.wikipedia.org/wiki/No_taxon'}},
]
assert build.parse_wikidata_bindings(bindings) == {
'1': {'title': 'Artemisia_(plant)', 'common': 'sagebrush'},
'2': {'title': 'Café'},
'3': {},
}
def test_fetch_wikidata_caches(test_directory):
cache_path = test_directory / 'wikidata.json'
asked = []
def query(taxon_ids):
asked.append(list(taxon_ids))
return [{'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/One'}}]
assert build.fetch_wikidata([1, 2], cache_path, query=query, delay=0) == {'1': {'title': 'One'}, '2': {}}
assert asked == [['1', '2']]
# Both are cached, even the taxon Wikidata knows nothing about.
assert build.fetch_wikidata([2, 1], cache_path, query=query, delay=0) == {'1': {'title': 'One'}, '2': {}}
assert len(asked) == 1
def test_fetch_wikidata_failure_not_cached(test_directory):
"""A batch that fails is not cached, so the next build asks again."""
cache_path = test_directory / 'wikidata.json'
def failing(taxon_ids):
raise RuntimeError('timeout')
assert build.fetch_wikidata([1, 2, 3], cache_path, query=failing, delay=0) == {}
assert not cache_path.exists()
def test_fetch_wikidata_splits_failing_batch(test_directory):
"""A failing batch is split; the halves that work are kept."""
ids = [str(i) for i in range(40)]
def query(taxon_ids):
if '0' in taxon_ids:
raise RuntimeError('this one is cursed')
return [{'inat': {'value': i}, 'common': {'value': f'name {i}'}} for i in taxon_ids]
found = build.fetch_wikidata(ids, test_directory / 'wikidata.json', query=query, delay=0)
# Halved until the batch of 10 holding '0' failed alone; the other 30 were answered. (Ids sort as text.)
failed = sorted(ids)[:10]
assert len(found) == 30
assert not set(failed) & set(found), 'the failed batch is not cached'
assert found['39'] == {'common': 'name 39'}
def assert_not_exists(path):
assert not path.exists(), f'{path} is still there when the manifest is signed'
def test_write_manifest(test_directory, west_pack):
db_path, _ = west_pack
# A signature from an earlier build: gpg would ask before replacing it, and wait forever for an answer.
old_signature = test_directory / 'manifest.json.sig'
old_signature.write_text('old')
with mock.patch.object(build, 'write_meta4', return_value='abc123') as write_meta4, \
mock.patch.object(build, 'sign_manifest', side_effect=lambda path: assert_not_exists(old_signature)) \
as sign_manifest:
manifest_path = build.write_manifest(test_directory, '20261123', 'https://cdn.example/inat',
{'us-west': db_path})
url = 'https://cdn.example/inat/20261123/inat-us-west-20261123.species.db'
manifest = json.loads(manifest_path.read_text())
assert manifest['version'] == '20261123'
assert manifest['regions'] == {'us-west': url}
assert manifest['sizes'] == {'us-west': db_path.stat().st_size}
assert manifest['sha256'] == {url: 'abc123'}
assert manifest['license'] == 'CC BY-NC 4.0'
write_meta4.assert_called_once_with(str(db_path), url)
sign_manifest.assert_called_once_with(str(manifest_path))
def test_main(test_directory, dwca_path, taxa_path, taxonomy_path):
"""The whole build, offline: given sources, two regions, no signing."""
work_dir, output_dir = test_directory / 'work', test_directory / 'out'
argv = ['build_inat_regions.py', str(work_dir), str(output_dir), '--dwca', str(dwca_path), '--taxa',
str(taxa_path), '--taxonomy', str(taxonomy_path), '--regions', 'us-west,us-central', '--no-sign']
with mock.patch('sys.argv', argv), \
mock.patch.object(build, 'query_wikidata', return_value=[]), \
mock.patch.object(build, 'download') as download:
build.main()
download.assert_not_called()
manifest = json.loads((output_dir / 'manifest.json').read_text())
assert set(manifest['regions']) == {'us-west', 'us-central'}
assert (output_dir / '20261123' / 'inat-us-central-20261123.species.db').is_file()
assert (output_dir / '20261123' / 'inat-us-west-20261123.species.db').is_file()
assert json.loads((work_dir / 'wikidata.json').read_text()) == {'12727': {}, '54001': {}, '88': {}, '6000': {}}
with sqlite3.connect(output_dir / '20261123' / 'inat-us-west-20261123.species.db') as db:
assert db.execute('SELECT common_name FROM species WHERE taxon_id = 12727').fetchone() == ('American Robin',)
# A rebuild of the same observations, with a new version, from the last build's region work files.
with mock.patch('sys.argv', argv + ['--version', '20261128', '--reuse-split']), \
mock.patch.object(build, 'query_wikidata', return_value=[]), \
mock.patch.object(build, 'read_observations') as read_observations:
build.main()
read_observations.assert_not_called()
manifest = json.loads((output_dir / 'manifest.json').read_text())
assert manifest['version'] == '20261128'
assert manifest['regions']['us-west'].endswith('/20261128/inat-us-west-20261128.species.db')
with sqlite3.connect(output_dir / '20261128' / 'inat-us-west-20261128.species.db') as db:
assert dict(db.execute('SELECT key, value FROM meta'))['version'] == '20261128'
assert db.execute('SELECT COUNT(*) FROM species').fetchone() == (4,)
@pytest.mark.parametrize('extra', [['--version', '2026-11-28'], ['--reuse-split']])
def test_main_invalid(test_directory, dwca_path, taxa_path, taxonomy_path, extra):
"""A version must be YYYYMMDD; --reuse-split needs the work files of a last build."""
argv = ['build_inat_regions.py', str(test_directory / 'work'), str(test_directory / 'out'), '--dwca',
str(dwca_path), '--taxa', str(taxa_path), '--taxonomy', str(taxonomy_path), '--no-sign', *extra]
with mock.patch('sys.argv', argv), pytest.raises(SystemExit):
build.main()
def test_main_unknown_region(test_directory):
argv = ['build_inat_regions.py', str(test_directory), str(test_directory), '--regions', 'atlantis']
with mock.patch('sys.argv', argv), pytest.raises(SystemExit):
build.main()
def test_planet(test_directory, dwca_path, taxa, taxonomy_path):
"""The planet is every observation once, though regions overlap, built from work files split by species."""
regions = build.bbox_regions(US_REGIONS)
paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory, planet=True)
buckets = paths['planet']
assert len(buckets) == build.PLANET_BUCKETS
# Each species is in one bucket; every observation of a species (in a region or not) is in it once.
species_of_bucket = [build.species_in(i) for i in buckets]
assert sum(len(i) for i in species_of_bucket) == len(set().union(*species_of_bucket)) == 4
# Bend robin x2, Prineville subspecies, boundary robin, 2 maples, 2 ladybugs (one in no region), other.
assert sum(len(i.read_text().splitlines()) for i in buckets) == 9
planet = test_directory / build.pack_name('planet', '20261123')
stats = build.build_pack(buckets, 'planet', build.PLANET_BBOX, taxa, WIKIDATA, '20261123', planet,
build.load_english_names(taxonomy_path))
assert (stats['species'], stats['observations']) == (4, 9)
db = sqlite3.connect(planet)
meta = dict(db.execute('SELECT key, value FROM meta'))
assert (meta['region'], meta['bbox'], meta['observations']) == ('planet', '-180.0,-90.0,180.0,90.0', '9')
# The boundary robin is in both us-west and us-central, but once here: Bend x2, Prineville, the boundary.
robin = db.execute('SELECT common_name, obs_count, months FROM species WHERE taxon_id = 12727').fetchone()
assert robin == ('American Robin', 4, '0,0,0,0,2,1,1,0,0,0,0,0')
assert db.execute('SELECT SUM(obs_count) FROM cell_species').fetchone() == (9,)
assert db.execute("SELECT rowid FROM species_fts WHERE species_fts MATCH '\"redbreast\"*'").fetchall() == [(12727,)]
def test_main_planet_alone(test_directory, dwca_path, taxa_path, taxonomy_path):
"""`--regions planet` builds only the planet; the manifest also lists the regions already built for the version."""
work_dir, output_dir = test_directory / 'work', test_directory / 'out'
argv = ['build_inat_regions.py', str(work_dir), str(output_dir), '--dwca', str(dwca_path), '--taxa',
str(taxa_path), '--taxonomy', str(taxonomy_path), '--no-sign']
with mock.patch('sys.argv', argv + ['--regions', 'us-west,us-central']), \
mock.patch.object(build, 'query_wikidata', return_value=[]):
build.main()
assert not (output_dir / '20261123' / 'inat-planet-20261123.species.db').exists()
with mock.patch('sys.argv', argv + ['--regions', 'planet']), \
mock.patch.object(build, 'query_wikidata', return_value=[]):
build.main()
manifest = json.loads((output_dir / 'manifest.json').read_text())
assert set(manifest['regions']) == {'us-west', 'us-central', 'planet'}
assert not (work_dir / 'regions' / 'us-west.tsv').read_text() == '', 'the regions\' work was left alone'

View file

@ -0,0 +1,51 @@
import pytest
from modules.map.species import (HIGH_GRID, LOW_GRID, cell_center, cell_id, decode_cells, decode_months, encode_cells,
encode_months, mask_months, month_bit)
@pytest.mark.parametrize('grid', [LOW_GRID, HIGH_GRID])
@pytest.mark.parametrize('lat,lon', [
(44.06, -121.31),
(-33.86, 151.21),
(0.0, 0.0),
(-90.0, -180.0),
(90.0, 180.0), # The north pole and the antimeridian fall in the last row/column.
(89.999, 179.999),
])
def test_cell_center_contains_point(grid, lat, lon):
"""The center of a point's cell is within half a cell of the point (or on the world's edge, the last cell)."""
center_lat, center_lon = cell_center(cell_id(lat, lon, grid), grid)
assert abs(center_lat - lat) <= grid / 2 + 1e-9
assert abs(center_lon - lon) <= grid / 2 + 1e-9
def test_cell_id_neighbors():
"""Cells are numbered row by row from the south-west corner."""
assert cell_id(-90, -180, LOW_GRID) == 0
assert cell_id(-90, -179.95, LOW_GRID) == 0
assert cell_id(-90, -179.85, LOW_GRID) == 1
assert cell_id(-89.85, -180, LOW_GRID) == 3600
assert cell_id(90, 180, LOW_GRID) == 1800 * 3600 - 1
@pytest.mark.parametrize('cells', [
[],
[0],
[5, 3, 5, 1], # Unsorted, with a duplicate.
[127, 128, 16_383, 16_384, 2 ** 28 - 1], # Varint boundaries and the largest high grid cell.
list(range(0, 1_000_000, 37)),
])
def test_encode_decode_cells(cells):
assert decode_cells(encode_cells(cells)) == sorted(set(cells))
def test_months():
assert [month_bit(i) for i in (0, 1, 12, 13)] == [0, 1, 2048, 0]
assert mask_months(month_bit(1) | month_bit(6) | month_bit(12)) == [1, 6, 12]
assert mask_months(0) == []
counts = [0, 0, 3, 10, 0, 0, 0, 0, 0, 0, 1, 0]
assert decode_months(encode_months(counts)) == counts
assert encode_months([0] * 12) is None
assert decode_months(None) == [0] * 12
assert decode_months('1,2') == [0] * 12, 'malformed'

View file

@ -0,0 +1,357 @@
"""Subscribing to species packs and downloading them: lib helpers, the downloaders, and the API."""
import json
from http import HTTPStatus
from unittest import mock
import pytest
import yaml
from modules.map import lib
from modules.map.catalog import MAP_REGIONS, SPECIES_MANIFEST_URL
from modules.map.downloader import (
ExecutedMapCatalog,
PreparedSpeciesPack,
species_catalog_downloader,
species_pack_downloader,
)
from wrolpi.conftest import make_test_ctx
from wrolpi.downloader import Download, DownloadFrequency, import_downloads_config
SHA256 = 'a' * 64
CDN = 'https://cdn.example.com/maps/inat'
def make_pack(region: str, version: str, contents: bytes = b'pack'):
path = lib.get_species_directory() / f'inat-{region}-{version}.species.db'
path.write_bytes(contents)
return path
def manifest(version: str = '20261123', *regions: str) -> dict:
regions = regions or ('us-west', 'us-alaska')
urls = {i: f'{CDN}/{version}/inat-{i}-{version}.species.db' for i in regions}
return {'version': version, 'regions': urls, 'sha256': {url: SHA256 for url in urls.values()}}
# ---------------------------------------------------------------------------
# lib
# ---------------------------------------------------------------------------
def test_species_catalog(test_directory):
"""Every map region with a bbox has a species pack; terrain does not."""
catalog = lib.get_species_catalog()
regions = {i['region'] for i in catalog}
assert regions == {i['region'] for i in MAP_REGIONS if i['bbox']} | {'planet'}
assert 'terrain-z0-8' not in regions
us_west, = [i for i in catalog if i['region'] == 'us-west']
assert us_west['name'] == 'United States (West)'
assert us_west['bbox'] == '-125.0,24.4,-104.0,49.4'
assert us_west['size_estimate'] > 0
def test_species_directory(test_directory, test_wrolpi_config):
"""Packs are kept in `inat/` of the map directory."""
assert lib.get_species_directory() == test_directory / 'map/inat'
assert lib.get_species_directory().is_dir()
def test_species_files(test_directory):
"""Only pack files are listed, with their region and version."""
make_pack('us-west', '20261123', b'12345')
make_pack('europe-ne-central', '20261123')
(lib.get_species_directory() / 'notes.txt').write_text('not a pack')
(lib.get_species_directory() / 'inat-us-west.species.db').write_text('no version')
files = lib.get_species_files()
assert [(i['region'], i['version']) for i in files] == [('europe-ne-central', '20261123'), ('us-west', '20261123')]
assert files[1]['size'] == 5
assert files[1]['name'] == 'inat-us-west-20261123.species.db'
def test_delete_species_files(test_directory):
"""Deleting a region's packs deletes every version of it, and no other region with the same prefix."""
old = make_pack('europe-ne', '20261023')
new = make_pack('europe-ne', '20261123')
other = make_pack('europe-ne-central', '20261123')
assert lib.delete_species_files('europe-ne') is True
assert not old.exists() and not new.exists()
assert other.exists()
assert lib.delete_species_files('europe-ne') is False
# A region never names a path.
assert lib.delete_species_files('../../etc') is False
@pytest.mark.asyncio
async def test_species_subscribe(async_client, test_session, test_directory):
"""Subscriptions share one recurring Download of the species manifest."""
await lib.species_subscribe(test_session, 'us-alaska')
await lib.species_subscribe(test_session, 'us-west')
await lib.species_subscribe(test_session, 'us-west') # Not duplicated.
await lib.species_subscribe(test_session, 'planet')
await lib.species_unsubscribe(test_session, 'planet')
assert lib.get_species_subscriptions(test_session) == [{'region': 'us-alaska'}, {'region': 'us-west'}]
download = lib._get_species_download(test_session)
assert download.url == SPECIES_MANIFEST_URL
assert download.downloader == 'species_catalog'
assert download.frequency == DownloadFrequency.days30
assert download.status == 'new'
with pytest.raises(ValueError):
await lib.species_subscribe(test_session, 'atlantis')
# Terrain is a map region, but has no species.
with pytest.raises(ValueError):
await lib.species_subscribe(test_session, 'terrain-z0-8')
@pytest.mark.asyncio
async def test_species_unsubscribe(async_client, test_session, test_directory):
"""Unsubscribing keeps the downloaded pack; the last one deletes the Download."""
pack = make_pack('us-alaska', '20261123')
await lib.species_subscribe(test_session, 'us-alaska')
await lib.species_subscribe(test_session, 'us-west')
await lib.species_unsubscribe(test_session, 'us-alaska')
assert lib.get_species_subscriptions(test_session) == [{'region': 'us-west'}]
assert pack.is_file()
await lib.species_unsubscribe(test_session, 'us-west')
assert lib.get_species_subscriptions(test_session) == []
assert lib._get_species_download(test_session) is None
with pytest.raises(ValueError):
await lib.species_unsubscribe(test_session, 'us-west')
@pytest.mark.asyncio
async def test_species_subscriptions_config(async_client, test_session, test_directory, test_download_manager_config,
await_switches):
"""Subscriptions are saved to the downloads config, and come back when it is imported."""
await lib.species_subscribe(test_session, 'us-west')
await await_switches()
with test_download_manager_config.open() as fh:
downloads = yaml.safe_load(fh)['downloads']
saved, = [i for i in downloads if i['url'] == SPECIES_MANIFEST_URL]
assert saved['downloader'] == 'species_catalog'
assert saved['settings'] == {'regions': [{'region': 'us-west'}]}
test_session.query(Download).delete()
test_session.commit()
assert lib.get_species_subscriptions(test_session) == []
await import_downloads_config()
assert lib.get_species_subscriptions(test_session) == [{'region': 'us-west'}]
# ---------------------------------------------------------------------------
# SpeciesCatalogDownloader
# ---------------------------------------------------------------------------
def test_catalog_creates_pack_downloads(test_session, test_directory):
"""A species_pack Download is created for each subscribed region in the manifest, with its signed hash."""
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog')
executed = ExecutedMapCatalog(manifest=manifest(), subscribed_regions=[{'region': 'us-west'}, {'region': 'mars'}])
result = species_catalog_downloader.finalize_download(test_session, download, executed)
assert result.success is True
child, = test_session.query(Download).filter_by(downloader='species_pack').all()
assert child.url == f'{CDN}/20261123/inat-us-west-20261123.species.db'
assert child.settings == {'region': 'us-west', 'version': '20261123', 'sha256': SHA256}
assert child.status == 'new'
def test_catalog_replaces_old_version(test_session, test_directory):
"""A new version replaces the old version's Download; other regions' Downloads are left alone."""
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog')
subscribed = [{'region': 'us-west'}, {'region': 'us-alaska'}]
species_catalog_downloader.finalize_download(
test_session, download, ExecutedMapCatalog(manifest=manifest('20261023'), subscribed_regions=subscribed))
test_session.commit()
# The next month only us-west was rebuilt.
new = manifest('20261123', 'us-west')
new['regions']['us-alaska'] = f'{CDN}/20261023/inat-us-alaska-20261023.species.db'
new['sha256'][new['regions']['us-alaska']] = SHA256
species_catalog_downloader.finalize_download(
test_session, download, ExecutedMapCatalog(manifest=new, subscribed_regions=subscribed))
test_session.commit()
urls = sorted(i.url for i in test_session.query(Download).filter_by(downloader='species_pack'))
assert urls == [f'{CDN}/20261023/inat-us-alaska-20261023.species.db',
f'{CDN}/20261123/inat-us-west-20261123.species.db']
@pytest.mark.parametrize('bad_manifest,error', [
({'regions': {}, 'version': '20261123'}, 'does not contain regions'),
({'regions': {'us-west': 'https://x'}}, 'does not contain regions'),
(manifest('20261123', 'mexico'), 'No subscribed species regions'),
])
def test_catalog_failures(test_session, test_directory, bad_manifest, error):
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog')
executed = ExecutedMapCatalog(manifest=bad_manifest, subscribed_regions=[{'region': 'us-west'}])
result = species_catalog_downloader.finalize_download(test_session, download, executed)
assert result.success is False
assert error in result.error
@pytest.mark.asyncio
async def test_catalog_fetches_species_manifest(test_session, test_directory):
"""The species catalog fetches (and verifies) the manifest at its Download's URL."""
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog', settings={'regions': []})
prepared = species_catalog_downloader.prepare_download(test_session, download)
with mock.patch('modules.map.lib.fetch_manifest', mock.AsyncMock(return_value=manifest())) as fetch:
executed = await species_catalog_downloader.execute_download(prepared, make_test_ctx())
fetch.assert_called_once_with(SPECIES_MANIFEST_URL)
assert executed.manifest == manifest()
# ---------------------------------------------------------------------------
# SpeciesPackDownloader
# ---------------------------------------------------------------------------
@pytest.mark.parametrize('settings', [
{},
{'region': 'us-west'},
{'region': 'us-west', 'version': 'latest'},
{'region': '../../etc', 'version': '20261123'},
{'region': 'US West', 'version': '20261123'},
])
def test_pack_prepare_invalid(test_session, test_directory, settings):
"""A pack's region and version must make a pack name; nothing else is downloaded."""
download = Download(url=f'{CDN}/x.species.db', downloader='species_pack', settings=settings)
prepared = species_pack_downloader.prepare_download(test_session, download)
assert prepared.error == 'Invalid region or version in download settings'
def test_pack_prepare_already_done(test_session, test_directory):
make_pack('us-west', '20261123')
download = Download(url=f'{CDN}/20261123/inat-us-west-20261123.species.db', downloader='species_pack',
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
prepared = species_pack_downloader.prepare_download(test_session, download)
assert prepared.already_done is True
assert prepared.output_path == test_directory / 'map/inat/inat-us-west-20261123.species.db'
@pytest.mark.asyncio
async def test_pack_refuses_without_signed_hash(test_session, test_directory):
"""With no hash in the manifest and no meta4, nothing is downloaded."""
url = f'{CDN}/20261123/inat-us-west-20261123.species.db'
download = Download(url=url, downloader='species_pack', settings={'region': 'us-west', 'version': '20261123'})
prepared = species_pack_downloader.prepare_download(test_session, download)
with mock.patch.object(species_pack_downloader, 'get_meta4_contents', mock.AsyncMock(return_value=None)), \
mock.patch.object(species_pack_downloader, 'download_file') as download_file:
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download)
assert 'No signed hash' in executed.error
download_file.assert_not_called()
@pytest.mark.asyncio
async def test_pack_download_replaces_old_version(test_session, test_directory):
"""The new pack is moved in only after aria2c checked it against the signed hash; then old versions go."""
old = make_pack('us-west', '20261023', b'old')
neighbor = make_pack('us-west-coast', '20261023', b'not this region') # Hypothetical region with the prefix.
url = f'{CDN}/20261123/inat-us-west-20261123.species.db'
download = Download(url=url, downloader='species_pack',
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
prepared = species_pack_downloader.prepare_download(test_session, download)
async def fake_download_file(download_, url_, destination, **kwargs):
assert SHA256.encode() in kwargs['meta4_xml']
# Not in the species directory until it is checked.
assert destination == test_directory / 'map/.partial'
path = destination / 'inat-us-west-20261123.species.db'
path.write_bytes(b'new')
return path
with mock.patch.object(species_pack_downloader, 'download_file', fake_download_file):
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download)
assert executed.error is None
assert (test_directory / 'map/inat/inat-us-west-20261123.species.db').read_bytes() == b'new'
assert not old.exists()
assert neighbor.exists()
assert species_pack_downloader.finalize_download(test_session, download, executed).success is True
@pytest.mark.asyncio
async def test_pack_download_failure_keeps_old_version(test_session, test_directory):
"""A failed (or rejected) download leaves the region's current pack in place."""
old = make_pack('us-west', '20261023', b'old')
url = f'{CDN}/20261123/inat-us-west-20261123.species.db'
download = Download(url=url, downloader='species_pack',
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
prepared = species_pack_downloader.prepare_download(test_session, download)
with mock.patch.object(species_pack_downloader, 'download_file',
mock.AsyncMock(side_effect=RuntimeError('aria2c failed with return code 32'))):
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download)
assert 'Download failed' in executed.error
assert old.read_bytes() == b'old'
assert not (test_directory / 'map/inat/inat-us-west-20261123.species.db').exists()
assert species_pack_downloader.finalize_download(test_session, download, executed).success is False
@pytest.mark.asyncio
async def test_pack_skipped(test_session, test_directory):
prepared = PreparedSpeciesPack(region='us-west', already_done=True)
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx())
assert executed.skipped is True
# ---------------------------------------------------------------------------
# API
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_species_api(async_client, test_session, test_directory):
"""The species catalog can be fetched, subscribed to, and unsubscribed from; packs can be deleted."""
request, response = await async_client.get('/api/map/species/subscribe')
assert response.status_code == HTTPStatus.OK
assert response.json['subscriptions'] == []
assert response.json['files'] == []
assert 'us-west' in [i['region'] for i in response.json['catalog']]
request, response = await async_client.post('/api/map/species/subscribe', content=json.dumps({'region': 'us-west'}))
assert response.status_code == HTTPStatus.CREATED
request, response = await async_client.post('/api/map/species/subscribe', content=json.dumps({'region': 'mars'}))
assert response.status_code == HTTPStatus.BAD_REQUEST
make_pack('us-west', '20261123', b'12345')
request, response = await async_client.get('/api/map/species/subscribe')
assert response.json['subscriptions'] == [{'region': 'us-west'}]
assert [(i['region'], i['version'], i['size']) for i in response.json['files']] == [('us-west', '20261123', 5)]
request, response = await async_client.delete('/api/map/species/subscribe/us-west')
assert response.status_code == HTTPStatus.NO_CONTENT
request, response = await async_client.delete('/api/map/species/subscribe/us-west')
assert response.status_code == HTTPStatus.NOT_FOUND
request, response = await async_client.delete('/api/map/species/files/us-west')
assert response.status_code == HTTPStatus.NO_CONTENT
request, response = await async_client.delete('/api/map/species/files/us-west')
assert response.status_code == HTTPStatus.NOT_FOUND
request, response = await async_client.get('/api/map/species/subscribe')
assert response.json['subscriptions'] == []
assert response.json['files'] == []
def test_pack_already_done_removes_old_versions(test_session, test_directory):
"""A download that stopped before deleting the older versions is finished on the next run."""
old = make_pack('us-west', '20261023', b'old')
make_pack('us-west', '20261123', b'new')
download = Download(url=f'{CDN}/20261123/inat-us-west-20261123.species.db', downloader='species_pack',
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
prepared = species_pack_downloader.prepare_download(test_session, download)
assert prepared.already_done is True
assert not old.exists()

View file

@ -0,0 +1,404 @@
"""Reading the species packs: search by name and place, details, range dots, and the Wikipedia article."""
import itertools
from http import HTTPStatus
from unittest import mock
import pytest
from modules.map import lib, species_search
from modules.map.species import HIGH_GRID, LOOKUP_GRID, LOW_GRID, cell_center, cell_id
from modules.map.species_search import cells_within, fts_query, haversine_km
BEND = (44.06, -121.31)
PRINEVILLE = (44.30, -120.83) # ~47 km east of Bend.
CRATER_LAKE = (42.94, -122.10) # ~140 km from Bend.
DENVER = (39.74, -104.99) # In us-central.
ASPEN = dict(taxon_id=1, name='Populus tremuloides', common_name='quaking aspen', wiki_title='one', grp=1)
GRASS = dict(taxon_id=2, name='Briza maxima', common_name='big quakinggrass', grp=1)
DEER = dict(taxon_id=3, name='Odocoileus hemionus', common_name='mule deer', wiki_title='Mule_deer', grp=3)
# Its (made up) common name is exactly "aspen".
FLEABANE = dict(taxon_id=4, name='Erigeron speciosus', common_name='aspen', grp=1)
@pytest.fixture
def us_packs(test_directory, make_species_pack):
make_species_pack('us-west', [
{**ASPEN, 'points': [BEND, BEND, BEND, CRATER_LAKE]},
{**GRASS, 'points': [PRINEVILLE] * 5},
{**DEER, 'points': [BEND] + [CRATER_LAKE] * 10},
{**FLEABANE, 'points': [PRINEVILLE]},
])
make_species_pack('us-central', [
{**ASPEN, 'points': [DENVER, DENVER]},
])
def taxa(results):
return [i['taxon_id'] for i in results]
# --- Cells ------------------------------------------------------------------------------------------------------------
def test_cells_within():
lat, lon = BEND
cells = cells_within(lat, lon, 30)
assert cell_id(lat, lon, LOOKUP_GRID) in cells
# Every cell has some part within the radius: its center is within the radius plus half its diagonal (~7 km).
assert all(haversine_km(lat, lon, *cell_center(i, LOOKUP_GRID)) < 30 + 8 for i in cells)
assert cell_id(lat, lon + 0.2, LOOKUP_GRID) in cells # ~16 km east.
assert cell_id(lat, lon + 0.6, LOOKUP_GRID) not in cells # ~48 km east.
assert cell_id(*PRINEVILLE, LOOKUP_GRID) not in cells
assert cell_id(*PRINEVILLE, LOOKUP_GRID) in cells_within(lat, lon, 60)
# A tiny radius is still the point's own cell.
assert cells_within(lat, lon, 0.001) == [cell_id(lat, lon, LOOKUP_GRID)]
def test_cells_within_antimeridian_and_pole():
# Fiji: the radius crosses the antimeridian into the first column.
cells = cells_within(-17.0, 179.99, 20)
assert cell_id(-17.0, -179.95, LOOKUP_GRID) in cells
assert cell_id(-17.0, 179.95, LOOKUP_GRID) in cells
# Near the pole every column of the last rows is near.
cells = cells_within(89.99, 0, 50)
assert cell_id(89.95, 179.95, LOOKUP_GRID) in cells
assert cell_id(89.95, -179.95, LOOKUP_GRID) in cells
@pytest.mark.parametrize('q,expected', [
('quaking asp', '"quaking"* "asp"*'),
("O'Brien", '"O"* "Brien"*'),
('"*', None),
('', None),
])
def test_fts_query(q, expected):
assert fts_query(q) == expected
# --- Search -----------------------------------------------------------------------------------------------------------
def test_search_no_packs(test_directory):
assert species_search.search_species(q='aspen') == []
assert species_search.search_species(lat=BEND[0], lon=BEND[1]) == []
def test_search_by_name(us_packs):
"""Every word is a prefix; without a place the most observed come first. A species in two regions is merged."""
results = species_search.search_species(q='quak')
assert taxa(results) == [1, 2]
aspen, grass = results
assert aspen['obs_count'] == 6 # 4 in us-west + 2 in us-central.
assert aspen['regions'] == ['us-central', 'us-west']
assert aspen['bbox'] == [CRATER_LAKE[1], DENVER[0], DENVER[1], BEND[0]]
assert aspen['near_count'] is None
assert aspen['group'] == 'Plants'
assert aspen['common_name'] == 'quaking aspen'
assert taxa(species_search.search_species(q='quaking aspen')) == [1]
assert taxa(species_search.search_species(q='odocoileus')) == [3]
assert taxa(species_search.search_species(q='nothing')) == []
assert taxa(species_search.search_species(q='"*')) == []
def test_search_exact_name_first(us_packs):
"""A species named exactly what was searched comes first, however rarely it was seen."""
assert taxa(species_search.search_species(q='aspen')) == [4, 1]
assert taxa(species_search.search_species(q='Populus tremuloides')) == [1]
def test_search_near(us_packs):
"""Without a name: only species seen within the radius, the most seen nearby first."""
lat, lon = BEND
results = species_search.search_species(lat=lat, lon=lon, radius_km=30)
assert [(i['taxon_id'], i['near_count']) for i in results] == [(1, 3), (3, 1)]
# Near counts are only nearby observations; totals are every region's.
assert results[1]['obs_count'] == 11
# Prineville is within 60 km. Equal near counts are ordered by total observations.
results = species_search.search_species(lat=lat, lon=lon, radius_km=60)
assert [(i['taxon_id'], i['near_count']) for i in results] == [(2, 5), (1, 3), (3, 1), (4, 1)]
# Nothing is seen in the ocean.
assert species_search.search_species(lat=30.0, lon=-140.0) == []
def test_search_name_and_near(us_packs):
"""With a name and a place, matching species seen nearby come first; the others are still listed."""
lat, lon = BEND
results = species_search.search_species(q='quak', lat=lat, lon=lon, radius_km=30)
assert [(i['taxon_id'], i['near_count']) for i in results] == [(1, 3), (2, 0)]
def test_search_group_and_limit(us_packs):
lat, lon = BEND
assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, group=3)) == [3]
assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, group=1)) == [2, 1, 4]
assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, limit=2)) == [2, 1]
# Neither a name nor a place: the most observed.
assert taxa(species_search.search_species(limit=2)) == [3, 1]
# --- Details and range ------------------------------------------------------------------------------------------------
def test_get_species(us_packs):
aspen = species_search.get_species(1)
assert aspen['name'] == 'Populus tremuloides'
assert aspen['obs_count'] == 6
assert aspen['regions'] == ['us-central', 'us-west']
assert species_search.get_species(999) is None
@pytest.mark.parametrize('grid,size', [('low', LOW_GRID), ('high', HIGH_GRID)])
def test_get_species_range(us_packs, grid, size):
"""Every cell the species was seen in, in every region, each once: sorted, as differences."""
found = species_search.get_species_range(1, grid)
assert found['grid'] == size
assert found['count'] == 3
cells = list(itertools.accumulate(found['deltas']))
assert cells == sorted(cell_id(*point, size) for point in (BEND, CRATER_LAKE, DENVER))
assert species_search.get_species_range(999, grid) is None
# --- Wikipedia --------------------------------------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_wikipedia_none(test_session, test_directory, zim_factory):
"""Without a Wikipedia Zim there is nowhere to read about a species."""
zim_factory('gutenberg_en_all_2026-01.zim')
assert await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') is None
@pytest.mark.asyncio
async def test_wikipedia_article(test_session, test_directory, zim_factory):
"""The article is found in the best Wikipedia Zim; a missing article falls back to a search for the name."""
mini = zim_factory('wikipedia_en_all_mini_2026-03.zim')
maxi = zim_factory('wikipedia_en_all_maxi_2026-01.zim')
old_maxi = zim_factory('wikipedia_en_all_maxi_2025-01.zim')
zim_factory('wiktionary_en_all_maxi_2026-01.zim')
test_session.commit()
assert species_search.wikipedia_zims(test_session) == [maxi, old_maxi, mini]
# The test Zim has an article at `one`.
article = await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides')
assert article == dict(zim_id=maxi.id, path='one', title='One', url=f'/api/zim/{maxi.id}/entry/one')
search = dict(zim_id=None, path=None, title=None, url='/search?q=Populus%20tremuloides')
assert await species_search.find_wikipedia_article(test_session, 'Populus_tremuloides',
'Populus tremuloides') == search
assert await species_search.find_wikipedia_article(test_session, None, 'Populus tremuloides') == search
# --- API --------------------------------------------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_species_search_api(async_client, us_packs):
request, response = await async_client.get('/api/map/species', params={'q': 'quak'})
assert response.status_code == HTTPStatus.OK
assert taxa(response.json['species']) == [1, 2]
assert response.json['packs'] == 2
assert {'code': 1, 'name': 'Plants'} in response.json['groups']
params = {'lat': BEND[0], 'lon': BEND[1], 'radius_km': 60, 'group': 1, 'limit': 2}
request, response = await async_client.get('/api/map/species', params=params)
assert [(i['taxon_id'], i['near_count']) for i in response.json['species']] == [(2, 5), (1, 3)]
@pytest.mark.asyncio
@pytest.mark.parametrize('params', [
{'lat': 40},
{'lat': 100, 'lon': 0},
{'lat': 0, 'lon': 181},
{'lat': 'x', 'lon': 0},
{'radius_km': 0},
{'radius_km': 201},
{'group': 'plants'},
{'limit': 0},
{'limit': 501},
])
async def test_species_search_api_invalid(async_client, test_directory, params):
request, response = await async_client.get('/api/map/species', params=params)
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_species_detail_api(async_client, test_session, us_packs, zim_factory):
request, response = await async_client.get('/api/map/species/1')
assert response.status_code == HTTPStatus.OK
assert response.json['common_name'] == 'quaking aspen'
assert response.json['wikipedia'] is None
zim = zim_factory('wikipedia_en_all_nopic_2026-01.zim')
test_session.commit()
request, response = await async_client.get('/api/map/species/1')
assert response.json['wikipedia']['url'] == f'/api/zim/{zim.id}/entry/one'
request, response = await async_client.get('/api/map/species/999')
assert response.status_code == HTTPStatus.NOT_FOUND
@pytest.mark.asyncio
async def test_species_range_api(async_client, us_packs):
for grid in ('low', 'high'):
request, response = await async_client.get('/api/map/species/1/range', params={'grid': grid})
assert response.status_code == HTTPStatus.OK
assert response.json['count'] == 3
request, response = await async_client.get('/api/map/species/1/range', params={'grid': 'medium'})
assert response.status_code == HTTPStatus.BAD_REQUEST
request, response = await async_client.get('/api/map/species/999/range')
assert response.status_code == HTTPStatus.NOT_FOUND
# --- Months and what was seen here -------------------------------------------------------------------------------------
@pytest.fixture
def dated_packs(test_directory, make_species_pack):
"""Aspen seen around Bend in May and October, and in us-central in October; deer at Bend in July."""
make_species_pack('us-west', [
{**ASPEN, 'points': [(*BEND, 5), (*BEND, 5), (*BEND, 10), CRATER_LAKE]}, # Crater Lake is undated.
{**DEER, 'points': [(*BEND, 7)]},
{**GRASS, 'points': [(*PRINEVILLE, 4)]},
])
make_species_pack('us-central', [{**ASPEN, 'points': [(*DENVER, 10)]}])
def test_species_months(dated_packs):
"""A species' months are summed over every region."""
aspen = species_search.get_species(1)
assert aspen['months'] == [0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0]
assert species_search.search_species(q='mule')[0]['months'][6] == 1
def test_species_here(dated_packs):
"""The species seen in the square of a point, the most seen first, with the months seen there."""
here = species_search.species_here(*BEND)
assert here['species_count'] == 2
assert [(i['taxon_id'], i['here_count'], i['here_months']) for i in here['species']] == [(1, 3, [5, 10]), (3, 1, [7])]
# The square holds the point, and is 0.1° wide.
west, south, east, north = here['bbox']
assert west <= BEND[1] <= east and south <= BEND[0] <= north
assert (east - west, north - south) == pytest.approx((LOOKUP_GRID, LOOKUP_GRID))
assert [i['taxon_id'] for i in species_search.species_here(*BEND, limit=1)['species']] == [1]
# The species asked about is there however few times it was seen, even beyond the limit.
deer = species_search.species_here(*BEND, limit=1, taxon_id=DEER['taxon_id'])['taxon']
assert (deer['taxon_id'], deer['here_count'], deer['here_months']) == (DEER['taxon_id'], 1, [7])
assert species_search.species_here(*BEND, taxon_id=GRASS['taxon_id'])['taxon'] is None, 'seen elsewhere only'
assert species_search.species_here(30.0, -140.0) == {
'taxon': None, 'bbox': pytest.approx([-140.0, 30.0, -139.9, 30.1]), 'species_count': 0, 'species': []}
def test_old_packs_have_no_months(test_directory, make_species_pack):
"""Packs built before months were kept still work, without months."""
make_species_pack('us-west', [{**ASPEN, 'points': [(*BEND, 5)]}], months=False)
assert species_search.get_species(1)['months'] == [0] * 12
assert species_search.search_species(q='aspen')[0]['obs_count'] == 1
here = species_search.species_here(*BEND)
assert [(i['taxon_id'], i['here_count'], i['here_months']) for i in here['species']] == [(1, 1, [])]
@pytest.mark.asyncio
async def test_species_here_api(async_client, dated_packs):
request, response = await async_client.get('/api/map/species/here',
params={'lat': BEND[0], 'lon': BEND[1], 'taxon_id': DEER['taxon_id']})
assert response.status_code == HTTPStatus.OK
assert response.json['taxon']['here_months'] == [7]
assert response.json['species'][0]['common_name'] == 'quaking aspen'
assert response.json['species'][0]['here_months'] == [5, 10]
for params in ({}, {'lat': BEND[0]}, {'lat': 'x', 'lon': 0}, {'lat': 91, 'lon': 0}, {'lat': 0, 'lon': 0, 'limit': 0}):
request, response = await async_client.get('/api/map/species/here', params=params)
assert response.status_code == HTTPStatus.BAD_REQUEST, params
# --- Review fixes --------------------------------------------------------------------------------------------------
def test_only_newest_version_counted(test_directory, make_species_pack):
"""An older version of a region left beside the newer one is not counted again."""
make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 3}], version='20261023')
make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 5}], version='20261123')
assert [i['version'] for i in lib.get_species_files()] == ['20261123']
aspen = species_search.get_species(1)
assert aspen['obs_count'] == 5
assert aspen['regions'] == ['us-west']
assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 5
def test_names_from_any_pack(test_directory, make_species_pack):
"""A name one region's pack lacks is taken from another's; the newest pack's name wins."""
make_species_pack('us-west', [{**ASPEN, 'common_name': None, 'wiki_title': None, 'points': [BEND]}],
version='20261123')
make_species_pack('us-central', [{**ASPEN, 'common_name': 'quaking aspen', 'points': [DENVER]}],
version='20261023')
aspen = species_search.get_species(1)
assert (aspen['common_name'], aspen['wiki_title']) == ('quaking aspen', 'one')
def test_other_names_searchable(test_directory, make_species_pack):
make_species_pack('us-west', [{**ASPEN, 'other_names': 'trembling aspen; popple', 'points': [BEND]}])
found, = species_search.search_species(q='popple')
assert found['taxon_id'] == 1
assert found['other_names'] == 'trembling aspen; popple'
def test_bbox_across_antimeridian(test_directory, make_species_pack):
"""A species in packs on both sides of the antimeridian has no bbox, not one the long way around the world."""
make_species_pack('russia-east', [{**DEER, 'points': [(60.0, 179.5)]}])
make_species_pack('us-alaska', [{**DEER, 'points': [(60.0, -179.5)]}])
deer = species_search.get_species(DEER['taxon_id'])
assert deer['bbox'] is None
assert species_search.get_species_range(DEER['taxon_id'])['count'] == 2
def test_wikipedia_zims_prefer_all(test_session, test_directory, zim_factory):
"""Within a flavor, all of Wikipedia comes before a newer selection of it."""
top = zim_factory('wikipedia_en_top_maxi_2026-06.zim')
everything = zim_factory('wikipedia_en_all_maxi_2026-01.zim')
nopic = zim_factory('wikipedia_en_all_nopic_2026-06.zim')
test_session.commit()
assert species_search.wikipedia_zims(test_session) == [everything, top, nopic]
@pytest.mark.asyncio
async def test_wikipedia_stops_at_first_article(test_session, test_directory, zim_factory):
"""Zims are opened one at a time, best first, until one has the article."""
zim_factory('wikipedia_en_all_maxi_2026-01.zim')
zim_factory('wikipedia_en_all_mini_2026-01.zim')
test_session.commit()
with mock.patch('modules.map.species_search.run_libzim_jobs',
mock.AsyncMock(return_value=[{'found': 'one', 'title': 'One'}])) as run:
article = await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides')
assert article['path'] == 'one'
run.assert_called_once()
assert run.call_args[0][0][0]['path'].endswith('wikipedia_en_all_maxi_2026-01.zim')
def test_planet_pack_is_read_alone(test_directory, make_species_pack):
"""With the planet pack downloaded, the regions' packs (which it holds) are not read too."""
make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 3}])
make_species_pack('planet', [{**ASPEN, 'points': [BEND] * 3 + [DENVER]}])
aspen = species_search.get_species(1)
assert (aspen['obs_count'], aspen['regions']) == (4, ['planet'])
assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 3
def test_overlapping_regions_not_counted_twice(test_directory, make_species_pack):
"""Regions overlap (us-west and mexico both hold southern Arizona): a square both hold is counted once, not twice."""
tucson = (32.22, -110.97)
make_species_pack('us-west', [{**DEER, 'points': [tucson] * 4 + [BEND]}])
make_species_pack('mexico', [{**DEER, 'points': [tucson] * 4}])
found, = species_search.search_species(lat=tucson[0], lon=tucson[1])
assert found['near_count'] == 4
here = species_search.species_here(*tucson)['species'][0]
assert here['here_count'] == 4
# Elsewhere one pack holds the square: its counts are its own.
assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 1